From e84ae4a4b2fab3f3e91607dc6fed04c7ca45b8c7 Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Sun, 25 Aug 2019 01:04:14 -0400 Subject: [PATCH] Feature-less backend selection This PR removes optional backend features in favor of run-time selection at the `request_adapter` entry point. Adapters from all supported gpu backends on the platform are reported. It also makes gfx-rs dependency to be public (for now). --- Cargo.lock | 672 ---------- Makefile | 30 +- examples/compute/CMakeLists.txt | 21 +- examples/compute/main.c | 6 +- examples/remote/main.c | 7 +- examples/triangle/CMakeLists.txt | 21 +- examples/triangle/main.c | 13 +- ffi/wgpu-remote.h | 22 +- ffi/wgpu.h | 175 ++- wgpu-native/Cargo.toml | 18 +- wgpu-native/src/command/allocator.rs | 11 +- wgpu-native/src/command/bind.rs | 17 +- wgpu-native/src/command/compute.rs | 101 +- wgpu-native/src/command/mod.rs | 747 +++++------ wgpu-native/src/command/render.rs | 237 +++- wgpu-native/src/command/transfer.rs | 98 +- wgpu-native/src/conv.rs | 1 - wgpu-native/src/device.rs | 1722 +++++++++++++------------- wgpu-native/src/hub.rs | 298 +++-- wgpu-native/src/id.rs | 117 +- wgpu-native/src/instance.rs | 448 +++---- wgpu-native/src/lib.rs | 55 +- wgpu-native/src/resource.rs | 24 +- wgpu-native/src/swap_chain.rs | 91 +- wgpu-native/src/track/buffer.rs | 2 +- wgpu-native/src/track/mod.rs | 41 +- wgpu-remote/Cargo.toml | 5 - wgpu-remote/src/lib.rs | 146 ++- wgpu-remote/src/server.rs | 27 +- 29 files changed, 2433 insertions(+), 2740 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0675e37e2..607eadd17 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,31 +1,5 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -[[package]] -name = "andrew" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", - "line_drawing 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", - "rusttype 0.7.6 (registry+https://github.com/rust-lang/crates.io-index)", - "walkdir 2.2.7 (registry+https://github.com/rust-lang/crates.io-index)", - "xdg 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "xml-rs 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "android_glue" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "approx" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "arrayvec" version = "0.4.10" @@ -113,15 +87,6 @@ name = "cfg-if" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "cgl" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "gleam 0.6.17 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.55 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "cloudabi" version = "0.0.3" @@ -197,15 +162,6 @@ dependencies = [ "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "d3d12" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "derivative" version = "1.0.2" @@ -216,19 +172,6 @@ dependencies = [ "syn 0.15.34 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "dlib" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "libloading 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "downcast-rs" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "failure" version = "0.1.5" @@ -299,39 +242,6 @@ name = "gcc" version = "0.3.55" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "gfx-backend-dx11" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", - "derivative 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "gfx-hal 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", - "range-alloc 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "smallvec 0.6.9 (registry+https://github.com/rust-lang/crates.io-index)", - "spirv_cross 0.14.2 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", - "wio 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "gfx-backend-dx12" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", - "d3d12 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "derivative 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "gfx-hal 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "range-alloc 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "smallvec 0.6.9 (registry+https://github.com/rust-lang/crates.io-index)", - "spirv_cross 0.14.2 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "gfx-backend-empty" version = "0.3.0" @@ -340,26 +250,6 @@ dependencies = [ "gfx-hal 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "gfx-backend-gl" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", - "gfx-hal 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "gl_generator 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "glow 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "glutin 0.21.0 (registry+https://github.com/rust-lang/crates.io-index)", - "js-sys 0.3.25 (registry+https://github.com/rust-lang/crates.io-index)", - "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "smallvec 0.6.9 (registry+https://github.com/rust-lang/crates.io-index)", - "spirv_cross 0.14.2 (registry+https://github.com/rust-lang/crates.io-index)", - "wasm-bindgen 0.2.48 (registry+https://github.com/rust-lang/crates.io-index)", - "web-sys 0.3.25 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "gfx-backend-metal" version = "0.3.0" @@ -411,120 +301,6 @@ dependencies = [ "fxhash 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "gl_generator" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "khronos_api 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "xml-rs 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "gl_generator" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "khronos_api 3.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "xml-rs 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "gleam" -version = "0.6.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "gl_generator 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "glow" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "gl_generator 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", - "js-sys 0.3.25 (registry+https://github.com/rust-lang/crates.io-index)", - "slotmap 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "wasm-bindgen 0.2.48 (registry+https://github.com/rust-lang/crates.io-index)", - "web-sys 0.3.25 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "glutin" -version = "0.21.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "android_glue 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "cgl 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "cocoa 0.18.4 (registry+https://github.com/rust-lang/crates.io-index)", - "core-foundation 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)", - "core-graphics 0.17.3 (registry+https://github.com/rust-lang/crates.io-index)", - "derivative 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "glutin_egl_sys 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", - "glutin_emscripten_sys 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "glutin_gles2_sys 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", - "glutin_glx_sys 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", - "glutin_wgl_sys 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", - "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "libloading 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", - "objc 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", - "osmesa-sys 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", - "wayland-client 0.21.12 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", - "winit 0.19.1 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "glutin_egl_sys" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "gl_generator 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "glutin_emscripten_sys" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "glutin_gles2_sys" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "gl_generator 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "objc 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "glutin_glx_sys" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "gl_generator 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "x11-dl 2.18.3 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "glutin_wgl_sys" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "gl_generator 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "heck" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "unicode-segmentation 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "hibitset" version = "0.6.2" @@ -576,16 +352,6 @@ dependencies = [ "winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "khronos_api" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "khronos_api" -version = "3.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "lazy_static" version = "1.3.0" @@ -596,32 +362,6 @@ name = "libc" version = "0.2.55" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "libloading" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cc 1.0.37 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "line_drawing" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "lock_api" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "owning_ref 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "scopeguard 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "lock_api" version = "0.3.1" @@ -646,20 +386,6 @@ dependencies = [ "libc 0.2.55 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "memchr" -version = "2.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "memmap" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "libc 0.2.55 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "metal" version = "0.15.0" @@ -714,37 +440,11 @@ dependencies = [ "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "nix" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", - "cc 1.0.37 (registry+https://github.com/rust-lang/crates.io-index)", - "cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.55 (registry+https://github.com/rust-lang/crates.io-index)", - "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "nodrop" version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "nom" -version = "4.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "memchr 2.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "num-traits" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "objc" version = "0.2.6" @@ -780,39 +480,6 @@ dependencies = [ "objc 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "ordered-float" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "osmesa-sys" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "shared_library 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "owning_ref" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "parking_lot" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "lock_api 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", - "parking_lot_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "parking_lot" version = "0.9.0" @@ -823,18 +490,6 @@ dependencies = [ "rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "parking_lot_core" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "libc 0.2.55 (registry+https://github.com/rust-lang/crates.io-index)", - "rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)", - "rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "smallvec 0.6.9 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "parking_lot_core" version = "0.6.1" @@ -849,11 +504,6 @@ dependencies = [ "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "percent-encoding" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "pkg-config" version = "0.3.14" @@ -1057,30 +707,6 @@ dependencies = [ "semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "rusttype" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "approx 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", - "arrayvec 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)", - "ordered-float 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "stb_truetype 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "same-file" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "winapi-util 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "scopeguard" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "scopeguard" version = "1.0.0" @@ -1131,47 +757,11 @@ name = "slab" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "slotmap" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "smallvec" version = "0.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "smithay-client-toolkit" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "andrew 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", - "dlib 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", - "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "memmap 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", - "nix 0.13.0 (registry+https://github.com/rust-lang/crates.io-index)", - "wayland-client 0.21.12 (registry+https://github.com/rust-lang/crates.io-index)", - "wayland-commons 0.21.12 (registry+https://github.com/rust-lang/crates.io-index)", - "wayland-protocols 0.21.12 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "sourcefile" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "spirv_cross" -version = "0.14.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cc 1.0.37 (registry+https://github.com/rust-lang/crates.io-index)", - "js-sys 0.3.25 (registry+https://github.com/rust-lang/crates.io-index)", - "wasm-bindgen 0.2.48 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "spirv_cross" version = "0.15.0" @@ -1182,19 +772,6 @@ dependencies = [ "wasm-bindgen 0.2.48 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "stable_deref_trait" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "stb_truetype" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "storage-map" version = "0.2.0" @@ -1237,11 +814,6 @@ dependencies = [ "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "unicode-segmentation" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "unicode-xid" version = "0.1.0" @@ -1260,26 +832,6 @@ name = "vec_map" version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "version_check" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "void" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "walkdir" -version = "2.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "same-file 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi-util 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "wasm-bindgen" version = "0.2.48" @@ -1328,95 +880,6 @@ name = "wasm-bindgen-shared" version = "0.2.48" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "wasm-bindgen-webidl" -version = "0.2.48" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", - "heck 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 0.15.34 (registry+https://github.com/rust-lang/crates.io-index)", - "wasm-bindgen-backend 0.2.48 (registry+https://github.com/rust-lang/crates.io-index)", - "weedle 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "wayland-client" -version = "0.21.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", - "downcast-rs 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.55 (registry+https://github.com/rust-lang/crates.io-index)", - "nix 0.13.0 (registry+https://github.com/rust-lang/crates.io-index)", - "wayland-commons 0.21.12 (registry+https://github.com/rust-lang/crates.io-index)", - "wayland-scanner 0.21.12 (registry+https://github.com/rust-lang/crates.io-index)", - "wayland-sys 0.21.12 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "wayland-commons" -version = "0.21.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "nix 0.13.0 (registry+https://github.com/rust-lang/crates.io-index)", - "wayland-sys 0.21.12 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "wayland-protocols" -version = "0.21.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", - "wayland-client 0.21.12 (registry+https://github.com/rust-lang/crates.io-index)", - "wayland-commons 0.21.12 (registry+https://github.com/rust-lang/crates.io-index)", - "wayland-scanner 0.21.12 (registry+https://github.com/rust-lang/crates.io-index)", - "wayland-sys 0.21.12 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "wayland-scanner" -version = "0.21.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)", - "xml-rs 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "wayland-sys" -version = "0.21.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "dlib 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", - "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "web-sys" -version = "0.3.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", - "js-sys 0.3.25 (registry+https://github.com/rust-lang/crates.io-index)", - "sourcefile 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", - "wasm-bindgen 0.2.48 (registry+https://github.com/rust-lang/crates.io-index)", - "wasm-bindgen-webidl 0.2.48 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "weedle" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "nom 4.2.3 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "wgpu-native" version = "0.3.3" @@ -1424,10 +887,7 @@ dependencies = [ "arrayvec 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)", "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", "copyless 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", - "gfx-backend-dx11 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "gfx-backend-dx12 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "gfx-backend-empty 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "gfx-backend-gl 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "gfx-backend-metal 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "gfx-backend-vulkan 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "gfx-hal 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1476,50 +936,11 @@ name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "winapi-util" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "winit" -version = "0.19.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "android_glue 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "backtrace 0.3.18 (registry+https://github.com/rust-lang/crates.io-index)", - "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", - "cocoa 0.18.4 (registry+https://github.com/rust-lang/crates.io-index)", - "core-foundation 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)", - "core-graphics 0.17.3 (registry+https://github.com/rust-lang/crates.io-index)", - "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.55 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "objc 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", - "parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", - "percent-encoding 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "smithay-client-toolkit 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", - "wayland-client 0.21.12 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", - "x11-dl 2.18.3 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "wio" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "ws2_32-sys" version = "0.2.1" @@ -1538,38 +959,7 @@ dependencies = [ "pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "x11-dl" -version = "2.18.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.55 (registry+https://github.com/rust-lang/crates.io-index)", - "pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "xdg" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "xml-rs" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "xml-rs" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - [metadata] -"checksum andrew 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "9b7f09f89872c2b6b29e319377b1fbe91c6f5947df19a25596e121cf19a7b35e" -"checksum android_glue 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "000444226fcff248f2bc4c7625be32c63caccfecc2723a2b9f78a7487a49c407" -"checksum approx 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f0e60b75072ecd4168020818c0107f2857bb6c4e64252d8d3983f6263b40a5c3" "checksum arrayvec 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)" = "92c7fb76bc8826a8b33b4ee5bb07a247a81e76764ab4d55e8f73e3a4d8808c71" "checksum ash 0.29.0 (registry+https://github.com/rust-lang/crates.io-index)" = "003d1fb2eb12eb06d4a03dbe02eea67a9fac910fa97932ab9e3a75b96a1ea5e5" "checksum atom 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "3c86699c3f02778ec07158376991c8f783dd1f2f95c579ffaf0738dc984b2fe2" @@ -1583,7 +973,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" "checksum byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a019b10a2a7cdeb292db131fc8113e57ea2a908f6e7894b0c3c671893b65dbeb" "checksum cc 1.0.37 (registry+https://github.com/rust-lang/crates.io-index)" = "39f75544d7bbaf57560d2168f28fd649ff9c76153874db88bdbdfd839b1a7e7d" "checksum cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "b486ce3ccf7ffd79fdeb678eac06a9e6c09fc88d33836340becb8fffe87c5e33" -"checksum cgl 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "55e7ec0b74fe5897894cbc207092c577e87c52f8a59e8ca8d97ef37551f60a49" "checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" "checksum cocoa 0.18.4 (registry+https://github.com/rust-lang/crates.io-index)" = "cf79daa4e11e5def06e55306aa3601b87de6b5149671529318da048f67cdd77b" "checksum colorful 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0bca1619ff57dd7a56b58a8e25ef4199f123e78e503fe1653410350a1b98ae65" @@ -1593,10 +982,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" "checksum core-graphics 0.17.3 (registry+https://github.com/rust-lang/crates.io-index)" = "56790968ab1c8a1202a102e6de05fc6e1ec87da99e4e93e9a7d13efbfc1e95a9" "checksum crossbeam-channel 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "0f0ed1a4de2235cabda8558ff5840bffb97fcb64c97827f354a451307df5f72b" "checksum crossbeam-utils 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)" = "f8306fcef4a7b563b76b7dd949ca48f52bc1141aa067d2ea09565f3e2652aa5c" -"checksum d3d12 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4fda5547c55c93b070d59108464bbfd7d9da9563b2ce78fceefc6430e972a420" "checksum derivative 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6073e9676dbebdddeabaeb63e3b7cefd23c86f5c41d381ee1237cc77b1079898" -"checksum dlib 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "77e51249a9d823a4cb79e3eca6dcd756153e8ed0157b6c04775d04bf1b13b76a" -"checksum downcast-rs 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "f2b92dfd5c2f75260cbf750572f95d387e7ca0ba5e3fbe9e1a33f23025be020f" "checksum failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "795bd83d3abeb9220f257e597aa0080a508b27533824adf336529648f6abf7e2" "checksum failure_derive 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "ea1063915fd7ef4309e222a5a07cf9c319fb9c7836b1f89b85458672dbb127e1" "checksum fnv 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "2fad85553e09a6f881f739c29f0b00b0f01357c743266d478b68951ce23285f3" @@ -1607,61 +993,31 @@ source = "registry+https://github.com/rust-lang/crates.io-index" "checksum fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7" "checksum fxhash 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c" "checksum gcc 0.3.55 (registry+https://github.com/rust-lang/crates.io-index)" = "8f5f3913fa0bfe7ee1fd8248b6b9f42a5af4b9d65ec2dd2c3c26132b950ecfc2" -"checksum gfx-backend-dx11 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "79b2bfb8b9c8d020062ab8c43e5bc48a049b780a638069cd9c261291ce8c83da" -"checksum gfx-backend-dx12 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "42a7ad96014d4b610d6846edf97dd70479374c38f5a64908abeb86c99b4c4fab" "checksum gfx-backend-empty 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "19ee69c0aaa5b96b0995914e7136676ba8a9b5bd8a87d8b21f26641e72aa309b" -"checksum gfx-backend-gl 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "221db07872ccdf8926260d9609d32701f56593ec017a4d8c996a8aaa7b361917" "checksum gfx-backend-metal 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d3a11d55ddb58c69f179bbcef317ffd7d8bac80251fd19be6f980ace2348ac31" "checksum gfx-backend-vulkan 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "057ee275c9802b98aa68777844dc986f5693204f6e93830b5302379eaaa93fb7" "checksum gfx-hal 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "70263c629d8466d0195b8c6c8c5d35a0373bf75515a08f04268c86753d3a6692" -"checksum gl_generator 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "39a23d5e872a275135d66895d954269cf5e8661d234eb1c2480f4ce0d586acbd" -"checksum gl_generator 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7a795170cbd85b5a7baa58d6d7525cae6a03e486859860c220f7ebbbdd379d0a" -"checksum gleam 0.6.17 (registry+https://github.com/rust-lang/crates.io-index)" = "7f46fd8874e043ffac0d638ed1567a2584f7814f6d72b4db37ab1689004a26c4" -"checksum glow 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "8efdf08c11e4af89f286a378adb74c003749240137b0466b9efa17d9e7ea89c5" -"checksum glutin 0.21.0 (registry+https://github.com/rust-lang/crates.io-index)" = "cb26027a84c3b9e1949ef0df0b6a3db8d0c124243a5c161ea25c7def90cb1474" -"checksum glutin_egl_sys 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "23f48987ab6cb2b61ad903b59e54a2fd0c380a7baff68cffd6826b69a73dd326" -"checksum glutin_emscripten_sys 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "245b3fdb08df6ffed7585365851f8404af9c7e2dd4b59f15262e968b6a95a0c7" -"checksum glutin_gles2_sys 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "89996c30857ae1b4de4b5189abf1ea822a20a9fe9e1c93e5e7b862ff0bdd5cdf" -"checksum glutin_glx_sys 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "1290a5ca5e46fcfa7f66f949cc9d9194b2cb6f2ed61892c8c2b82343631dba57" -"checksum glutin_wgl_sys 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "f801bbc91efc22dd1c4818a47814fc72bf74d024510451b119381579bfa39021" -"checksum heck 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "20564e78d53d2bb135c343b3f47714a56af2061f1c928fdb541dc7b9fdd94205" "checksum hibitset 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "47e7292fd9f7fe89fa35c98048f2d0a69b79ed243604234d18f6f8a1aa6f408d" "checksum iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "dbe6e417e7d0975db6512b90796e8ce223145ac4e33c377e4a42882a0e88bb08" "checksum ipc-channel 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "79d98ee7dd1d2e796d254807fd86ea7189d07571aeaa74007603e29a79d15217" "checksum js-sys 0.3.25 (registry+https://github.com/rust-lang/crates.io-index)" = "da3ea71161651a4cd97d999b2da139109c537b15ab33abc8ae4ead38deac8a03" "checksum kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" -"checksum khronos_api 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "037ab472c33f67b5fbd3e9163a2645319e5356fcd355efa6d4eb7fff4bbcb554" -"checksum khronos_api 3.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" "checksum lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bc5729f27f159ddd61f4df6228e827e86643d4d3e7c32183cb30a1c08f604a14" "checksum libc 0.2.55 (registry+https://github.com/rust-lang/crates.io-index)" = "42914d39aad277d9e176efbdad68acb1d5443ab65afe0e0e4f0d49352a950880" -"checksum libloading 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9c3ad660d7cb8c5822cd83d10897b0f1f1526792737a179e73896152f85b88c2" -"checksum line_drawing 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5cc7ad3d82c845bdb5dde34ffdcc7a5fb4d2996e1e1ee0f19c33bc80e15196b9" -"checksum lock_api 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "62ebf1391f6acad60e5c8b43706dde4582df75c06698ab44511d15016bc2442c" "checksum lock_api 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "f8912e782533a93a167888781b836336a6ca5da6175c05944c86cf28c31104dc" "checksum log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c84ec4b527950aa83a329754b01dbe3f58361d1c5efacd1f6d68c494d08a17c6" "checksum malloc_buf 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb" -"checksum memchr 2.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "88579771288728879b57485cc7d6b07d648c9f0141eb955f8ab7f9d45394468e" -"checksum memmap 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "6585fd95e7bb50d6cc31e20d4cf9afb4e2ba16c5846fc76793f11218da9c475b" "checksum metal 0.15.0 (registry+https://github.com/rust-lang/crates.io-index)" = "508aa26b306fdc5b927b200f9d16d9eb668c3d4034f0354242bf5be15f0bb431" "checksum mio 0.6.17 (registry+https://github.com/rust-lang/crates.io-index)" = "049ba5ca2b63e837adeee724aa9e36b408ed593529dcc802aa96ca14bd329bdf" "checksum miow 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8c1f2f3b1cf331de6896aabf6e9d55dca90356cc9960cca7eaaf408a355ae919" "checksum net2 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)" = "42550d9fb7b6684a6d404d9fa7250c2eb2646df731d1c06afc06dcee9e1bcf88" -"checksum nix 0.13.0 (registry+https://github.com/rust-lang/crates.io-index)" = "46f0f3210768d796e8fa79ec70ee6af172dacbe7147f5e69be5240a47778302b" "checksum nodrop 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)" = "2f9667ddcc6cc8a43afc9b7917599d7216aa09c463919ea32c59ed6cac8bc945" -"checksum nom 4.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2ad2a91a8e869eeb30b9cb3119ae87773a8f4ae617f41b1eb9c154b2905f7bd6" -"checksum num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "0b3a5d7cc97d6d30d8b9bc8fa19bf45349ffe46241e8816f50f62f6d6aaabee1" "checksum objc 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "31d20fd2b37e07cf5125be68357b588672e8cefe9a96f8c17a9d46053b3e590d" "checksum objc-foundation 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "1add1b659e36c9607c7aab864a76c7a4c2760cd0cd2e120f3fb8b952c7e22bf9" "checksum objc_exception 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "098cd29a2fa3c230d3463ae069cecccc3fdfd64c0d2496ab5b96f82dab6a00dc" "checksum objc_id 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "c92d4ddb4bd7b50d730c215ff871754d0da6b2178849f8a2a2ab69712d0c073b" -"checksum ordered-float 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "18869315e81473c951eb56ad5558bbc56978562d3ecfb87abb7a1e944cea4518" -"checksum osmesa-sys 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "88cfece6e95d2e717e0872a7f53a8684712ad13822a7979bc760b9c77ec0013b" -"checksum owning_ref 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "49a4b8ea2179e6a2e27411d3bca09ca6dd630821cf6894c6c7c8467a8ee7ef13" -"checksum parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "ab41b4aed082705d1056416ae4468b6ea99d52599ecf3169b00088d43113e337" "checksum parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f842b1982eb6c2fe34036a4fbfb06dd185a3f5c8edfaacdf7d1ea10b07de6252" -"checksum parking_lot_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "94c8c7923936b28d546dfd14d4472eaf34c99b14e1c973a32b3e6d4eb04298c9" "checksum parking_lot_core 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)" = "1a7bbaa05312363e0480e1efee133fff1a09ef4a6406b65e226b9a793c223a32" -"checksum percent-encoding 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "31010dd2e1ac33d5b46a5b413495239882813e0369f8ed8a5e266f173602f831" "checksum pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)" = "676e8eb2b1b4c9043511a9b7bea0915320d7e502b0a079fb03f9635a5252b18c" "checksum proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)" = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" "checksum quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)" = "faf4799c5d274f3868a4aae320a0a182cbd2baee377b378f080e16a23e9d80db" @@ -1685,9 +1041,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" "checksum rendy-memory 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "557ed61c95042de292b4347124e9e77ec76954618cb6eeb50cec1a98d3adf51f" "checksum rustc-demangle 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)" = "ccc78bfd5acd7bf3e89cffcf899e5cb1a52d6fafa8dec2739ad70c9577a57288" "checksum rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" -"checksum rusttype 0.7.6 (registry+https://github.com/rust-lang/crates.io-index)" = "25951e85bb2647960969f72c559392245a5bd07446a589390bf427dda31cdc4a" -"checksum same-file 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "8f20c4be53a8a1ff4c1f1b2bd14570d2f634628709752f0702ecdd2b3f9a5267" -"checksum scopeguard 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "94258f53601af11e6a49f722422f6e3425c52b06245a5cf9bc09908b174f5e27" "checksum scopeguard 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b42e15e59b18a828bbf5c58ea01debb36b9b096346de35d941dcb89009f24a0d" "checksum semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" "checksum semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" @@ -1695,49 +1048,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index" "checksum serde_derive 1.0.91 (registry+https://github.com/rust-lang/crates.io-index)" = "101b495b109a3e3ca8c4cbe44cf62391527cdfb6ba15821c5ce80bcd5ea23f9f" "checksum shared_library 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "5a9e7e0f2bfae24d8a5b5a66c5b257a83c7412304311512a0c054cd5e619da11" "checksum slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" -"checksum slotmap 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "759fd553261805f128e2900bf69ab3d034260bc338caf7f0ee54dbf035c85acd" "checksum smallvec 0.6.9 (registry+https://github.com/rust-lang/crates.io-index)" = "c4488ae950c49d403731982257768f48fada354a5203fe81f9bb6f43ca9002be" -"checksum smithay-client-toolkit 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)" = "aa4899558362a65589b53313935099835acf999740915e134dff20cca7c6a28b" -"checksum sourcefile 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "4bf77cb82ba8453b42b6ae1d692e4cdc92f9a47beaf89a847c8be83f4e328ad3" -"checksum spirv_cross 0.14.2 (registry+https://github.com/rust-lang/crates.io-index)" = "b03b5986fa339f976b69dc363b4facb9df5683f40ec48c9716c38b42a4cb10cc" "checksum spirv_cross 0.15.0 (registry+https://github.com/rust-lang/crates.io-index)" = "cd72403fee8f7ec2f4f453dfbaf39ccdd4c6d0157d67d6e65513cd26cc49289f" -"checksum stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "dba1a27d3efae4351c8051072d619e3ade2820635c3958d826bfea39d59b54c8" -"checksum stb_truetype 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "69b7df505db8e81d54ff8be4693421e5b543e08214bd8d99eb761fcb4d5668ba" "checksum storage-map 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fd0a4829a5c591dc24a944a736d6b1e4053e51339a79fd5d4702c4c999a9c45e" "checksum syn 0.15.34 (registry+https://github.com/rust-lang/crates.io-index)" = "a1393e4a97a19c01e900df2aec855a29f71cf02c402e2f443b8d2747c25c5dbe" "checksum synstructure 0.10.2 (registry+https://github.com/rust-lang/crates.io-index)" = "02353edf96d6e4dc81aea2d8490a7e9db177bf8acb0e951c24940bf866cb313f" "checksum tempfile 3.0.8 (registry+https://github.com/rust-lang/crates.io-index)" = "7dc4738f2e68ed2855de5ac9cdbe05c9216773ecde4739b2f095002ab03a13ef" -"checksum unicode-segmentation 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1967f4cdfc355b37fd76d2a954fb2ed3871034eb4f26d60537d88795cfc332a9" "checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" "checksum uuid 0.7.4 (registry+https://github.com/rust-lang/crates.io-index)" = "90dbc611eb48397705a6b0f6e917da23ae517e4d127123d2cf7674206627d32a" "checksum vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "05c78687fb1a80548ae3250346c3db86a80a7cdd77bda190189f2d0a0987c81a" -"checksum version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "914b1a6776c4c929a602fafd8bc742e06365d4bcbe48c30f9cca5824f70dc9dd" -"checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" -"checksum walkdir 2.2.7 (registry+https://github.com/rust-lang/crates.io-index)" = "9d9d7ed3431229a144296213105a390676cc49c9b6a72bd19f3176c98e129fa1" "checksum wasm-bindgen 0.2.48 (registry+https://github.com/rust-lang/crates.io-index)" = "4de97fa1806bb1a99904216f6ac5e0c050dc4f8c676dc98775047c38e5c01b55" "checksum wasm-bindgen-backend 0.2.48 (registry+https://github.com/rust-lang/crates.io-index)" = "5d82c170ef9f5b2c63ad4460dfcee93f3ec04a9a36a4cc20bc973c39e59ab8e3" "checksum wasm-bindgen-macro 0.2.48 (registry+https://github.com/rust-lang/crates.io-index)" = "f07d50f74bf7a738304f6b8157f4a581e1512cd9e9cdb5baad8c31bbe8ffd81d" "checksum wasm-bindgen-macro-support 0.2.48 (registry+https://github.com/rust-lang/crates.io-index)" = "95cf8fe77e45ba5f91bc8f3da0c3aa5d464b3d8ed85d84f4d4c7cc106436b1d7" "checksum wasm-bindgen-shared 0.2.48 (registry+https://github.com/rust-lang/crates.io-index)" = "d9c2d4d4756b2e46d3a5422e06277d02e4d3e1d62d138b76a4c681e925743623" -"checksum wasm-bindgen-webidl 0.2.48 (registry+https://github.com/rust-lang/crates.io-index)" = "24e47859b4eba3d3b9a5c2c299f9d6f8d0b613671315f6f0c5c7f835e524b36a" -"checksum wayland-client 0.21.12 (registry+https://github.com/rust-lang/crates.io-index)" = "e77d1e6887f07ea2e5d79a3d7d03a875e62d3746334a909b5035d779d849a523" -"checksum wayland-commons 0.21.12 (registry+https://github.com/rust-lang/crates.io-index)" = "dff69a5399ca212efa4966f3ee2a3773f19960d0fa329b9aca046a8508a0e09f" -"checksum wayland-protocols 0.21.12 (registry+https://github.com/rust-lang/crates.io-index)" = "c9ccddf6a4407d982898e0f0a1172217843f3d40fe4272f828060b56a2d40d81" -"checksum wayland-scanner 0.21.12 (registry+https://github.com/rust-lang/crates.io-index)" = "63bc5efa7dcdb8f04d2e5d1571c0d0577fc47076d133d68e056bdb299f1b60e2" -"checksum wayland-sys 0.21.12 (registry+https://github.com/rust-lang/crates.io-index)" = "e76af81a601b84d400744f85f083381daa77ac01f6c8711e57e662dc3a35d69d" -"checksum web-sys 0.3.25 (registry+https://github.com/rust-lang/crates.io-index)" = "86d515d2f713d3a6ab198031d2181b7540f8e319e4637ec2d4a41a208335ef29" -"checksum weedle 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3bb43f70885151e629e2a19ce9e50bd730fd436cfd4b666894c9ce4de9141164" "checksum winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" "checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" "checksum winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" "checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" -"checksum winapi-util 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7168bab6e1daee33b4557efd0e95d5ca70a03706d39fa5f3fe7a236f584b03c9" "checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" -"checksum winit 0.19.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d233301129ddd33260b47f76900b50e154b7254546e2edba0e5468a1a5fe4de3" -"checksum wio 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "5d129932f4644ac2396cb456385cbf9e63b5b30c6e8dc4820bdca4eb082037a5" "checksum ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" "checksum x11 2.18.1 (registry+https://github.com/rust-lang/crates.io-index)" = "39697e3123f715483d311b5826e254b6f3cfebdd83cf7ef3358f579c3d68e235" -"checksum x11-dl 2.18.3 (registry+https://github.com/rust-lang/crates.io-index)" = "940586acb859ea05c53971ac231685799a7ec1dee66ac0bccc0e6ad96e06b4e3" -"checksum xdg 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d089681aa106a86fade1b0128fb5daf07d5867a509ab036d99988dec80429a57" -"checksum xml-rs 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3c1cb601d29fe2c2ac60a2b2e5e293994d87a1f6fa9687a31a15270f909be9c2" -"checksum xml-rs 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "541b12c998c5b56aa2b4e6f18f03664eef9a4fd0a246a55594efae6cc2d964b5" diff --git a/Makefile b/Makefile index 024c5cfe9..9830795cc 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,5 @@ RUST_BACKTRACE:=1 EXCLUDES:= -FEATURE_RUST:= -FEATURE_NATIVE:= GENERATOR_PLATFORM:= @@ -23,27 +21,9 @@ ifeq ($(OS),Windows_NT) CLEAN_FFI_DIR=del $(FFI_DIR)\*.* /Q /S CREATE_BUILD_DIR=mkdir $(BUILD_DIR) GENERATOR_PLATFORM=-DCMAKE_GENERATOR_PLATFORM=x64 - - ifeq ($(TARGET),x86_64-pc-windows-gnu) - FEATURE_RUST=vulkan - FEATURE_NATIVE=gfx-backend-vulkan - else - FEATURE_RUST=dx12 - FEATURE_NATIVE=gfx-backend-dx12 - endif else CLEAN_FFI_DIR=rm $(FFI_DIR)/** CREATE_BUILD_DIR=mkdir -p $(BUILD_DIR) - - UNAME_S:=$(shell uname -s) - ifeq ($(UNAME_S),Linux) - FEATURE_RUST=vulkan - FEATURE_NATIVE=gfx-backend-vulkan - endif - ifeq ($(UNAME_S),Darwin) - FEATURE_RUST=metal - FEATURE_NATIVE=gfx-backend-metal - endif endif .PHONY: all check test doc clear lib-native lib-remote example-compute example-triangle example-remote @@ -54,7 +34,7 @@ check: cargo check --all test: - cargo test --all --features "$(FEATURE_NATIVE) $(FEATURE_RUST)" + cargo test --all doc: cargo doc --all @@ -64,10 +44,10 @@ clear: $(CLEAN_FFI_DIR) lib-native: Cargo.lock wgpu-native/Cargo.toml $(WILDCARD_WGPU_NATIVE) - cargo build --manifest-path wgpu-native/Cargo.toml --features "local,$(FEATURE_NATIVE)" + cargo build --manifest-path wgpu-native/Cargo.toml lib-remote: Cargo.lock wgpu-remote/Cargo.toml $(WILDCARD_WGPU_NATIVE_AND_REMOTE) - cargo build --manifest-path wgpu-remote/Cargo.toml --features $(FEATURE_RUST) + cargo build --manifest-path wgpu-remote/Cargo.toml $(FFI_DIR)/wgpu.h: wgpu-native/cbindgen.toml $(WILDCARD_WGPU_NATIVE) rustup run nightly cbindgen -o $(FFI_DIR)/wgpu.h wgpu-native @@ -76,10 +56,10 @@ $(FFI_DIR)/wgpu-remote.h: wgpu-remote/cbindgen.toml $(WILDCARD_WGPU_NATIVE_AND_R rustup run nightly cbindgen -o $(FFI_DIR)/wgpu-remote.h wgpu-remote example-compute: lib-native $(FFI_DIR)/wgpu.h examples/compute/main.c - cd examples/compute && $(CREATE_BUILD_DIR) && cd build && cmake .. -DBACKEND=$(FEATURE_RUST) $(GENERATOR_PLATFORM) && cmake --build . + cd examples/compute && $(CREATE_BUILD_DIR) && cd build && cmake .. $(GENERATOR_PLATFORM) && cmake --build . example-triangle: lib-native $(FFI_DIR)/wgpu.h examples/triangle/main.c - cd examples/triangle && $(CREATE_BUILD_DIR) && cd build && cmake .. -DBACKEND=$(FEATURE_RUST) $(GENERATOR_PLATFORM) && cmake --build . + cd examples/triangle && $(CREATE_BUILD_DIR) && cd build && cmake .. $(GENERATOR_PLATFORM) && cmake --build . example-remote: lib-remote $(FFI_DIR)/wgpu-remote.h examples/remote/main.c cd examples/remote && $(CREATE_BUILD_DIR) && cd build && cmake .. && cmake --build . diff --git a/examples/compute/CMakeLists.txt b/examples/compute/CMakeLists.txt index e8558c774..9b4c748f1 100644 --- a/examples/compute/CMakeLists.txt +++ b/examples/compute/CMakeLists.txt @@ -1,19 +1,5 @@ cmake_minimum_required(VERSION 3.11b) -set(BACKEND_VULKAN "vulkan") -set(BACKEND_METAL "metal") -set(BACKEND_DX11 "dx11") -set(BACKEND_DX12 "dx12") -set(AVAILABLE_BACKENDS - ${BACKEND_VULKAN} - ${BACKEND_METAL} - ${BACKEND_DX11} - ${BACKEND_DX12}) - -if(NOT DEFINED BACKEND OR NOT "${BACKEND}" IN_LIST AVAILABLE_BACKENDS) - message(FATAL_ERROR "BACKEND invalid or undefined, available backends: ${AVAILABLE_BACKENDS}") -endif() - project(compute) set(TARGET_NAME compute) @@ -23,12 +9,7 @@ add_executable(compute main.c ../framework.c) if(MSVC) add_definitions(-DWGPU_TARGET=WGPU_TARGET_WINDOWS) target_compile_options(${TARGET_NAME} PRIVATE /W4) - set(OS_LIBRARIES "userenv" "ws2_32" "Dwmapi" "dbghelp") - if("${BACKEND}" STREQUAL "${BACKEND_DX11}") - list(APPEND OS_LIBRARIES "d3dcompiler" "D3D11" "DXGI") - elseif("${BACKEND}" STREQUAL "${BACKEND_DX12}") - list(APPEND OS_LIBRARIES "d3dcompiler" "D3D12" "DXGI") - endif() + set(OS_LIBRARIES "userenv" "ws2_32" "Dwmapi" "dbghelp" "d3dcompiler" "D3D12" "D3D11" "DXGI") elseif(APPLE) add_definitions(-DWGPU_TARGET=WGPU_TARGET_MACOS) set(OS_LIBRARIES "-framework Cocoa" "-framework CoreVideo" "-framework IOKit" "-framework QuartzCore") diff --git a/examples/compute/main.c b/examples/compute/main.c index da7942a3c..879396554 100644 --- a/examples/compute/main.c +++ b/examples/compute/main.c @@ -7,6 +7,7 @@ #include #include +#include #define BINDINGS_LENGTH (1) #define BIND_GROUP_LAYOUTS_LENGTH (1) @@ -31,8 +32,7 @@ int main( uint32_t numbers_length = size / sizeof(uint32_t); - WGPUInstanceId instance = wgpu_create_instance(); - WGPUAdapterId adapter = wgpu_instance_request_adapter(instance, NULL); + WGPUAdapterId adapter = wgpu_request_adapter(NULL); WGPUDeviceId device = wgpu_adapter_request_device(adapter, NULL); uint8_t *staging_memory; @@ -106,7 +106,7 @@ int main( encoder, staging_buffer, 0, storage_buffer, 0, size); WGPUComputePassId command_pass = - wgpu_command_encoder_begin_compute_pass(encoder); + wgpu_command_encoder_begin_compute_pass(encoder, NULL); wgpu_compute_pass_set_pipeline(command_pass, compute_pipeline); wgpu_compute_pass_set_bind_group(command_pass, 0, bind_group, NULL, 0); diff --git a/examples/remote/main.c b/examples/remote/main.c index 581961551..81229e173 100644 --- a/examples/remote/main.c +++ b/examples/remote/main.c @@ -4,17 +4,14 @@ int main() { WGPUInfrastructure infra = wgpu_initialize(); - if (!infra.factory || !infra.server || infra.error) { + if (!infra.client || !infra.server || infra.error) { printf("Cannot initialize WGPU: %s", infra.error); return 1; } - WGPUClient* client = wgpu_client_create(infra.factory); - //TODO: do something meaningful - wgpu_client_destroy(infra.factory, client); - wgpu_terminate(infra.factory); + wgpu_terminate(infra.client); return 0; } diff --git a/examples/triangle/CMakeLists.txt b/examples/triangle/CMakeLists.txt index 0cc07c370..e02d478a5 100644 --- a/examples/triangle/CMakeLists.txt +++ b/examples/triangle/CMakeLists.txt @@ -1,19 +1,5 @@ cmake_minimum_required(VERSION 3.11b) -set(BACKEND_VULKAN "vulkan") -set(BACKEND_METAL "metal") -set(BACKEND_DX11 "dx11") -set(BACKEND_DX12 "dx12") -set(AVAILABLE_BACKENDS - ${BACKEND_VULKAN} - ${BACKEND_METAL} - ${BACKEND_DX11} - ${BACKEND_DX12}) - -if(NOT DEFINED BACKEND OR NOT "${BACKEND}" IN_LIST AVAILABLE_BACKENDS) - message(FATAL_ERROR "BACKEND invalid or undefined, available backends: ${AVAILABLE_BACKENDS}") -endif() - project(triangle) set(TARGET_NAME triangle) @@ -23,12 +9,7 @@ add_executable(triangle main.c ../framework.c) if(MSVC) add_definitions(-DWGPU_TARGET=WGPU_TARGET_WINDOWS) target_compile_options(${TARGET_NAME} PRIVATE /W4) - set(OS_LIBRARIES "userenv" "ws2_32" "Dwmapi" "dbghelp") - if("${BACKEND}" STREQUAL "${BACKEND_DX11}") - list(APPEND OS_LIBRARIES "d3dcompiler" "D3D11" "DXGI") - elseif("${BACKEND}" STREQUAL "${BACKEND_DX12}") - list(APPEND OS_LIBRARIES "d3dcompiler" "D3D12" "DXGI") - endif() + set(OS_LIBRARIES "userenv" "ws2_32" "Dwmapi" "dbghelp" "d3dcompiler" "D3D12" "D3D11" "DXGI") elseif(APPLE) add_definitions(-DWGPU_TARGET=WGPU_TARGET_MACOS) set(OS_LIBRARIES "-framework Cocoa" "-framework CoreVideo" "-framework IOKit" "-framework QuartzCore") diff --git a/examples/triangle/main.c b/examples/triangle/main.c index 4feff6c0d..36b153615 100644 --- a/examples/triangle/main.c +++ b/examples/triangle/main.c @@ -33,9 +33,7 @@ #define BIND_GROUP_LAYOUTS_LENGTH (1) int main() { - WGPUInstanceId instance = wgpu_create_instance(); - - WGPUAdapterId adapter = wgpu_instance_request_adapter(instance, + WGPUAdapterId adapter = wgpu_request_adapter( &(WGPURequestAdapterOptions){ .power_preference = WGPUPowerPreference_LowPower, }); @@ -157,22 +155,19 @@ int main() { [ns_window.contentView setWantsLayer:YES]; metal_layer = [CAMetalLayer layer]; [ns_window.contentView setLayer:metal_layer]; - surface = wgpu_instance_create_surface_from_macos_layer( - instance, metal_layer); + surface = wgpu_create_surface_from_macos_layer(metal_layer); } #elif WGPU_TARGET == WGPU_TARGET_LINUX { Display *x11_display = glfwGetX11Display(); Window x11_window = glfwGetX11Window(window); - surface = wgpu_instance_create_surface_from_xlib( - instance, (const void **)x11_display, x11_window); + surface = wgpu_create_surface_from_xlib((const void **)x11_display, x11_window); } #elif WGPU_TARGET == WGPU_TARGET_WINDOWS { HWND hwnd = glfwGetWin32Window(window); HINSTANCE hinstance = GetModuleHandle(NULL); - surface = wgpu_instance_create_surface_from_windows_hwnd( - instance, hinstance, hwnd); + surface = wgpu_create_surface_from_windows_hwnd(hinstance, hwnd); } #else #error "Unsupported WGPU_TARGET" diff --git a/ffi/wgpu-remote.h b/ffi/wgpu-remote.h index 407aef503..5cc04d6fe 100644 --- a/ffi/wgpu-remote.h +++ b/ffi/wgpu-remote.h @@ -15,17 +15,15 @@ typedef enum { typedef struct WGPUClient WGPUClient; -typedef struct WGPUClientFactory WGPUClientFactory; - typedef struct WGPUServer WGPUServer; -typedef uint64_t WGPUId_DeviceHandle; +typedef uint64_t WGPUId_Device_Dummy; -typedef WGPUId_DeviceHandle WGPUDeviceId; +typedef WGPUId_Device_Dummy WGPUDeviceId; -typedef uint64_t WGPUId_AdapterHandle; +typedef uint64_t WGPUId_Adapter_Dummy; -typedef WGPUId_AdapterHandle WGPUAdapterId; +typedef WGPUId_Adapter_Dummy WGPUAdapterId; typedef struct { bool anisotropic_filtering; @@ -45,7 +43,7 @@ typedef struct { } WGPURequestAdapterOptions; typedef struct { - WGPUClientFactory *factory; + WGPUClient *client; WGPUServer *server; const uint8_t *error; } WGPUInfrastructure; @@ -54,15 +52,11 @@ WGPUDeviceId wgpu_client_adapter_create_device(const WGPUClient *client, WGPUAdapterId adapter_id, const WGPUDeviceDescriptor *desc); -WGPUClient *wgpu_client_create(const WGPUClientFactory *factory); - -void wgpu_client_destroy(const WGPUClientFactory *factory, WGPUClient *client); - -WGPUAdapterId wgpu_client_get_adapter(const WGPUClient *client, - const WGPURequestAdapterOptions *desc); +WGPUAdapterId wgpu_client_request_adapter(const WGPUClient *client, + const WGPURequestAdapterOptions *desc); WGPUInfrastructure wgpu_initialize(void); void wgpu_server_process(const WGPUServer *server); -void wgpu_terminate(WGPUClientFactory *factory); +void wgpu_terminate(WGPUClient *client); diff --git a/ffi/wgpu.h b/ffi/wgpu.h index e4ba720d1..5874a73f0 100644 --- a/ffi/wgpu.h +++ b/ffi/wgpu.h @@ -240,13 +240,13 @@ typedef enum { WGPUVertexFormat_Int4 = 48, } WGPUVertexFormat; -typedef uint64_t WGPUId_DeviceHandle; +typedef uint64_t WGPUId_Device_Dummy; -typedef WGPUId_DeviceHandle WGPUDeviceId; +typedef WGPUId_Device_Dummy WGPUDeviceId; -typedef uint64_t WGPUId_AdapterHandle; +typedef uint64_t WGPUId_Adapter_Dummy; -typedef WGPUId_AdapterHandle WGPUAdapterId; +typedef WGPUId_Adapter_Dummy WGPUAdapterId; typedef struct { bool anisotropic_filtering; @@ -261,13 +261,13 @@ typedef struct { WGPULimits limits; } WGPUDeviceDescriptor; -typedef uint64_t WGPUId_BindGroupHandle; +typedef uint64_t WGPUId_BindGroup_Dummy; -typedef WGPUId_BindGroupHandle WGPUBindGroupId; +typedef WGPUId_BindGroup_Dummy WGPUBindGroupId; -typedef uint64_t WGPUId_BufferHandle; +typedef uint64_t WGPUId_Buffer_Dummy; -typedef WGPUId_BufferHandle WGPUBufferId; +typedef WGPUId_Buffer_Dummy WGPUBufferId; typedef uint64_t WGPUBufferAddress; @@ -275,23 +275,27 @@ typedef void (*WGPUBufferMapReadCallback)(WGPUBufferMapAsyncStatus status, const typedef void (*WGPUBufferMapWriteCallback)(WGPUBufferMapAsyncStatus status, uint8_t *data, uint8_t *userdata); -typedef uint64_t WGPUId_ComputePassHandle; +typedef uint64_t WGPUId_ComputePass_Dummy; -typedef WGPUId_ComputePassHandle WGPUComputePassId; +typedef WGPUId_ComputePass_Dummy WGPUComputePassId; -typedef uint64_t WGPUId_CommandBufferHandle; +typedef uint64_t WGPUId_CommandBuffer_Dummy; -typedef WGPUId_CommandBufferHandle WGPUCommandBufferId; +typedef WGPUId_CommandBuffer_Dummy WGPUCommandBufferId; typedef WGPUCommandBufferId WGPUCommandEncoderId; -typedef uint64_t WGPUId_RenderPassHandle; +typedef struct { + uint32_t todo; +} WGPUComputePassDescriptor; -typedef WGPUId_RenderPassHandle WGPURenderPassId; +typedef uint64_t WGPUId_RenderPass_Dummy; -typedef uint64_t WGPUId_TextureViewHandle; +typedef WGPUId_RenderPass_Dummy WGPURenderPassId; -typedef WGPUId_TextureViewHandle WGPUTextureViewId; +typedef uint64_t WGPUId_TextureView_Dummy; + +typedef WGPUId_TextureView_Dummy WGPUTextureViewId; typedef struct { double r; @@ -337,9 +341,9 @@ typedef struct { uint32_t image_height; } WGPUBufferCopyView; -typedef uint64_t WGPUId_TextureHandle; +typedef uint64_t WGPUId_Texture_Dummy; -typedef WGPUId_TextureHandle WGPUTextureId; +typedef WGPUId_Texture_Dummy WGPUTextureId; typedef struct { float x; @@ -367,27 +371,17 @@ typedef struct { typedef const char *WGPURawString; -typedef uint64_t WGPUId_ComputePipelineHandle; +typedef uint64_t WGPUId_ComputePipeline_Dummy; -typedef WGPUId_ComputePipelineHandle WGPUComputePipelineId; +typedef WGPUId_ComputePipeline_Dummy WGPUComputePipelineId; -typedef uint64_t WGPUId_InstanceHandle; +typedef uint64_t WGPUId_Surface; -typedef uint64_t WGPUId_SurfaceHandle; +typedef WGPUId_Surface WGPUSurfaceId; -typedef WGPUId_SurfaceHandle WGPUSurfaceId; +typedef uint64_t WGPUId_BindGroupLayout_Dummy; -#if !defined(WGPU_BACKEND_GL) -typedef WGPUId_InstanceHandle WGPUInstanceId; -#endif - -#if defined(WGPU_BACKEND_GL) -typedef WGPUSurfaceId WGPUInstanceId; -#endif - -typedef uint64_t WGPUId_BindGroupLayoutHandle; - -typedef WGPUId_BindGroupLayoutHandle WGPUBindGroupLayoutId; +typedef WGPUId_BindGroupLayout_Dummy WGPUBindGroupLayoutId; typedef struct { WGPUBufferId buffer; @@ -395,9 +389,9 @@ typedef struct { WGPUBufferAddress size; } WGPUBufferBinding; -typedef uint64_t WGPUId_SamplerHandle; +typedef uint64_t WGPUId_Sampler_Dummy; -typedef WGPUId_SamplerHandle WGPUSamplerId; +typedef WGPUId_Sampler_Dummy WGPUSamplerId; typedef enum { WGPUBindingResource_Buffer, @@ -479,13 +473,13 @@ typedef struct { uint32_t todo; } WGPUCommandEncoderDescriptor; -typedef uint64_t WGPUId_PipelineLayoutHandle; +typedef uint64_t WGPUId_PipelineLayout_Dummy; -typedef WGPUId_PipelineLayoutHandle WGPUPipelineLayoutId; +typedef WGPUId_PipelineLayout_Dummy WGPUPipelineLayoutId; -typedef uint64_t WGPUId_ShaderModuleHandle; +typedef uint64_t WGPUId_ShaderModule_Dummy; -typedef WGPUId_ShaderModuleHandle WGPUShaderModuleId; +typedef WGPUId_ShaderModule_Dummy WGPUShaderModuleId; typedef struct { WGPUShaderModuleId module; @@ -502,9 +496,9 @@ typedef struct { uintptr_t bind_group_layouts_length; } WGPUPipelineLayoutDescriptor; -typedef uint64_t WGPUId_RenderPipelineHandle; +typedef uint64_t WGPUId_RenderPipeline_Dummy; -typedef WGPUId_RenderPipelineHandle WGPURenderPipelineId; +typedef WGPUId_RenderPipeline_Dummy WGPURenderPipelineId; typedef struct { WGPUFrontFace front_face; @@ -609,7 +603,9 @@ typedef struct { WGPUU32Array code; } WGPUShaderModuleDescriptor; -typedef WGPUSurfaceId WGPUSwapChainId; +typedef uint64_t WGPUId_SwapChain_Dummy; + +typedef WGPUId_SwapChain_Dummy WGPUSwapChainId; typedef uint32_t WGPUTextureUsage; #define WGPUTextureUsage_COPY_SRC 1 @@ -640,14 +636,14 @@ typedef struct { typedef WGPUDeviceId WGPUQueueId; +typedef uint64_t WGPUId_RenderBundle_Dummy; + +typedef WGPUId_RenderBundle_Dummy WGPURenderBundleId; + typedef struct { WGPUPowerPreference power_preference; } WGPURequestAdapterOptions; -typedef uint64_t WGPUId_RenderBundleHandle; - -typedef WGPUId_RenderBundleHandle WGPURenderBundleId; - typedef struct { WGPUTextureId texture_id; WGPUTextureViewId view_id; @@ -663,7 +659,7 @@ typedef struct { uint32_t array_layer_count; } WGPUTextureViewDescriptor; -#if defined(WGPU_LOCAL) +#if !defined(WGPU_REMOTE) WGPUDeviceId wgpu_adapter_request_device(WGPUAdapterId adapter_id, const WGPUDeviceDescriptor *desc); #endif @@ -686,12 +682,13 @@ void wgpu_buffer_map_write_async(WGPUBufferId buffer_id, void wgpu_buffer_unmap(WGPUBufferId buffer_id); -#if defined(WGPU_LOCAL) -WGPUComputePassId wgpu_command_encoder_begin_compute_pass(WGPUCommandEncoderId command_encoder_id); +#if !defined(WGPU_REMOTE) +WGPUComputePassId wgpu_command_encoder_begin_compute_pass(WGPUCommandEncoderId encoder_id, + const WGPUComputePassDescriptor *desc); #endif -#if defined(WGPU_LOCAL) -WGPURenderPassId wgpu_command_encoder_begin_render_pass(WGPUCommandEncoderId command_encoder_id, +#if !defined(WGPU_REMOTE) +WGPURenderPassId wgpu_command_encoder_begin_render_pass(WGPUCommandEncoderId encoder_id, const WGPURenderPassDescriptor *desc); #endif @@ -717,8 +714,8 @@ void wgpu_command_encoder_copy_texture_to_texture(WGPUCommandEncoderId command_e const WGPUTextureCopyView *destination, WGPUExtent3d copy_size); -WGPUCommandBufferId wgpu_command_encoder_finish(WGPUCommandEncoderId command_encoder_id, - const WGPUCommandBufferDescriptor *_desc); +WGPUCommandBufferId wgpu_command_encoder_finish(WGPUCommandEncoderId encoder_id, + const WGPUCommandBufferDescriptor *desc); void wgpu_compute_pass_dispatch(WGPUComputePassId pass_id, uint32_t x, uint32_t y, uint32_t z); @@ -742,72 +739,80 @@ void wgpu_compute_pass_set_bind_group(WGPUComputePassId pass_id, void wgpu_compute_pass_set_pipeline(WGPUComputePassId pass_id, WGPUComputePipelineId pipeline_id); -#if (defined(WGPU_LOCAL) && !defined(WGPU_BACKEND_GL)) -WGPUInstanceId wgpu_create_instance(void); +#if !defined(WGPU_REMOTE) +WGPUSurfaceId wgpu_create_surface_from_macos_layer(void *layer); #endif -#if defined(WGPU_LOCAL) +#if !defined(WGPU_REMOTE) +WGPUSurfaceId wgpu_create_surface_from_windows_hwnd(void *hinstance, void *hwnd); +#endif + +#if !defined(WGPU_REMOTE) +WGPUSurfaceId wgpu_create_surface_from_xlib(const void **display, uint64_t window); +#endif + +#if !defined(WGPU_REMOTE) WGPUBindGroupId wgpu_device_create_bind_group(WGPUDeviceId device_id, const WGPUBindGroupDescriptor *desc); #endif -#if defined(WGPU_LOCAL) +#if !defined(WGPU_REMOTE) WGPUBindGroupLayoutId wgpu_device_create_bind_group_layout(WGPUDeviceId device_id, const WGPUBindGroupLayoutDescriptor *desc); #endif -#if defined(WGPU_LOCAL) +#if !defined(WGPU_REMOTE) WGPUBufferId wgpu_device_create_buffer(WGPUDeviceId device_id, const WGPUBufferDescriptor *desc); #endif -#if defined(WGPU_LOCAL) +#if !defined(WGPU_REMOTE) WGPUBufferId wgpu_device_create_buffer_mapped(WGPUDeviceId device_id, const WGPUBufferDescriptor *desc, uint8_t **mapped_ptr_out); #endif -#if defined(WGPU_LOCAL) +#if !defined(WGPU_REMOTE) WGPUCommandEncoderId wgpu_device_create_command_encoder(WGPUDeviceId device_id, const WGPUCommandEncoderDescriptor *desc); #endif -#if defined(WGPU_LOCAL) +#if !defined(WGPU_REMOTE) WGPUComputePipelineId wgpu_device_create_compute_pipeline(WGPUDeviceId device_id, const WGPUComputePipelineDescriptor *desc); #endif -#if defined(WGPU_LOCAL) +#if !defined(WGPU_REMOTE) WGPUPipelineLayoutId wgpu_device_create_pipeline_layout(WGPUDeviceId device_id, const WGPUPipelineLayoutDescriptor *desc); #endif -#if defined(WGPU_LOCAL) +#if !defined(WGPU_REMOTE) WGPURenderPipelineId wgpu_device_create_render_pipeline(WGPUDeviceId device_id, const WGPURenderPipelineDescriptor *desc); #endif -#if defined(WGPU_LOCAL) +#if !defined(WGPU_REMOTE) WGPUSamplerId wgpu_device_create_sampler(WGPUDeviceId device_id, const WGPUSamplerDescriptor *desc); #endif -#if defined(WGPU_LOCAL) +#if !defined(WGPU_REMOTE) WGPUShaderModuleId wgpu_device_create_shader_module(WGPUDeviceId device_id, const WGPUShaderModuleDescriptor *desc); #endif -#if defined(WGPU_LOCAL) +#if !defined(WGPU_REMOTE) WGPUSwapChainId wgpu_device_create_swap_chain(WGPUDeviceId device_id, WGPUSurfaceId surface_id, const WGPUSwapChainDescriptor *desc); #endif -#if defined(WGPU_LOCAL) +#if !defined(WGPU_REMOTE) WGPUTextureId wgpu_device_create_texture(WGPUDeviceId device_id, const WGPUTextureDescriptor *desc); #endif void wgpu_device_destroy(WGPUDeviceId device_id); -#if defined(WGPU_LOCAL) +#if !defined(WGPU_REMOTE) void wgpu_device_get_limits(WGPUDeviceId _device_id, WGPULimits *limits); #endif @@ -815,28 +820,6 @@ WGPUQueueId wgpu_device_get_queue(WGPUDeviceId device_id); void wgpu_device_poll(WGPUDeviceId device_id, bool force_wait); -#if (defined(WGPU_LOCAL) && !defined(WGPU_BACKEND_GL)) -WGPUSurfaceId wgpu_instance_create_surface_from_macos_layer(WGPUInstanceId instance_id, - void *layer); -#endif - -#if (defined(WGPU_LOCAL) && !defined(WGPU_BACKEND_GL)) -WGPUSurfaceId wgpu_instance_create_surface_from_windows_hwnd(WGPUInstanceId instance_id, - void *hinstance, - void *hwnd); -#endif - -#if (defined(WGPU_LOCAL) && !defined(WGPU_BACKEND_GL)) -WGPUSurfaceId wgpu_instance_create_surface_from_xlib(WGPUInstanceId instance_id, - const void **display, - uint64_t window); -#endif - -#if defined(WGPU_LOCAL) -WGPUAdapterId wgpu_instance_request_adapter(WGPUInstanceId instance_id, - const WGPURequestAdapterOptions *desc); -#endif - void wgpu_queue_submit(WGPUQueueId queue_id, const WGPUCommandBufferId *command_buffers, uintptr_t command_buffers_length); @@ -882,10 +865,6 @@ void wgpu_render_pass_set_bind_group(WGPURenderPassId pass_id, void wgpu_render_pass_set_blend_color(WGPURenderPassId pass_id, const WGPUColor *color); -void wgpu_render_pass_set_index_buffer(WGPURenderPassId pass_id, - WGPUBufferId buffer_id, - WGPUBufferAddress offset); - void wgpu_render_pass_set_pipeline(WGPURenderPassId pass_id, WGPURenderPipelineId pipeline_id); void wgpu_render_pass_set_scissor_rect(WGPURenderPassId pass_id, @@ -910,11 +889,15 @@ void wgpu_render_pass_set_viewport(WGPURenderPassId pass_id, float min_depth, float max_depth); +#if !defined(WGPU_REMOTE) +WGPUAdapterId wgpu_request_adapter(const WGPURequestAdapterOptions *desc); +#endif + WGPUSwapChainOutput wgpu_swap_chain_get_next_texture(WGPUSwapChainId swap_chain_id); void wgpu_swap_chain_present(WGPUSwapChainId swap_chain_id); -#if defined(WGPU_LOCAL) +#if !defined(WGPU_REMOTE) WGPUTextureViewId wgpu_texture_create_view(WGPUTextureId texture_id, const WGPUTextureViewDescriptor *desc); #endif diff --git a/wgpu-native/Cargo.toml b/wgpu-native/Cargo.toml index 721540676..760ba0bff 100644 --- a/wgpu-native/Cargo.toml +++ b/wgpu-native/Cargo.toml @@ -17,11 +17,10 @@ crate-type = ["lib", "cdylib", "staticlib"] [features] default = [] -local = [] remote = ["serde"] metal-auto-capture = ["gfx-backend-metal/auto-capture"] #NOTE: glutin feature is not stable, use at your own risk -glutin = ["gfx-backend-gl/glutin"] +#glutin = ["gfx-backend-gl/glutin"] [dependencies] arrayvec = "0.4" @@ -30,12 +29,7 @@ copyless = "0.1" lazy_static = "1.1.0" log = "0.4" hal = { package = "gfx-hal", version = "0.3.0" } -gfx-backend-empty = { version = "0.3.0" } -gfx-backend-vulkan = { version = "0.3.0", features = ["x11"], optional = true } -gfx-backend-dx12 = { version = "0.3.0", optional = true } -gfx-backend-dx11 = { version = "0.3.0", optional = true } -gfx-backend-metal = { version = "0.3.0", optional = true } -gfx-backend-gl = { version = "0.3.0", optional = true } +gfx-backend-empty = "0.3" parking_lot = "0.9" raw-window-handle = "0.1" rendy-memory = "0.4" @@ -43,3 +37,11 @@ rendy-descriptor = "0.4" serde = { version = "1.0", features = ["serde_derive"], optional = true } vec_map = "0.8" +[target.'cfg(unix)'.dependencies] +gfx-backend-vulkan = { version = "0.3.0", features = ["x11"] } + +[target.'cfg(not(unix))'.dependencies] +gfx-backend-vulkan = "0.3.0" + +[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies] +gfx-backend-metal = "0.3" diff --git a/wgpu-native/src/command/allocator.rs b/wgpu-native/src/command/allocator.rs index 7fed4ca9b..fec7a7f39 100644 --- a/wgpu-native/src/command/allocator.rs +++ b/wgpu-native/src/command/allocator.rs @@ -1,5 +1,9 @@ use super::CommandBuffer; -use crate::{track::TrackerSet, DeviceId, LifeGuard, Stored, SubmissionIndex}; +use crate::{ + hub::GfxBackend, + track::TrackerSet, + DeviceId, LifeGuard, Stored, SubmissionIndex, +}; use hal::{command::RawCommandBuffer, pool::RawCommandPool, Device}; use log::trace; @@ -48,7 +52,7 @@ pub struct CommandAllocator { inner: Mutex>, } -impl CommandAllocator { +impl CommandAllocator { pub fn new(queue_family: hal::queue::QueueFamilyId) -> Self { CommandAllocator { queue_family, @@ -64,6 +68,7 @@ impl CommandAllocator { device_id: Stored, device: &B::Device, ) -> CommandBuffer { + //debug_assert_eq!(device_id.backend(), B::VARIANT); let thread_id = thread::current().id(); let mut inner = self.inner.lock(); @@ -85,7 +90,7 @@ impl CommandAllocator { recorded_thread_id: thread_id, device_id, life_guard: LifeGuard::new(), - trackers: TrackerSet::new(), + trackers: TrackerSet::new(B::VARIANT), swap_chain_links: Vec::new(), } } diff --git a/wgpu-native/src/command/bind.rs b/wgpu-native/src/command/bind.rs index 4ca822d49..3b9458893 100644 --- a/wgpu-native/src/command/bind.rs +++ b/wgpu-native/src/command/bind.rs @@ -1,4 +1,7 @@ -use crate::{BindGroupHandle, BindGroupId, BindGroupLayoutId, BufferAddress, PipelineLayoutId, Stored}; +use crate::{ + hub::GfxBackend, + BindGroup, BindGroupId, BindGroupLayoutId, BufferAddress, PipelineLayoutId, Stored, +}; use log::trace; @@ -50,12 +53,14 @@ pub struct BindGroupEntry { } impl BindGroupEntry { - fn provide( + fn provide( &mut self, bind_group_id: BindGroupId, - bind_group: &BindGroupHandle, + bind_group: &BindGroup, offsets: &[BufferAddress], ) -> Provision { + debug_assert_eq!(B::VARIANT, bind_group_id.backend()); + let was_compatible = match self.provided { Some(BindGroupPair { layout_id, @@ -142,11 +147,11 @@ impl Binder { /// (i.e. compatible with current expectations). Also returns an iterator /// of bind group IDs to be bound with it: those are compatible bind groups /// that were previously blocked because the current one was incompatible. - pub(crate) fn provide_entry<'a>( + pub(crate) fn provide_entry<'a, B: GfxBackend>( &'a mut self, index: usize, bind_group_id: BindGroupId, - bind_group: &BindGroupHandle, + bind_group: &BindGroup, offsets: &[BufferAddress], ) -> Option<( PipelineLayoutId, @@ -154,6 +159,8 @@ impl Binder { impl 'a + Iterator, )> { 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) { Provision::Unchanged => None, Provision::Changed { diff --git a/wgpu-native/src/command/compute.rs b/wgpu-native/src/command/compute.rs index ee5ed2903..05b6dec69 100644 --- a/wgpu-native/src/command/compute.rs +++ b/wgpu-native/src/command/compute.rs @@ -1,7 +1,8 @@ use crate::{ + gfx_select, command::bind::{Binder, LayoutChange}, device::all_buffer_stages, - hub::{HUB, Token}, + hub::{GfxBackend, Token}, track::{Stitch, TrackerSet}, BindGroupId, BufferAddress, @@ -46,11 +47,11 @@ impl ComputePass { // Common routines between render/compute -#[no_mangle] -pub extern "C" fn wgpu_compute_pass_end_pass(pass_id: ComputePassId) { +pub fn compute_pass_end_pass(pass_id: ComputePassId) { let mut token = Token::root(); - let (mut cmb_guard, mut token) = HUB.command_buffers.write(&mut token); - let (pass, _) = HUB.compute_passes.unregister(pass_id, &mut token); + let hub = B::hub(); + 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]; // There are no transitions to be made: we've already been inserting barriers @@ -60,17 +61,22 @@ pub extern "C" fn wgpu_compute_pass_end_pass(pass_id: ComputePassId) { } #[no_mangle] -pub extern "C" fn wgpu_compute_pass_set_bind_group( +pub extern "C" fn wgpu_compute_pass_end_pass(pass_id: ComputePassId) { + gfx_select!(pass_id => compute_pass_end_pass(pass_id)) +} + +pub fn compute_pass_set_bind_group( pass_id: ComputePassId, index: u32, bind_group_id: BindGroupId, - offsets: *const BufferAddress, - offsets_length: usize, + offsets: &[BufferAddress], ) { + let hub = B::hub(); 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); - let (mut pass_guard, mut token) = HUB.compute_passes.write(&mut token); + + let (pipeline_layout_guard, mut token) = hub.pipeline_layouts.read(&mut token); + let (bind_group_guard, mut token) = hub.bind_groups.read(&mut token); + let (mut pass_guard, mut token) = hub.compute_passes.write(&mut token); let pass = &mut pass_guard[pass_id]; let bind_group = pass @@ -79,12 +85,7 @@ pub extern "C" fn wgpu_compute_pass_set_bind_group( .use_extend(&*bind_group_guard, bind_group_id, (), ()) .unwrap(); - assert_eq!(bind_group.dynamic_count, offsets_length); - let offsets = if offsets_length != 0 { - unsafe { slice::from_raw_parts(offsets, offsets_length) } - } else { - &[] - }; + assert_eq!(bind_group.dynamic_count, offsets.len()); if cfg!(debug_assertions) { for off in offsets { @@ -100,8 +101,8 @@ pub extern "C" fn wgpu_compute_pass_set_bind_group( //Note: currently, WebGPU compute passes have synchronization defined // at a dispatch granularity, so we insert the necessary barriers here. - let (buffer_guard, mut token) = HUB.buffers.read(&mut token); - let (texture_guard, _) = HUB.textures.read(&mut token); + let (buffer_guard, mut token) = hub.buffers.read(&mut token); + let (texture_guard, _) = hub.textures.read(&mut token); trace!("Encoding barriers on binding of {:?} in pass {:?}", bind_group_id, pass_id); CommandBuffer::insert_barriers( @@ -133,6 +134,22 @@ pub extern "C" fn wgpu_compute_pass_set_bind_group( }; } +#[no_mangle] +pub extern "C" fn wgpu_compute_pass_set_bind_group( + pass_id: ComputePassId, + index: u32, + bind_group_id: BindGroupId, + offsets: *const BufferAddress, + offsets_length: usize, +) { + let offsets = if offsets_length != 0 { + unsafe { slice::from_raw_parts(offsets, offsets_length) } + } else { + &[] + }; + gfx_select!(pass_id => compute_pass_set_bind_group(pass_id, index, bind_group_id, offsets)) +} + #[no_mangle] pub extern "C" fn wgpu_compute_pass_push_debug_group(_pass_id: ComputePassId, _label: RawString) { //TODO @@ -153,24 +170,31 @@ pub extern "C" fn wgpu_compute_pass_insert_debug_marker( // Compute-specific routines -#[no_mangle] -pub extern "C" fn wgpu_compute_pass_dispatch(pass_id: ComputePassId, x: u32, y: u32, z: u32) { +pub fn compute_pass_dispatch( + pass_id: ComputePassId, x: u32, y: u32, z: u32 +) { + let hub = B::hub(); let mut token = Token::root(); - let (mut pass_guard, _) = HUB.compute_passes.write(&mut token); + let (mut pass_guard, _) = hub.compute_passes.write(&mut token); unsafe { pass_guard[pass_id].raw.dispatch([x, y, z]); } } #[no_mangle] -pub extern "C" fn wgpu_compute_pass_dispatch_indirect( +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)) +} + +pub fn compute_pass_dispatch_indirect( pass_id: ComputePassId, indirect_buffer_id: BufferId, indirect_offset: BufferAddress, ) { + let hub = B::hub(); let mut token = Token::root(); - let (buffer_guard, _) = HUB.buffers.read(&mut token); - let (mut pass_guard, _) = HUB.compute_passes.write(&mut token); + let (buffer_guard, _) = hub.buffers.read(&mut token); + let (mut pass_guard, _) = hub.compute_passes.write(&mut token); let pass = &mut pass_guard[pass_id]; let (src_buffer, src_pending) = pass @@ -196,16 +220,25 @@ pub extern "C" fn wgpu_compute_pass_dispatch_indirect( } #[no_mangle] -pub extern "C" fn wgpu_compute_pass_set_pipeline( +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)) +} + +pub fn compute_pass_set_pipeline( pass_id: ComputePassId, pipeline_id: ComputePipelineId, ) { + let hub = B::hub(); 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); - let (mut pass_guard, mut token) = HUB.compute_passes.write(&mut token); + let (pipeline_layout_guard, mut token) = hub.pipeline_layouts.read(&mut token); + let (bind_group_guard, mut token) = hub.bind_groups.read(&mut token); + let (mut pass_guard, mut token) = hub.compute_passes.write(&mut token); let pass = &mut pass_guard[pass_id]; - let (pipeline_guard, _) = HUB.compute_pipelines.read(&mut token); + let (pipeline_guard, _) = hub.compute_pipelines.read(&mut token); let pipeline = &pipeline_guard[pipeline_id]; unsafe { @@ -240,3 +273,11 @@ pub extern "C" fn wgpu_compute_pass_set_pipeline( } } } + +#[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)) +} diff --git a/wgpu-native/src/command/mod.rs b/wgpu-native/src/command/mod.rs index 695869e01..a187d7510 100644 --- a/wgpu-native/src/command/mod.rs +++ b/wgpu-native/src/command/mod.rs @@ -10,6 +10,7 @@ pub use self::render::*; pub use self::transfer::*; use crate::{ + gfx_select, conv, device::{ all_buffer_stages, @@ -18,29 +19,28 @@ use crate::{ RenderPassContext, RenderPassKey, }, - hub::{HUB, Storage, Token}, + hub::{GfxBackend, Storage, Token}, + id::{Input, Output}, resource::TexturePlacement, swap_chain::{SwapChainLink, SwapImageEpoch}, track::{Stitch, TrackerSet}, - BufferHandle, + Buffer, BufferId, Color, - CommandBufferHandle, CommandBufferId, CommandEncoderId, + ComputePassId, DeviceId, LifeGuard, + RenderPassId, Stored, - TextureHandle, + Texture, TextureId, TextureUsage, TextureViewId, }; -#[cfg(feature = "local")] -use crate::{ComputePassId, RenderPassId}; use arrayvec::ArrayVec; -use back::Backend; use hal::{ adapter::PhysicalDevice, command::RawCommandBuffer, @@ -48,7 +48,21 @@ use hal::{ }; use log::trace; -use std::{collections::hash_map::Entry, iter, mem, slice, ptr, thread::ThreadId}; +use std::{ + collections::hash_map::Entry, + iter, + mem, + slice, + ptr, + thread::ThreadId, +}; +#[cfg(not(feature = "remote"))] +use std::marker::PhantomData; + + +pub struct RenderBundle { + _raw: B::CommandBuffer, +} #[repr(C)] #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] @@ -94,6 +108,12 @@ pub struct RenderPassDescriptor { pub depth_stencil_attachment: *const RenderPassDepthStencilAttachmentDescriptor, } +#[repr(C)] +#[derive(Clone, Debug, Default)] +pub struct ComputePassDescriptor { + pub todo: u32, +} + #[derive(Debug)] pub struct CommandBuffer { pub(crate) raw: Vec, @@ -105,16 +125,19 @@ pub struct CommandBuffer { pub(crate) swap_chain_links: Vec>, } -impl CommandBufferHandle { +impl CommandBuffer { pub(crate) fn insert_barriers( - raw: &mut ::CommandBuffer, + raw: &mut B::CommandBuffer, base: &mut TrackerSet, head: &TrackerSet, stitch: Stitch, - buffer_guard: &Storage, - texture_guard: &Storage, + buffer_guard: &Storage, BufferId>, + texture_guard: &Storage, TextureId>, ) { trace!("\tstitch {:?}", stitch); + debug_assert_eq!(B::VARIANT, base.backend()); + debug_assert_eq!(B::VARIANT, head.backend()); + let buffer_barriers = base.buffers .merge_replace(&head.buffers, stitch) @@ -154,7 +177,7 @@ impl CommandBufferHandle { } #[repr(C)] -#[derive(Debug)] +#[derive(Clone, Debug, Default)] pub struct CommandEncoderDescriptor { // MSVC doesn't allow zero-sized structs // We can remove this when we actually have a field @@ -162,37 +185,48 @@ pub struct CommandEncoderDescriptor { } #[repr(C)] -#[derive(Debug)] +#[derive(Clone, Debug, Default)] pub struct CommandBufferDescriptor { pub todo: u32, } -#[no_mangle] -pub extern "C" fn wgpu_command_encoder_finish( - command_encoder_id: CommandEncoderId, - _desc: Option<&CommandBufferDescriptor>, +pub fn command_encoder_finish( + encoder_id: CommandEncoderId, + _desc: &CommandBufferDescriptor, ) -> CommandBufferId { + let hub = B::hub(); let mut token = Token::root(); //TODO: actually close the last recorded command buffer - let (mut comb_guard, _) = HUB.command_buffers.write(&mut token); - comb_guard[command_encoder_id].is_recording = false; //TODO: check for the old value - command_encoder_id + let (mut comb_guard, _) = hub.command_buffers.write(&mut token); + comb_guard[encoder_id].is_recording = false; //TODO: check for the old value + encoder_id } -pub fn command_encoder_begin_render_pass( - command_encoder_id: CommandEncoderId, +#[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)) +} + +pub fn command_encoder_begin_render_pass( + encoder_id: CommandEncoderId, desc: &RenderPassDescriptor, -) -> RenderPass { + id_in: Input, +) -> Output { + let hub = B::hub(); let mut token = Token::root(); - let (adapter_guard, mut token) = HUB.adapters.read(&mut token); - let (device_guard, mut token) = HUB.devices.read(&mut token); - let (mut cmb_guard, mut token) = HUB.command_buffers.write(&mut token); - let cmb = &mut cmb_guard[command_encoder_id]; + + let (adapter_guard, mut token) = hub.adapters.read(&mut token); + let (device_guard, mut token) = hub.devices.read(&mut token); + let (mut cmb_guard, mut token) = hub.command_buffers.write(&mut token); + let cmb = &mut cmb_guard[encoder_id]; let device = &device_guard[cmb.device_id.value]; - let (_, mut token) = HUB.buffers.read(&mut token); //skip token - let (texture_guard, mut token) = HUB.textures.read(&mut token); - let (view_guard, _) = HUB.texture_views.read(&mut token); + let limits = adapter_guard[device.adapter_id].raw.physical_device.limits(); + let samples_count_limit = limits.framebuffer_color_sample_counts; let mut current_comb = device.com_allocator.extend(cmb); unsafe { @@ -201,146 +235,90 @@ pub fn command_encoder_begin_render_pass( hal::command::CommandBufferInheritanceInfo::default(), ); } - let mut extent = None; - let mut barriers = Vec::new(); - let limits = adapter_guard[device.adapter_id].physical_device.limits(); - let samples_count_limit = limits.framebuffer_color_sample_counts; + let pass = { + let (_, mut token) = hub.buffers.read(&mut token); //skip token + let (texture_guard, mut token) = hub.textures.read(&mut token); + let (view_guard, _) = hub.texture_views.read(&mut token); - let color_attachments = - unsafe { slice::from_raw_parts(desc.color_attachments, desc.color_attachments_length) }; - let depth_stencil_attachment = unsafe { desc.depth_stencil_attachment.as_ref() }; + let mut extent = None; + let mut barriers = Vec::new(); - let sample_count = color_attachments.get(0).map(|at| view_guard[at.attachment].samples).unwrap_or(1); - assert!(sample_count & samples_count_limit != 0, "Attachment sample_count must be supported by physical device limits"); - for at in color_attachments.iter() { - let sample_count_check = view_guard[at.attachment].samples; - assert_eq!(sample_count_check, sample_count, "All attachments must have the same sample_count"); + let color_attachments = + unsafe { slice::from_raw_parts(desc.color_attachments, desc.color_attachments_length) }; + let depth_stencil_attachment = unsafe { desc.depth_stencil_attachment.as_ref() }; - if let Some(resolve) = unsafe { at.resolve_target.as_ref() } { - assert_eq!(view_guard[*resolve].samples, 1, "All target_resolves must have a sample_count of 1"); + let sample_count = color_attachments.get(0).map(|at| view_guard[at.attachment].samples).unwrap_or(1); + assert!(sample_count & samples_count_limit != 0, "Attachment sample_count must be supported by physical device limits"); + for at in color_attachments.iter() { + let sample_count_check = view_guard[at.attachment].samples; + assert_eq!(sample_count_check, sample_count, "All attachments must have the same sample_count"); + + if let Some(resolve) = unsafe { at.resolve_target.as_ref() } { + assert_eq!(view_guard[*resolve].samples, 1, "All target_resolves must have a sample_count of 1"); + } } - } - trace!("Encoding render pass begin in command buffer {:?}", command_encoder_id); - let rp_key = { - let trackers = &mut cmb.trackers; - let swap_chain_links = &mut cmb.swap_chain_links; + trace!("Encoding render pass begin in command buffer {:?}", encoder_id); + let rp_key = { + let trackers = &mut cmb.trackers; + let swap_chain_links = &mut cmb.swap_chain_links; - let depth_stencil = depth_stencil_attachment.map(|at| { - let view = trackers.views - .use_extend(&*view_guard, at.attachment, (), ()) - .unwrap(); - if let Some(ex) = extent { - assert_eq!(ex, view.extent); - } else { - extent = Some(view.extent); - } - let old_layout = match trackers.textures.query( - view.texture_id.value, - view.range.clone(), - ) { - Some(usage) => { - conv::map_texture_state( - usage, - hal::format::Aspects::DEPTH | hal::format::Aspects::STENCIL, - ).1 + let depth_stencil = depth_stencil_attachment.map(|at| { + let view = trackers.views + .use_extend(&*view_guard, at.attachment, (), ()) + .unwrap(); + if let Some(ex) = extent { + assert_eq!(ex, view.extent); + } else { + extent = Some(view.extent); } - None => { - // Required sub-resources have inconsistent states, we need to - // issue individual barriers instead of relying on the render pass. - let (texture, pending) = trackers.textures.use_replace( - &*texture_guard, - view.texture_id.value, - view.range.clone(), - TextureUsage::OUTPUT_ATTACHMENT, - ); - barriers.extend(pending.map(|pending| { - trace!("\tdepth-stencil {:?}", pending); - hal::memory::Barrier::Image { - states: pending.to_states(), - target: &texture.raw, - families: None, - range: pending.selector, - } - })); - hal::image::Layout::DepthStencilAttachmentOptimal - } - }; - hal::pass::Attachment { - format: Some(conv::map_texture_format(view.format)), - samples: view.samples, - ops: conv::map_load_store_ops(at.depth_load_op, at.depth_store_op), - stencil_ops: conv::map_load_store_ops(at.stencil_load_op, at.stencil_store_op), - layouts: old_layout .. hal::image::Layout::DepthStencilAttachmentOptimal, - } - }); - - let mut colors = ArrayVec::new(); - let mut resolves = ArrayVec::new(); - - for at in color_attachments { - let view = trackers.views - .use_extend(&*view_guard, at.attachment, (), ()) - .unwrap(); - if let Some(ex) = extent { - assert_eq!(ex, view.extent); - } else { - extent = Some(view.extent); - } - - if view.is_owned_by_swap_chain { - let link = match texture_guard[view.texture_id.value].placement { - TexturePlacement::SwapChain(ref link) => SwapChainLink { - swap_chain_id: link.swap_chain_id.clone(), - epoch: *link.epoch.lock(), - image_index: link.image_index, - }, - TexturePlacement::Memory(_) | TexturePlacement::Void => unreachable!(), + let old_layout = match trackers.textures.query( + view.texture_id.value, + view.range.clone(), + ) { + Some(usage) => { + conv::map_texture_state( + usage, + hal::format::Aspects::DEPTH | hal::format::Aspects::STENCIL, + ).1 + } + None => { + // Required sub-resources have inconsistent states, we need to + // issue individual barriers instead of relying on the render pass. + let (texture, pending) = trackers.textures.use_replace( + &*texture_guard, + view.texture_id.value, + view.range.clone(), + TextureUsage::OUTPUT_ATTACHMENT, + ); + barriers.extend(pending.map(|pending| { + trace!("\tdepth-stencil {:?}", pending); + hal::memory::Barrier::Image { + states: pending.to_states(), + target: &texture.raw, + families: None, + range: pending.selector, + } + })); + hal::image::Layout::DepthStencilAttachmentOptimal + } }; - swap_chain_links.push(link); - } - - let old_layout = match trackers.textures.query( - view.texture_id.value, - view.range.clone(), - ) { - Some(usage) => { - conv::map_texture_state(usage, hal::format::Aspects::COLOR).1 + hal::pass::Attachment { + format: Some(conv::map_texture_format(view.format)), + samples: view.samples, + ops: conv::map_load_store_ops(at.depth_load_op, at.depth_store_op), + stencil_ops: conv::map_load_store_ops(at.stencil_load_op, at.stencil_store_op), + layouts: old_layout .. hal::image::Layout::DepthStencilAttachmentOptimal, } - None => { - // Required sub-resources have inconsistent states, we need to - // issue individual barriers instead of relying on the render pass. - let (texture, pending) = trackers.textures.use_replace( - &*texture_guard, - view.texture_id.value, - 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 - } - }; - - colors.push(hal::pass::Attachment { - format: Some(conv::map_texture_format(view.format)), - samples: view.samples, - ops: conv::map_load_store_ops(at.load_op, at.store_op), - stencil_ops: hal::pass::AttachmentOps::DONT_CARE, - layouts: old_layout .. hal::image::Layout::ColorAttachmentOptimal, }); - if let Some(resolve_target) = unsafe { at.resolve_target.as_ref() } { + let mut colors = ArrayVec::new(); + let mut resolves = ArrayVec::new(); + + for at in color_attachments { let view = trackers.views - .use_extend(&*view_guard, *resolve_target, (), ()) + .use_extend(&*view_guard, at.attachment, (), ()) .unwrap(); if let Some(ex) = extent { assert_eq!(ex, view.extent); @@ -355,7 +333,7 @@ pub fn command_encoder_begin_render_pass( epoch: *link.epoch.lock(), image_index: link.image_index, }, - TexturePlacement::Memory(_) | TexturePlacement::Void => unreachable!(), + TexturePlacement::Memory(_) => unreachable!(), }; swap_chain_links.push(link); } @@ -377,7 +355,7 @@ pub fn command_encoder_begin_render_pass( TextureUsage::OUTPUT_ATTACHMENT, ); barriers.extend(pending.map(|pending| { - trace!("\tresolve {:?}", pending); + trace!("\tcolor {:?}", pending); hal::memory::Barrier::Image { states: pending.to_states(), target: &texture.raw, @@ -389,231 +367,300 @@ pub fn command_encoder_begin_render_pass( } }; - resolves.push(hal::pass::Attachment { + colors.push(hal::pass::Attachment { format: Some(conv::map_texture_format(view.format)), samples: view.samples, - ops: hal::pass::AttachmentOps::new(hal::pass::AttachmentLoadOp::DontCare, hal::pass::AttachmentStoreOp::Store), + ops: conv::map_load_store_ops(at.load_op, at.store_op), stencil_ops: hal::pass::AttachmentOps::DONT_CARE, layouts: old_layout .. hal::image::Layout::ColorAttachmentOptimal, }); - } - } - RenderPassKey { - colors, - resolves, - depth_stencil, - } - }; - - if !barriers.is_empty() { - unsafe { - current_comb.pipeline_barrier( - all_image_stages() .. all_image_stages(), - hal::memory::Dependencies::empty(), - barriers, - ); - } - } - - let mut render_pass_cache = device.render_passes.lock(); - let render_pass = match render_pass_cache.entry(rp_key.clone()) { - Entry::Occupied(e) => e.into_mut(), - Entry::Vacant(e) => { - let color_ids = [ - (0, hal::image::Layout::ColorAttachmentOptimal), - (1, hal::image::Layout::ColorAttachmentOptimal), - (2, hal::image::Layout::ColorAttachmentOptimal), - (3, hal::image::Layout::ColorAttachmentOptimal), - ]; - - let mut resolve_ids = ArrayVec::<[_; crate::device::MAX_COLOR_TARGETS]>::new(); - let mut attachment_index = color_attachments.len(); - if color_attachments.iter().any(|at| at.resolve_target != ptr::null()) { - for (i, at) in color_attachments.iter().enumerate() { - if at.resolve_target == ptr::null() { - resolve_ids.push((hal::pass::ATTACHMENT_UNUSED, hal::image::Layout::ColorAttachmentOptimal)); + if let Some(resolve_target) = unsafe { at.resolve_target.as_ref() } { + let view = trackers.views + .use_extend(&*view_guard, *resolve_target, (), ()) + .unwrap(); + if let Some(ex) = extent { + assert_eq!(ex, view.extent); } else { - let sample_count_check = view_guard[color_attachments[i].attachment].samples; - assert!(sample_count_check > 1, "RenderPassColorAttachmentDescriptor with a resolve_target must have an attachment with sample_count > 1"); - resolve_ids.push((attachment_index, hal::image::Layout::ColorAttachmentOptimal)); - attachment_index += 1; + extent = Some(view.extent); } - } - } - let depth_id = ( - attachment_index, - hal::image::Layout::DepthStencilAttachmentOptimal, - ); + if view.is_owned_by_swap_chain { + let link = match texture_guard[view.texture_id.value].placement { + TexturePlacement::SwapChain(ref link) => SwapChainLink { + swap_chain_id: link.swap_chain_id.clone(), + epoch: *link.epoch.lock(), + image_index: link.image_index, + }, + TexturePlacement::Memory(_) => unreachable!(), + }; + swap_chain_links.push(link); + } - let subpass = hal::pass::SubpassDesc { - colors: &color_ids[.. color_attachments.len()], - resolves: &resolve_ids, - depth_stencil: depth_stencil_attachment.map(|_| &depth_id), - inputs: &[], - preserves: &[], - }; - - let pass = unsafe { - device - .raw - .create_render_pass(e.key().all(), &[subpass], &[]) - } - .unwrap(); - e.insert(pass) - } - }; - - let mut framebuffer_cache = device.framebuffers.lock(); - let fb_key = FramebufferKey { - colors: color_attachments.iter().map(|at| at.attachment).collect(), - resolves: color_attachments.iter().filter_map(|at| - unsafe { at.resolve_target.as_ref() }.cloned() - ).collect(), - depth_stencil: depth_stencil_attachment.map(|at| at.attachment), - }; - let framebuffer = match framebuffer_cache.entry(fb_key) { - Entry::Occupied(e) => e.into_mut(), - Entry::Vacant(e) => { - let fb = { - let attachments = e.key().all().map(|&id| &view_guard[id].raw); - - unsafe { - device - .raw - .create_framebuffer(&render_pass, attachments, extent.unwrap()) - } - .unwrap() - }; - e.insert(fb) - } - }; - - let rect = { - let ex = extent.unwrap(); - hal::pso::Rect { - x: 0, - y: 0, - w: ex.width as _, - h: ex.height as _, - } - }; - - let clear_values = color_attachments - .iter() - .zip(&rp_key.colors) - .flat_map(|(at, key)| { - match at.load_op { - LoadOp::Load => None, - LoadOp::Clear => { - use hal::format::ChannelType; - //TODO: validate sign/unsign and normalized ranges of the color values - let value = match key.format.unwrap().base_format().1 { - ChannelType::Unorm | - ChannelType::Snorm | - ChannelType::Ufloat | - ChannelType::Sfloat | - ChannelType::Uscaled | - ChannelType::Sscaled | - ChannelType::Srgb => { - hal::command::ClearColor::Sfloat(conv::map_color_f32(&at.clear_color)) + let old_layout = match trackers.textures.query( + view.texture_id.value, + view.range.clone(), + ) { + Some(usage) => { + conv::map_texture_state(usage, hal::format::Aspects::COLOR).1 } - ChannelType::Sint => { - hal::command::ClearColor::Sint(conv::map_color_i32(&at.clear_color)) - } - ChannelType::Uint => { - hal::command::ClearColor::Uint(conv::map_color_u32(&at.clear_color)) + None => { + // Required sub-resources have inconsistent states, we need to + // issue individual barriers instead of relying on the render pass. + let (texture, pending) = trackers.textures.use_replace( + &*texture_guard, + view.texture_id.value, + 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 } }; - Some(hal::command::ClearValueRaw::from(hal::command::ClearValue::Color(value))) - } - } - }) - .chain(depth_stencil_attachment.and_then(|at| { - match (at.depth_load_op, at.stencil_load_op) { - (LoadOp::Load, LoadOp::Load) => None, - (LoadOp::Clear, _) | (_, LoadOp::Clear) => { - let value = hal::command::ClearDepthStencil(at.clear_depth, at.clear_stencil); - Some(hal::command::ClearValueRaw::from(hal::command::ClearValue::DepthStencil(value))) - } - } - })); - unsafe { - current_comb.begin_render_pass( - render_pass, - framebuffer, - rect, - clear_values, - hal::command::SubpassContents::Inline, - ); - current_comb.set_scissors(0, iter::once(&rect)); - current_comb.set_viewports( - 0, - iter::once(hal::pso::Viewport { + resolves.push(hal::pass::Attachment { + format: Some(conv::map_texture_format(view.format)), + samples: view.samples, + ops: hal::pass::AttachmentOps::new(hal::pass::AttachmentLoadOp::DontCare, hal::pass::AttachmentStoreOp::Store), + stencil_ops: hal::pass::AttachmentOps::DONT_CARE, + layouts: old_layout .. hal::image::Layout::ColorAttachmentOptimal, + }); + } + } + + RenderPassKey { + colors, + resolves, + depth_stencil, + } + }; + + if !barriers.is_empty() { + unsafe { + current_comb.pipeline_barrier( + all_image_stages() .. all_image_stages(), + hal::memory::Dependencies::empty(), + barriers, + ); + } + } + + let mut render_pass_cache = device.render_passes.lock(); + let render_pass = match render_pass_cache.entry(rp_key.clone()) { + Entry::Occupied(e) => e.into_mut(), + Entry::Vacant(e) => { + let color_ids = [ + (0, hal::image::Layout::ColorAttachmentOptimal), + (1, hal::image::Layout::ColorAttachmentOptimal), + (2, hal::image::Layout::ColorAttachmentOptimal), + (3, hal::image::Layout::ColorAttachmentOptimal), + ]; + + let mut resolve_ids = ArrayVec::<[_; crate::device::MAX_COLOR_TARGETS]>::new(); + let mut attachment_index = color_attachments.len(); + if color_attachments.iter().any(|at| at.resolve_target != ptr::null()) { + for (i, at) in color_attachments.iter().enumerate() { + if at.resolve_target == ptr::null() { + resolve_ids.push((hal::pass::ATTACHMENT_UNUSED, hal::image::Layout::ColorAttachmentOptimal)); + } else { + let sample_count_check = view_guard[color_attachments[i].attachment].samples; + assert!(sample_count_check > 1, "RenderPassColorAttachmentDescriptor with a resolve_target must have an attachment with sample_count > 1"); + resolve_ids.push((attachment_index, hal::image::Layout::ColorAttachmentOptimal)); + attachment_index += 1; + } + } + } + + let depth_id = ( + attachment_index, + hal::image::Layout::DepthStencilAttachmentOptimal, + ); + + let subpass = hal::pass::SubpassDesc { + colors: &color_ids[.. color_attachments.len()], + resolves: &resolve_ids, + depth_stencil: depth_stencil_attachment.map(|_| &depth_id), + inputs: &[], + preserves: &[], + }; + + let pass = unsafe { + device + .raw + .create_render_pass(e.key().all(), &[subpass], &[]) + } + .unwrap(); + e.insert(pass) + } + }; + + let mut framebuffer_cache = device.framebuffers.lock(); + let fb_key = FramebufferKey { + colors: color_attachments.iter().map(|at| at.attachment).collect(), + resolves: color_attachments.iter().filter_map(|at| + unsafe { at.resolve_target.as_ref() }.cloned() + ).collect(), + depth_stencil: depth_stencil_attachment.map(|at| at.attachment), + }; + let framebuffer = match framebuffer_cache.entry(fb_key) { + Entry::Occupied(e) => e.into_mut(), + Entry::Vacant(e) => { + let fb = { + let attachments = e.key().all().map(|&id| &view_guard[id].raw); + + unsafe { + device + .raw + .create_framebuffer(&render_pass, attachments, extent.unwrap()) + } + .unwrap() + }; + e.insert(fb) + } + }; + + let rect = { + let ex = extent.unwrap(); + hal::pso::Rect { + x: 0, + y: 0, + w: ex.width as _, + h: ex.height as _, + } + }; + + let clear_values = color_attachments + .iter() + .zip(&rp_key.colors) + .flat_map(|(at, key)| { + match at.load_op { + LoadOp::Load => None, + LoadOp::Clear => { + use hal::format::ChannelType; + //TODO: validate sign/unsign and normalized ranges of the color values + let value = match key.format.unwrap().base_format().1 { + ChannelType::Unorm | + ChannelType::Snorm | + ChannelType::Ufloat | + ChannelType::Sfloat | + ChannelType::Uscaled | + ChannelType::Sscaled | + ChannelType::Srgb => { + hal::command::ClearColor::Sfloat(conv::map_color_f32(&at.clear_color)) + } + ChannelType::Sint => { + hal::command::ClearColor::Sint(conv::map_color_i32(&at.clear_color)) + } + ChannelType::Uint => { + hal::command::ClearColor::Uint(conv::map_color_u32(&at.clear_color)) + } + }; + Some(hal::command::ClearValueRaw::from(hal::command::ClearValue::Color(value))) + } + } + }) + .chain(depth_stencil_attachment.and_then(|at| { + match (at.depth_load_op, at.stencil_load_op) { + (LoadOp::Load, LoadOp::Load) => None, + (LoadOp::Clear, _) | (_, LoadOp::Clear) => { + let value = hal::command::ClearDepthStencil(at.clear_depth, at.clear_stencil); + Some(hal::command::ClearValueRaw::from(hal::command::ClearValue::DepthStencil(value))) + } + } + })); + + unsafe { + current_comb.begin_render_pass( + render_pass, + framebuffer, rect, - depth: 0.0 .. 1.0, - }), - ); - } + clear_values, + hal::command::SubpassContents::Inline, + ); + current_comb.set_scissors(0, iter::once(&rect)); + current_comb.set_viewports( + 0, + iter::once(hal::pso::Viewport { + rect, + depth: 0.0 .. 1.0, + }), + ); + } - let context = RenderPassContext { - colors: color_attachments - .iter() - .map(|at| view_guard[at.attachment].format) - .collect(), - resolves: color_attachments - .iter() - .filter_map(|at| unsafe { at.resolve_target.as_ref() }) - .map(|resolve| view_guard[*resolve].format) - .collect(), - depth_stencil: depth_stencil_attachment.map(|at| view_guard[at.attachment].format), + let context = RenderPassContext { + colors: color_attachments + .iter() + .map(|at| view_guard[at.attachment].format) + .collect(), + resolves: color_attachments + .iter() + .filter_map(|at| unsafe { at.resolve_target.as_ref() }) + .map(|resolve| view_guard[*resolve].format) + .collect(), + depth_stencil: depth_stencil_attachment.map(|at| view_guard[at.attachment].format), + }; + + RenderPass::new( + current_comb, + Stored { + value: encoder_id, + ref_count: cmb.life_guard.ref_count.clone(), + }, + context, + sample_count, + ) }; - - RenderPass::new( - current_comb, - Stored { - value: command_encoder_id, - ref_count: cmb.life_guard.ref_count.clone(), - }, - context, - sample_count, - ) + hub.render_passes.register_identity(id_in, pass, &mut token) } -#[cfg(feature = "local")] +#[cfg(not(feature = "remote"))] #[no_mangle] pub extern "C" fn wgpu_command_encoder_begin_render_pass( - command_encoder_id: CommandEncoderId, + encoder_id: CommandEncoderId, desc: &RenderPassDescriptor, ) -> RenderPassId { - let pass = command_encoder_begin_render_pass(command_encoder_id, desc); - HUB.render_passes.register_local(pass, &mut Token::root()) + gfx_select!(encoder_id => command_encoder_begin_render_pass(encoder_id, desc, PhantomData)) } -pub fn command_encoder_begin_compute_pass( - command_encoder_id: CommandEncoderId, -) -> ComputePass { +pub fn command_encoder_begin_compute_pass( + encoder_id: CommandEncoderId, + _desc: &ComputePassDescriptor, + id_in: Input, +) -> Output { + let hub = B::hub(); let mut token = Token::root(); - let (mut cmb_guard, _) = HUB.command_buffers.write(&mut token); - let cmb = &mut cmb_guard[command_encoder_id]; + + let (mut cmb_guard, mut token) = hub.command_buffers.write(&mut token); + let cmb = &mut cmb_guard[encoder_id]; let raw = cmb.raw.pop().unwrap(); - let trackers = mem::replace(&mut cmb.trackers, TrackerSet::new()); + let trackers = mem::replace( + &mut cmb.trackers, + TrackerSet::new(encoder_id.backend()), + ); let stored = Stored { - value: command_encoder_id, + value: encoder_id, ref_count: cmb.life_guard.ref_count.clone(), }; - ComputePass::new(raw, stored, trackers) + let pass = ComputePass::new(raw, stored, trackers); + hub.compute_passes.register_identity(id_in, pass, &mut token) } -#[cfg(feature = "local")] +#[cfg(not(feature = "remote"))] #[no_mangle] pub extern "C" fn wgpu_command_encoder_begin_compute_pass( - command_encoder_id: CommandEncoderId, + encoder_id: CommandEncoderId, + desc: Option<&ComputePassDescriptor>, ) -> ComputePassId { - let pass = command_encoder_begin_compute_pass(command_encoder_id); - HUB.compute_passes.register_local(pass, &mut Token::root()) + let desc = &desc.cloned().unwrap_or_default(); + gfx_select!(encoder_id => command_encoder_begin_compute_pass(encoder_id, desc, PhantomData)) } diff --git a/wgpu-native/src/command/render.rs b/wgpu-native/src/command/render.rs index 31e98024d..8c67435ac 100644 --- a/wgpu-native/src/command/render.rs +++ b/wgpu-native/src/command/render.rs @@ -1,8 +1,9 @@ use crate::{ + gfx_select, command::bind::{Binder, LayoutChange}, conv, device::{RenderPassContext, BIND_BUFFER_ALIGNMENT, MAX_VERTEX_BUFFERS}, - hub::{Token, HUB}, + hub::{GfxBackend, Token}, pipeline::{IndexFormat, InputStepMode, PipelineFlags}, resource::BufferUsage, track::{Stitch, TrackerSet}, @@ -125,7 +126,7 @@ pub struct RenderPass { sample_count: u8, } -impl RenderPass { +impl RenderPass { pub(crate) fn new( raw: B::CommandBuffer, cmb_id: Stored, @@ -137,7 +138,7 @@ impl RenderPass { cmb_id, context, binder: Binder::default(), - trackers: TrackerSet::new(), + trackers: TrackerSet::new(B::VARIANT), blend_color_status: OptionalState::Unused, stencil_reference_status: OptionalState::Unused, index_state: IndexState { @@ -175,21 +176,21 @@ impl RenderPass { // Common routines between render/compute -#[no_mangle] -pub extern "C" fn wgpu_render_pass_end_pass(pass_id: RenderPassId) { +pub fn render_pass_end_pass(pass_id: RenderPassId) { + let hub = B::hub(); 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); + 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); unsafe { pass.raw.end_render_pass(); } pass.trackers.optimize(); let cmb = &mut cmb_guard[pass.cmb_id.value]; - let (buffer_guard, mut token) = HUB.buffers.read(&mut token); - let (texture_guard, _) = HUB.textures.read(&mut token); + let (buffer_guard, mut token) = hub.buffers.read(&mut token); + let (texture_guard, _) = hub.textures.read(&mut token); match cmb.raw.last_mut() { - Some(ref mut last) => { + Some(last) => { trace!("Encoding barriers before pass {:?}", pass_id); CommandBuffer::insert_barriers( last, @@ -210,18 +211,22 @@ pub extern "C" fn wgpu_render_pass_end_pass(pass_id: RenderPassId) { } #[no_mangle] -pub extern "C" fn wgpu_render_pass_set_bind_group( +pub extern "C" fn wgpu_render_pass_end_pass(pass_id: RenderPassId) { + gfx_select!(pass_id => render_pass_end_pass(pass_id)) +} + +pub fn render_pass_set_bind_group( pass_id: RenderPassId, index: u32, bind_group_id: BindGroupId, - offsets: *const BufferAddress, - offsets_length: usize, + offsets: &[BufferAddress], ) { + let hub = B::hub(); 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); + let (pipeline_layout_guard, mut token) = hub.pipeline_layouts.read(&mut token); + let (bind_group_guard, mut token) = hub.bind_groups.read(&mut token); - let (mut pass_guard, _) = HUB.render_passes.write(&mut token); + let (mut pass_guard, _) = hub.render_passes.write(&mut token); let pass = &mut pass_guard[pass_id]; let bind_group = pass @@ -230,12 +235,7 @@ pub extern "C" fn wgpu_render_pass_set_bind_group( .use_extend(&*bind_group_guard, bind_group_id, (), ()) .unwrap(); - assert_eq!(bind_group.dynamic_count, offsets_length); - let offsets = if offsets_length != 0 { - unsafe { slice::from_raw_parts(offsets, offsets_length) } - } else { - &[] - }; + assert_eq!(bind_group.dynamic_count, offsets.len()); if cfg!(debug_assertions) { for off in offsets { @@ -271,6 +271,22 @@ pub extern "C" fn wgpu_render_pass_set_bind_group( }; } +#[no_mangle] +pub extern "C" fn wgpu_render_pass_set_bind_group( + pass_id: RenderPassId, + index: u32, + bind_group_id: BindGroupId, + offsets: *const BufferAddress, + offsets_length: usize, +) { + let offsets = if offsets_length != 0 { + unsafe { slice::from_raw_parts(offsets, offsets_length) } + } else { + &[] + }; + gfx_select!(pass_id => render_pass_set_bind_group(pass_id, index, bind_group_id, offsets)) +} + #[no_mangle] pub extern "C" fn wgpu_render_pass_push_debug_group(_pass_id: RenderPassId, _label: RawString) { //TODO @@ -288,15 +304,15 @@ pub extern "C" fn wgpu_render_pass_insert_debug_marker(_pass_id: RenderPassId, _ // Render-specific routines -#[no_mangle] -pub extern "C" fn wgpu_render_pass_set_index_buffer( +pub fn render_pass_set_index_buffer( pass_id: RenderPassId, buffer_id: BufferId, offset: BufferAddress, ) { + let hub = B::hub(); 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); + let (mut pass_guard, mut token) = hub.render_passes.write(&mut token); + let (buffer_guard, _) = hub.buffers.read(&mut token); let pass = &mut pass_guard[pass_id]; let buffer = pass @@ -320,19 +336,26 @@ pub extern "C" fn wgpu_render_pass_set_index_buffer( } } -#[no_mangle] -pub extern "C" fn wgpu_render_pass_set_vertex_buffers( +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)) +} + +pub fn render_pass_set_vertex_buffers( pass_id: RenderPassId, start_slot: u32, - buffers: *const BufferId, - offsets: *const BufferAddress, - length: usize, + buffers: &[BufferId], + offsets: &[BufferAddress], ) { + let hub = B::hub(); 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); - let buffers = unsafe { slice::from_raw_parts(buffers, length) }; - let offsets = unsafe { slice::from_raw_parts(offsets, length) }; + assert_eq!(buffers.len(), offsets.len()); + + let (mut pass_guard, mut token) = hub.render_passes.write(&mut token); + let (buffer_guard, _) = hub.buffers.read(&mut token); let pass = &mut pass_guard[pass_id]; for (vbs, (&id, &offset)) in pass.vertex_state.inputs[start_slot as usize ..].iter_mut().zip(buffers.iter().zip(offsets)) { @@ -356,15 +379,28 @@ pub extern "C" fn wgpu_render_pass_set_vertex_buffers( } #[no_mangle] -pub extern "C" fn wgpu_render_pass_draw( +pub extern "C" fn wgpu_render_pass_set_vertex_buffers( + pass_id: RenderPassId, + start_slot: u32, + buffers: *const BufferId, + offsets: *const BufferAddress, + length: usize, +) { + 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)) +} + +pub fn render_pass_draw( pass_id: RenderPassId, vertex_count: u32, instance_count: u32, first_vertex: u32, first_instance: u32, ) { + let hub = B::hub(); let mut token = Token::root(); - let (mut pass_guard, _) = HUB.render_passes.write(&mut token); + let (mut pass_guard, _) = hub.render_passes.write(&mut token); let pass = &mut pass_guard[pass_id]; pass.is_ready().unwrap(); @@ -380,14 +416,25 @@ pub extern "C" fn wgpu_render_pass_draw( } #[no_mangle] -pub extern "C" fn wgpu_render_pass_draw_indirect( +pub extern "C" fn wgpu_render_pass_draw( + pass_id: RenderPassId, + vertex_count: u32, + instance_count: u32, + first_vertex: u32, + first_instance: u32, +) { + gfx_select!(pass_id => render_pass_draw(pass_id, vertex_count, instance_count, first_vertex, first_instance)) +} + +pub fn render_pass_draw_indirect( pass_id: RenderPassId, indirect_buffer_id: BufferId, indirect_offset: BufferAddress, ) { + let hub = B::hub(); let mut token = Token::root(); - let (mut pass_guard, _) = HUB.render_passes.write(&mut token); - let (buffer_guard, _) = HUB.buffers.read(&mut token); + let (mut pass_guard, _) = hub.render_passes.write(&mut token); + let (buffer_guard, _) = hub.buffers.read(&mut token); let pass = &mut pass_guard[pass_id]; pass.is_ready().unwrap(); @@ -408,7 +455,15 @@ pub extern "C" fn wgpu_render_pass_draw_indirect( } #[no_mangle] -pub extern "C" fn wgpu_render_pass_draw_indexed( +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)) +} + +pub fn render_pass_draw_indexed( pass_id: RenderPassId, index_count: u32, instance_count: u32, @@ -416,8 +471,9 @@ pub extern "C" fn wgpu_render_pass_draw_indexed( base_vertex: i32, first_instance: u32, ) { + let hub = B::hub(); let mut token = Token::root(); - let (mut pass_guard, _) = HUB.render_passes.write(&mut token); + let (mut pass_guard, _) = hub.render_passes.write(&mut token); let pass = &mut pass_guard[pass_id]; pass.is_ready().unwrap(); @@ -435,14 +491,26 @@ pub extern "C" fn wgpu_render_pass_draw_indexed( } #[no_mangle] -pub extern "C" fn wgpu_render_pass_draw_indexed_indirect( +pub extern "C" fn wgpu_render_pass_draw_indexed( + pass_id: RenderPassId, + index_count: u32, + instance_count: u32, + first_index: u32, + 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)) +} + +pub fn render_pass_draw_indexed_indirect( pass_id: RenderPassId, indirect_buffer_id: BufferId, indirect_offset: BufferAddress, ) { + let hub = B::hub(); let mut token = Token::root(); - let (mut pass_guard, _) = HUB.render_passes.write(&mut token); - let (buffer_guard, _) = HUB.buffers.read(&mut token); + let (mut pass_guard, _) = hub.render_passes.write(&mut token); + let (buffer_guard, _) = hub.buffers.read(&mut token); let pass = &mut pass_guard[pass_id]; pass.is_ready().unwrap(); @@ -463,16 +531,25 @@ pub extern "C" fn wgpu_render_pass_draw_indexed_indirect( } #[no_mangle] -pub extern "C" fn wgpu_render_pass_set_pipeline( +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)) +} + +pub fn render_pass_set_pipeline( pass_id: RenderPassId, pipeline_id: RenderPipelineId, ) { + let hub = B::hub(); 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); - let (mut pass_guard, mut token) = HUB.render_passes.write(&mut token); + let (pipeline_layout_guard, mut token) = hub.pipeline_layouts.read(&mut token); + let (bind_group_guard, mut token) = hub.bind_groups.read(&mut token); + let (mut pass_guard, mut token) = hub.render_passes.write(&mut token); let pass = &mut pass_guard[pass_id]; - let (pipeline_guard, mut token) = HUB.render_pipelines.read(&mut token); + let (pipeline_guard, mut token) = hub.render_pipelines.read(&mut token); let pipeline = &pipeline_guard[pipeline_id]; assert!( @@ -524,7 +601,7 @@ pub extern "C" fn wgpu_render_pass_set_pipeline( pass.index_state.update_limit(); if let Some((buffer_id, ref range)) = pass.index_state.bound_buffer_view { - let (buffer_guard, _) = HUB.buffers.read(&mut token); + let (buffer_guard, _) = hub.buffers.read(&mut token); let buffer = pass .trackers .buffers @@ -555,9 +632,17 @@ pub extern "C" fn wgpu_render_pass_set_pipeline( } #[no_mangle] -pub extern "C" fn wgpu_render_pass_set_blend_color(pass_id: RenderPassId, color: &Color) { +pub extern "C" fn wgpu_render_pass_set_pipeline( + pass_id: RenderPassId, + pipeline_id: RenderPipelineId, +) { + gfx_select!(pass_id => render_pass_set_pipeline(pass_id, pipeline_id)) +} + +pub fn render_pass_set_blend_color(pass_id: RenderPassId, color: &Color) { + let hub = B::hub(); let mut token = Token::root(); - let (mut pass_guard, _) = HUB.render_passes.write(&mut token); + let (mut pass_guard, _) = hub.render_passes.write(&mut token); let pass = &mut pass_guard[pass_id]; pass.blend_color_status = OptionalState::Set; @@ -568,9 +653,14 @@ pub extern "C" fn wgpu_render_pass_set_blend_color(pass_id: RenderPassId, color: } #[no_mangle] -pub extern "C" fn wgpu_render_pass_set_stencil_reference(pass_id: RenderPassId, value: u32) { +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)) +} + +pub fn render_pass_set_stencil_reference(pass_id: RenderPassId, value: u32) { + let hub = B::hub(); let mut token = Token::root(); - let (mut pass_guard, _) = HUB.render_passes.write(&mut token); + let (mut pass_guard, _) = hub.render_passes.write(&mut token); let pass = &mut pass_guard[pass_id]; pass.stencil_reference_status = OptionalState::Set; @@ -581,7 +671,11 @@ pub extern "C" fn wgpu_render_pass_set_stencil_reference(pass_id: RenderPassId, } #[no_mangle] -pub extern "C" fn wgpu_render_pass_set_viewport( +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)) +} + +pub fn render_pass_set_viewport( pass_id: RenderPassId, x: f32, y: f32, @@ -590,8 +684,9 @@ pub extern "C" fn wgpu_render_pass_set_viewport( min_depth: f32, max_depth: f32, ) { + let hub = B::hub(); let mut token = Token::root(); - let (mut pass_guard, _) = HUB.render_passes.write(&mut token); + let (mut pass_guard, _) = hub.render_passes.write(&mut token); let pass = &mut pass_guard[pass_id]; unsafe { @@ -614,15 +709,28 @@ pub extern "C" fn wgpu_render_pass_set_viewport( } #[no_mangle] -pub extern "C" fn wgpu_render_pass_set_scissor_rect( +pub extern "C" fn wgpu_render_pass_set_viewport( + pass_id: RenderPassId, + x: f32, + y: f32, + w: f32, + h: f32, + min_depth: f32, + max_depth: f32, +) { + gfx_select!(pass_id => render_pass_set_viewport(pass_id, x, y, w, h, min_depth, max_depth)) +} + +pub fn render_pass_set_scissor_rect( pass_id: RenderPassId, x: u32, y: u32, w: u32, h: u32, ) { + let hub = B::hub(); let mut token = Token::root(); - let (mut pass_guard, _) = HUB.render_passes.write(&mut token); + let (mut pass_guard, _) = hub.render_passes.write(&mut token); let pass = &mut pass_guard[pass_id]; unsafe { @@ -641,6 +749,17 @@ pub extern "C" fn wgpu_render_pass_set_scissor_rect( } } +#[no_mangle] +pub extern "C" fn wgpu_render_pass_set_scissor_rect( + pass_id: RenderPassId, + x: u32, + y: u32, + w: u32, + h: u32, +) { + gfx_select!(pass_id => render_pass_set_scissor_rect(pass_id, x, y, w, h)) +} + #[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 a633cc334..154e0ee0e 100644 --- a/wgpu-native/src/command/transfer.rs +++ b/wgpu-native/src/command/transfer.rs @@ -1,7 +1,8 @@ use crate::{ + gfx_select, conv, device::{all_buffer_stages, all_image_stages}, - hub::{HUB, Token}, + hub::{GfxBackend, Token}, resource::TexturePlacement, swap_chain::SwapChainLink, BufferAddress, @@ -64,8 +65,7 @@ impl TextureCopyView { } } -#[no_mangle] -pub extern "C" fn wgpu_command_encoder_copy_buffer_to_buffer( +pub fn command_encoder_copy_buffer_to_buffer( command_encoder_id: CommandEncoderId, source: BufferId, source_offset: BufferAddress, @@ -73,10 +73,12 @@ pub extern "C" fn wgpu_command_encoder_copy_buffer_to_buffer( destination_offset: BufferAddress, size: BufferAddress, ) { + let hub = B::hub(); let mut token = Token::root(); - let (mut cmb_guard, mut token) = HUB.command_buffers.write(&mut token); + + let (mut cmb_guard, mut token) = hub.command_buffers.write(&mut token); let cmb = &mut cmb_guard[command_encoder_id]; - let (buffer_guard, _) = HUB.buffers.read(&mut token); + let (buffer_guard, _) = hub.buffers.read(&mut token); // we can't hold both src_pending and dst_pending in scope because they // borrow the buffer tracker mutably... let mut barriers = Vec::new(); @@ -120,17 +122,35 @@ pub extern "C" fn wgpu_command_encoder_copy_buffer_to_buffer( } #[no_mangle] -pub extern "C" fn wgpu_command_encoder_copy_buffer_to_texture( +pub extern "C" fn wgpu_command_encoder_copy_buffer_to_buffer( + command_encoder_id: CommandEncoderId, + source: BufferId, + source_offset: BufferAddress, + destination: BufferId, + destination_offset: BufferAddress, + size: BufferAddress, +) { + gfx_select!(command_encoder_id => command_encoder_copy_buffer_to_buffer( + command_encoder_id, + source, source_offset, + destination, + destination_offset, + size)) +} + +pub fn command_encoder_copy_buffer_to_texture( command_encoder_id: CommandEncoderId, source: &BufferCopyView, destination: &TextureCopyView, copy_size: Extent3d, ) { + let hub = B::hub(); let mut token = Token::root(); - let (mut cmb_guard, mut token) = HUB.command_buffers.write(&mut token); + + let (mut cmb_guard, mut token) = hub.command_buffers.write(&mut token); let cmb = &mut cmb_guard[command_encoder_id]; - let (buffer_guard, mut token) = HUB.buffers.read(&mut token); - let (texture_guard, _) = HUB.textures.read(&mut token); + let (buffer_guard, mut token) = hub.buffers.read(&mut token); + let (texture_guard, _) = hub.textures.read(&mut token); let aspects = texture_guard[destination.texture].full_range.aspects; let (src_buffer, src_pending) = cmb @@ -198,17 +218,31 @@ pub extern "C" fn wgpu_command_encoder_copy_buffer_to_texture( } #[no_mangle] -pub extern "C" fn wgpu_command_encoder_copy_texture_to_buffer( +pub extern "C" fn wgpu_command_encoder_copy_buffer_to_texture( + command_encoder_id: CommandEncoderId, + source: &BufferCopyView, + destination: &TextureCopyView, + copy_size: Extent3d, +) { + gfx_select!(command_encoder_id => command_encoder_copy_buffer_to_texture( + command_encoder_id, + source, + destination, + copy_size)) +} + +pub fn command_encoder_copy_texture_to_buffer( command_encoder_id: CommandEncoderId, source: &TextureCopyView, destination: &BufferCopyView, copy_size: Extent3d, ) { + let hub = B::hub(); let mut token = Token::root(); - let (mut cmb_guard, mut token) = HUB.command_buffers.write(&mut token); + let (mut cmb_guard, mut token) = hub.command_buffers.write(&mut token); let cmb = &mut cmb_guard[command_encoder_id]; - let (buffer_guard, mut token) = HUB.buffers.read(&mut token); - let (texture_guard, _) = HUB.textures.read(&mut token); + let (buffer_guard, mut token) = hub.buffers.read(&mut token); + let (texture_guard, _) = hub.textures.read(&mut token); let aspects = texture_guard[source.texture].full_range.aspects; let (src_texture, src_pending) = cmb.trackers.textures.use_replace( @@ -225,7 +259,6 @@ pub extern "C" fn wgpu_command_encoder_copy_texture_to_buffer( }); match src_texture.placement { TexturePlacement::SwapChain(_) => unimplemented!(), - TexturePlacement::Void => unreachable!(), TexturePlacement::Memory(_) => (), } @@ -275,17 +308,32 @@ pub extern "C" fn wgpu_command_encoder_copy_texture_to_buffer( } #[no_mangle] -pub extern "C" fn wgpu_command_encoder_copy_texture_to_texture( +pub extern "C" fn wgpu_command_encoder_copy_texture_to_buffer( + command_encoder_id: CommandEncoderId, + source: &TextureCopyView, + destination: &BufferCopyView, + copy_size: Extent3d, +) { + gfx_select!(command_encoder_id => command_encoder_copy_texture_to_buffer( + command_encoder_id, + source, + destination, + copy_size)) +} + +pub fn command_encoder_copy_texture_to_texture( command_encoder_id: CommandEncoderId, source: &TextureCopyView, destination: &TextureCopyView, copy_size: Extent3d, ) { + let hub = B::hub(); let mut token = Token::root(); - let (mut cmb_guard, mut token) = HUB.command_buffers.write(&mut token); + + let (mut cmb_guard, mut token) = hub.command_buffers.write(&mut token); let cmb = &mut cmb_guard[command_encoder_id]; - let (_, mut token) = HUB.buffers.read(&mut token); // skip token - let (texture_guard, _) = HUB.textures.read(&mut token); + let (_, mut token) = hub.buffers.read(&mut token); // skip token + let (texture_guard, _) = hub.textures.read(&mut token); // we can't hold both src_pending and dst_pending in scope because they // borrow the buffer tracker mutably... let mut barriers = Vec::new(); @@ -350,3 +398,17 @@ pub extern "C" fn wgpu_command_encoder_copy_texture_to_texture( ); } } + +#[no_mangle] +pub extern "C" fn wgpu_command_encoder_copy_texture_to_texture( + command_encoder_id: CommandEncoderId, + source: &TextureCopyView, + destination: &TextureCopyView, + copy_size: Extent3d, +) { + gfx_select!(command_encoder_id => command_encoder_copy_texture_to_texture( + command_encoder_id, + source, + destination, + copy_size)) +} diff --git a/wgpu-native/src/conv.rs b/wgpu-native/src/conv.rs index 1669c46c5..23d6530ee 100644 --- a/wgpu-native/src/conv.rs +++ b/wgpu-native/src/conv.rs @@ -451,7 +451,6 @@ pub fn map_texture_dimension_size( } } -#[cfg(feature = "local")] pub fn map_texture_view_dimension( dimension: resource::TextureViewDimension, ) -> hal::image::ViewKind { diff --git a/wgpu-native/src/device.rs b/wgpu-native/src/device.rs index c9264bd5f..b39462873 100644 --- a/wgpu-native/src/device.rs +++ b/wgpu-native/src/device.rs @@ -1,45 +1,46 @@ use crate::{ + gfx_select, binding_model, command, conv, - hub::{HUB, Root, Token}, + hub::{GLOBAL, GfxBackend, Token}, + id::{Input, Output}, pipeline, resource, swap_chain, track::{Stitch, TrackerSet}, AdapterId, BindGroupId, + BindGroupLayoutId, BufferAddress, BufferId, BufferMapAsyncStatus, BufferMapOperation, CommandBufferId, + CommandEncoderId, + ComputePipelineId, DeviceId, LifeGuard, + PipelineLayoutId, QueueId, RefCount, + RenderPipelineId, + SamplerId, + ShaderModuleId, Stored, SubmissionIndex, SurfaceId, + SwapChainId, TextureId, TextureViewId, TextureDimension, }; -#[cfg(feature = "local")] +#[cfg(not(feature = "remote"))] use crate::{ instance::Limits, - BindGroupLayoutId, - CommandEncoderId, - ComputePipelineId, - PipelineLayoutId, - RenderPipelineId, - SamplerId, - ShaderModuleId, - SwapChainId, }; use arrayvec::ArrayVec; -use back; use copyless::VecHelper as _; use hal::{ self, @@ -54,9 +55,18 @@ use parking_lot::Mutex; use rendy_descriptor::{DescriptorSet, DescriptorAllocator, DescriptorRanges}; use rendy_memory::{Block, Heaps, MemoryBlock}; -#[cfg(feature = "local")] -use std::sync::atomic::AtomicBool; -use std::{collections::hash_map::Entry, ffi, iter, ptr, ops::Range, slice, sync::atomic::Ordering}; +use std::{ + collections::hash_map::Entry, + ffi, + iter, + ptr, + ops::Range, + slice, + sync::atomic::{AtomicBool, Ordering}, +}; +#[cfg(not(feature = "remote"))] +use std::marker::PhantomData; + const CLEANUP_WAIT_MS: u64 = 5000; pub const MAX_COLOR_TARGETS: usize = 4; @@ -170,10 +180,7 @@ struct PendingResources { ready_to_map: Vec, } -unsafe impl Send for PendingResources {} -unsafe impl Sync for PendingResources {} - -impl PendingResources { +impl PendingResources { fn destroy(&mut self, resource_id: ResourceId, ref_count: RefCount) { debug_assert!(!self.referenced.iter().any(|r| r.0 == resource_id)); self.referenced.push((resource_id, ref_count)); @@ -253,12 +260,12 @@ impl PendingResources { last_done } -} -type DeviceToken<'a> = Token<'a, Device>; - -impl PendingResources { - fn triage_referenced(&mut self, trackers: &mut TrackerSet, mut token: &mut DeviceToken) { + fn triage_referenced( + &mut self, + 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 @@ -268,11 +275,13 @@ impl PendingResources { if self.referenced.iter().all(|r| r.1.load() >= MIN_REFS) { return; } + + let hub = B::hub(); //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); - let (mut texture_guard, mut token) = HUB.textures.write(&mut token); - let (mut teview_view_guard, _) = HUB.texture_views.write(&mut token); + let (mut bind_group_guard, mut token) = hub.bind_groups.write(&mut token); + let (mut buffer_guard, mut token) = hub.buffers.write(&mut token); + let (mut texture_guard, mut token) = hub.textures.write(&mut token); + let (mut teview_view_guard, _) = hub.texture_views.write(&mut token); for i in (0 .. self.referenced.len()).rev() { let num_refs = self.referenced[i].1.load(); @@ -290,35 +299,34 @@ impl PendingResources { } trackers.buffers.remove(id); let buf = buffer_guard.remove(id); - #[cfg(feature = "local")] - HUB.buffers.identity.lock().free(id); + #[cfg(not(feature = "remote"))] + 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); - #[cfg(feature = "local")] - HUB.textures.identity.lock().free(id); + #[cfg(not(feature = "remote"))] + hub.textures.identity.lock().free(id); let memory = match tex.placement { // swapchain-owned images don't need explicit destruction resource::TexturePlacement::SwapChain(_) => continue, resource::TexturePlacement::Memory(mem) => mem, - resource::TexturePlacement::Void => unreachable!(), }; (tex.life_guard, NativeResource::Image(tex.raw, memory)) } ResourceId::TextureView(id) => { trackers.views.remove(id); let view = teview_view_guard.remove(id); - #[cfg(feature = "local")] - HUB.texture_views.identity.lock().free(id); + #[cfg(not(feature = "remote"))] + hub.texture_views.identity.lock().free(id); (view.life_guard, NativeResource::ImageView(view.raw)) } ResourceId::BindGroup(id) => { trackers.bind_groups.remove(id); let bind_group = bind_group_guard.remove(id); - #[cfg(feature = "local")] - HUB.bind_groups.identity.lock().free(id); + #[cfg(not(feature = "remote"))] + hub.bind_groups.identity.lock().free(id); (bind_group.life_guard, NativeResource::DescriptorSet(bind_group.raw)) } }; @@ -334,11 +342,11 @@ impl PendingResources { } } - fn triage_mapped(&mut self, mut token: &mut DeviceToken) { + fn triage_mapped(&mut self, token: &mut Token>) { if self.mapped.is_empty() { return; } - let (buffer_guard, _) = HUB.buffers.read(&mut token); + let (buffer_guard, _) = B::hub().buffers.read(token); for stored in self.mapped.drain(..) { let resource_id = stored.value; @@ -362,13 +370,10 @@ impl PendingResources { fn triage_framebuffers( &mut self, - framebuffers: &mut FastHashMap< - FramebufferKey, - ::Framebuffer, - >, - mut token: &mut DeviceToken, + framebuffers: &mut FastHashMap, + token: &mut Token>, ) { - let (texture_view_guard, _) = HUB.texture_views.read(&mut token); + let (texture_view_guard, _) = B::hub().texture_views.read(token); let remove_list = framebuffers .keys() .filter_map(|key| { @@ -403,13 +408,13 @@ impl PendingResources { fn handle_mapping( &mut self, - raw: &::Device, - mut token: &mut DeviceToken, + raw: &B::Device, + token: &mut Token>, ) -> Vec { if self.ready_to_map.is_empty() { return Vec::new() } - let (mut buffer_guard, _) = HUB.buffers.write(&mut token); + let (mut buffer_guard, _) = B::hub().buffers.write(token); self.ready_to_map .drain(..) .map(|buffer_id| { @@ -432,9 +437,9 @@ impl PendingResources { type BufferMapResult = Result<*mut u8, hal::mapping::Error>; type BufferMapPendingCallback = (BufferMapOperation, BufferMapResult); -fn map_buffer( - raw: &::Device, - buffer: &mut resource::Buffer, +fn map_buffer( + raw: &B::Device, + buffer: &mut resource::Buffer, buffer_range: Range, kind: HostMap, ) -> BufferMapResult { @@ -478,7 +483,7 @@ pub struct Device { pending: Mutex>, } -impl Device { +impl Device { pub(crate) fn new( raw: B::Device, adapter_id: AdapterId, @@ -524,7 +529,7 @@ impl Device { desc_allocator: Mutex::new(DescriptorAllocator::new()), queue_group, life_guard, - trackers: Mutex::new(TrackerSet::new()), + trackers: Mutex::new(TrackerSet::new(B::VARIANT)), render_passes: Mutex::new(FastHashMap::default()), framebuffers: Mutex::new(FastHashMap::default()), pending: Mutex::new(PendingResources { @@ -536,11 +541,9 @@ impl Device { }), } } -} -impl Device { fn maintain( - &self, force_wait: bool, token: &mut DeviceToken, + &self, force_wait: bool, token: &mut Token, ) -> Vec { let mut pending = self.pending.lock(); let mut trackers = self.trackers.lock(); @@ -581,9 +584,133 @@ impl Device { } } } + + fn create_buffer( + &self, self_id: DeviceId, desc: &resource::BufferDescriptor + ) -> resource::Buffer { + debug_assert_eq!(self_id.backend(), B::VARIANT); + let (usage, _memory_properties) = conv::map_buffer_usage(desc.usage); + + let rendy_usage = { + use resource::BufferUsage as Bu; + use rendy_memory::MemoryUsageValue as Muv; + + if !desc.usage.intersects(Bu::MAP_READ | Bu::MAP_WRITE) { + Muv::Data + } else if (Bu::MAP_WRITE | Bu::COPY_SRC).contains(desc.usage) { + Muv::Upload + } else if (Bu::MAP_READ | Bu::COPY_DST).contains(desc.usage) { + Muv::Download + } else { + Muv::Dynamic + } + }; + + let mut buffer = unsafe { self.raw.create_buffer(desc.size, usage).unwrap() }; + let requirements = unsafe { self.raw.get_buffer_requirements(&buffer) }; + let memory = self.mem_allocator + .lock() + .allocate( + &self.raw, + requirements.type_mask as u32, + rendy_usage, + requirements.size, + requirements.alignment, + ) + .unwrap(); + + unsafe { + self.raw + .bind_buffer_memory(memory.memory(), memory.range().start, &mut buffer) + .unwrap() + }; + + resource::Buffer { + raw: buffer, + device_id: Stored { + value: self_id, + ref_count: self.life_guard.ref_count.clone(), + }, + memory, + size: desc.size, + mapped_write_ranges: Vec::new(), + pending_map_operation: None, + life_guard: LifeGuard::new(), + } + } + + fn create_texture( + &self, + self_id: DeviceId, + desc: &resource::TextureDescriptor, + ) -> resource::Texture { + debug_assert_eq!(self_id.backend(), B::VARIANT); + let kind = conv::map_texture_dimension_size(desc.dimension, desc.size, desc.array_layer_count, desc.sample_count); + let format = conv::map_texture_format(desc.format); + let aspects = format.surface_desc().aspects; + let usage = conv::map_texture_usage(desc.usage, aspects); + + assert!((desc.mip_level_count as usize) < MAX_MIP_LEVELS); + let mut view_capabilities = hal::image::ViewCapabilities::empty(); + + // 2D textures with array layer counts that are multiples of 6 could be cubemaps + // Following gpuweb/gpuweb#68 always add the hint in that case + if desc.dimension == TextureDimension::D2 && desc.array_layer_count % 6 == 0 { + view_capabilities |= hal::image::ViewCapabilities::KIND_CUBE; + }; + + // TODO: 2D arrays, cubemap arrays + + let mut image = unsafe { + self.raw.create_image( + kind, + desc.mip_level_count as hal::image::Level, + format, + hal::image::Tiling::Optimal, + usage, + view_capabilities, + ) + } + .unwrap(); + let requirements = unsafe { self.raw.get_image_requirements(&image) }; + + let memory = self.mem_allocator + .lock() + .allocate( + &self.raw, + requirements.type_mask as u32, + rendy_memory::Data, + requirements.size, + requirements.alignment, + ) + .unwrap(); + + unsafe { + self.raw + .bind_image_memory(memory.memory(), memory.range().start, &mut image) + .unwrap() + }; + + resource::Texture { + raw: image, + device_id: Stored { + value: self_id, + ref_count: self.life_guard.ref_count.clone(), + }, + kind, + format: desc.format, + full_range: hal::image::SubresourceRange { + aspects, + levels: 0 .. desc.mip_level_count as hal::image::Level, + layers: 0 .. desc.array_layer_count as hal::image::Layer, + }, + placement: resource::TexturePlacement::Memory(memory), + life_guard: LifeGuard::new(), + } + } } -#[cfg(feature = "local")] +#[cfg(not(feature = "remote"))] #[no_mangle] pub extern "C" fn wgpu_device_get_limits( _device_id: DeviceId, @@ -597,137 +724,106 @@ pub struct ShaderModule { pub(crate) raw: B::ShaderModule, } -pub fn device_create_buffer( +pub fn device_create_buffer( device_id: DeviceId, desc: &resource::BufferDescriptor, -) -> resource::Buffer { - let (device_guard, _) = HUB.devices.read(&mut Token::root()); + id_in: Input, +) -> Output { + let hub = B::hub(); + let mut token = Token::root(); + + let (device_guard, _) = hub.devices.read(&mut token); let device = &device_guard[device_id]; - let (usage, _memory_properties) = conv::map_buffer_usage(desc.usage); + let buffer = device.create_buffer(device_id, desc); - let rendy_usage = { - use resource::BufferUsage as Bu; - use rendy_memory::MemoryUsageValue as Muv; - - if !desc.usage.intersects(Bu::MAP_READ | Bu::MAP_WRITE) { - Muv::Data - } else if (Bu::MAP_WRITE | Bu::COPY_SRC).contains(desc.usage) { - Muv::Upload - } else if (Bu::MAP_READ | Bu::COPY_DST).contains(desc.usage) { - Muv::Download - } else { - Muv::Dynamic - } - }; - - let mut buffer = unsafe { device.raw.create_buffer(desc.size, usage).unwrap() }; - let requirements = unsafe { device.raw.get_buffer_requirements(&buffer) }; - let memory = device.mem_allocator - .lock() - .allocate( - &device.raw, - requirements.type_mask as u32, - rendy_usage, - requirements.size, - requirements.alignment, - ) - .unwrap(); - - unsafe { - device.raw - .bind_buffer_memory(memory.memory(), memory.range().start, &mut buffer) - .unwrap() - }; - - resource::Buffer { - raw: buffer, - device_id: Stored { - value: device_id, - ref_count: device.life_guard.ref_count.clone(), - }, - memory, - size: desc.size, - mapped_write_ranges: Vec::new(), - pending_map_operation: None, - life_guard: LifeGuard::new(), - } -} - -pub fn device_track_buffer( - device_id: DeviceId, - buffer_id: BufferId, - ref_count: RefCount, - flags: resource::BufferUsage, - token: &mut Token, -) { - let (device_guard, _) = HUB.devices.read(token); - let ok = device_guard[device_id] - .trackers + let (id, id_out) = hub.buffers.new_identity(id_in); + let ok = device.trackers .lock() .buffers - .init(buffer_id, &ref_count, (), flags); + .init( + id, + &buffer.life_guard.ref_count, + (), + resource::BufferUsage::empty(), + ); assert!(ok); + + hub.buffers.register(id, buffer, &mut token); + id_out } -#[cfg(feature = "local")] +#[cfg(not(feature = "remote"))] #[no_mangle] pub extern "C" fn wgpu_device_create_buffer( device_id: DeviceId, desc: &resource::BufferDescriptor, ) -> BufferId { - let buffer = device_create_buffer(device_id, desc); - let ref_count = buffer.life_guard.ref_count.clone(); - let mut token = Token::root(); - let id = HUB.buffers.register_local(buffer, &mut token); - device_track_buffer(device_id, id, ref_count, resource::BufferUsage::empty(), &mut token); - id + gfx_select!(device_id => device_create_buffer(device_id, desc, PhantomData)) } -#[cfg(feature = "local")] +pub fn device_create_buffer_mapped( + device_id: DeviceId, + desc: &resource::BufferDescriptor, + mapped_ptr_out: *mut *mut u8, + id_in: Input, +) -> Output { + let hub = B::hub(); + let mut token = Token::root(); + let mut desc = desc.clone(); + desc.usage |= resource::BufferUsage::MAP_WRITE; + + let (device_guard, _) = hub.devices.read(&mut token); + let device = &device_guard[device_id]; + let mut buffer = device.create_buffer(device_id, &desc); + + match map_buffer( + &device.raw, + &mut buffer, + 0 .. desc.size, + HostMap::Write, + ) { + Ok(ptr) => unsafe { + *mapped_ptr_out = ptr; + }, + Err(e) => { + log::error!("failed to create buffer in a mapped state: {}", e); + unsafe { + *mapped_ptr_out = ptr::null_mut(); + } + } + } + + let (id, id_out) = hub.buffers.new_identity(id_in); + let ok = device.trackers + .lock() + .buffers + .init( + id, + &buffer.life_guard.ref_count, + (), + resource::BufferUsage::MAP_WRITE, + ); + assert!(ok); + + hub.buffers.register(id, buffer, &mut token); + id_out +} + +#[cfg(not(feature = "remote"))] #[no_mangle] pub extern "C" fn wgpu_device_create_buffer_mapped( device_id: DeviceId, desc: &resource::BufferDescriptor, mapped_ptr_out: *mut *mut u8, ) -> BufferId { - let mut desc = desc.clone(); - desc.usage |= resource::BufferUsage::MAP_WRITE; - let mut buffer = device_create_buffer(device_id, &desc); - let mut token = Token::root(); - - { - let (device_guard, _) = HUB.devices.read(&mut token); - let device = &device_guard[device_id]; - - match map_buffer( - &device.raw, - &mut buffer, - 0 .. desc.size, - HostMap::Write, - ) { - Ok(ptr) => unsafe { - *mapped_ptr_out = ptr; - }, - Err(e) => { - log::error!("failed to create buffer in a mapped state: {}", e); - unsafe { - *mapped_ptr_out = ptr::null_mut(); - } - } - } - } - - let ref_count = buffer.life_guard.ref_count.clone(); - let id = HUB.buffers.register_local(buffer, &mut token); - device_track_buffer(device_id, id, ref_count, resource::BufferUsage::MAP_WRITE, &mut token); - id + gfx_select!(device_id => device_create_buffer_mapped(device_id, desc, mapped_ptr_out, PhantomData)) } -#[no_mangle] -pub extern "C" fn wgpu_buffer_destroy(buffer_id: BufferId) { +pub fn buffer_destroy(buffer_id: BufferId) { + let hub = B::hub(); let mut token = Token::root(); - let (device_guard, mut token) = HUB.devices.read(&mut token); - let (buffer_guard, _) = HUB.buffers.read(&mut token); + let (device_guard, mut token) = hub.devices.read(&mut token); + let (buffer_guard, _) = hub.buffers.read(&mut token); let buffer = &buffer_guard[buffer_id]; device_guard[buffer.device_id.value].pending.lock().destroy( ResourceId::Buffer(buffer_id), @@ -735,180 +831,61 @@ pub extern "C" fn wgpu_buffer_destroy(buffer_id: BufferId) { ); } -pub fn device_create_texture( - device_id: DeviceId, - desc: &resource::TextureDescriptor, -) -> resource::Texture { - let kind = conv::map_texture_dimension_size(desc.dimension, desc.size, desc.array_layer_count, desc.sample_count); - let format = conv::map_texture_format(desc.format); - let aspects = format.surface_desc().aspects; - let usage = conv::map_texture_usage(desc.usage, aspects); - - let (device_guard, _) = HUB.devices.read(&mut Token::root()); - let device = &device_guard[device_id]; - - assert!((desc.mip_level_count as usize) < MAX_MIP_LEVELS); - - let mut view_capabilities = hal::image::ViewCapabilities::empty(); - - // 2D textures with array layer counts that are multiples of 6 could be cubemaps - // Following gpuweb/gpuweb#68 always add the hint in that case - if desc.dimension == TextureDimension::D2 && desc.array_layer_count % 6 == 0 { - view_capabilities |= hal::image::ViewCapabilities::KIND_CUBE; - }; - - // TODO: 2D arrays, cubemap arrays - - let mut image = unsafe { - device.raw.create_image( - kind, - desc.mip_level_count as hal::image::Level, - format, - hal::image::Tiling::Optimal, - usage, - view_capabilities, - ) - } - .unwrap(); - let requirements = unsafe { device.raw.get_image_requirements(&image) }; - - let memory = device.mem_allocator - .lock() - .allocate( - &device.raw, - requirements.type_mask as u32, - rendy_memory::Data, - requirements.size, - requirements.alignment, - ) - .unwrap(); - - unsafe { - device.raw - .bind_image_memory(memory.memory(), memory.range().start, &mut image) - .unwrap() - }; - - resource::Texture { - raw: image, - device_id: Stored { - value: device_id, - ref_count: device.life_guard.ref_count.clone(), - }, - kind, - format: desc.format, - full_range: hal::image::SubresourceRange { - aspects, - levels: 0 .. desc.mip_level_count as hal::image::Level, - layers: 0 .. desc.array_layer_count as hal::image::Layer, - }, - placement: resource::TexturePlacement::Memory(memory), - life_guard: LifeGuard::new(), - } +#[no_mangle] +pub extern "C" fn wgpu_buffer_destroy(buffer_id: BufferId) { + gfx_select!(buffer_id => buffer_destroy(buffer_id)) } -pub fn device_track_texture( +pub fn device_create_texture( device_id: DeviceId, - texture_id: TextureId, - ref_count: RefCount, - full_range: hal::image::SubresourceRange, - token: &mut Token, -) { - let (device_guard, _) = HUB.devices.read(token); - let ok = device_guard[device_id] - .trackers + desc: &resource::TextureDescriptor, + id_in: Input, +) -> Output { + let hub = B::hub(); + let mut token = Token::root(); + + let (device_guard, _) = hub.devices.read(&mut token); + let device = &device_guard[device_id]; + let texture = device.create_texture(device_id, desc); + + let (id, id_out) = hub.textures.new_identity(id_in); + let ok = device.trackers .lock() .textures .init( - texture_id, - &ref_count, - full_range, + id, + &texture.life_guard.ref_count, + texture.full_range.clone(), resource::TextureUsage::UNINITIALIZED, ); assert!(ok); + + hub.textures.register(id, texture, &mut token); + id_out + } -#[cfg(feature = "local")] +#[cfg(not(feature = "remote"))] #[no_mangle] pub extern "C" fn wgpu_device_create_texture( device_id: DeviceId, desc: &resource::TextureDescriptor, ) -> TextureId { - let texture = device_create_texture(device_id, desc); - let ref_count = texture.life_guard.ref_count.clone(); - let range = texture.full_range.clone(); - let mut token = Token::root(); - let id = HUB.textures.register_local(texture, &mut token); - device_track_texture(device_id, id, ref_count, range, &mut token); - id + gfx_select!(device_id => device_create_texture(device_id, desc, PhantomData)) } -pub fn texture_create_view( - texture_id: TextureId, - format: resource::TextureFormat, - view_kind: hal::image::ViewKind, - range: hal::image::SubresourceRange, - token: &mut Token, -) -> resource::TextureView { - let (device_guard, mut token) = HUB.devices.read(token); - let (texture_guard, _) = HUB.textures.read(&mut token); - let texture = &texture_guard[texture_id]; - - let raw = unsafe { - device_guard[texture.device_id.value] - .raw - .create_image_view( - &texture.raw, - view_kind, - conv::map_texture_format(format), - hal::format::Swizzle::NO, - range.clone(), - ) - .unwrap() - }; - - resource::TextureView { - raw, - texture_id: Stored { - value: texture_id, - ref_count: texture.life_guard.ref_count.clone(), - }, - format: texture.format, - extent: texture.kind.extent().at_level(range.levels.start), - samples: texture.kind.num_samples(), - range, - is_owned_by_swap_chain: false, - life_guard: LifeGuard::new(), - } -} - -pub fn device_track_view( - texture_id: TextureId, - view_id: TextureViewId, - ref_count: RefCount, - token: &mut Token, -) { - let (device_guard, mut token) = HUB.devices.read(token); - let (texture_guard, _) = HUB.textures.read(&mut token); - - let device_id = texture_guard[texture_id].device_id.value; - let ok = device_guard[device_id] - .trackers - .lock() - .views - .init(view_id, &ref_count, (), ()); - assert!(ok); -} - -#[cfg(feature = "local")] -#[no_mangle] -pub extern "C" fn wgpu_texture_create_view( +pub fn texture_create_view( texture_id: TextureId, desc: Option<&resource::TextureViewDescriptor>, -) -> TextureViewId { + id_in: Input +) -> Output { + let hub = B::hub(); let mut token = Token::root(); - let (texture_guard, _) = HUB.textures.read(&mut token); + + let (device_guard, mut token) = hub.devices.read(&mut token); + let (texture_guard, mut token) = hub.textures.read(&mut token); let texture = &texture_guard[texture_id]; + let device = &device_guard[texture.device_id.value]; let (format, view_kind, range) = match desc { Some(desc) => { @@ -946,18 +923,63 @@ pub extern "C" fn wgpu_texture_create_view( } }; - let view = texture_create_view(texture_id, format, view_kind, range, &mut token); - let ref_count = view.life_guard.ref_count.clone(); - let id = HUB.texture_views.register_local(view, &mut token); - device_track_view(texture_id, id, ref_count, &mut token); - id + let raw = unsafe { + device.raw + .create_image_view( + &texture.raw, + view_kind, + conv::map_texture_format(format), + hal::format::Swizzle::NO, + range.clone(), + ) + .unwrap() + }; + + let view = resource::TextureView { + raw, + texture_id: Stored { + value: texture_id, + ref_count: texture.life_guard.ref_count.clone(), + }, + format: texture.format, + extent: texture.kind.extent().at_level(range.levels.start), + samples: texture.kind.num_samples(), + range, + is_owned_by_swap_chain: false, + life_guard: LifeGuard::new(), + }; + + let (id, id_out) = hub.texture_views.new_identity(id_in); + let ok = device.trackers + .lock() + .views + .init( + id, + &view.life_guard.ref_count, + (), + (), + ); + assert!(ok); + + hub.texture_views.register(id, view, &mut token); + id_out } +#[cfg(not(feature = "remote"))] #[no_mangle] -pub extern "C" fn wgpu_texture_destroy(texture_id: TextureId) { +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)) +} + +pub fn texture_destroy(texture_id: TextureId) { + let hub = B::hub(); let mut token = Token::root(); - let (device_guard, mut token) = HUB.devices.read(&mut token); - let (texture_guard, _) = HUB.textures.read(&mut token); + + let (device_guard, mut token) = hub.devices.read(&mut token); + let (texture_guard, _) = hub.textures.read(&mut token); let texture = &texture_guard[texture_id]; device_guard[texture.device_id.value] .pending @@ -969,11 +991,16 @@ pub extern "C" fn wgpu_texture_destroy(texture_id: TextureId) { } #[no_mangle] -pub extern "C" fn wgpu_texture_view_destroy(texture_view_id: TextureViewId) { +pub extern "C" fn wgpu_texture_destroy(texture_id: TextureId) { + gfx_select!(texture_id => texture_destroy(texture_id)) +} + +pub fn texture_view_destroy(texture_view_id: TextureViewId) { + let hub = B::hub(); 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 (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 = texture_guard[view.texture_id.value].device_id.value; device_guard[device_id].pending.lock().destroy( @@ -982,12 +1009,19 @@ pub extern "C" fn wgpu_texture_view_destroy(texture_view_id: TextureViewId) { ); } -pub fn device_create_sampler( +#[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)) +} + +pub fn device_create_sampler( device_id: DeviceId, desc: &resource::SamplerDescriptor, - token: &mut Token, -) -> resource::Sampler { - let (device_guard, _) = HUB.devices.read(token); + id_in: Input, +) -> Output { + let hub = B::hub(); + let mut token = Token::root(); + let (device_guard, mut token) = hub.devices.read(&mut token); let device = &device_guard[device_id]; let info = hal::image::SamplerInfo { @@ -1010,27 +1044,29 @@ pub fn device_create_sampler( normalized: true, anisotropic: hal::image::Anisotropic::Off, //TODO }; - let raw = unsafe { device.raw.create_sampler(info).unwrap() }; - resource::Sampler { raw } + let sampler = resource::Sampler { + raw: unsafe { device.raw.create_sampler(info).unwrap() }, + }; + hub.samplers.register_identity(id_in, sampler, &mut token) } -#[cfg(feature = "local")] +#[cfg(not(feature = "remote"))] #[no_mangle] pub extern "C" fn wgpu_device_create_sampler( device_id: DeviceId, desc: &resource::SamplerDescriptor, ) -> SamplerId { - let mut token = Token::root(); - let sampler = device_create_sampler(device_id, desc, &mut token); - HUB.samplers.register_local(sampler, &mut token) + gfx_select!(device_id => device_create_sampler(device_id, desc, PhantomData)) } -pub fn device_create_bind_group_layout( +pub fn device_create_bind_group_layout( device_id: DeviceId, desc: &binding_model::BindGroupLayoutDescriptor, - token: &mut Token, -) -> binding_model::BindGroupLayout { + id_in: Input, +) -> Output { + let mut token = Token::root(); + let hub = B::hub(); let bindings = unsafe { slice::from_raw_parts(desc.bindings, desc.bindings_length) }; let raw_bindings = bindings @@ -1045,14 +1081,14 @@ pub fn device_create_bind_group_layout( .collect::>(); //TODO: avoid heap allocation let raw = unsafe { - let (device_guard, _) = HUB.devices.read(token); + let (device_guard, _) = hub.devices.read(&mut token); device_guard[device_id] .raw .create_descriptor_set_layout(&raw_bindings, &[]) .unwrap() }; - binding_model::BindGroupLayout { + let layout = binding_model::BindGroupLayout { raw, bindings: bindings.to_vec(), desc_ranges: DescriptorRanges::from_bindings(&raw_bindings), @@ -1060,66 +1096,72 @@ pub fn device_create_bind_group_layout( .iter() .filter(|b| b.dynamic) .count(), - } + }; + + hub.bind_group_layouts.register_identity(id_in, layout, &mut token) } -#[cfg(feature = "local")] +#[cfg(not(feature = "remote"))] #[no_mangle] pub extern "C" fn wgpu_device_create_bind_group_layout( device_id: DeviceId, desc: &binding_model::BindGroupLayoutDescriptor, ) -> BindGroupLayoutId { - let mut token = Token::root(); - let layout = device_create_bind_group_layout(device_id, desc, &mut token); - HUB.bind_group_layouts.register_local(layout, &mut token) + gfx_select!(device_id => device_create_bind_group_layout(device_id, desc, PhantomData)) } -pub fn device_create_pipeline_layout( +pub fn device_create_pipeline_layout( device_id: DeviceId, desc: &binding_model::PipelineLayoutDescriptor, - token: &mut Token, -) -> binding_model::PipelineLayout { - let (device_guard, mut token) = HUB.devices.read(token); + id_in: Input, +) -> Output { + let hub = B::hub(); + let mut token = Token::root(); + + let (device_guard, mut token) = hub.devices.read(&mut token); let bind_group_layout_ids = unsafe { slice::from_raw_parts(desc.bind_group_layouts, desc.bind_group_layouts_length) }; - let (bind_group_layout_guard, _) = HUB.bind_group_layouts.read(&mut token); - let descriptor_set_layouts = bind_group_layout_ids - .iter() - .map(|&id| &bind_group_layout_guard[id].raw); // TODO: push constants - let pipeline_layout = unsafe { - device_guard[device_id] - .raw - .create_pipeline_layout(descriptor_set_layouts, &[]) - } - .unwrap(); + let pipeline_layout = { + let (bind_group_layout_guard, _) = hub.bind_group_layouts.read(&mut token); + let descriptor_set_layouts = bind_group_layout_ids + .iter() + .map(|&id| &bind_group_layout_guard[id].raw); + unsafe { + device_guard[device_id] + .raw + .create_pipeline_layout(descriptor_set_layouts, &[]) + }.unwrap() + }; - binding_model::PipelineLayout { + let layout = binding_model::PipelineLayout { raw: pipeline_layout, bind_group_layout_ids: bind_group_layout_ids.iter().cloned().collect(), - } + }; + hub.pipeline_layouts.register_identity(id_in, layout, &mut token) } -#[cfg(feature = "local")] +#[cfg(not(feature = "remote"))] #[no_mangle] pub extern "C" fn wgpu_device_create_pipeline_layout( device_id: DeviceId, desc: &binding_model::PipelineLayoutDescriptor, ) -> PipelineLayoutId { - let mut token = Token::root(); - let layout = device_create_pipeline_layout(device_id, desc, &mut token); - HUB.pipeline_layouts.register_local(layout, &mut token) + gfx_select!(device_id => device_create_pipeline_layout(device_id, desc, PhantomData)) } -pub fn device_create_bind_group( +pub fn device_create_bind_group( device_id: DeviceId, desc: &binding_model::BindGroupDescriptor, - token: &mut Token, -) -> binding_model::BindGroup { - let (device_guard, mut token) = HUB.devices.read(token); + id_in: Input, +) -> Output { + let hub = B::hub(); + let mut token = Token::root(); + + let (device_guard, mut token) = hub.devices.read(&mut token); let device = &device_guard[device_id]; - let (bind_group_layout_guard, _) = HUB.bind_group_layouts.read(&mut token); + let (bind_group_layout_guard, _) = hub.bind_group_layouts.read(&mut token); let bind_group_layout = &bind_group_layout_guard[desc.layout]; let bindings = unsafe { slice::from_raw_parts(desc.bindings, desc.bindings_length as usize) }; assert_eq!(bindings.len(), bind_group_layout.bindings.len()); @@ -1139,104 +1181,107 @@ pub fn device_create_bind_group( desc_sets.pop().unwrap() }; - let (buffer_guard, mut token) = HUB.buffers.read(&mut token); - let (_, mut token) = HUB.textures.read(&mut token); //skip token - let (texture_view_guard, mut token) = HUB.texture_views.read(&mut token); - let (sampler_guard, _) = HUB.samplers.read(&mut token); + // fill out the descriptors + let mut used = TrackerSet::new(B::VARIANT); + { + let (buffer_guard, mut token) = hub.buffers.read(&mut token); + let (_, mut token) = hub.textures.read(&mut token); //skip token + let (texture_view_guard, mut token) = hub.texture_views.read(&mut token); + let (sampler_guard, _) = hub.samplers.read(&mut token); - //TODO: group writes into contiguous sections - let mut writes = Vec::new(); - let mut used = TrackerSet::new(); - for (b, decl) in bindings.iter().zip(&bind_group_layout.bindings) { - let descriptor = match b.resource { - binding_model::BindingResource::Buffer(ref bb) => { - let (alignment, usage) = match decl.ty { - binding_model::BindingType::UniformBuffer => { - (BIND_BUFFER_ALIGNMENT, resource::BufferUsage::UNIFORM) - } - binding_model::BindingType::StorageBuffer => { - (BIND_BUFFER_ALIGNMENT, resource::BufferUsage::STORAGE) - } - binding_model::BindingType::ReadonlyStorageBuffer => { - (BIND_BUFFER_ALIGNMENT, resource::BufferUsage::STORAGE_READ) - } - binding_model::BindingType::Sampler - | binding_model::BindingType::SampledTexture - | binding_model::BindingType::StorageTexture => { - panic!("Mismatched buffer binding for {:?}", decl) - } - }; - assert_eq!( - bb.offset as hal::buffer::Offset % alignment, - 0, - "Misaligned buffer offset {}", - bb.offset - ); - let buffer = used - .buffers - .use_extend(&*buffer_guard, bb.buffer, (), usage) - .unwrap(); - - let end = if bb.size == 0 { - None - } else { - let end = bb.offset + bb.size; - assert!( - end <= buffer.size, - "Bound buffer range {:?} does not fit in buffer size {}", - bb.offset .. end, - buffer.size + //TODO: group writes into contiguous sections + let mut writes = Vec::new(); + for (b, decl) in bindings.iter().zip(&bind_group_layout.bindings) { + let descriptor = match b.resource { + binding_model::BindingResource::Buffer(ref bb) => { + let (alignment, usage) = match decl.ty { + binding_model::BindingType::UniformBuffer => { + (BIND_BUFFER_ALIGNMENT, resource::BufferUsage::UNIFORM) + } + binding_model::BindingType::StorageBuffer => { + (BIND_BUFFER_ALIGNMENT, resource::BufferUsage::STORAGE) + } + binding_model::BindingType::ReadonlyStorageBuffer => { + (BIND_BUFFER_ALIGNMENT, resource::BufferUsage::STORAGE_READ) + } + binding_model::BindingType::Sampler + | binding_model::BindingType::SampledTexture + | binding_model::BindingType::StorageTexture => { + panic!("Mismatched buffer binding for {:?}", decl) + } + }; + assert_eq!( + bb.offset as hal::buffer::Offset % alignment, + 0, + "Misaligned buffer offset {}", + bb.offset ); - Some(end) - }; + let buffer = used + .buffers + .use_extend(&*buffer_guard, bb.buffer, (), usage) + .unwrap(); - let range = Some(bb.offset) .. end; - hal::pso::Descriptor::Buffer(&buffer.raw, range) - } - binding_model::BindingResource::Sampler(id) => { - assert_eq!(decl.ty, binding_model::BindingType::Sampler); - let sampler = &sampler_guard[id]; - hal::pso::Descriptor::Sampler(&sampler.raw) - } - binding_model::BindingResource::TextureView(id) => { - let (usage, image_layout) = match decl.ty { - binding_model::BindingType::SampledTexture => ( - resource::TextureUsage::SAMPLED, - hal::image::Layout::ShaderReadOnlyOptimal, - ), - binding_model::BindingType::StorageTexture => ( - resource::TextureUsage::STORAGE, - hal::image::Layout::General, - ), - _ => panic!("Mismatched texture binding for {:?}", decl), - }; - let view = used.views - .use_extend(&*texture_view_guard, id, (), ()) - .unwrap(); - used.textures - .change_extend( - view.texture_id.value, - &view.texture_id.ref_count, - view.range.clone(), - usage, - ) - .unwrap(); - hal::pso::Descriptor::Image(&view.raw, image_layout) - } - }; - writes.alloc().init(hal::pso::DescriptorSetWrite { - set: desc_set.raw(), - binding: b.binding, - array_offset: 0, //TODO - descriptors: iter::once(descriptor), - }); + let end = if bb.size == 0 { + None + } else { + let end = bb.offset + bb.size; + assert!( + end <= buffer.size, + "Bound buffer range {:?} does not fit in buffer size {}", + bb.offset .. end, + buffer.size + ); + Some(end) + }; + + let range = Some(bb.offset) .. end; + hal::pso::Descriptor::Buffer(&buffer.raw, range) + } + binding_model::BindingResource::Sampler(id) => { + assert_eq!(decl.ty, binding_model::BindingType::Sampler); + let sampler = &sampler_guard[id]; + hal::pso::Descriptor::Sampler(&sampler.raw) + } + binding_model::BindingResource::TextureView(id) => { + let (usage, image_layout) = match decl.ty { + binding_model::BindingType::SampledTexture => ( + resource::TextureUsage::SAMPLED, + hal::image::Layout::ShaderReadOnlyOptimal, + ), + binding_model::BindingType::StorageTexture => ( + resource::TextureUsage::STORAGE, + hal::image::Layout::General, + ), + _ => panic!("Mismatched texture binding for {:?}", decl), + }; + let view = used.views + .use_extend(&*texture_view_guard, id, (), ()) + .unwrap(); + used.textures + .change_extend( + view.texture_id.value, + &view.texture_id.ref_count, + view.range.clone(), + usage, + ) + .unwrap(); + hal::pso::Descriptor::Image(&view.raw, image_layout) + } + }; + writes.alloc().init(hal::pso::DescriptorSetWrite { + set: desc_set.raw(), + binding: b.binding, + array_offset: 0, //TODO + descriptors: iter::once(descriptor), + }); + } + + unsafe { + device.raw.write_descriptor_sets(writes); + } } - unsafe { - device.raw.write_descriptor_sets(writes); - } - - binding_model::BindGroup { + let bind_group = binding_model::BindGroup { raw: desc_set, device_id: Stored { value: device_id, @@ -1246,43 +1291,32 @@ pub fn device_create_bind_group( life_guard: LifeGuard::new(), used, dynamic_count: bind_group_layout.dynamic_count, - } -} - -pub fn device_track_bind_group( - device_id: DeviceId, - bind_group_id: BindGroupId, - ref_count: RefCount, - token: &mut Token, -) { - let (device_guard, _) = HUB.devices.read(token); - let ok = device_guard[device_id] - .trackers + }; + let (id, id_out) = hub.bind_groups.new_identity(id_in); + let ok = device.trackers .lock() .bind_groups - .init(bind_group_id, &ref_count, (), ()); + .init(id, &bind_group.life_guard.ref_count, (), ()); assert!(ok); + + hub.bind_groups.register(id, bind_group, &mut token); + id_out } -#[cfg(feature = "local")] +#[cfg(not(feature = "remote"))] #[no_mangle] pub extern "C" fn wgpu_device_create_bind_group( device_id: DeviceId, desc: &binding_model::BindGroupDescriptor, ) -> BindGroupId { - let mut token = Token::root(); - let bind_group = device_create_bind_group(device_id, desc, &mut token); - let ref_count = bind_group.life_guard.ref_count.clone(); - let id = HUB.bind_groups.register_local(bind_group, &mut token); - device_track_bind_group(device_id, id, ref_count, &mut token); - id + gfx_select!(device_id => device_create_bind_group(device_id, desc, PhantomData)) } -#[no_mangle] -pub extern "C" fn wgpu_bind_group_destroy(bind_group_id: BindGroupId) { +pub fn bind_group_destroy(bind_group_id: BindGroupId) { + let hub = B::hub(); 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); + let (device_guard, mut token) = hub.devices.read(&mut token); + let (bind_group_guard, _) = hub.bind_groups.read(&mut token); let bind_group = &bind_group_guard[bind_group_id]; device_guard[bind_group.device_id.value].pending.lock().destroy( ResourceId::BindGroup(bind_group_id), @@ -1290,65 +1324,77 @@ pub extern "C" fn wgpu_bind_group_destroy(bind_group_id: BindGroupId) { ); } -pub fn device_create_shader_module( - device_id: DeviceId, - desc: &pipeline::ShaderModuleDescriptor, - token: &mut Token, -) -> ShaderModule { - let spv = unsafe { slice::from_raw_parts(desc.code.bytes, desc.code.length) }; - let (device_guard, _) = HUB.devices.read(token); - let shader = unsafe { - device_guard[device_id] - .raw - .create_shader_module(spv) - .unwrap() - }; - - ShaderModule { raw: shader } +#[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)) } -#[cfg(feature = "local")] +pub fn device_create_shader_module( + device_id: DeviceId, + desc: &pipeline::ShaderModuleDescriptor, + id_in: Input +) -> Output { + let hub = B::hub(); + let mut token = Token::root(); + + let spv = unsafe { slice::from_raw_parts(desc.code.bytes, desc.code.length) }; + let shader = { + let (device_guard, _) = hub.devices.read(&mut token); + ShaderModule { + raw: unsafe { + device_guard[device_id] + .raw + .create_shader_module(spv) + .unwrap() + }, + } + }; + hub.shader_modules.register_identity(id_in, shader, &mut token) +} + +#[cfg(not(feature = "remote"))] #[no_mangle] pub extern "C" fn wgpu_device_create_shader_module( device_id: DeviceId, desc: &pipeline::ShaderModuleDescriptor, ) -> ShaderModuleId { - let mut token = Token::root(); - let module = device_create_shader_module(device_id, desc, &mut token); - HUB.shader_modules.register_local(module, &mut token) + gfx_select!(device_id => device_create_shader_module(device_id, desc, PhantomData)) } -pub fn device_create_command_encoder( +pub fn device_create_command_encoder( device_id: DeviceId, _desc: &command::CommandEncoderDescriptor, - token: &mut Token, -) -> command::CommandBuffer { - let (device_guard, _) = HUB.devices.read(token); + id_in: Input, +) -> Output { + let hub = B::hub(); + let mut token = Token::root(); + + let (device_guard, mut token) = hub.devices.read(&mut token); let device = &device_guard[device_id]; let dev_stored = Stored { value: device_id, ref_count: device.life_guard.ref_count.clone(), }; - let mut cmb = device.com_allocator.allocate(dev_stored, &device.raw); + let mut comb = device.com_allocator.allocate(dev_stored, &device.raw); unsafe { - cmb.raw.last_mut().unwrap().begin( + comb.raw.last_mut().unwrap().begin( hal::command::CommandBufferFlags::ONE_TIME_SUBMIT, hal::command::CommandBufferInheritanceInfo::default(), ); } - cmb + + hub.command_buffers.register_identity(id_in, comb, &mut token) } -#[cfg(feature = "local")] +#[cfg(not(feature = "remote"))] #[no_mangle] pub extern "C" fn wgpu_device_create_command_encoder( device_id: DeviceId, - desc: &command::CommandEncoderDescriptor, + desc: Option<&command::CommandEncoderDescriptor>, ) -> CommandEncoderId { - let mut token = Token::root(); - let cmb = device_create_command_encoder(device_id, desc, &mut token); - HUB.command_buffers.register_local(cmb, &mut token) + let desc = &desc.cloned().unwrap_or_default(); + gfx_select!(device_id => device_create_command_encoder(device_id, desc, PhantomData)) } #[no_mangle] @@ -1356,19 +1402,16 @@ pub extern "C" fn wgpu_device_get_queue(device_id: DeviceId) -> QueueId { device_id } -#[no_mangle] -pub extern "C" fn wgpu_queue_submit( +pub fn queue_submit( queue_id: QueueId, - command_buffers: *const CommandBufferId, - command_buffers_length: usize, + command_buffer_ids: &[CommandBufferId], ) { - let command_buffer_ids = - unsafe { slice::from_raw_parts(command_buffers, command_buffers_length) }; + let hub = B::hub(); let (submit_index, fence) = { let mut token = Token::root(); - let (surface_guard, mut token) = HUB.surfaces.read(&mut token); - let (mut device_guard, mut token) = HUB.devices.write(&mut token); + let (mut device_guard, mut token) = hub.devices.write(&mut token); + let (swap_chain_guard, mut token) = hub.swap_chains.read(&mut token); let device = &mut device_guard[queue_id]; let mut trackers = device.trackers.lock(); let mut wait_semaphores = Vec::new(); @@ -1382,17 +1425,17 @@ pub extern "C" fn wgpu_queue_submit( // native command buffer of the previous chain instead of always creating // a temporary one, since the chains are not finished. { - let (mut command_buffer_guard, mut token) = HUB.command_buffers.write(&mut token); - let (bind_group_guard, mut token) = HUB.bind_groups.read(&mut token); - let (buffer_guard, mut token) = HUB.buffers.read(&mut token); - let (texture_guard, mut token) = HUB.textures.read(&mut token); - let (texture_view_guard, _) = HUB.texture_views.read(&mut token); + let (mut command_buffer_guard, mut token) = hub.command_buffers.write(&mut token); + let (bind_group_guard, mut token) = hub.bind_groups.read(&mut token); + let (buffer_guard, mut token) = hub.buffers.read(&mut token); + let (texture_guard, mut token) = hub.textures.read(&mut token); + let (texture_view_guard, _) = hub.texture_views.read(&mut token); // finish all the command buffers first for &cmb_id in command_buffer_ids { let comb = &mut command_buffer_guard[cmb_id]; for link in comb.swap_chain_links.drain(..) { - let swap_chain = surface_guard[link.swap_chain_id].swap_chain.as_ref().unwrap(); + let swap_chain = &swap_chain_guard[link.swap_chain_id]; let frame = &swap_chain.frames[link.image_index as usize]; if frame.need_waiting.swap(false, Ordering::AcqRel) { assert_eq!(frame.acquired_epoch, Some(link.epoch), @@ -1467,9 +1510,9 @@ pub extern "C" fn wgpu_queue_submit( // now prepare the GPU submission let fence = device.raw.create_fence(false).unwrap(); { - let (command_buffer_guard, _) = HUB.command_buffers.read(&mut token); + let (command_buffer_guard, _) = hub.command_buffers.read(&mut token); let submission = - hal::queue::Submission::<_, _, &[::Semaphore]> { + hal::queue::Submission::<_, _, &[B::Semaphore]> { //TODO: may `OneShot` be enough? command_buffers: command_buffer_ids .iter() @@ -1491,7 +1534,7 @@ pub extern "C" fn wgpu_queue_submit( // No need for write access to the device from here on out let callbacks = { let mut token = Token::root(); - let (device_guard, mut token) = HUB.devices.read(&mut token); + let (device_guard, mut token) = hub.devices.read(&mut token); let device = &device_guard[queue_id]; let callbacks = device.maintain(false, &mut token); @@ -1504,121 +1547,44 @@ pub extern "C" fn wgpu_queue_submit( // finally, return the command buffers to the allocator for &cmb_id in command_buffer_ids { - let (cmd_buf, _) = HUB.command_buffers.unregister(cmb_id, &mut token); + let (cmd_buf, _) = hub.command_buffers.unregister(cmb_id, &mut token); device.com_allocator.after_submit(cmd_buf, submit_index); } callbacks }; - Device::fire_map_callbacks(callbacks); + Device::::fire_map_callbacks(callbacks); } -pub fn device_create_render_pipeline( +#[no_mangle] +pub extern "C" fn wgpu_queue_submit( + queue_id: QueueId, + command_buffers: *const CommandBufferId, + command_buffers_length: usize, +) { + 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)) +} + +pub fn device_create_render_pipeline( device_id: DeviceId, desc: &pipeline::RenderPipelineDescriptor, - token: &mut Token, -) -> pipeline::RenderPipeline { + id_in: Input, +) -> Output { + let hub = B::hub(); + let mut token = Token::root(); + let sc = desc.sample_count; assert!(sc == 1 || sc == 2 || sc == 4 || sc == 8 || sc == 16 || sc == 32, "Invalid sample_count of {}", sc); let sc = sc as u8; - let (device_guard, mut token) = HUB.devices.read(token); - let device = &device_guard[device_id]; - let (pipeline_layout_guard, mut token) = HUB.pipeline_layouts.read(&mut token); - let layout = &pipeline_layout_guard[desc.layout].raw; - let (shader_module_guard, _) = HUB.shader_modules.read(&mut token); - let color_states = unsafe { slice::from_raw_parts(desc.color_states, desc.color_states_length) }; let depth_stencil_state = unsafe { desc.depth_stencil_state.as_ref() }; - let rp_key = RenderPassKey { - colors: color_states - .iter() - .map(|at| hal::pass::Attachment { - format: Some(conv::map_texture_format(at.format)), - samples: sc, - ops: hal::pass::AttachmentOps::PRESERVE, - stencil_ops: hal::pass::AttachmentOps::DONT_CARE, - layouts: hal::image::Layout::General .. hal::image::Layout::General, - }) - .collect(), - // We can ignore the resolves as the vulkan specs says: - // As an additional special case, if two render passes have a single subpass, - // they are compatible even if they have different resolve attachment references - // or depth/stencil resolve modes but satisfy the other compatibility conditions. - resolves: ArrayVec::new(), - depth_stencil: depth_stencil_state.map(|at| hal::pass::Attachment { - format: Some(conv::map_texture_format(at.format)), - samples: sc, - ops: hal::pass::AttachmentOps::PRESERVE, - stencil_ops: hal::pass::AttachmentOps::PRESERVE, - layouts: hal::image::Layout::General .. hal::image::Layout::General, - }), - }; - - let mut render_pass_cache = device.render_passes.lock(); - let main_pass = match render_pass_cache.entry(rp_key) { - Entry::Occupied(e) => e.into_mut(), - Entry::Vacant(e) => { - let color_ids = [ - (0, hal::image::Layout::ColorAttachmentOptimal), - (1, hal::image::Layout::ColorAttachmentOptimal), - (2, hal::image::Layout::ColorAttachmentOptimal), - (3, hal::image::Layout::ColorAttachmentOptimal), - ]; - - let depth_id = ( - desc.color_states_length, - hal::image::Layout::DepthStencilAttachmentOptimal, - ); - - let subpass = hal::pass::SubpassDesc { - colors: &color_ids[.. desc.color_states_length], - depth_stencil: depth_stencil_state.map(|_| &depth_id), - inputs: &[], - resolves: &[], - preserves: &[], - }; - - let pass = unsafe { - device - .raw - .create_render_pass(e.key().all(), &[subpass], &[]) - } - .unwrap(); - e.insert(pass) - } - }; - - let vertex = hal::pso::EntryPoint:: { - entry: unsafe { ffi::CStr::from_ptr(desc.vertex_stage.entry_point) } - .to_str() - .to_owned() - .unwrap(), // TODO - module: &shader_module_guard[desc.vertex_stage.module].raw, - specialization: hal::pso::Specialization::EMPTY, - }; - let fragment = unsafe { desc.fragment_stage.as_ref() }.map(|stage| hal::pso::EntryPoint::< - back::Backend, - > { - entry: unsafe { ffi::CStr::from_ptr(stage.entry_point) } - .to_str() - .to_owned() - .unwrap(), // TODO - module: &shader_module_guard[stage.module].raw, - specialization: hal::pso::Specialization::EMPTY, - }); - - let shaders = hal::pso::GraphicsShaderSet { - vertex, - hull: None, - domain: None, - geometry: None, - fragment, - }; let rasterizer = conv::map_rasterization_state_descriptor( &unsafe { desc.rasterization_state.as_ref() } .cloned() @@ -1698,38 +1664,131 @@ pub fn device_create_render_pipeline( depth_bounds: None, }; - let subpass = hal::pass::Subpass { - index: 0, - main_pass, - }; + let raw_pipeline = { + let (device_guard, mut token) = hub.devices.read(&mut token); + let device = &device_guard[device_id]; + let (pipeline_layout_guard, mut token) = hub.pipeline_layouts.read(&mut token); + let layout = &pipeline_layout_guard[desc.layout].raw; + let (shader_module_guard, _) = hub.shader_modules.read(&mut token); - // TODO - let flags = hal::pso::PipelineCreationFlags::empty(); - // TODO - let parent = hal::pso::BasePipeline::None; + let rp_key = RenderPassKey { + colors: color_states + .iter() + .map(|at| hal::pass::Attachment { + format: Some(conv::map_texture_format(at.format)), + samples: sc, + ops: hal::pass::AttachmentOps::PRESERVE, + stencil_ops: hal::pass::AttachmentOps::DONT_CARE, + layouts: hal::image::Layout::General .. hal::image::Layout::General, + }) + .collect(), + // We can ignore the resolves as the vulkan specs says: + // As an additional special case, if two render passes have a single subpass, + // they are compatible even if they have different resolve attachment references + // or depth/stencil resolve modes but satisfy the other compatibility conditions. + resolves: ArrayVec::new(), + depth_stencil: depth_stencil_state.map(|at| hal::pass::Attachment { + format: Some(conv::map_texture_format(at.format)), + samples: sc, + ops: hal::pass::AttachmentOps::PRESERVE, + stencil_ops: hal::pass::AttachmentOps::PRESERVE, + layouts: hal::image::Layout::General .. hal::image::Layout::General, + }), + }; - let pipeline_desc = hal::pso::GraphicsPipelineDesc { - shaders, - rasterizer, - vertex_buffers, - attributes, - input_assembler, - blender, - depth_stencil, - multisampling, - baked_states, - layout, - subpass, - flags, - parent, - }; + let mut render_pass_cache = device.render_passes.lock(); + let main_pass = match render_pass_cache.entry(rp_key) { + Entry::Occupied(e) => e.into_mut(), + Entry::Vacant(e) => { + let color_ids = [ + (0, hal::image::Layout::ColorAttachmentOptimal), + (1, hal::image::Layout::ColorAttachmentOptimal), + (2, hal::image::Layout::ColorAttachmentOptimal), + (3, hal::image::Layout::ColorAttachmentOptimal), + ]; - // TODO: cache - let pipeline = unsafe { - device - .raw - .create_graphics_pipeline(&pipeline_desc, None) - .unwrap() + let depth_id = ( + desc.color_states_length, + hal::image::Layout::DepthStencilAttachmentOptimal, + ); + + let subpass = hal::pass::SubpassDesc { + colors: &color_ids[.. desc.color_states_length], + depth_stencil: depth_stencil_state.map(|_| &depth_id), + inputs: &[], + resolves: &[], + preserves: &[], + }; + + let pass = unsafe { + device + .raw + .create_render_pass(e.key().all(), &[subpass], &[]) + } + .unwrap(); + e.insert(pass) + } + }; + + let vertex = hal::pso::EntryPoint:: { + entry: unsafe { ffi::CStr::from_ptr(desc.vertex_stage.entry_point) } + .to_str() + .to_owned() + .unwrap(), // TODO + module: &shader_module_guard[desc.vertex_stage.module].raw, + specialization: hal::pso::Specialization::EMPTY, + }; + let fragment = unsafe { desc.fragment_stage.as_ref() } + .map(|stage| hal::pso::EntryPoint:: { + entry: unsafe { ffi::CStr::from_ptr(stage.entry_point) } + .to_str() + .to_owned() + .unwrap(), // TODO + module: &shader_module_guard[stage.module].raw, + specialization: hal::pso::Specialization::EMPTY, + }); + + let shaders = hal::pso::GraphicsShaderSet { + vertex, + hull: None, + domain: None, + geometry: None, + fragment, + }; + + let subpass = hal::pass::Subpass { + index: 0, + main_pass, + }; + + // TODO + let flags = hal::pso::PipelineCreationFlags::empty(); + // TODO + let parent = hal::pso::BasePipeline::None; + + let pipeline_desc = hal::pso::GraphicsPipelineDesc { + shaders, + rasterizer, + vertex_buffers, + attributes, + input_assembler, + blender, + depth_stencil, + multisampling, + baked_states, + layout, + subpass, + flags, + parent, + }; + + // TODO: cache + unsafe { + device + .raw + .create_graphics_pipeline(&pipeline_desc, None) + .unwrap() + } }; let pass_context = RenderPassContext { @@ -1750,104 +1809,110 @@ pub fn device_create_render_pipeline( } } - pipeline::RenderPipeline { - raw: pipeline, + let pipeline = pipeline::RenderPipeline { + raw: raw_pipeline, layout_id: desc.layout, pass_context, flags, index_format: desc.vertex_input.index_format, vertex_strides, sample_count: sc, - } + }; + + hub.render_pipelines.register_identity(id_in, pipeline, &mut token) } -#[cfg(feature = "local")] +#[cfg(not(feature = "remote"))] #[no_mangle] pub extern "C" fn wgpu_device_create_render_pipeline( device_id: DeviceId, desc: &pipeline::RenderPipelineDescriptor, ) -> RenderPipelineId { - let mut token = Token::root(); - let pipeline = device_create_render_pipeline(device_id, desc, &mut token); - HUB.render_pipelines.register_local(pipeline, &mut token) + gfx_select!(device_id => device_create_render_pipeline(device_id, desc, PhantomData)) } -pub fn device_create_compute_pipeline( +pub fn device_create_compute_pipeline( device_id: DeviceId, desc: &pipeline::ComputePipelineDescriptor, - token: &mut Token, -) -> pipeline::ComputePipeline { - let (device_guard, mut token) = HUB.devices.read(token); - let device = &device_guard[device_id].raw; - let (pipeline_layout_guard, mut token) = HUB.pipeline_layouts.read(&mut token); - let layout = &pipeline_layout_guard[desc.layout].raw; - let pipeline_stage = &desc.compute_stage; - let (shader_module_guard, _) = HUB.shader_modules.read(&mut token); + id_in: Input +) -> Output { + let hub = B::hub(); + let mut token = Token::root(); - let shader = hal::pso::EntryPoint:: { - entry: unsafe { ffi::CStr::from_ptr(pipeline_stage.entry_point) } - .to_str() - .to_owned() - .unwrap(), // TODO - module: &shader_module_guard[pipeline_stage.module].raw, - specialization: hal::pso::Specialization::EMPTY, + let raw_pipeline = { + let (device_guard, mut token) = hub.devices.read(&mut token); + let device = &device_guard[device_id].raw; + let (pipeline_layout_guard, mut token) = hub.pipeline_layouts.read(&mut token); + let layout = &pipeline_layout_guard[desc.layout].raw; + let pipeline_stage = &desc.compute_stage; + let (shader_module_guard, _) = hub.shader_modules.read(&mut token); + + let shader = hal::pso::EntryPoint:: { + entry: unsafe { ffi::CStr::from_ptr(pipeline_stage.entry_point) } + .to_str() + .to_owned() + .unwrap(), // TODO + module: &shader_module_guard[pipeline_stage.module].raw, + specialization: hal::pso::Specialization::EMPTY, + }; + + // TODO + let flags = hal::pso::PipelineCreationFlags::empty(); + // TODO + let parent = hal::pso::BasePipeline::None; + + let pipeline_desc = hal::pso::ComputePipelineDesc { + shader, + layout, + flags, + parent, + }; + + unsafe { + device + .create_compute_pipeline(&pipeline_desc, None) + .unwrap() + } }; - // TODO - let flags = hal::pso::PipelineCreationFlags::empty(); - // TODO - let parent = hal::pso::BasePipeline::None; - - let pipeline_desc = hal::pso::ComputePipelineDesc { - shader, - layout, - flags, - parent, - }; - - let pipeline = unsafe { - device - .create_compute_pipeline(&pipeline_desc, None) - .unwrap() - }; - - pipeline::ComputePipeline { - raw: pipeline, + let pipeline = pipeline::ComputePipeline { + raw: raw_pipeline, layout_id: desc.layout, - } + }; + hub.compute_pipelines.register_identity(id_in, pipeline, &mut token) } -#[cfg(feature = "local")] +#[cfg(not(feature = "remote"))] #[no_mangle] pub extern "C" fn wgpu_device_create_compute_pipeline( device_id: DeviceId, desc: &pipeline::ComputePipelineDescriptor, ) -> ComputePipelineId { - let mut token = Token::root(); - let pipeline = device_create_compute_pipeline(device_id, desc, &mut token); - HUB.compute_pipelines.register_local(pipeline, &mut token) + gfx_select!(device_id => device_create_compute_pipeline(device_id, desc, PhantomData)) } -pub fn device_create_swap_chain( +pub fn device_create_swap_chain( device_id: DeviceId, surface_id: SurfaceId, desc: &swap_chain::SwapChainDescriptor, - token: &mut Token, -) -> Vec> { + id_in: Input, + image_ids: Vec<(Input, Input)>, +) -> Output { info!("creating swap chain {:?}", desc); + let hub = B::hub(); + let mut token = Token::root(); - let (mut surface_guard, mut token) = HUB.surfaces.write(token); - let (adapter_guard, mut token) = HUB.adapters.read(&mut token); - let (device_guard, _) = HUB.devices.read(&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 device = &device_guard[device_id]; let surface = &mut surface_guard[surface_id]; let (caps, formats, _present_modes) = { + let suf = B::get_surface_mut(surface); let adapter = &adapter_guard[device.adapter_id]; - assert!(surface - .raw - .supports_queue_family(&adapter.queue_families[0])); - surface.raw.compatibility(&adapter.physical_device) + assert!(suf.supports_queue_family(&adapter.raw.queue_families[0])); + suf.compatibility(&adapter.raw.physical_device) }; let num_frames = *caps.image_count.start(); //TODO: configure? let usage = conv::map_texture_usage(desc.usage, hal::format::Aspects::COLOR); @@ -1881,10 +1946,12 @@ pub fn device_create_swap_chain( */ let (old_raw, sem_available, command_pool) = match surface.swap_chain.take() { - Some(mut old) => { + Some(old_id) => { //TODO: remove this once gfx-rs stops destroying the old swapchain device.raw.wait_idle().unwrap(); let mut pending = device.pending.lock(); + + let (mut old, _) = hub.swap_chains.unregister(old_id, &mut token); assert_eq!(old.device_id.value, device_id); for frame in old.frames { pending.destroy( @@ -1912,14 +1979,20 @@ pub fn device_create_swap_chain( }, }; - let (raw, images) = unsafe { + let (raw_swap_chain, images) = unsafe { + let suf = B::get_surface_mut(surface); device .raw - .create_swapchain(&mut surface.raw, config.with_image_usage(usage), old_raw) + .create_swapchain(suf, config.with_image_usage(usage), old_raw) .unwrap() }; - surface.swap_chain = Some(swap_chain::SwapChain { - raw, + + let (id, id_out) = hub.swap_chains.new_identity(id_in); + surface.swap_chain = Some(id); + + let mut trackers = device.trackers.lock(); + let mut swap_chain = swap_chain::SwapChain { + raw: raw_swap_chain, device_id: Stored { value: device_id, ref_count: device.life_guard.ref_count.clone(), @@ -1929,91 +2002,80 @@ pub fn device_create_swap_chain( acquired: Vec::with_capacity(1), //TODO: get it from gfx-hal? sem_available, command_pool, - }); + }; - images + for ((i, image), (id_texture_in, id_view_in)) in images .into_iter() - .map(|raw| resource::Texture { - raw, - device_id: Stored { - value: device_id, - ref_count: device.life_guard.ref_count.clone(), - }, - kind: hal::image::Kind::D2(desc.width, desc.height, 1, 1), - format: desc.format, - full_range: hal::image::SubresourceRange { - aspects: hal::format::Aspects::COLOR, - levels: 0 .. 1, - layers: 0 .. 1, - }, - placement: resource::TexturePlacement::Void, - life_guard: LifeGuard::new(), - }) - .collect() -} - -#[cfg(feature = "local")] -pub fn swap_chain_populate_textures( - swap_chain_id: SwapChainId, - textures: Vec>, - token: &mut Token, -) { - let (mut surface_guard, mut token) = HUB.surfaces.write(token); - let swap_chain = surface_guard[swap_chain_id].swap_chain.as_mut().unwrap(); - let (device_guard, mut token) = HUB.devices.read(&mut token); - let device = &device_guard[swap_chain.device_id.value]; - let mut trackers = device.trackers.lock(); - - for (i, mut texture) in textures.into_iter().enumerate() { - let format = texture.format; - let kind = texture.kind; - let range = texture.full_range.clone(); + .enumerate() + .zip(image_ids) + { + let kind = hal::image::Kind::D2(desc.width, desc.height, 1, 1); + let range = hal::image::SubresourceRange { + aspects: hal::format::Aspects::COLOR, + levels: 0 .. 1, + layers: 0 .. 1, + }; let view_raw = unsafe { device .raw .create_image_view( - &texture.raw, + &image, hal::image::ViewKind::D2, - conv::map_texture_format(format), + conv::map_texture_format(desc.format), hal::format::Swizzle::NO, range.clone(), ) .unwrap() }; - texture.placement = resource::TexturePlacement::SwapChain(swap_chain::SwapChainLink { - swap_chain_id, //TODO: strongly - epoch: Mutex::new(0), - image_index: i as hal::SwapImageIndex, - }); + let texture = resource::Texture { + raw: image, + device_id: Stored { + value: device_id, + ref_count: device.life_guard.ref_count.clone(), + }, + kind, + format: desc.format, + full_range: range.clone(), + placement: resource::TexturePlacement::SwapChain(swap_chain::SwapChainLink { + swap_chain_id: id, //TODO: strongly + epoch: Mutex::new(0), + image_index: i as hal::SwapImageIndex, + }), + life_guard: LifeGuard::new(), + }; + let (id_texture, _) = hub.textures.new_identity(id_texture_in); let texture_id = Stored { ref_count: texture.life_guard.ref_count.clone(), - value: HUB.textures.register_local(texture, &mut token), + value: id_texture, }; trackers.textures.init( - texture_id.value, + id_texture, &texture_id.ref_count, range.clone(), resource::TextureUsage::UNINITIALIZED, ); + hub.textures.register(id_texture, texture, &mut token); let view = resource::TextureView { raw: view_raw, texture_id: texture_id.clone(), - format, + format: desc.format, extent: kind.extent(), samples: kind.num_samples(), range, is_owned_by_swap_chain: true, life_guard: LifeGuard::new(), }; + let (id_view, _) = hub.texture_views.new_identity(id_view_in); let view_id = Stored { ref_count: view.life_guard.ref_count.clone(), - value: HUB.texture_views.register_local(view, &mut token), + value: id_view, }; trackers .views - .init(view_id.value, &view_id.ref_count, (), ()); + .init(id_view, &view_id.ref_count, (), ()); + hub.texture_views.register(id_view, view, &mut token); swap_chain.frames.alloc().init(swap_chain::Frame { texture_id, @@ -2026,35 +2088,46 @@ pub fn swap_chain_populate_textures( comb: swap_chain.command_pool.acquire_command_buffer(), }); } + + hub.swap_chains.register(id, swap_chain, &mut token); + id_out } -#[cfg(feature = "local")] +#[cfg(not(feature = "remote"))] #[no_mangle] pub extern "C" fn wgpu_device_create_swap_chain( device_id: DeviceId, surface_id: SurfaceId, desc: &swap_chain::SwapChainDescriptor, ) -> SwapChainId { - let mut token = Token::root(); - let textures = device_create_swap_chain(device_id, surface_id, desc, &mut token); - swap_chain_populate_textures(surface_id, textures, &mut token); - surface_id + let image_ids = vec![(PhantomData, PhantomData); 10]; //TODO: make this compatible with "remote" + gfx_select!(device_id => device_create_swap_chain(device_id, surface_id, desc, PhantomData, image_ids)) +} + +pub fn device_poll(device_id: DeviceId, force_wait: bool) { + let hub = B::hub(); + let callbacks = { + let (device_guard, mut token) = hub.devices.read(&mut Token::root()); + device_guard[device_id].maintain(force_wait, &mut token) + }; + Device::::fire_map_callbacks(callbacks); } #[no_mangle] pub extern "C" fn wgpu_device_poll(device_id: DeviceId, force_wait: bool) { - let callbacks = { - let (device_guard, mut token) = HUB.devices.read(&mut Token::root()); - device_guard[device_id].maintain(force_wait, &mut token) - }; - Device::fire_map_callbacks(callbacks); + gfx_select!(device_id => device_poll(device_id, force_wait)) +} + +pub fn device_destroy(device_id: DeviceId) { + let hub = B::hub(); + let (device, mut token) = hub.devices.unregister(device_id, &mut Token::root()); + device.maintain(true, &mut token); + device.com_allocator.destroy(&device.raw); } #[no_mangle] pub extern "C" fn wgpu_device_destroy(device_id: DeviceId) { - let (device, mut token) = HUB.devices.unregister(device_id, &mut Token::root()); - device.maintain(true, &mut token); - device.com_allocator.destroy(&device.raw); + gfx_select!(device_id => device_destroy(device_id)) } pub type BufferMapReadCallback = @@ -2062,29 +2135,25 @@ pub type BufferMapReadCallback = pub type BufferMapWriteCallback = extern "C" fn(status: BufferMapAsyncStatus, data: *mut u8, userdata: *mut u8); -#[no_mangle] -pub extern "C" fn wgpu_buffer_map_read_async( +pub fn buffer_map_async( buffer_id: BufferId, - start: BufferAddress, - size: BufferAddress, - callback: BufferMapReadCallback, - userdata: *mut u8, + usage: resource::BufferUsage, + operation: BufferMapOperation, ) { + let hub = B::hub(); let mut token = Token::root(); - let (device_guard, mut token) = HUB.devices.read(&mut token); + let (device_guard, mut token) = hub.devices.read(&mut token); let (device_id, ref_count) = { - let (mut buffer_guard, _) = HUB.buffers.write(&mut token); + let (mut buffer_guard, _) = hub.buffers.write(&mut token); let buffer = &mut buffer_guard[buffer_id]; if buffer.pending_map_operation.is_some() { - log::error!("wgpu_buffer_map_read_async failed: buffer mapping is pending"); - callback(BufferMapAsyncStatus::Error, std::ptr::null_mut(), userdata); + operation.call_error(); return; } - let range = start .. start + size; - buffer.pending_map_operation = Some(BufferMapOperation::Read(range, callback, userdata)); + buffer.pending_map_operation = Some(operation); (buffer.device_id.value, buffer.life_guard.ref_count.clone()) }; @@ -2094,11 +2163,23 @@ pub extern "C" fn wgpu_buffer_map_read_async( .trackers .lock() .buffers - .change_replace(buffer_id, &ref_count, (), resource::BufferUsage::MAP_READ); + .change_replace(buffer_id, &ref_count, (), usage); device.pending.lock().map(buffer_id, ref_count); } +#[no_mangle] +pub extern "C" fn wgpu_buffer_map_read_async( + buffer_id: BufferId, + start: BufferAddress, + size: BufferAddress, + callback: BufferMapReadCallback, + 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)) +} + #[no_mangle] pub extern "C" fn wgpu_buffer_map_write_async( buffer_id: BufferId, @@ -2107,40 +2188,16 @@ pub extern "C" fn wgpu_buffer_map_write_async( callback: BufferMapWriteCallback, userdata: *mut u8, ) { - let mut token = Token::root(); - let (device_guard, mut token) = HUB.devices.read(&mut token); - - let (device_id, ref_count) = { - let (mut buffer_guard, _) = HUB.buffers.write(&mut token); - let buffer = &mut buffer_guard[buffer_id]; - - if buffer.pending_map_operation.is_some() { - log::error!("wgpu_buffer_map_write_async failed: buffer mapping is pending"); - callback(BufferMapAsyncStatus::Error, std::ptr::null_mut(), userdata); - return; - } - - let range = start .. start + size; - buffer.pending_map_operation = Some(BufferMapOperation::Write(range, callback, userdata)); - (buffer.device_id.value, buffer.life_guard.ref_count.clone()) - }; - - let device = &device_guard[device_id]; - - device - .trackers - .lock() - .buffers - .change_replace(buffer_id, &ref_count, (), resource::BufferUsage::MAP_WRITE); - - device.pending.lock().map(buffer_id, ref_count); + let operation = BufferMapOperation::Write(start .. start + size, callback, userdata); + gfx_select!(buffer_id => buffer_map_async(buffer_id, resource::BufferUsage::MAP_WRITE, operation)) } -#[no_mangle] -pub extern "C" fn wgpu_buffer_unmap(buffer_id: BufferId) { +pub fn buffer_unmap(buffer_id: BufferId) { + let hub = B::hub(); let mut token = Token::root(); - let (device_guard, mut token) = HUB.devices.read(&mut token); - let (mut buffer_guard, _) = HUB.buffers.write(&mut token); + + let (device_guard, mut token) = hub.devices.read(&mut token); + let (mut buffer_guard, _) = hub.buffers.write(&mut token); let buffer = &mut buffer_guard[buffer_id]; let device_raw = &device_guard[buffer.device_id.value].raw; @@ -2161,3 +2218,8 @@ pub extern "C" fn wgpu_buffer_unmap(buffer_id: BufferId) { buffer.memory.unmap(device_raw); } + +#[no_mangle] +pub extern "C" fn wgpu_buffer_unmap(buffer_id: BufferId) { + gfx_select!(buffer_id => buffer_unmap(buffer_id)) +} diff --git a/wgpu-native/src/hub.rs b/wgpu-native/src/hub.rs index 8b8208e4f..5acefa3d9 100644 --- a/wgpu-native/src/hub.rs +++ b/wgpu-native/src/hub.rs @@ -1,46 +1,48 @@ use crate::{ - AdapterHandle, + id::{Input, Output}, + Adapter, AdapterId, Backend, - BindGroupHandle, + BindGroup, BindGroupId, - BindGroupLayoutHandle, + BindGroupLayout, BindGroupLayoutId, - BufferHandle, + Buffer, BufferId, - CommandBufferHandle, + CommandBuffer, CommandBufferId, - ComputePassHandle, + ComputePass, ComputePassId, - ComputePipelineHandle, + ComputePipeline, ComputePipelineId, - DeviceHandle, + Device, DeviceId, Epoch, Index, - PipelineLayoutHandle, + Instance, + PipelineLayout, PipelineLayoutId, - RenderPassHandle, + RenderPass, RenderPassId, - RenderPipelineHandle, + RenderPipeline, RenderPipelineId, - SamplerHandle, + Sampler, SamplerId, - ShaderModuleHandle, + ShaderModule, ShaderModuleId, - SurfaceHandle, + Surface, SurfaceId, - TextureHandle, + SwapChain, + SwapChainId, + Texture, TextureId, - TextureViewHandle, + TextureView, TextureViewId, TypedId, }; -#[cfg(not(feature = "gfx-backend-gl"))] -use crate::{InstanceHandle, InstanceId}; use lazy_static::lazy_static; -#[cfg(feature = "local")] +#[cfg(not(feature = "remote"))] use parking_lot::Mutex; use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use vec_map::VecMap; @@ -59,14 +61,16 @@ use std::{ pub struct IdentityManager { free: Vec, epochs: Vec, + backend: Backend, phantom: PhantomData, } -impl Default for IdentityManager { - fn default() -> IdentityManager { +impl IdentityManager { + pub fn new(backend: Backend) -> Self { IdentityManager { free: Default::default(), epochs: Default::default(), + backend, phantom: PhantomData, } } @@ -74,12 +78,11 @@ impl Default for IdentityManager { impl IdentityManager { pub fn alloc(&mut self) -> I { - let backend = Backend::Vulkan; match self.free.pop() { - Some(index) => I::zip(index, self.epochs[index as usize], backend), + Some(index) => I::zip(index, self.epochs[index as usize], self.backend), None => { let epoch = 1; - let id = I::zip(self.epochs.len() as Index, epoch, backend); + let id = I::zip(self.epochs.len() as Index, epoch, self.backend); self.epochs.push(epoch); id } @@ -87,7 +90,8 @@ impl IdentityManager { } pub fn free(&mut self, id: I) { - let (index, epoch, _) = id.unzip(); + let (index, epoch, backend) = id.unzip(); + debug_assert_eq!(backend, self.backend); // avoid doing this check in release if cfg!(debug_assertions) { assert!(!self.free.contains(&index)); @@ -157,54 +161,58 @@ pub trait Access {} pub enum Root {} //TODO: establish an order instead of declaring all the pairs. #[cfg(not(feature = "gfx-backend-gl"))] -impl Access for Root {} -impl Access for Root {} +impl Access for Root {} +impl Access for Root {} #[cfg(not(feature = "gfx-backend-gl"))] -impl Access for InstanceHandle {} -impl Access for Root {} -impl Access for SurfaceHandle {} -impl Access for Root {} -impl Access for SurfaceHandle {} -impl Access for AdapterHandle {} -impl Access for Root {} -impl Access for DeviceHandle {} -impl Access for Root {} -impl Access for DeviceHandle {} -impl Access for Root {} -impl Access for DeviceHandle {} -impl Access for PipelineLayoutHandle {} -impl Access for CommandBufferHandle {} -impl Access for Root {} -impl Access for DeviceHandle {} -impl Access for Root {} -impl Access for BindGroupHandle {} -impl Access for CommandBufferHandle {} -impl Access for Root {} -impl Access for BindGroupHandle {} -impl Access for CommandBufferHandle {} -impl Access for Root {} -impl Access for ComputePassHandle {} -impl Access for Root {} -impl Access for RenderPassHandle {} -impl Access for Root {} -impl Access for PipelineLayoutHandle {} -impl Access for Root {} -impl Access for DeviceHandle {} -impl Access for BindGroupLayoutHandle {} -impl Access for BindGroupHandle {} -impl Access for CommandBufferHandle {} -impl Access for ComputePassHandle {} -impl Access for ComputePipelineHandle {} -impl Access for RenderPassHandle {} -impl Access for RenderPipelineHandle {} -impl Access for Root {} -impl Access for DeviceHandle {} -impl Access for BufferHandle {} -impl Access for Root {} -impl Access for DeviceHandle {} -impl Access for TextureHandle {} -impl Access for Root {} -impl Access for TextureViewHandle {} +impl Access for Instance {} +impl Access> for Root {} +impl Access> for Surface {} +impl Access> for Root {} +impl Access> for Surface {} +impl Access> for Adapter {} +impl Access> for Device {} +impl Access> for Root {} +impl Access> for Device {} +impl Access> for Root {} +impl Access> for Device {} +impl Access> for Root {} +impl Access> for Device {} +impl Access> for PipelineLayout {} +impl Access> for CommandBuffer {} +impl Access> for Root {} +impl Access> for Device {} +impl Access> for SwapChain {} +impl Access> for Root {} +impl Access> for BindGroup {} +impl Access> for CommandBuffer {} +impl Access> for Root {} +impl Access> for BindGroup {} +impl Access> for CommandBuffer {} +impl Access> for Root {} +impl Access> for ComputePass {} +impl Access> for Root {} +impl Access> for RenderPass {} +impl Access> for Root {} +impl Access> for PipelineLayout {} +impl Access> for Root {} +impl Access> for Device {} +impl Access> for BindGroupLayout {} +impl Access> for BindGroup {} +impl Access> for CommandBuffer {} +impl Access> for ComputePass {} +impl Access> for ComputePipeline {} +impl Access> for RenderPass {} +impl Access> for RenderPipeline {} +impl Access> for Root {} +impl Access> for Device {} +impl Access> for SwapChain {} +impl Access> for Buffer {} +impl Access> for Root {} +impl Access> for Device {} +impl Access> for Texture {} +impl Access> for Root {} +impl Access> for Device {} +impl Access> for TextureView {} #[cfg(debug_assertions)] thread_local! { @@ -260,20 +268,22 @@ impl<'a, T> Drop for Token<'a, T> { #[derive(Debug)] pub struct Registry { - #[cfg(feature = "local")] + #[cfg(not(feature = "remote"))] pub identity: Mutex>, data: RwLock>, + backend: Backend, } -impl Default for Registry { - fn default() -> Self { +impl Registry { + fn new(backend: Backend) -> Self { Registry { - #[cfg(feature = "local")] - identity: Mutex::new(IdentityManager::default()), + #[cfg(not(feature = "remote"))] + identity: Mutex::new(IdentityManager::new(backend)), data: RwLock::new(Storage { map: VecMap::new(), _phantom: PhantomData, }), + backend, } } } @@ -282,7 +292,8 @@ impl Registry { pub fn register>( &self, id: I, value: T, _token: &mut Token ) { - let (index, epoch, _) = id.unzip(); + let (index, epoch, backend) = id.unzip(); + debug_assert_eq!(backend, self.backend); let old = self .data .write() @@ -291,13 +302,24 @@ impl Registry { assert!(old.is_none()); } - #[cfg(feature = "local")] - pub fn register_local>( - &self, value: T, token: &mut Token - ) -> I { + #[cfg(not(feature = "remote"))] + pub fn new_identity(&self, _id_in: Input) -> (I, Output) { let id = self.identity.lock().alloc(); + (id, id) + } + + #[cfg(feature = "remote")] + pub fn new_identity(&self, id_in: Input) -> (I, Output) { + //debug_assert_eq!(self.backend, id_in.backend()); + (id_in, PhantomData) + } + + pub fn register_identity>( + &self, id_in: Input, value: T, token: &mut Token + ) -> Output { + let (id, output) = self.new_identity(id_in); self.register(id, value, token); - id + output } pub fn unregister>( @@ -305,7 +327,7 @@ impl Registry { ) -> (T, Token) { let value = self.data.write().remove(id); //Note: careful about the order here! - #[cfg(feature = "local")] + #[cfg(not(feature = "remote"))] self.identity.lock().free(id); (value, Token::new()) } @@ -323,28 +345,94 @@ impl Registry { } } -#[derive(Default, Debug)] -pub struct Hub { - #[cfg(not(feature = "gfx-backend-gl"))] - pub instances: Arc>, - pub surfaces: Arc>, - pub adapters: Arc>, - pub devices: Arc>, - pub pipeline_layouts: Arc>, - pub shader_modules: Arc>, - pub bind_group_layouts: Arc>, - pub bind_groups: Arc>, - pub command_buffers: Arc>, - pub render_passes: Arc>, - pub render_pipelines: Arc>, - pub compute_passes: Arc>, - pub compute_pipelines: Arc>, - pub buffers: Arc>, - pub textures: Arc>, - pub texture_views: Arc>, - pub samplers: Arc>, +#[derive(Debug)] +pub struct Hub { + pub adapters: Registry, AdapterId>, + pub devices: Registry, DeviceId>, + pub swap_chains: Registry, SwapChainId>, + pub pipeline_layouts: Registry, PipelineLayoutId>, + pub shader_modules: Registry, ShaderModuleId>, + pub bind_group_layouts: Registry, BindGroupLayoutId>, + pub bind_groups: Registry, BindGroupId>, + pub command_buffers: Registry, CommandBufferId>, + pub render_passes: Registry, RenderPassId>, + pub render_pipelines: Registry, RenderPipelineId>, + pub compute_passes: Registry, ComputePassId>, + pub compute_pipelines: Registry, ComputePipelineId>, + pub buffers: Registry, BufferId>, + pub textures: Registry, TextureId>, + pub texture_views: Registry, TextureViewId>, + pub samplers: Registry, SamplerId>, +} + +impl Default for Hub { + fn default() -> Self { + Hub { + adapters: Registry::new(B::VARIANT), + devices: Registry::new(B::VARIANT), + swap_chains: Registry::new(B::VARIANT), + pipeline_layouts: Registry::new(B::VARIANT), + shader_modules: Registry::new(B::VARIANT), + bind_group_layouts: Registry::new(B::VARIANT), + bind_groups: Registry::new(B::VARIANT), + command_buffers: Registry::new(B::VARIANT), + render_passes: Registry::new(B::VARIANT), + render_pipelines: Registry::new(B::VARIANT), + compute_passes: Registry::new(B::VARIANT), + compute_pipelines: Registry::new(B::VARIANT), + buffers: Registry::new(B::VARIANT), + textures: Registry::new(B::VARIANT), + texture_views: Registry::new(B::VARIANT), + samplers: Registry::new(B::VARIANT), + } + } +} + +#[derive(Debug, Default)] +pub struct Hubs { + vulkan: Hub, + #[cfg(any(target_os = "ios", target_os = "macos"))] + metal: Hub, +} + +#[derive(Debug)] +pub struct Global { + pub instance: Instance, + pub surfaces: Registry, + hubs: Hubs, } lazy_static! { - pub static ref HUB: Hub = Hub::default(); + pub static ref GLOBAL: Arc = Arc::new(Global { + instance: Instance::new("wgpu", 1), + surfaces: Registry::new(Backend::Empty), + hubs: Hubs::default(), + }); +} + +pub trait GfxBackend: hal::Backend { + const VARIANT: Backend; + fn hub() -> &'static Hub; + fn get_surface_mut(surface: &mut Surface) -> &mut Self::Surface; +} + +impl GfxBackend for gfx_backend_vulkan::Backend { + const VARIANT: Backend = Backend::Vulkan; + fn hub() -> &'static Hub { + &GLOBAL.hubs.vulkan + } + fn get_surface_mut(surface: &mut Surface) -> &mut Self::Surface { + surface.vulkan.as_mut().unwrap() + } +} + +#[cfg(any(target_os = "ios", target_os = "macos"))] +impl GfxBackend for gfx_backend_metal::Backend { + const VARIANT: Backend = Backend::Metal; + fn hub() -> &'static Hub { + &GLOBAL.hubs.metal + } + fn get_surface_mut(surface: &mut Surface) -> &mut Self::Surface { + &mut surface.metal + } } diff --git a/wgpu-native/src/id.rs b/wgpu-native/src/id.rs index 26d0c0f44..015256923 100644 --- a/wgpu-native/src/id.rs +++ b/wgpu-native/src/id.rs @@ -6,11 +6,27 @@ use std::{ #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; +const BACKEND_BITS: usize = 3; +type Dummy = crate::backend::Empty; #[repr(transparent)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct Id(u64, PhantomData); +impl Id { + pub fn backend(&self) -> Backend { + match self.0 >> (64 - BACKEND_BITS) as u8 { + 0 => Backend::Empty, + 1 => Backend::Vulkan, + 2 => Backend::Gl, + 3 => Backend::Metal, + 4 => Backend::Dx12, + 5 => Backend::Dx11, + _ => unreachable!(), + } + } +} + impl Copy for Id {} impl Clone for Id { @@ -43,85 +59,52 @@ pub trait TypedId { } impl TypedId for Id { - fn zip(index: Index, epoch: Epoch, _backend: Backend) -> Self { - Id(index as u64 | ((epoch as u64) << 32), PhantomData) + fn zip(index: Index, epoch: Epoch, backend: Backend) -> Self { + assert_eq!(0, epoch >> 32 - BACKEND_BITS); + let v = index as u64 | + ((epoch as u64) << 32) | + ((backend as u64) << (64 - BACKEND_BITS)); + Id(v, PhantomData) } fn unzip(self) -> (Index, Epoch, Backend) { - (self.0 as u32, (self.0 >> 32) as u32, Backend::Vulkan) + (self.0 as u32, (self.0 >> 32) as u32, self.backend()) } } -#[cfg(not(feature = "gfx-backend-gl"))] -pub type InstanceId = Id; +#[cfg(feature = "remote")] +pub type Input = T; +#[cfg(not(feature = "remote"))] +pub type Input = PhantomData; +#[cfg(not(feature = "remote"))] +pub type Output = T; +#[cfg(feature = "remote")] +pub type Output = PhantomData; -#[cfg(feature = "gfx-backend-gl")] -pub type InstanceId = SurfaceId; - -#[cfg(not(feature = "gfx-backend-gl"))] -pub type InstanceHandle = back::Instance; - -pub type AdapterId = Id; -pub type AdapterHandle = hal::Adapter; - -pub type DeviceId = Id; -pub type DeviceHandle = crate::Device; +pub type AdapterId = Id>; +pub type DeviceId = Id>; pub type QueueId = DeviceId; - // Resource -pub type BufferId = Id; -pub type BufferHandle = crate::Buffer; - -pub type TextureViewId = Id; -pub type TextureViewHandle = crate::TextureView; - -pub type TextureId = Id; -pub type TextureHandle = crate::Texture; - -pub type SamplerId = Id; -pub type SamplerHandle = crate::Sampler; - +pub type BufferId = Id>; +pub type TextureViewId = Id>; +pub type TextureId = Id>; +pub type SamplerId = Id>; // Binding model -pub type BindGroupLayoutId = Id; -pub type BindGroupLayoutHandle = crate::BindGroupLayout; - -pub type PipelineLayoutId = Id; -pub type PipelineLayoutHandle = crate::PipelineLayout; - -pub type BindGroupId = Id; -pub type BindGroupHandle = crate::BindGroup; - +pub type BindGroupLayoutId = Id>; +pub type PipelineLayoutId = Id>; +pub type BindGroupId = Id>; // Pipeline -pub type InputStateId = Id; -pub enum InputStateHandle {} - -pub type ShaderModuleId = Id; -pub type ShaderModuleHandle = crate::ShaderModule; - -pub type RenderPipelineId = Id; -pub type RenderPipelineHandle = crate::RenderPipeline; - -pub type ComputePipelineId = Id; -pub type ComputePipelineHandle = crate::ComputePipeline; - +pub type InputStateId = Id; +pub type ShaderModuleId = Id>; +pub type RenderPipelineId = Id>; +pub type ComputePipelineId = Id>; // Command -pub type CommandBufferId = Id; -pub type CommandBufferHandle = crate::CommandBuffer; - +pub type CommandBufferId = Id>; pub type CommandEncoderId = CommandBufferId; - -pub type RenderBundleId = Id; -pub enum RenderBundleHandle {} - -pub type RenderPassId = Id; -pub type RenderPassHandle = crate::RenderPass; - -pub type ComputePassId = Id; -pub type ComputePassHandle = crate::ComputePass; - +pub type RenderBundleId = Id>; +pub type RenderPassId = Id>; +pub type ComputePassId = Id>; // Swap chain -pub type SurfaceId = Id; -pub type SurfaceHandle = crate::Surface; - -pub type SwapChainId = SurfaceId; +pub type SurfaceId = Id; +pub type SwapChainId = Id>; diff --git a/wgpu-native/src/instance.rs b/wgpu-native/src/instance.rs index 64875aa37..adbc3147c 100644 --- a/wgpu-native/src/instance.rs +++ b/wgpu-native/src/instance.rs @@ -1,21 +1,61 @@ use crate::{ binding_model::MAX_BIND_GROUPS, - hub::{HUB, Root, Token}, - AdapterHandle, + device::BIND_BUFFER_ALIGNMENT, + hub::{GLOBAL, GfxBackend, Token}, + id::{Input, Output}, AdapterId, - DeviceHandle, - InstanceId, - SurfaceHandle, + Backend, + Device, + DeviceId, + SwapChainId, }; -#[cfg(feature = "local")] -use crate::{device::BIND_BUFFER_ALIGNMENT, DeviceId, SurfaceId}; +#[cfg(not(feature = "remote"))] +use crate::{gfx_select, SurfaceId}; -#[cfg(feature = "local")] use log::info; #[cfg(feature = "remote")] use serde::{Deserialize, Serialize}; use hal::{self, Instance as _, PhysicalDevice as _}; +#[cfg(not(feature = "remote"))] +use std::marker::PhantomData; + + +#[derive(Debug, Default)] +pub struct Instance { + vulkan: Option, + #[cfg(any(target_os = "ios", target_os = "macos"))] + metal: gfx_backend_metal::Instance, +} + +impl Instance { + pub(crate) fn new(name: &str, version: u32) -> Self { + Instance { + #[cfg(any(unix, windows))] + vulkan: Some(gfx_backend_vulkan::Instance::create(name, version)), + #[cfg(not(any(unix, windows)))] + vulkan: None, + #[cfg(any(target_os = "ios", target_os = "macos"))] + metal: gfx_backend_metal::Instance::create(name, version), + } + } +} + +type GfxSurface = ::Surface; + +#[derive(Debug)] +pub struct Surface { + pub(crate) swap_chain: Option, + pub(crate) vulkan: Option>, + #[cfg(any(target_os = "ios", target_os = "macos"))] + pub(crate) metal: GfxSurface, +} + +#[derive(Debug)] +pub struct Adapter { + pub(crate) raw: hal::Adapter, +} + #[repr(C)] #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] @@ -69,212 +109,163 @@ pub struct DeviceDescriptor { pub limits: Limits, } -#[cfg(not(feature = "gfx-backend-gl"))] -pub fn create_instance() -> ::back::Instance { - ::back::Instance::create("wgpu", 1) -} - -#[cfg(all(feature = "local", not(feature = "gfx-backend-gl")))] -#[no_mangle] -pub extern "C" fn wgpu_create_instance() -> InstanceId { - let inst = create_instance(); - HUB.instances.register_local(inst, &mut Token::root()) -} - -#[cfg(all(feature = "local", feature = "glutin"))] -pub fn wgpu_create_gl_instance(windowed_context: back::glutin::RawContext) -> InstanceId { +#[cfg(all(not(feature = "remote"), feature = "glutin"))] +pub fn wgpu_create_gl_surface(windowed_context: back::glutin::RawContext) -> SurfaceId { let raw = back::Surface::from_context(windowed_context); let surface = SurfaceHandle::new(raw); - HUB.surfaces.register_local(surface, &mut Token::root()) + GLOBAL.surfaces.register_local(surface, &mut Token::root()) } -#[cfg(all(feature = "local", not(feature = "gfx-backend-gl")))] -pub fn wgpu_instance_create_surface( - instance_id: InstanceId, +#[cfg(not(feature = "remote"))] +pub fn wgpu_create_surface( raw_handle: raw_window_handle::RawWindowHandle, ) -> SurfaceId { - let mut token = Token::root(); - let (instance_guard, mut token) = HUB.instances.read(&mut token); - let instance = &instance_guard[instance_id]; - let raw = match raw_handle { - #[cfg(all(target_os = "ios", feature = "gfx-backend-metal"))] - raw_window_handle::RawWindowHandle::IOS(h) => - instance.create_surface_from_uiview(h.ui_view, cfg!(debug_assertions)), - #[cfg(all(target_os = "macos", feature = "gfx-backend-metal"))] - raw_window_handle::RawWindowHandle::MacOS(h) => - instance.create_surface_from_nsview(h.ns_view, cfg!(debug_assertions)), - #[cfg(all(target_os = "macos", feature = "gfx-backend-vulkan"))] - raw_window_handle::RawWindowHandle::MacOS(h) => - instance.create_surface_from_nsview(h.ns_view), - #[cfg(all(unix, feature = "gfx-backend-vulkan"))] - raw_window_handle::RawWindowHandle::X11(h) => - instance.create_surface_from_xlib(h.display as _, h.window as _), - #[cfg(all(unix, feature = "gfx-backend-vulkan"))] - raw_window_handle::RawWindowHandle::Wayland(h) => - instance.create_surface_from_wayland(h.display, h.surface), - #[cfg(all(windows, feature = "gfx-backend-vulkan"))] - raw_window_handle::RawWindowHandle::Windows(h) => - instance.create_surface_from_hwnd(std::ptr::null_mut(), h.hwnd), - #[cfg(all(windows, feature = "gfx-backend-dx11"))] - raw_window_handle::RawWindowHandle::Windows(h) => - instance.create_surface_from_hwnd(h.hwnd), - #[cfg(all(windows, feature = "gfx-backend-dx12"))] - raw_window_handle::RawWindowHandle::Windows(h) => - instance.create_surface_from_hwnd(h.hwnd), - #[cfg(any( - feature = "gfx-backend-vulkan", - feature = "gfx-backend-dx11", - feature = "gfx-backend-dx12", - feature = "gfx-backend-metal", - feature = "gfx-backend-gl", - ))] + use raw_window_handle::RawWindowHandle as Rwh; + + let instance = &GLOBAL.instance; + let surface = match raw_handle { + #[cfg(target_os = "ios")] + Rwh::IOS(h) => Surface { + swap_chain: None, + vulkan: None, + metal: instance.metal.create_surface_from_uiview(h.ui_view, cfg!(debug_assertions)), + }, + #[cfg(target_os = "macos")] + Rwh::MacOS(h) => Surface { + swap_chain: None, + vulkan: instance.vulkan + .as_ref() + .map(|inst| inst.create_surface_from_nsview(h.ns_view)), + metal: instance.metal.create_surface_from_nsview(h.ns_view, cfg!(debug_assertions)), + }, + #[cfg(unix)] + Rwh::X11(h) => Surface { + swap_chain: None, + vulkan: instance.vulkan + .as_ref() + .map(|inst| inst.create_surface_from_xlib(h.display as _, h.window as _)), + }, + #[cfg(unix)] + Rwh::Wayland(h) => Surface { + swap_chain: None, + vulkan: instance.vulkan + .as_ref() + .map(|inst| inst.create_surface_from_wayland(h.display, h.surface)), + }, + #[cfg(windows)] + Rwh::Windows(h) => Surface { + swap_chain: None, + vulkan: instance.vulkan + .as_ref() + .map(|inst| inst.create_surface_from_hwnd(std::ptr::null_mut(), h.hwnd)), + //dx11: instance.dx11.create_surface_from_hwnd(h.hwnd), + //dx12: instance.dx11 + // .as_ref() + // .map(|inst| inst.create_surface_from_hwnd(h.hwnd), + }, _ => panic!("Unsupported window handle"), - #[cfg(not(any( - feature = "gfx-backend-vulkan", - feature = "gfx-backend-dx11", - feature = "gfx-backend-dx12", - feature = "gfx-backend-metal", - feature = "gfx-backend-gl", - )))] - _ => { let _ = instance; back::Surface }, }; - let surface = SurfaceHandle::new(raw); - HUB.surfaces.register_local(surface, &mut token) + + let mut token = Token::root(); + GLOBAL.surfaces.register_identity(PhantomData, surface, &mut token) } -#[cfg(not(feature = "gfx-backend-gl"))] -#[allow(unused_variables)] -pub fn instance_create_surface_from_xlib( - instance_id: InstanceId, - display: *mut *const std::ffi::c_void, - window: u64, - token: &mut Token, -) -> SurfaceHandle { - #[cfg(not(all(unix, feature = "gfx-backend-vulkan")))] - unimplemented!(); - - #[cfg(all(unix, feature = "gfx-backend-vulkan"))] - { - let (instance_guard, _) = HUB.instances.read(token); - SurfaceHandle::new(instance_guard[instance_id].create_surface_from_xlib(display, window)) - } -} - -#[cfg(all(feature = "local", not(feature = "gfx-backend-gl")))] +#[cfg(all(not(feature = "remote"), unix))] #[no_mangle] -pub extern "C" fn wgpu_instance_create_surface_from_xlib( - instance_id: InstanceId, +pub extern "C" fn wgpu_create_surface_from_xlib( display: *mut *const std::ffi::c_void, window: u64, ) -> SurfaceId { - let mut token = Token::root(); - let surface = instance_create_surface_from_xlib(instance_id, display, window, &mut token); - HUB.surfaces.register_local(surface, &mut token) + use raw_window_handle::unix::X11Handle; + wgpu_create_surface( + raw_window_handle::RawWindowHandle::X11(X11Handle { + window, + display: display as *mut _, + .. X11Handle::empty() + }), + ) } -#[cfg(not(feature = "gfx-backend-gl"))] -#[allow(unused_variables)] -pub fn instance_create_surface_from_macos_layer( - instance_id: InstanceId, - layer: *mut std::ffi::c_void, - token: &mut Token, -) -> SurfaceHandle { - #[cfg(not(feature = "gfx-backend-metal"))] - unimplemented!(); - - #[cfg(feature = "gfx-backend-metal")] - { - let (instance_guard, _) = HUB.instances.read(token); - SurfaceHandle::new( - instance_guard[instance_id] - .create_surface_from_layer(layer as *mut _, cfg!(debug_assertions)), - ) - } -} - -#[cfg(all(feature = "local", not(feature = "gfx-backend-gl")))] +#[cfg(all(not(feature = "remote"), any(target_os = "ios", target_os = "macos")))] #[no_mangle] -pub extern "C" fn wgpu_instance_create_surface_from_macos_layer( - instance_id: InstanceId, +pub extern "C" fn wgpu_create_surface_from_metal_layer( layer: *mut std::ffi::c_void, ) -> SurfaceId { - let mut token = Token::root(); - let surface = instance_create_surface_from_macos_layer(instance_id, layer, &mut token); - HUB.surfaces.register_local(surface, &mut token) + let surface = Surface { + swap_chain: None, + vulkan: GLOBAL.instance.vulkan + .as_ref() + .map(|inst| inst.create_surface_from_layer(h.ns_view)), + metal: GLOBAL.instance.metal.create_surface_from_nsview(h.ns_view, cfg!(debug_assertions)), + }; + + GLOBAL.surfaces.register_identity(PhantomData, surface, &mut Token::root()) } -#[cfg(not(feature = "gfx-backend-gl"))] -#[allow(unused_variables)] -pub fn instance_create_surface_from_windows_hwnd( - instance_id: InstanceId, - hinstance: *mut std::ffi::c_void, - hwnd: *mut std::ffi::c_void, - token: &mut Token, -) -> SurfaceHandle { - let (instance_guard, _) = HUB.instances.read(token); - - #[cfg(not(any( - feature = "gfx-backend-dx11", - feature = "gfx-backend-dx12", - all(target_os = "windows", feature = "gfx-backend-vulkan"), - )))] - let raw = unimplemented!(); - - #[cfg(any(feature = "gfx-backend-dx11", feature = "gfx-backend-dx12"))] - let raw = instance_guard[instance_id].create_surface_from_hwnd(hwnd); - - #[cfg(all(target_os = "windows", feature = "gfx-backend-vulkan"))] - let raw = instance_guard[instance_id].create_surface_from_hwnd(hinstance, hwnd); - - #[allow(unreachable_code)] - SurfaceHandle::new(raw) -} - -#[cfg(all(feature = "local", not(feature = "gfx-backend-gl")))] +#[cfg(all(not(feature = "remote"), windows))] #[no_mangle] -pub extern "C" fn wgpu_instance_create_surface_from_windows_hwnd( - instance_id: InstanceId, - hinstance: *mut std::ffi::c_void, +pub extern "C" fn wgpu_create_surface_from_windows_hwnd( + _hinstance: *mut std::ffi::c_void, hwnd: *mut std::ffi::c_void, ) -> SurfaceId { - let mut token = Token::root(); - let surface = instance_create_surface_from_windows_hwnd(instance_id, hinstance, hwnd, &mut token); - HUB.surfaces.register_local(surface, &mut token) + use raw_window_handle::windows::Handle; + wgpu_create_surface( + raw_window_handle::RawWindowHandle::Windows(raw_window_handle::windows::Handle { + hwnd, + .. Handle::empty() + }), + ) } -#[cfg(all(feature = "local", feature = "gfx-backend-gl"))] -pub fn wgpu_instance_get_gl_surface(instance_id: InstanceId) -> SurfaceId { +#[cfg(all(not(feature = "remote"), feature = "gfx-backend-gl"))] +pub fn wgpu_get_gl_surface() -> SurfaceId { instance_id } -pub fn instance_get_adapter( - instance_id: InstanceId, +pub fn request_adapter( desc: &RequestAdapterOptions, - token: &mut Token, -) -> AdapterHandle { - #[cfg(not(feature = "gfx-backend-gl"))] - let adapters = { - let (instance_guard, _) = HUB.instances.read(token); - instance_guard[instance_id].enumerate_adapters() - }; - #[cfg(feature = "glutin")] - let adapters = { - let (surface_guard, _) = HUB.surfaces.read(token); - surface_guard[instance_id].raw.enumerate_adapters() - }; - #[cfg(all(not(feature = "glutin"), feature = "gfx-backend-gl"))] - let adapters = Vec::::new(); + input_ids: &[Input], +) -> Option> { + let instance = &GLOBAL.instance; + let mut device_types = Vec::new(); - let (mut integrated_first, mut discrete_first, mut discrete_last, mut alternative) = - (None, None, None, None); + #[cfg(feature = "remote")] + let find_input = |b: Backend| input_ids.iter().find(|id| id.backend() == b).cloned(); + #[cfg(not(feature = "remote"))] + let find_input = |_: Backend| { let _ = input_ids; Some(PhantomData) }; + + let id_vulkan = find_input(Backend::Vulkan); + let id_metal = find_input(Backend::Metal); + + let mut adapters_vk = match instance.vulkan { + Some(ref inst) if id_vulkan.is_some() => { + inst.enumerate_adapters() + } + _ => Vec::new(), + }; + device_types.extend(adapters_vk.iter().map(|ad| ad.info.device_type.clone())); + #[cfg(any(target_os = "ios", target_os = "macos"))] + let mut adaptres_mtl = if id_metal.is_some() { + let adapters = instance.metal.enumerate_adapters(); + device_types.extend(adapters.iter().map(|ad| ad.info.device_type.clone())); + adapters + } else { + Vec::new() + }; + + if device_types.is_empty() { + panic!("No adapters are available!"); + } + + let (mut integrated_first, mut discrete_first, mut discrete_last) = (None, None, None); // On Windows > 1803, dx12 enumerate_adapters returns the adapters in order from highest to // lowest performance. Therefore, the first found adapter in each category is selected. // // TODO: move power/performance policy querying into gfx, which has more context into // performance policy than wgpu - for (i, adapter) in adapters.iter().enumerate() { - match adapter.info.device_type { + for (i, ty) in device_types.into_iter().enumerate() { + match ty { hal::adapter::DeviceType::IntegratedGpu => { integrated_first = integrated_first.or(Some(i)); } @@ -282,7 +273,7 @@ pub fn instance_get_adapter( discrete_first = discrete_first.or(Some(i)); discrete_last = Some(i); } - _ => alternative = Some(i), + _ => {}, } } @@ -293,62 +284,83 @@ pub fn instance_get_adapter( discrete_first.or(integrated_first) } }; + let mut token = Token::root(); - let selected = preferred_gpu - .or(alternative) - .expect("No adapters found. Please enable the feature for one of the graphics backends: vulkan, metal, dx12, dx11, gl"); - - adapters.into_iter().nth(selected).unwrap() + let mut selected = preferred_gpu.unwrap_or(0); + { + if selected < adapters_vk.len() { + let adapter = Adapter { + raw: adapters_vk.swap_remove(selected), + }; + info!("Adapter Vulkan {:?}", adapter.raw.info); + let id_out = gfx_backend_vulkan::Backend::hub() + .adapters + .register_identity(id_vulkan.unwrap(), adapter, &mut token); + return Some(id_out); + } + selected -= adapters_vk.len(); + } + #[cfg(any(target_os = "ios", target_os = "macos"))] + { + if selected < adapters_mtl.len() { + let adapter = Adapter { + raw: adapters_mtl.swap_remove(selected), + }; + info!("Adapter Metal {:?}", adapter.raw.info); + let id_out = gfx_backend_metal::Backend::hub() + .adapters + .register_identity(id_metal.unwrap(), adapter, &mut token); + return Some(id_out); + } + selected -= adapters_mtl.len(); + } + let _ = (selected, id_metal); + None } -#[cfg(feature = "local")] +#[cfg(not(feature = "remote"))] #[no_mangle] -pub extern "C" fn wgpu_instance_request_adapter( - instance_id: InstanceId, +pub extern "C" fn wgpu_request_adapter( desc: Option<&RequestAdapterOptions>, ) -> AdapterId { - let mut token = Token::root(); - let adapter = instance_get_adapter(instance_id, &desc.cloned().unwrap_or_default(), &mut token); - let limits = adapter.physical_device.limits(); - - info!("Adapter {:?}", adapter.info); - - assert!( - BIND_BUFFER_ALIGNMENT % limits.min_storage_buffer_offset_alignment == 0, - "Adapter storage buffer offset alignment not compatible with WGPU" - ); - assert!( - BIND_BUFFER_ALIGNMENT % limits.min_uniform_buffer_offset_alignment == 0, - "Adapter uniform buffer offset alignment not compatible with WGPU" - ); - - HUB.adapters.register_local(adapter, &mut token) + request_adapter(&desc.cloned().unwrap_or_default(), &[]).unwrap() } -pub fn adapter_create_device( +pub fn adapter_request_device( adapter_id: AdapterId, _desc: &DeviceDescriptor, - token: &mut Token, -) -> DeviceHandle { - let (adapter_guard, _) = HUB.adapters.read(token); - let adapter = &adapter_guard[adapter_id]; - let (raw, queue_group) = adapter.open_with::<_, hal::General>(1, |_qf| true).unwrap(); - let mem_props = adapter.physical_device.memory_properties(); + id_in: Input, +) -> Output { + let hub = B::hub(); + let mut token = Token::root(); + let device = { + let (adapter_guard, _) = hub.adapters.read(&mut token); + let adapter = &adapter_guard[adapter_id].raw; + let (raw, queue_group) = adapter.open_with::<_, hal::General>(1, |_qf| true).unwrap(); - DeviceHandle::new(raw, adapter_id, queue_group, mem_props) + let limits = adapter.physical_device.limits(); + assert_eq!( + 0, BIND_BUFFER_ALIGNMENT % limits.min_storage_buffer_offset_alignment, + "Adapter storage buffer offset alignment not compatible with WGPU" + ); + assert_eq!( + 0, BIND_BUFFER_ALIGNMENT % limits.min_uniform_buffer_offset_alignment, + "Adapter uniform buffer offset alignment not compatible with WGPU" + ); + + let mem_props = adapter.physical_device.memory_properties(); + Device::new(raw, adapter_id, queue_group, mem_props) + }; + + hub.devices.register_identity(id_in, device, &mut token) } -#[cfg(feature = "local")] +#[cfg(not(feature = "remote"))] #[no_mangle] pub extern "C" fn wgpu_adapter_request_device( adapter_id: AdapterId, desc: Option<&DeviceDescriptor>, ) -> DeviceId { - let mut token = Token::root(); - let device = adapter_create_device( - adapter_id, - &desc.cloned().unwrap_or_default(), - &mut token, - ); - HUB.devices.register_local(device, &mut token) + let desc = &desc.cloned().unwrap_or_default(); + gfx_select!(adapter_id => adapter_request_device(adapter_id, desc, PhantomData)) } diff --git a/wgpu-native/src/lib.rs b/wgpu-native/src/lib.rs index 4a4697219..faedef458 100644 --- a/wgpu-native/src/lib.rs +++ b/wgpu-native/src/lib.rs @@ -1,21 +1,9 @@ -#[cfg(feature = "gfx-backend-dx11")] -extern crate gfx_backend_dx11 as back; -#[cfg(feature = "gfx-backend-dx12")] -extern crate gfx_backend_dx12 as back; -#[cfg(not(any( - feature = "gfx-backend-vulkan", - feature = "gfx-backend-dx11", - feature = "gfx-backend-dx12", - feature = "gfx-backend-metal", - feature = "gfx-backend-gl", -)))] -extern crate gfx_backend_empty as back; -#[cfg(feature = "gfx-backend-metal")] -extern crate gfx_backend_metal as back; -#[cfg(feature = "gfx-backend-vulkan")] -extern crate gfx_backend_vulkan as back; -#[cfg(feature = "gfx-backend-gl")] -extern crate gfx_backend_gl as back; +pub mod backend { + pub use gfx_backend_empty::Backend as Empty; + pub use gfx_backend_vulkan::Backend as Vulkan; + #[cfg(any(target_os = "ios", target_os = "macos"))] + pub use gfx_backend_metal::Backend as Metal; +} mod binding_model; mod command; @@ -32,8 +20,8 @@ mod id; pub use self::binding_model::*; pub use self::command::*; pub use self::device::*; -#[cfg(not(feature = "local"))] -pub use self::hub::{Access, IdentityManager, Registry, Token, HUB}; +#[cfg(feature = "remote")] +pub use self::hub::{Access, IdentityManager, Registry, Token}; pub use self::instance::*; pub use self::pipeline::*; pub use self::resource::*; @@ -54,13 +42,15 @@ type SubmissionIndex = usize; type Index = u32; type Epoch = u32; +#[repr(u8)] #[derive(Clone, Copy, Debug, PartialEq)] pub enum Backend { - Vulkan, - Gl, - Metal, - Dx12, - Dx11, + Empty = 0, + Vulkan = 1, + Gl = 2, + Metal = 3, + Dx12 = 4, + Dx11 = 5, } pub type BufferAddress = u64; @@ -203,3 +193,18 @@ pub struct U32Array { pub bytes: *const u32, pub length: usize, } + +#[derive(Debug)] +pub enum InputState {} + +#[macro_export] +macro_rules! gfx_select { + ($id:expr => $function:ident( $($param:expr),+ )) => { + match $id.backend() { + $crate::Backend::Vulkan => $function::<$crate::backend::Vulkan>( $($param),+ ), + #[cfg(any(target_os = "ios", target_os = "macos"))] + $crate::Backend::Metal => $function::<$crate::backend::Metal>( $($param),+ ), + _ => unreachable!() + } + }; +} diff --git a/wgpu-native/src/resource.rs b/wgpu-native/src/resource.rs index 418dc8ac2..1a2a668a9 100644 --- a/wgpu-native/src/resource.rs +++ b/wgpu-native/src/resource.rs @@ -62,7 +62,7 @@ pub enum BufferMapAsyncStatus { } #[derive(Clone, Debug)] -pub(crate) enum BufferMapOperation { +pub enum BufferMapOperation { Read(std::ops::Range, BufferMapReadCallback, *mut u8), Write(std::ops::Range, BufferMapWriteCallback, *mut u8), } @@ -70,6 +70,21 @@ pub(crate) enum BufferMapOperation { unsafe impl Send for BufferMapOperation {} unsafe impl Sync for BufferMapOperation {} +impl BufferMapOperation { + pub(crate) fn call_error(self) { + match self { + BufferMapOperation::Read(_, callback, userdata) => { + log::error!("wgpu_buffer_map_read_async failed: buffer mapping is pending"); + callback(BufferMapAsyncStatus::Error, std::ptr::null_mut(), userdata); + } + BufferMapOperation::Write(_, callback, userdata) => { + log::error!("wgpu_buffer_map_write_async failed: buffer mapping is pending"); + callback(BufferMapAsyncStatus::Error, std::ptr::null_mut(), userdata); + } + } + } +} + #[derive(Debug)] pub struct Buffer { pub(crate) raw: B::Buffer, @@ -193,17 +208,16 @@ pub struct TextureDescriptor { #[derive(Debug)] pub(crate) enum TexturePlacement { - #[cfg_attr(not(feature = "local"), allow(unused))] + #[cfg_attr(not(not(feature = "remote")), allow(unused))] SwapChain(SwapChainLink>), Memory(MemoryBlock), - Void, } impl TexturePlacement { pub fn as_swap_chain(&self) -> &SwapChainLink> { match *self { TexturePlacement::SwapChain(ref link) => link, - TexturePlacement::Memory(_) | TexturePlacement::Void => { + TexturePlacement::Memory(_) => { panic!("Expected swap chain link!") } } @@ -274,7 +288,7 @@ pub struct TextureView { pub(crate) samples: hal::image::NumSamples, pub(crate) range: hal::image::SubresourceRange, pub(crate) is_owned_by_swap_chain: bool, - #[cfg_attr(not(feature = "local"), allow(dead_code))] + #[cfg_attr(not(not(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 8f4417c14..8fcb703cb 100644 --- a/wgpu-native/src/swap_chain.rs +++ b/wgpu-native/src/swap_chain.rs @@ -1,7 +1,8 @@ use crate::{ + gfx_select, conv, device::all_image_stages, - hub::{HUB, Token}, + hub::{GfxBackend, Token}, resource, DeviceId, Extent3d, @@ -40,21 +41,6 @@ impl SwapChainLink> { } } -#[derive(Debug)] -pub struct Surface { - pub(crate) raw: B::Surface, - pub(crate) swap_chain: Option>, -} - -impl Surface { - pub(crate) fn new(raw: B::Surface) -> Self { - Surface { - raw, - swap_chain: None, - } - } -} - #[derive(Debug)] pub(crate) struct Frame { pub texture_id: Stored, @@ -76,7 +62,7 @@ pub struct SwapChain { pub(crate) frames: Vec>, pub(crate) acquired: Vec, pub(crate) sem_available: B::Semaphore, - #[cfg_attr(not(feature = "local"), allow(dead_code))] //TODO: remove + #[cfg_attr(not(not(feature = "remote")), allow(dead_code))] //TODO: remove pub(crate) command_pool: hal::CommandPool, } @@ -122,39 +108,31 @@ pub struct SwapChainOutput { pub view_id: TextureViewId, } -#[no_mangle] -pub extern "C" fn wgpu_swap_chain_get_next_texture(swap_chain_id: SwapChainId) -> SwapChainOutput { +pub fn swap_chain_get_next_texture(swap_chain_id: SwapChainId) -> SwapChainOutput { + let hub = B::hub(); let mut token = Token::root(); - let (image_index, device_id, descriptor) = { - let (mut surface_guard, _) = HUB.surfaces.write(&mut token); - let swap_chain = surface_guard[swap_chain_id].swap_chain.as_mut().unwrap(); - let result = unsafe { - swap_chain - .raw - .acquire_image(!0, Some(&swap_chain.sem_available), None) - }; - ( - result.ok(), - swap_chain.device_id.value, - swap_chain.desc.clone(), - ) - }; - #[cfg(not(feature = "local"))] - let _ = descriptor; - #[cfg(feature = "local")] + let (device_guard, mut token) = hub.devices.read(&mut token); + let (mut swap_chain_guard, _) = hub.swap_chains.write(&mut token); + let swap_chain = &mut swap_chain_guard[swap_chain_id]; + let device = &device_guard[swap_chain.device_id.value]; + + let image_index = unsafe { + swap_chain.raw + .acquire_image(!0, Some(&swap_chain.sem_available), None) + }.ok(); + + #[cfg(not(feature = "remote"))] { - use crate::device::{device_create_swap_chain, swap_chain_populate_textures}; + //use crate::device::device_create_swap_chain_textures} if image_index.is_none() { warn!("acquire_image failed, re-creating"); - let textures = device_create_swap_chain(device_id, swap_chain_id, &descriptor, &mut token); - swap_chain_populate_textures(swap_chain_id, textures, &mut token); + unimplemented!() + //let textures = device_create_swap_chain(device_id, swap_chain_id, &descriptor, &mut token); + //swap_chain_populate_textures(swap_chain_id, textures, &mut token); //TODO? } } - let (mut surface_guard, mut token) = HUB.surfaces.write(&mut token); - let swap_chain = surface_guard[swap_chain_id].swap_chain.as_mut().unwrap(); - let image_index = match image_index { Some((index, suboptimal)) => { if suboptimal.is_some() { @@ -171,9 +149,6 @@ pub extern "C" fn wgpu_swap_chain_get_next_texture(swap_chain_id: SwapChainId) - }, }; - let (device_guard, mut token) = HUB.devices.read(&mut token); - let device = &device_guard[device_id]; - assert_ne!( swap_chain.acquired.len(), swap_chain.acquired.capacity(), @@ -196,7 +171,7 @@ pub extern "C" fn wgpu_swap_chain_get_next_texture(swap_chain_id: SwapChainId) - mem::swap(&mut frame.sem_available, &mut swap_chain.sem_available); frame.need_waiting.store(true, Ordering::Release); - let (texture_guard, _) = HUB.textures.read(&mut token); + let (texture_guard, _) = hub.textures.read(&mut token); let frame_epoch = texture_guard[frame.texture_id.value] .placement .as_swap_chain() @@ -215,10 +190,18 @@ pub extern "C" fn wgpu_swap_chain_get_next_texture(swap_chain_id: SwapChainId) - } #[no_mangle] -pub extern "C" fn wgpu_swap_chain_present(swap_chain_id: SwapChainId) { +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)) +} + +pub fn swap_chain_present(swap_chain_id: SwapChainId) { + let hub = B::hub(); let mut token = Token::root(); - let (mut surface_guard, mut token) = HUB.surfaces.write(&mut token); - let swap_chain = surface_guard[swap_chain_id].swap_chain.as_mut().unwrap(); + + 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 swap_chain = &mut swap_chain_guard[swap_chain_id]; + let device = &mut device_guard[swap_chain.device_id.value]; let image_index = swap_chain.acquired.remove(0); let frame = &mut swap_chain.frames[image_index as usize]; @@ -234,10 +217,7 @@ pub extern "C" fn wgpu_swap_chain_present(swap_chain_id: SwapChainId) { image_index ); - let (mut device_guard, mut token) = HUB.devices.write(&mut token); - let device = &mut device_guard[swap_chain.device_id.value]; - - let (texture_guard, _) = HUB.textures.read(&mut token); + let (texture_guard, _) = hub.textures.read(&mut token); let texture = &texture_guard[frame.texture_id.value]; texture.placement.as_swap_chain().bump_epoch(); @@ -292,3 +272,8 @@ pub extern "C" fn wgpu_swap_chain_present(swap_chain_id: SwapChainId) { warn!("present failed: {:?}", e); } } + +#[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)) +} diff --git a/wgpu-native/src/track/buffer.rs b/wgpu-native/src/track/buffer.rs index 1483a52a3..7a39006c0 100644 --- a/wgpu-native/src/track/buffer.rs +++ b/wgpu-native/src/track/buffer.rs @@ -119,7 +119,7 @@ mod test { init: BufferUsage::INDEX, last: BufferUsage::STORAGE, }; - let id = TypedId::zip(0, 0, Backend::Vulkan); + let id = TypedId::zip(0, 0, Backend::Empty); assert!(bs.change(id, (), BufferUsage::VERTEX, None).is_err()); bs.change(id, (), BufferUsage::VERTEX, Some(&mut Vec::new())).unwrap(); bs.change(id, (), BufferUsage::INDEX, None).unwrap(); diff --git a/wgpu-native/src/track/mod.rs b/wgpu-native/src/track/mod.rs index 60dd90a12..927ce3cd2 100644 --- a/wgpu-native/src/track/mod.rs +++ b/wgpu-native/src/track/mod.rs @@ -158,22 +158,24 @@ pub struct ResourceTracker { map: FastHashMap>, /// Temporary storage for collecting transitions. temp: Vec>, + /// The backend variant for all the tracked resources. backend: Backend, } impl ResourceTracker { /// Create a new empty tracker. - pub fn new() -> Self { + pub fn new(backend: Backend) -> Self { ResourceTracker { map: FastHashMap::default(), temp: Vec::new(), - backend: Backend::Vulkan, //TODO + backend, } } /// Remove an id from the tracked map. pub fn remove(&mut self, id: S::Id) -> bool { - let (index, epoch, _) = id.unzip(); + let (index, epoch, backend) = id.unzip(); + debug_assert_eq!(backend, self.backend); match self.map.remove(&index) { Some(resource) => { assert_eq!(resource.epoch, epoch); @@ -195,7 +197,9 @@ impl ResourceTracker { let backend = self.backend; self.map .iter() - .map(move |(&index, resource)| S::Id::zip(index, resource.epoch, backend)) + .map(move |(&index, resource)| { + S::Id::zip(index, resource.epoch, backend) + }) } /// Clear the tracked contents. @@ -224,7 +228,8 @@ impl ResourceTracker { Err(_) => unreachable!(), } - let (index, epoch, _) = id.unzip(); + let (index, epoch, backend) = id.unzip(); + debug_assert_eq!(backend, self.backend); self.map .insert(index, Resource { ref_count: ref_count.clone(), @@ -243,7 +248,8 @@ impl ResourceTracker { id: S::Id, selector: S::Selector, ) -> Option { - let (index, epoch, _) = id.unzip(); + let (index, epoch, backend) = id.unzip(); + debug_assert_eq!(backend, self.backend); let res = self.map.get(&index)?; assert_eq!(res.epoch, epoch); res.state.query(selector) @@ -252,11 +258,13 @@ impl ResourceTracker { /// Make sure that a resource is tracked, and return a mutable /// reference to it. fn get_or_insert<'a>( + self_backend: Backend, map: &'a mut FastHashMap>, id: S::Id, ref_count: &RefCount, ) -> &'a mut Resource { - let (index, epoch, _) = id.unzip(); + let (index, epoch, backend) = id.unzip(); + debug_assert_eq!(self_backend, backend); match map.entry(index) { Entry::Vacant(e) => { e.insert(Resource { @@ -282,7 +290,7 @@ impl ResourceTracker { selector: S::Selector, usage: S::Usage, ) -> Result<(), PendingTransition> { - Self::get_or_insert(&mut self.map, id, ref_count) + Self::get_or_insert(self.backend, &mut self.map, id, ref_count) .state.change(id, selector, usage, None) } @@ -294,7 +302,7 @@ impl ResourceTracker { selector: S::Selector, usage: S::Usage, ) -> Drain> { - let res = Self::get_or_insert(&mut self.map, id, ref_count); + let res = Self::get_or_insert(self.backend, &mut self.map, id, ref_count); res.state.change(id, selector, usage, Some(&mut self.temp)) .ok(); //TODO: unwrap? self.temp.drain(..) @@ -305,6 +313,7 @@ impl ResourceTracker { pub fn merge_extend( &mut self, other: &Self, ) -> Result<(), PendingTransition> { + debug_assert_eq!(self.backend, other.backend); for (&index, new) in other.map.iter() { match self.map.entry(index) { Entry::Vacant(e) => { @@ -429,12 +438,12 @@ pub struct TrackerSet { impl TrackerSet { /// Create an empty set. - pub fn new() -> Self { + pub fn new(backend: Backend) -> Self { TrackerSet { - buffers: ResourceTracker::new(), - textures: ResourceTracker::new(), - views: ResourceTracker::new(), - bind_groups: ResourceTracker::new(), + buffers: ResourceTracker::new(backend), + textures: ResourceTracker::new(backend), + views: ResourceTracker::new(backend), + bind_groups: ResourceTracker::new(backend), } } @@ -462,4 +471,8 @@ impl TrackerSet { self.views.merge_extend(&other.views).unwrap(); self.bind_groups.merge_extend(&other.bind_groups).unwrap(); } + + pub fn backend(&self) -> Backend { + self.buffers.backend + } } diff --git a/wgpu-remote/Cargo.toml b/wgpu-remote/Cargo.toml index e3d00abcd..a7ae1db2b 100644 --- a/wgpu-remote/Cargo.toml +++ b/wgpu-remote/Cargo.toml @@ -12,11 +12,6 @@ crate-type = ["lib", "cdylib", "staticlib"] [features] default = [] -vulkan = ["wgpu-native/gfx-backend-vulkan"] -dx11 = ["wgpu-native/gfx-backend-dx11"] -dx12 = ["wgpu-native/gfx-backend-dx12"] -metal = ["wgpu-native/gfx-backend-metal"] -gl = ["wgpu-native/gfx-backend-gl"] [dependencies] wgpu-native = { path = "../wgpu-native", version = "0.3", features = ["remote"] } diff --git a/wgpu-remote/src/lib.rs b/wgpu-remote/src/lib.rs index 4428bb7d7..5a0c2d98c 100644 --- a/wgpu-remote/src/lib.rs +++ b/wgpu-remote/src/lib.rs @@ -1,6 +1,6 @@ //TODO: remove once `cbindgen` is smart enough extern crate wgpu_native as wgn; -use wgn::{AdapterId, DeviceId, InstanceId}; +use wgn::{AdapterId, Backend, DeviceId, IdentityManager, SurfaceId}; use crate::server::Server; @@ -9,22 +9,15 @@ use log::error; use parking_lot::Mutex; use serde::{Deserialize, Serialize}; -use std::ptr; +use std::{ptr, sync::Arc}; mod server; -#[derive(Serialize, Deserialize, Debug)] -enum InstanceMessage { - Create(wgn::InstanceId), - InstanceRequestAdapter(wgn::InstanceId, wgn::RequestAdapterOptions, wgn::AdapterId), - AdapterCreateDevice(wgn::AdapterId, wgn::DeviceDescriptor, wgn::DeviceId), - Destroy(wgn::InstanceId), -} - /// A message on the timeline of devices, queues, and resources. #[derive(Serialize, Deserialize, Debug)] enum GlobalMessage { - Instance(InstanceMessage), + RequestAdapter(wgn::RequestAdapterOptions, Vec), + AdapterRequestDevice(wgn::AdapterId, wgn::DeviceDescriptor, wgn::DeviceId), //Device(DeviceMessage), //Queue(QueueMessage), //Texture(TextureMessage), @@ -32,29 +25,75 @@ enum GlobalMessage { Terminate, } -#[derive(Default, Debug)] +#[derive(Debug)] struct IdentityHub { - adapters: wgn::IdentityManager, - devices: wgn::IdentityManager, + adapters: IdentityManager, + devices: IdentityManager, + /* + pipeline_layouts: IdentityManager, + shader_modules: IdentityManager, + bind_group_layouts: IdentityManager, + bind_groups: IdentityManager, + command_buffers: IdentityManager, + render_passes: IdentityManager, + render_pipelines: IdentityManager, + compute_passes: IdentityManager, + compute_pipelines: IdentityManager, + buffers: IdentityManager, + textures: IdentityManager, + texture_views: IdentityManager, + samplers: IdentityManager, + */ +} + +impl IdentityHub { + fn new(backend: Backend) -> Self { + IdentityHub { + adapters: IdentityManager::new(backend), + devices: IdentityManager::new(backend), + } + } } #[derive(Debug)] +struct Identities { + surfaces: IdentityManager, + vulkan: IdentityHub, + #[cfg(any(target_os = "ios", target_os = "macos"))] + metal: IdentityHub, +} + +impl Identities { + fn new() -> Self { + Identities { + surfaces: IdentityManager::new(Backend::Empty), + vulkan: IdentityHub::new(Backend::Vulkan), + #[cfg(any(target_os = "ios", target_os = "macos"))] + metal: IdentityHub::new(Backend::Metal), + } + } + + fn select(&mut self, backend: Backend) -> &mut IdentityHub { + match backend { + Backend::Vulkan => &mut self.vulkan, + #[cfg(any(target_os = "ios", target_os = "macos"))] + Backend::Metal => &mut self.metal, + _ => panic!("Unexpected backend: {:?}", backend), + } + } +} + + +#[derive(Clone, Debug)] pub struct Client { channel: ipc::IpcSender, - instance_id: wgn::InstanceId, - identity: Mutex, -} - -#[derive(Debug)] -pub struct ClientFactory { - channel: ipc::IpcSender, - instance_identities: Mutex>, + identities: Arc>, } #[repr(C)] #[derive(Debug)] pub struct Infrastructure { - pub factory: *mut ClientFactory, + pub client: *mut Client, pub server: *mut Server, pub error: *const u8, } @@ -63,13 +102,13 @@ pub struct Infrastructure { pub extern "C" fn wgpu_initialize() -> Infrastructure { match ipc::channel() { Ok((sender, receiver)) => { - let factory = ClientFactory { + let client = Client { channel: sender, - instance_identities: Mutex::new(wgn::IdentityManager::default()), + identities: Arc::new(Mutex::new(Identities::new())), }; let server = Server::new(receiver); Infrastructure { - factory: Box::into_raw(Box::new(factory)), + client: Box::into_raw(Box::new(client)), server: Box::into_raw(Box::new(server)), error: ptr::null(), } @@ -77,7 +116,7 @@ pub extern "C" fn wgpu_initialize() -> Infrastructure { Err(e) => { error!("WGPU initialize failed: {:?}", e); Infrastructure { - factory: ptr::null_mut(), + client: ptr::null_mut(), server: ptr::null_mut(), error: ptr::null(), //TODO_remote_ } @@ -86,45 +125,29 @@ pub extern "C" fn wgpu_initialize() -> Infrastructure { } #[no_mangle] -pub extern "C" fn wgpu_terminate(factory: *mut ClientFactory) { - let factory = unsafe { Box::from_raw(factory) }; - let _ = factory.channel.send(GlobalMessage::Terminate); -} - -#[no_mangle] -pub extern "C" fn wgpu_client_create(factory: &ClientFactory) -> *mut Client { - let instance_id = factory.instance_identities.lock().alloc(); - let msg = GlobalMessage::Instance(InstanceMessage::Create(instance_id)); - factory.channel.send(msg).unwrap(); - let client = Client { - channel: factory.channel.clone(), - instance_id, - identity: Mutex::new(IdentityHub::default()), - }; - Box::into_raw(Box::new(client)) -} - -#[no_mangle] -pub extern "C" fn wgpu_client_destroy(factory: &ClientFactory, client: *mut Client) { +pub extern "C" fn wgpu_terminate(client: *mut Client) { let client = unsafe { Box::from_raw(client) }; - factory.instance_identities.lock().free(client.instance_id); - let msg = GlobalMessage::Instance(InstanceMessage::Destroy(client.instance_id)); - client.channel.send(msg).unwrap(); + let msg = GlobalMessage::Terminate; + let _ = client.channel.send(msg); } #[no_mangle] -pub extern "C" fn wgpu_client_get_adapter( +pub extern "C" fn wgpu_client_request_adapter( client: &Client, desc: &wgn::RequestAdapterOptions, ) -> wgn::AdapterId { - let adapter_id = client.identity.lock().adapters.alloc(); - let msg = GlobalMessage::Instance(InstanceMessage::InstanceRequestAdapter( - client.instance_id, + let mut identities = client.identities.lock(); + let ids = vec![ + identities.vulkan.adapters.alloc(), + #[cfg(any(target_os = "ios", target_os = "macos"))] + identities.metal.adapters.alloc(), + ]; + let msg = GlobalMessage::RequestAdapter( desc.clone(), - adapter_id, - )); + ids, + ); client.channel.send(msg).unwrap(); - adapter_id + unimplemented!() } #[no_mangle] @@ -133,12 +156,15 @@ pub extern "C" fn wgpu_client_adapter_create_device( adapter_id: wgn::AdapterId, desc: &wgn::DeviceDescriptor, ) -> wgn::DeviceId { - let device_id = client.identity.lock().devices.alloc(); - let msg = GlobalMessage::Instance(InstanceMessage::AdapterCreateDevice( + let device_id = client.identities + .lock() + .select(adapter_id.backend()) + .devices.alloc(); + let msg = GlobalMessage::AdapterRequestDevice( adapter_id, desc.clone(), device_id, - )); + ); client.channel.send(msg).unwrap(); device_id } diff --git a/wgpu-remote/src/server.rs b/wgpu-remote/src/server.rs index 8c128e9e0..20eb2f02f 100644 --- a/wgpu-remote/src/server.rs +++ b/wgpu-remote/src/server.rs @@ -1,4 +1,4 @@ -use crate::{GlobalMessage, InstanceMessage}; +use crate::{GlobalMessage}; use ipc_channel::ipc::IpcReceiver; use wgn; @@ -20,25 +20,14 @@ enum ControlFlow { } fn process(message: GlobalMessage) -> ControlFlow { - let mut token = &mut wgn::Token::root(); match message { - GlobalMessage::Instance(msg) => match msg { - InstanceMessage::Create(instance_id) => { - let instance = wgn::create_instance(); - wgn::HUB.instances.register(instance_id, instance, &mut token); - } - InstanceMessage::InstanceRequestAdapter(instance_id, ref desc, id) => { - let adapter = wgn::instance_get_adapter(instance_id, desc, &mut token); - wgn::HUB.adapters.register(id, adapter, &mut token); - } - InstanceMessage::AdapterCreateDevice(adapter_id, ref desc, id) => { - let device = wgn::adapter_create_device(adapter_id, desc, &mut token); - wgn::HUB.devices.register(id, device, &mut token); - } - InstanceMessage::Destroy(instance_id) => { - wgn::HUB.instances.unregister(instance_id, &mut token); - } - }, + GlobalMessage::RequestAdapter(ref desc, ref ids) => { + wgn::request_adapter(desc, ids); + } + GlobalMessage::AdapterRequestDevice(adapter_id, ref desc, id) => { + use wgn::adapter_request_device as fun; + wgn::gfx_select!(adapter_id => fun(adapter_id, desc, id)); + } GlobalMessage::Terminate => return ControlFlow::Terminate, }