diff --git a/.travis.yml b/.travis.yml index ab52d8422..d5fa7ea9e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -57,10 +57,8 @@ before_install: script: - cargo test - - (cd wgpu-native && cargo check --features local,glutin) - # TODO: Temporarily only test building the gl backend, properly test when it is usable from C - - if [[ $TRAVIS_OS_NAME == "windows" ]]; then (cd wgpu-native && cargo check --features gfx-backend-dx11); fi - - if [[ $TRAVIS_OS_NAME == "windows" ]]; then (cd wgpu-native && cargo check --features gfx-backend-dx12); fi + # TODO: enable GL backend + #- (cd wgpu-native && cargo check --features local,glutin) - if [[ $TRAVIS_OS_NAME == "linux" ]]; then cargo check --release; fi - if [[ $TRAVIS_RUST_VERSION == "nightly" ]]; then cargo +nightly install cbindgen; fi - if [[ $TRAVIS_RUST_VERSION == "nightly" ]] && [[ $TRAVIS_OS_NAME == "windows" ]]; then diff --git a/Cargo.lock b/Cargo.lock index 0dc8f5020..521a1960c 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" @@ -216,19 +181,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" @@ -340,26 +292,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 +343,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 +394,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,23 +404,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" @@ -646,20 +437,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 +491,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,22 +531,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" @@ -849,11 +584,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,25 +787,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" @@ -1131,37 +842,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" @@ -1187,14 +872,6 @@ 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 +914,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 +932,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,98 +980,9 @@ 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.2" +version = "0.3.3" 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)", @@ -1427,7 +990,6 @@ dependencies = [ "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)", @@ -1449,7 +1011,7 @@ dependencies = [ "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.91 (registry+https://github.com/rust-lang/crates.io-index)", - "wgpu-native 0.3.2", + "wgpu-native 0.3.3", ] [[package]] @@ -1476,42 +1038,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" @@ -1538,38 +1069,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 +1083,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" @@ -1595,8 +1094,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" "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" @@ -1610,58 +1107,34 @@ source = "registry+https://github.com/rust-lang/crates.io-index" "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,8 +1158,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" @@ -1695,49 +1166,27 @@ 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..35d6a0f09 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) @@ -16,7 +17,7 @@ int main( char *argv[]) { if (argc != 5) { - printf("You must pass 4 positive integers!"); + printf("You must pass 4 positive integers!\n"); return 0; } @@ -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/framework.c b/examples/framework.c index 82a09e93c..46f73dd1d 100644 --- a/examples/framework.c +++ b/examples/framework.c @@ -8,6 +8,10 @@ WGPUU32Array read_file(const char *name) { FILE *file = fopen(name, "rb"); + if (!file) { + printf("Unable to open %s\n", name); + exit(1); + } fseek(file, 0, SEEK_END); long length = ftell(file); unsigned char *bytes = malloc(length); @@ -27,7 +31,7 @@ void read_buffer_map( (void)userdata; if (status == WGPUBufferMapAsyncStatus_Success) { uint32_t *times = (uint32_t *) data; - printf("Times: [%d, %d, %d, %d]", + printf("Times: [%d, %d, %d, %d]\n", times[0], times[1], times[2], 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..0de981262 100644 --- a/examples/triangle/main.c +++ b/examples/triangle/main.c @@ -33,11 +33,10 @@ #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, + .backends = 2 | 4 | 8, }); WGPUDeviceId device = wgpu_adapter_request_device(adapter, @@ -157,22 +156,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_metal_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 4f8665ecd..234fd571d 100644 --- a/ffi/wgpu-remote.h +++ b/ffi/wgpu-remote.h @@ -15,26 +15,15 @@ typedef enum { typedef struct WGPUClient WGPUClient; -typedef struct WGPUClientFactory WGPUClientFactory; - typedef struct WGPUServer WGPUServer; -typedef uint32_t WGPUIndex; +typedef uint64_t WGPUId_Device_Dummy; -typedef uint32_t WGPUEpoch; +typedef WGPUId_Device_Dummy WGPUDeviceId; -typedef struct { - WGPUIndex _0; - WGPUEpoch _1; -} WGPUId; +typedef uint64_t WGPUId_Adapter_Dummy; -typedef WGPUId WGPUGenericId_DeviceHandle; - -typedef WGPUGenericId_DeviceHandle WGPUDeviceId; - -typedef WGPUId WGPUGenericId_AdapterHandle; - -typedef WGPUGenericId_AdapterHandle WGPUAdapterId; +typedef WGPUId_Adapter_Dummy WGPUAdapterId; typedef struct { bool anisotropic_filtering; @@ -49,12 +38,15 @@ typedef struct { WGPULimits limits; } WGPUDeviceDescriptor; +typedef uint32_t WGPUBackendBit; + typedef struct { WGPUPowerPreference power_preference; + WGPUBackendBit backends; } WGPURequestAdapterOptions; typedef struct { - WGPUClientFactory *factory; + WGPUClient *client; WGPUServer *server; const uint8_t *error; } WGPUInfrastructure; @@ -63,15 +55,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 b11f693f9..2c658d6cb 100644 --- a/ffi/wgpu.h +++ b/ffi/wgpu.h @@ -240,22 +240,13 @@ typedef enum { WGPUVertexFormat_Int4 = 48, } WGPUVertexFormat; -typedef uint32_t WGPUIndex; +typedef uint64_t WGPUId_Device_Dummy; -typedef uint32_t WGPUEpoch; +typedef WGPUId_Device_Dummy WGPUDeviceId; -typedef struct { - WGPUIndex _0; - WGPUEpoch _1; -} WGPUId; +typedef uint64_t WGPUId_Adapter_Dummy; -typedef WGPUId WGPUGenericId_DeviceHandle; - -typedef WGPUGenericId_DeviceHandle WGPUDeviceId; - -typedef WGPUId WGPUGenericId_AdapterHandle; - -typedef WGPUGenericId_AdapterHandle WGPUAdapterId; +typedef WGPUId_Adapter_Dummy WGPUAdapterId; typedef struct { bool anisotropic_filtering; @@ -270,13 +261,13 @@ typedef struct { WGPULimits limits; } WGPUDeviceDescriptor; -typedef WGPUId WGPUGenericId_BindGroupHandle; +typedef uint64_t WGPUId_BindGroup_Dummy; -typedef WGPUGenericId_BindGroupHandle WGPUBindGroupId; +typedef WGPUId_BindGroup_Dummy WGPUBindGroupId; -typedef WGPUId WGPUGenericId_BufferHandle; +typedef uint64_t WGPUId_Buffer_Dummy; -typedef WGPUGenericId_BufferHandle WGPUBufferId; +typedef WGPUId_Buffer_Dummy WGPUBufferId; typedef uint64_t WGPUBufferAddress; @@ -284,23 +275,27 @@ typedef void (*WGPUBufferMapReadCallback)(WGPUBufferMapAsyncStatus status, const typedef void (*WGPUBufferMapWriteCallback)(WGPUBufferMapAsyncStatus status, uint8_t *data, uint8_t *userdata); -typedef WGPUId WGPUGenericId_ComputePassHandle; +typedef uint64_t WGPUId_ComputePass_Dummy; -typedef WGPUGenericId_ComputePassHandle WGPUComputePassId; +typedef WGPUId_ComputePass_Dummy WGPUComputePassId; -typedef WGPUId WGPUGenericId_CommandBufferHandle; +typedef uint64_t WGPUId_CommandBuffer_Dummy; -typedef WGPUGenericId_CommandBufferHandle WGPUCommandBufferId; +typedef WGPUId_CommandBuffer_Dummy WGPUCommandBufferId; typedef WGPUCommandBufferId WGPUCommandEncoderId; -typedef WGPUId WGPUGenericId_RenderPassHandle; +typedef struct { + uint32_t todo; +} WGPUComputePassDescriptor; -typedef WGPUGenericId_RenderPassHandle WGPURenderPassId; +typedef uint64_t WGPUId_RenderPass_Dummy; -typedef WGPUId WGPUGenericId_TextureViewHandle; +typedef WGPUId_RenderPass_Dummy WGPURenderPassId; -typedef WGPUGenericId_TextureViewHandle WGPUTextureViewId; +typedef uint64_t WGPUId_TextureView_Dummy; + +typedef WGPUId_TextureView_Dummy WGPUTextureViewId; typedef struct { double r; @@ -346,9 +341,9 @@ typedef struct { uint32_t image_height; } WGPUBufferCopyView; -typedef WGPUId WGPUGenericId_TextureHandle; +typedef uint64_t WGPUId_Texture_Dummy; -typedef WGPUGenericId_TextureHandle WGPUTextureId; +typedef WGPUId_Texture_Dummy WGPUTextureId; typedef struct { float x; @@ -376,27 +371,17 @@ typedef struct { typedef const char *WGPURawString; -typedef WGPUId WGPUGenericId_ComputePipelineHandle; +typedef uint64_t WGPUId_ComputePipeline_Dummy; -typedef WGPUGenericId_ComputePipelineHandle WGPUComputePipelineId; +typedef WGPUId_ComputePipeline_Dummy WGPUComputePipelineId; -typedef WGPUId WGPUGenericId_InstanceHandle; +typedef uint64_t WGPUId_Surface; -typedef WGPUId WGPUGenericId_SurfaceHandle; +typedef WGPUId_Surface WGPUSurfaceId; -typedef WGPUGenericId_SurfaceHandle WGPUSurfaceId; +typedef uint64_t WGPUId_BindGroupLayout_Dummy; -#if !defined(WGPU_BACKEND_GL) -typedef WGPUGenericId_InstanceHandle WGPUInstanceId; -#endif - -#if defined(WGPU_BACKEND_GL) -typedef WGPUSurfaceId WGPUInstanceId; -#endif - -typedef WGPUId WGPUGenericId_BindGroupLayoutHandle; - -typedef WGPUGenericId_BindGroupLayoutHandle WGPUBindGroupLayoutId; +typedef WGPUId_BindGroupLayout_Dummy WGPUBindGroupLayoutId; typedef struct { WGPUBufferId buffer; @@ -404,9 +389,9 @@ typedef struct { WGPUBufferAddress size; } WGPUBufferBinding; -typedef WGPUId WGPUGenericId_SamplerHandle; +typedef uint64_t WGPUId_Sampler_Dummy; -typedef WGPUGenericId_SamplerHandle WGPUSamplerId; +typedef WGPUId_Sampler_Dummy WGPUSamplerId; typedef enum { WGPUBindingResource_Buffer, @@ -488,13 +473,13 @@ typedef struct { uint32_t todo; } WGPUCommandEncoderDescriptor; -typedef WGPUId WGPUGenericId_PipelineLayoutHandle; +typedef uint64_t WGPUId_PipelineLayout_Dummy; -typedef WGPUGenericId_PipelineLayoutHandle WGPUPipelineLayoutId; +typedef WGPUId_PipelineLayout_Dummy WGPUPipelineLayoutId; -typedef WGPUId WGPUGenericId_ShaderModuleHandle; +typedef uint64_t WGPUId_ShaderModule_Dummy; -typedef WGPUGenericId_ShaderModuleHandle WGPUShaderModuleId; +typedef WGPUId_ShaderModule_Dummy WGPUShaderModuleId; typedef struct { WGPUShaderModuleId module; @@ -511,9 +496,9 @@ typedef struct { uintptr_t bind_group_layouts_length; } WGPUPipelineLayoutDescriptor; -typedef WGPUId WGPUGenericId_RenderPipelineHandle; +typedef uint64_t WGPUId_RenderPipeline_Dummy; -typedef WGPUGenericId_RenderPipelineHandle WGPURenderPipelineId; +typedef WGPUId_RenderPipeline_Dummy WGPURenderPipelineId; typedef struct { WGPUFrontFace front_face; @@ -618,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 @@ -649,14 +636,17 @@ typedef struct { typedef WGPUDeviceId WGPUQueueId; +typedef uint64_t WGPUId_RenderBundle_Dummy; + +typedef WGPUId_RenderBundle_Dummy WGPURenderBundleId; + +typedef uint32_t WGPUBackendBit; + typedef struct { WGPUPowerPreference power_preference; + WGPUBackendBit backends; } WGPURequestAdapterOptions; -typedef WGPUId WGPUGenericId_RenderBundleHandle; - -typedef WGPUGenericId_RenderBundleHandle WGPURenderBundleId; - typedef struct { WGPUTextureId texture_id; WGPUTextureViewId view_id; @@ -672,7 +662,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 @@ -695,12 +685,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 @@ -726,8 +717,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); @@ -751,72 +742,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_metal_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 @@ -824,28 +823,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); @@ -891,10 +868,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, @@ -919,11 +892,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..c44fc6daa 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,15 @@ 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" + +[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies] +gfx-backend-metal = "0.3" + +[target.'cfg(windows)'.dependencies] +gfx-backend-dx12 = "0.3" +gfx-backend-dx11 = "0.3" diff --git a/wgpu-native/src/command/allocator.rs b/wgpu-native/src/command/allocator.rs index 7fed4ca9b..d4af3f54e 100644 --- a/wgpu-native/src/command/allocator.rs +++ b/wgpu-native/src/command/allocator.rs @@ -1,5 +1,5 @@ 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 +48,7 @@ pub struct CommandAllocator { inner: Mutex>, } -impl CommandAllocator { +impl CommandAllocator { pub fn new(queue_family: hal::queue::QueueFamilyId) -> Self { CommandAllocator { queue_family, @@ -64,6 +64,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 +86,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..41939dcec 100644 --- a/wgpu-native/src/command/bind.rs +++ b/wgpu-native/src/command/bind.rs @@ -1,4 +1,12 @@ -use crate::{BindGroupHandle, BindGroupId, BindGroupLayoutId, BufferAddress, PipelineLayoutId, Stored}; +use crate::{ + hub::GfxBackend, + BindGroup, + BindGroupId, + BindGroupLayoutId, + BufferAddress, + PipelineLayoutId, + Stored, +}; use log::trace; @@ -50,12 +58,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 +152,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 +164,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 { @@ -181,7 +193,7 @@ impl Binder { }, self.entries[index + 1 ..] .iter() - .flat_map(|entry| entry.dynamic_offsets.as_slice()) + .flat_map(|entry| entry.dynamic_offsets.as_slice()), ) }) } else { diff --git a/wgpu-native/src/command/compute.rs b/wgpu-native/src/command/compute.rs index ee5ed2903..755783df3 100644 --- a/wgpu-native/src/command/compute.rs +++ b/wgpu-native/src/command/compute.rs @@ -1,7 +1,8 @@ use crate::{ command::bind::{Binder, LayoutChange}, device::all_buffer_stages, - hub::{HUB, Token}, + gfx_select, + hub::{GfxBackend, Token}, track::{Stitch, TrackerSet}, BindGroupId, BufferAddress, @@ -11,9 +12,9 @@ use crate::{ CommandBufferId, ComputePassId, ComputePipelineId, - BIND_BUFFER_ALIGNMENT, RawString, Stored, + BIND_BUFFER_ALIGNMENT, }; use hal::{self, command::RawCommandBuffer}; @@ -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,10 +101,14 @@ 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); + trace!( + "Encoding barriers on binding of {:?} in pass {:?}", + bind_group_id, + pass_id + ); CommandBuffer::insert_barriers( &mut pass.raw, &mut pass.trackers, @@ -113,9 +118,9 @@ pub extern "C" fn wgpu_compute_pass_set_bind_group( &*texture_guard, ); - if let Some((pipeline_layout_id, follow_up_sets, follow_up_offsets)) = - pass.binder - .provide_entry(index as usize, bind_group_id, bind_group, offsets) + if let Some((pipeline_layout_id, follow_up_sets, follow_up_offsets)) = pass + .binder + .provide_entry(index as usize, bind_group_id, bind_group, offsets) { let bind_groups = iter::once(bind_group.raw.raw()) .chain(follow_up_sets.map(|bg_id| bind_group_guard[bg_id].raw.raw())); @@ -133,6 +138,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,30 +174,37 @@ 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 - .trackers - .buffers - .use_replace(&*buffer_guard, indirect_buffer_id, (), BufferUsage::INDIRECT); + let (src_buffer, src_pending) = pass.trackers.buffers.use_replace( + &*buffer_guard, + indirect_buffer_id, + (), + BufferUsage::INDIRECT, + ); let barriers = src_pending.map(|pending| hal::memory::Barrier::Buffer { states: pending.to_states(), @@ -196,16 +224,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 +277,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..4e705fba5 100644 --- a/wgpu-native/src/command/mod.rs +++ b/wgpu-native/src/command/mod.rs @@ -18,37 +18,40 @@ use crate::{ RenderPassContext, RenderPassKey, }, - hub::{HUB, Storage, Token}, + gfx_select, + 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, - Device as _ -}; +use hal::{adapter::PhysicalDevice, command::RawCommandBuffer, Device as _}; use log::trace; -use std::{collections::hash_map::Entry, iter, mem, slice, ptr, thread::ThreadId}; +#[cfg(not(feature = "remote"))] +use std::marker::PhantomData; +use std::{collections::hash_map::Entry, iter, mem, ptr, slice, thread::ThreadId}; + + +pub struct RenderBundle { + _raw: B::CommandBuffer, +} #[repr(C)] #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] @@ -94,6 +97,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,28 +114,31 @@ 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); - let buffer_barriers = - base.buffers - .merge_replace(&head.buffers, stitch) - .map(|pending| { - trace!("\tbuffer -> {:?}", pending); - hal::memory::Barrier::Buffer { - states: pending.to_states(), - target: &buffer_guard[pending.id].raw, - range: None .. None, - families: None, - } - }); + debug_assert_eq!(B::VARIANT, base.backend()); + debug_assert_eq!(B::VARIANT, head.backend()); + + let buffer_barriers = base + .buffers + .merge_replace(&head.buffers, stitch) + .map(|pending| { + trace!("\tbuffer -> {:?}", pending); + hal::memory::Barrier::Buffer { + states: pending.to_states(), + target: &buffer_guard[pending.id].raw, + range: None .. None, + families: None, + } + }); let texture_barriers = base .textures .merge_replace(&head.textures, stitch) @@ -154,7 +166,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 +174,51 @@ 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 +227,108 @@ 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 view = trackers.views - .use_extend(&*view_guard, *resolve_target, (), ()) + 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); @@ -355,18 +343,16 @@ 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); } - 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 - } + 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, None => { // Required sub-resources have inconsistent states, we need to // issue individual barriers instead of relying on the render pass. @@ -377,7 +363,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 +375,318 @@ 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..5ce504d78 100644 --- a/wgpu-native/src/command/render.rs +++ b/wgpu-native/src/command/render.rs @@ -2,7 +2,8 @@ use crate::{ command::bind::{Binder, LayoutChange}, conv, device::{RenderPassContext, BIND_BUFFER_ALIGNMENT, MAX_VERTEX_BUFFERS}, - hub::{Token, HUB}, + gfx_select, + hub::{GfxBackend, Token}, pipeline::{IndexFormat, InputStepMode, PipelineFlags}, resource::BufferUsage, track::{Stitch, TrackerSet}, @@ -100,7 +101,7 @@ impl VertexState { self.instance_limit = !0; for vbs in &self.inputs { if vbs.stride == 0 { - continue + continue; } let limit = (vbs.total_size / vbs.stride) as u32; match vbs.rate { @@ -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 { @@ -251,9 +251,9 @@ pub extern "C" fn wgpu_render_pass_set_bind_group( pass.trackers.merge_extend(&bind_group.used); - if let Some((pipeline_layout_id, follow_up_sets, follow_up_offsets)) = - pass.binder - .provide_entry(index as usize, bind_group_id, bind_group, offsets) + if let Some((pipeline_layout_id, follow_up_sets, follow_up_offsets)) = pass + .binder + .provide_entry(index as usize, bind_group_id, bind_group, offsets) { let bind_groups = iter::once(bind_group.raw.raw()) .chain(follow_up_sets.map(|bg_id| bind_group_guard[bg_id].raw.raw())); @@ -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,23 +336,34 @@ 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)) { - let buffer = pass.trackers + for (vbs, (&id, &offset)) in pass.vertex_state.inputs[start_slot as usize ..] + .iter_mut() + .zip(buffers.iter().zip(offsets)) + { + let buffer = pass + .trackers .buffers .use_extend(&*buffer_guard, id, (), BufferUsage::VERTEX) .unwrap(); @@ -356,20 +383,39 @@ 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(); - assert!(first_vertex + vertex_count <= pass.vertex_state.vertex_limit, "Vertex out of range!"); - assert!(first_instance + instance_count <= pass.vertex_state.instance_limit, "Instance out of range!"); + assert!( + first_vertex + vertex_count <= pass.vertex_state.vertex_limit, + "Vertex out of range!" + ); + assert!( + first_instance + instance_count <= pass.vertex_state.instance_limit, + "Instance out of range!" + ); unsafe { pass.raw.draw( @@ -380,29 +426,82 @@ 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(); let buffer = pass .trackers .buffers - .use_extend(&*buffer_guard, indirect_buffer_id, (), BufferUsage::INDIRECT) + .use_extend( + &*buffer_guard, + indirect_buffer_id, + (), + BufferUsage::INDIRECT, + ) .unwrap(); unsafe { - pass.raw.draw_indirect( - &buffer.raw, - indirect_offset, - 1, - 0 + pass.raw.draw_indirect(&buffer.raw, indirect_offset, 1, 0); + } +} + +#[no_mangle] +pub extern "C" fn wgpu_render_pass_draw_indirect( + pass_id: RenderPassId, + indirect_buffer_id: BufferId, + indirect_offset: BufferAddress, +) { + gfx_select!(pass_id => render_pass_draw_indirect(pass_id, indirect_buffer_id, indirect_offset)) +} + +pub fn render_pass_draw_indexed( + pass_id: RenderPassId, + index_count: u32, + instance_count: u32, + first_index: u32, + 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 pass = &mut pass_guard[pass_id]; + pass.is_ready().unwrap(); + + //TODO: validate that base_vertex + max_index() is within the provided range + assert!( + first_index + index_count <= pass.index_state.limit, + "Index out of range!" + ); + assert!( + first_instance + instance_count <= pass.vertex_state.instance_limit, + "Instance out of range!" + ); + + unsafe { + pass.raw.draw_indexed( + first_index .. first_index + index_count, + base_vertex, + first_instance .. first_instance + instance_count, ); } } @@ -416,21 +515,35 @@ pub extern "C" fn wgpu_render_pass_draw_indexed( base_vertex: i32, first_instance: u32, ) { + gfx_select!(pass_id => render_pass_draw_indexed(pass_id, index_count, instance_count, first_index, base_vertex, first_instance)) +} + +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 (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(); - //TODO: validate that base_vertex + max_index() is within the provided range - assert!(first_index + index_count <= pass.index_state.limit, "Index out of range!"); - assert!(first_instance + instance_count <= pass.vertex_state.instance_limit, "Instance out of range!"); + let buffer = pass + .trackers + .buffers + .use_extend( + &*buffer_guard, + indirect_buffer_id, + (), + BufferUsage::INDIRECT, + ) + .unwrap(); unsafe { - pass.raw.draw_indexed( - first_index .. first_index + index_count, - base_vertex, - first_instance .. first_instance + instance_count, - ); + pass.raw + .draw_indexed_indirect(&buffer.raw, indirect_offset, 1, 0); } } @@ -440,46 +553,30 @@ pub extern "C" fn wgpu_render_pass_draw_indexed_indirect( indirect_buffer_id: BufferId, indirect_offset: BufferAddress, ) { - let mut token = Token::root(); - 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(); - - let buffer = pass - .trackers - .buffers - .use_extend(&*buffer_guard, indirect_buffer_id, (), BufferUsage::INDIRECT) - .unwrap(); - - unsafe { - pass.raw.draw_indexed_indirect( - &buffer.raw, - indirect_offset, - 1, - 0 - ); - } + gfx_select!(pass_id => render_pass_draw_indexed_indirect(pass_id, indirect_buffer_id, indirect_offset)) } -#[no_mangle] -pub extern "C" fn wgpu_render_pass_set_pipeline( +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!( pass.context.compatible(&pipeline.pass_context), "The render pipeline is not compatible with the pass!" ); - assert_eq!(pipeline.sample_count, pass.sample_count, "The render pipeline and renderpass have mismatching sample_count"); + assert_eq!( + pipeline.sample_count, pass.sample_count, + "The render pipeline and renderpass have mismatching sample_count" + ); pass.blend_color_status .require(pipeline.flags.contains(PipelineFlags::BLEND_COLOR)); @@ -524,7 +621,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 @@ -543,11 +640,16 @@ pub extern "C" fn wgpu_render_pass_set_pipeline( } } // Update vertex buffer limits - for (vbs, &(stride, rate)) in pass.vertex_state.inputs.iter_mut().zip(&pipeline.vertex_strides) { + for (vbs, &(stride, rate)) in pass + .vertex_state + .inputs + .iter_mut() + .zip(&pipeline.vertex_strides) + { vbs.stride = stride; vbs.rate = rate; } - for vbs in pass.vertex_state.inputs[pipeline.vertex_strides.len() .. ].iter_mut() { + for vbs in pass.vertex_state.inputs[pipeline.vertex_strides.len() ..].iter_mut() { vbs.stride = 0; vbs.rate = InputStepMode::Vertex; } @@ -555,9 +657,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 +678,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 +696,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 +709,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 +734,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 +774,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..39ce5296a 100644 --- a/wgpu-native/src/command/transfer.rs +++ b/wgpu-native/src/command/transfer.rs @@ -1,7 +1,8 @@ use crate::{ conv, device::{all_buffer_stages, all_image_stages}, - hub::{HUB, Token}, + gfx_select, + hub::{GfxBackend, Token}, resource::TexturePlacement, swap_chain::SwapChainLink, BufferAddress, @@ -52,9 +53,7 @@ impl TextureCopyView { } } - fn to_sub_layers( - &self, aspects: hal::format::Aspects - ) -> hal::image::SubresourceLayers { + fn to_sub_layers(&self, aspects: hal::format::Aspects) -> hal::image::SubresourceLayers { let layer = self.array_layer as hal::image::Layer; hal::image::SubresourceLayers { aspects, @@ -64,8 +63,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,18 +71,20 @@ 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(); - let (src_buffer, src_pending) = cmb - .trackers - .buffers - .use_replace(&*buffer_guard, source, (), BufferUsage::COPY_SRC); + let (src_buffer, src_pending) = + cmb.trackers + .buffers + .use_replace(&*buffer_guard, source, (), BufferUsage::COPY_SRC); barriers.extend(src_pending.map(|pending| hal::memory::Barrier::Buffer { states: pending.to_states(), target: &src_buffer.raw, @@ -92,10 +92,10 @@ pub extern "C" fn wgpu_command_encoder_copy_buffer_to_buffer( range: None .. None, })); - let (dst_buffer, dst_pending) = cmb - .trackers - .buffers - .use_replace(&*buffer_guard, destination, (), BufferUsage::COPY_DST); + let (dst_buffer, dst_pending) = + cmb.trackers + .buffers + .use_replace(&*buffer_guard, destination, (), BufferUsage::COPY_DST); barriers.extend(dst_pending.map(|pending| hal::memory::Barrier::Buffer { states: pending.to_states(), target: &dst_buffer.raw, @@ -120,23 +120,41 @@ 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 - .trackers - .buffers - .use_replace(&*buffer_guard, source.buffer, (), BufferUsage::COPY_SRC); + let (src_buffer, src_pending) = + cmb.trackers + .buffers + .use_replace(&*buffer_guard, source.buffer, (), BufferUsage::COPY_SRC); let src_barriers = src_pending.map(|pending| hal::memory::Barrier::Buffer { states: pending.to_states(), target: &src_buffer.raw, @@ -198,17 +216,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 +257,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,22 +306,37 @@ 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(); - let aspects = texture_guard[source.texture].full_range.aspects & - texture_guard[destination.texture].full_range.aspects; + let aspects = texture_guard[source.texture].full_range.aspects + & texture_guard[destination.texture].full_range.aspects; let (src_texture, src_pending) = cmb.trackers.textures.use_replace( &*texture_guard, @@ -350,3 +396,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..e96281a88 100644 --- a/wgpu-native/src/conv.rs +++ b/wgpu-native/src/conv.rs @@ -73,21 +73,26 @@ pub fn map_texture_usage( value } -pub fn map_binding_type(binding: &binding_model::BindGroupLayoutBinding) -> hal::pso::DescriptorType { +pub fn map_binding_type( + binding: &binding_model::BindGroupLayoutBinding, +) -> hal::pso::DescriptorType { use crate::binding_model::BindingType as Bt; use hal::pso::DescriptorType as H; match binding.ty { - Bt::UniformBuffer => if binding.dynamic { - H::UniformBufferDynamic - } else { - H::UniformBuffer - }, - Bt::StorageBuffer | - Bt::ReadonlyStorageBuffer => if binding.dynamic { - H::StorageBufferDynamic - } else { - H::StorageBuffer - }, + Bt::UniformBuffer => { + if binding.dynamic { + H::UniformBufferDynamic + } else { + H::UniformBuffer + } + } + Bt::StorageBuffer | Bt::ReadonlyStorageBuffer => { + if binding.dynamic { + H::StorageBufferDynamic + } else { + H::StorageBuffer + } + } Bt::Sampler => H::Sampler, Bt::SampledTexture => H::SampledImage, Bt::StorageTexture => H::StorageImage, @@ -157,7 +162,7 @@ pub fn map_color_state_descriptor( }; hal::pso::ColorBlendDesc { mask: map_color_write_flags(color_mask), - blend: blend_state + blend: blend_state, } } @@ -244,19 +249,11 @@ pub fn map_depth_stencil_state_descriptor( { Some(hal::pso::StencilTest { faces: hal::pso::Sided { - front: map_stencil_face( - &desc.stencil_front, - ), - back: map_stencil_face( - &desc.stencil_back, - ), + front: map_stencil_face(&desc.stencil_front), + back: map_stencil_face(&desc.stencil_back), }, - read_masks: hal::pso::State::Static( - hal::pso::Sided::new(desc.stencil_read_mask), - ), - write_masks: hal::pso::State::Static( - hal::pso::Sided::new(desc.stencil_write_mask), - ), + read_masks: hal::pso::State::Static(hal::pso::Sided::new(desc.stencil_read_mask)), + write_masks: hal::pso::State::Static(hal::pso::Sided::new(desc.stencil_write_mask)), reference_values: if desc.needs_stencil_reference() { hal::pso::State::Dynamic } else { @@ -438,10 +435,22 @@ pub fn map_texture_dimension_size( } D2 => { assert_eq!(depth, 1); - assert!(sample_size == 1 || sample_size == 2 || sample_size == 4 - || sample_size == 8 || sample_size == 16 || sample_size == 32, - "Invalid sample_count of {}", sample_size); - H::D2(width, height, checked_u32_as_u16(array_size), sample_size as u8) + assert!( + sample_size == 1 + || sample_size == 2 + || sample_size == 4 + || sample_size == 8 + || sample_size == 16 + || sample_size == 32, + "Invalid sample_count of {}", + sample_size + ); + H::D2( + width, + height, + checked_u32_as_u16(array_size), + sample_size as u8, + ) } D3 => { assert_eq!(array_size, 1); @@ -451,7 +460,6 @@ pub fn map_texture_dimension_size( } } -#[cfg(feature = "local")] pub fn map_texture_view_dimension( dimension: resource::TextureViewDimension, ) -> hal::image::ViewKind { @@ -554,13 +562,28 @@ pub fn map_load_store_ops( } pub fn map_color_f32(color: &Color) -> hal::pso::ColorValue { - [color.r as f32, color.g as f32, color.b as f32, color.a as f32] + [ + color.r as f32, + color.g as f32, + color.b as f32, + color.a as f32, + ] } pub fn map_color_i32(color: &Color) -> [i32; 4] { - [color.r as i32, color.g as i32, color.b as i32, color.a as i32] + [ + color.r as i32, + color.g as i32, + color.b as i32, + color.a as i32, + ] } pub fn map_color_u32(color: &Color) -> [u32; 4] { - [color.r as u32, color.g as u32, color.b as u32, color.a as u32] + [ + color.r as u32, + color.g as u32, + color.b as u32, + color.a as u32, + ] } pub fn map_filter(filter: resource::FilterMode) -> hal::image::Filter { diff --git a/wgpu-native/src/device.rs b/wgpu-native/src/device.rs index c9264bd5f..ea57388e0 100644 --- a/wgpu-native/src/device.rs +++ b/wgpu-native/src/device.rs @@ -1,45 +1,44 @@ +#[cfg(not(feature = "remote"))] +use crate::instance::Limits; use crate::{ binding_model, command, conv, - hub::{HUB, Root, Token}, + gfx_select, + hub::{GfxBackend, Token, GLOBAL}, + id::{Input, Output}, pipeline, resource, swap_chain, track::{Stitch, TrackerSet}, AdapterId, BindGroupId, + BindGroupLayoutId, BufferAddress, BufferId, BufferMapAsyncStatus, BufferMapOperation, CommandBufferId, - DeviceId, - LifeGuard, - QueueId, - RefCount, - Stored, - SubmissionIndex, - SurfaceId, - TextureId, - TextureViewId, - TextureDimension, -}; -#[cfg(feature = "local")] -use crate::{ - instance::Limits, - BindGroupLayoutId, CommandEncoderId, ComputePipelineId, + DeviceId, + LifeGuard, PipelineLayoutId, + QueueId, + RefCount, RenderPipelineId, SamplerId, ShaderModuleId, + Stored, + SubmissionIndex, + SurfaceId, SwapChainId, + TextureDimension, + TextureId, + TextureViewId, }; use arrayvec::ArrayVec; -use back; use copyless::VecHelper as _; use hal::{ self, @@ -51,12 +50,21 @@ use hal::{ }; use log::{info, trace}; use parking_lot::Mutex; -use rendy_descriptor::{DescriptorSet, DescriptorAllocator, DescriptorRanges}; +use rendy_descriptor::{DescriptorAllocator, DescriptorRanges, DescriptorSet}; 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}; +#[cfg(not(feature = "remote"))] +use std::marker::PhantomData; +use std::{ + collections::hash_map::Entry, + ffi, + iter, + ops::Range, + ptr, + slice, + sync::atomic::{AtomicBool, Ordering}, +}; + const CLEANUP_WAIT_MS: u64 = 5000; pub const MAX_COLOR_TARGETS: usize = 4; @@ -102,7 +110,10 @@ pub(crate) struct AttachmentData { impl Eq for AttachmentData {} impl AttachmentData { pub(crate) fn all(&self) -> impl Iterator { - self.colors.iter().chain(&self.resolves).chain(&self.depth_stencil) + self.colors + .iter() + .chain(&self.resolves) + .chain(&self.depth_stencil) } } @@ -170,10 +181,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)); @@ -215,7 +223,7 @@ impl PendingResources { let last_done = if done_count != 0 { self.active[done_count - 1].index } else { - return 0 + return 0; }; for a in self.active.drain(.. done_count) { @@ -253,12 +261,8 @@ 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 +272,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(); @@ -286,40 +292,42 @@ impl PendingResources { let (life_guard, resource) = match resource_id { ResourceId::Buffer(id) => { if buffer_guard[id].pending_map_operation.is_some() { - continue + continue; } 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); - (bind_group.life_guard, NativeResource::DescriptorSet(bind_group.raw)) + #[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() + 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,13 +437,14 @@ 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 { - let is_coherent = buffer.memory + let is_coherent = buffer + .memory .properties() .contains(hal::memory::Properties::COHERENT); let (ptr, mapped_range) = { @@ -449,10 +455,11 @@ fn map_buffer( if !is_coherent { match kind { HostMap::Read => unsafe { - raw.invalidate_mapped_memory_ranges( - iter::once((buffer.memory.memory(), mapped_range)), - ) - .unwrap(); + raw.invalidate_mapped_memory_ranges(iter::once(( + buffer.memory.memory(), + mapped_range, + ))) + .unwrap(); }, HostMap::Write => { buffer.mapped_write_ranges.push(mapped_range); @@ -478,7 +485,7 @@ pub struct Device { pending: Mutex>, } -impl Device { +impl Device { pub(crate) fn new( raw: B::Device, adapter_id: AdapterId, @@ -490,30 +497,25 @@ impl Device { life_guard.submission_index.fetch_add(1, Ordering::Relaxed); let heaps = { - let types = mem_props.memory_types - .iter() - .map(|mt| { - use rendy_memory::{HeapsConfig, LinearConfig, DynamicConfig}; - let config = HeapsConfig { - linear: if mt.properties.contains(hal::memory::Properties::CPU_VISIBLE) { - Some(LinearConfig { - linear_size: 0x10_00_00, - }) - } else { - None - }, - dynamic: Some(DynamicConfig { - block_size_granularity: 0x1_00, - max_chunk_size: 0x1_00_00_00, - min_device_allocation: 0x1_00_00, - }), - }; - (mt.properties.into(), mt.heap_index as u32, config) - }); - unsafe { - Heaps::new(types, mem_props.memory_heaps.iter().cloned()) - } - + let types = mem_props.memory_types.iter().map(|mt| { + use rendy_memory::{DynamicConfig, HeapsConfig, LinearConfig}; + let config = HeapsConfig { + linear: if mt.properties.contains(hal::memory::Properties::CPU_VISIBLE) { + Some(LinearConfig { + linear_size: 0x10_00_00, + }) + } else { + None + }, + dynamic: Some(DynamicConfig { + block_size_granularity: 0x1_00, + max_chunk_size: 0x1_00_00_00, + min_device_allocation: 0x1_00_00, + }), + }; + (mt.properties.into(), mt.heap_index as u32, config) + }); + unsafe { Heaps::new(types, mem_props.memory_heaps.iter().cloned()) } }; Device { @@ -524,7 +526,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,25 +538,24 @@ impl Device { }), } } -} -impl Device { - fn maintain( - &self, force_wait: bool, token: &mut DeviceToken, - ) -> Vec { + fn maintain(&self, force_wait: bool, token: &mut Token) -> Vec { let mut pending = self.pending.lock(); let mut trackers = self.trackers.lock(); pending.triage_referenced(&mut *trackers, token); pending.triage_mapped(token); pending.triage_framebuffers(&mut *self.framebuffers.lock(), token); - let last_done = pending.cleanup(&self.raw, &self.mem_allocator, &self.desc_allocator, force_wait); + let last_done = pending.cleanup( + &self.raw, + &self.mem_allocator, + &self.desc_allocator, + force_wait, + ); let callbacks = pending.handle_mapping(&self.raw, token); unsafe { - self.desc_allocator - .lock() - .cleanup(&self.raw); + self.desc_allocator.lock().cleanup(&self.raw); } if last_done != 0 { @@ -581,14 +582,144 @@ 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 rendy_memory::MemoryUsageValue as Muv; + use resource::BufferUsage as Bu; + + 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, - limits: &mut Limits, -) { +pub extern "C" fn wgpu_device_get_limits(_device_id: DeviceId, limits: &mut Limits) { *limits = Limits::default(); // TODO } @@ -597,137 +728,95 @@ 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 - .lock() - .buffers - .init(buffer_id, &ref_count, (), flags); + 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::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 +824,57 @@ pub extern "C" fn wgpu_buffer_destroy(buffer_id: BufferId) { ); } -pub fn device_create_texture( +#[no_mangle] +pub extern "C" fn wgpu_buffer_destroy(buffer_id: BufferId) { + gfx_select!(buffer_id => buffer_destroy(buffer_id)) +} + +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); + id_in: Input, +) -> Output { + let hub = B::hub(); + let mut token = Token::root(); - let (device_guard, _) = HUB.devices.read(&mut Token::root()); + let (device_guard, _) = hub.devices.read(&mut token); let device = &device_guard[device_id]; + let texture = device.create_texture(device_id, desc); - 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(), - } -} - -pub fn device_track_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 - .lock() - .textures - .init( - texture_id, - &ref_count, - full_range, - resource::TextureUsage::UNINITIALIZED, - ); + let (id, id_out) = hub.textures.new_identity(id_in); + let ok = device.trackers.lock().textures.init( + 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 +912,60 @@ 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 +977,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 +995,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 +1030,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,88 +1067,95 @@ 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), - dynamic_count: bindings - .iter() - .filter(|b| b.dynamic) - .count(), - } + dynamic_count: bindings.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()); let desc_set = unsafe { let mut desc_sets = ArrayVec::<[_; 1]>::new(); - device.desc_allocator + device + .desc_allocator .lock() .allocate( &device.raw, @@ -1139,104 +1168,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,109 +1278,116 @@ 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] + }; + 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 { + gfx_select!(device_id => device_create_bind_group(device_id, desc, PhantomData)) +} + +pub fn bind_group_destroy(bind_group_id: BindGroupId) { + let hub = B::hub(); 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 + 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), + bind_group.life_guard.ref_count.clone(), + ); } #[no_mangle] pub extern "C" fn wgpu_bind_group_destroy(bind_group_id: BindGroupId) { - 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 bind_group = &bind_group_guard[bind_group_id]; - device_guard[bind_group.device_id.value].pending.lock().destroy( - ResourceId::BindGroup(bind_group_id), - bind_group.life_guard.ref_count.clone(), - ); + gfx_select!(bind_group_id => bind_group_destroy(bind_group_id)) } -pub fn device_create_shader_module( +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() - }; + id_in: Input, +) -> Output { + let hub = B::hub(); + let mut token = Token::root(); - ShaderModule { raw: shader } + 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(feature = "local")] +#[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 +1395,13 @@ pub extern "C" fn wgpu_device_get_queue(device_id: DeviceId) -> QueueId { device_id } -#[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) }; +pub fn queue_submit(queue_id: QueueId, command_buffer_ids: &[CommandBufferId]) { + 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 +1415,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,16 +1500,15 @@ 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 submission = - hal::queue::Submission::<_, _, &[::Semaphore]> { - //TODO: may `OneShot` be enough? - command_buffers: command_buffer_ids - .iter() - .flat_map(|&cmb_id| &command_buffer_guard[cmb_id].raw), - wait_semaphores, - signal_semaphores: &[], //TODO: signal `sem_present`? - }; + let (command_buffer_guard, _) = hub.command_buffers.read(&mut token); + let submission = hal::queue::Submission::<_, _, &[B::Semaphore]> { + //TODO: may `OneShot` be enough? + command_buffers: command_buffer_ids + .iter() + .flat_map(|&cmb_id| &command_buffer_guard[cmb_id].raw), + wait_semaphores, + signal_semaphores: &[], //TODO: signal `sem_present`? + }; unsafe { device.queue_group.queues[0] @@ -1491,7 +1523,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 +1536,47 @@ 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 { - 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; + id_in: Input, +) -> Output { + let hub = B::hub(); + let mut token = Token::root(); - 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 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 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() @@ -1635,7 +1593,9 @@ pub fn device_create_render_pipeline( let mut vertex_buffers = Vec::with_capacity(desc_vbs.len()); let mut attributes = Vec::new(); for (i, vb_state) in desc_vbs.iter().enumerate() { - vertex_strides.alloc().init((vb_state.stride, vb_state.step_mode)); + vertex_strides + .alloc() + .init((vb_state.stride, vb_state.step_mode)); if vb_state.attributes_length == 0 { continue; } @@ -1698,38 +1658,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 +1803,112 @@ 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 +1942,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 +1975,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 +1998,74 @@ pub fn device_create_swap_chain( acquired: Vec::with_capacity(1), //TODO: get it from gfx-hal? sem_available, command_pool, - }); + }; - 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(); + for ((i, image), (id_texture_in, id_view_in)) in images.into_iter().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, (), ()); + trackers.views.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 +2078,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 +2125,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 +2153,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 +2178,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 +2208,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 f2a663ff5..ca42563bc 100644 --- a/wgpu-native/src/hub.rs +++ b/wgpu-native/src/hub.rs @@ -1,56 +1,56 @@ use crate::{ - AdapterHandle, + backend, + id::{Input, Output}, + Adapter, AdapterId, - BindGroupHandle, + Backend, + 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; #[allow(unused)] use std::cell::Cell; -use std::{ - marker::PhantomData, - ops, - sync::Arc, -}; +use std::{marker::PhantomData, ops, sync::Arc}; /// A simple structure to manage identities of objects. @@ -58,14 +58,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,17 +76,19 @@ impl Default for IdentityManager { impl IdentityManager { pub fn alloc(&mut self) -> I { match self.free.pop() { - Some(index) => I::new(index, self.epochs[index as usize]), + Some(index) => I::zip(index, self.epochs[index as usize], self.backend), None => { - let id = I::new(self.epochs.len() as Index, 1); - self.epochs.push(id.epoch()); + let epoch = 1; + let id = I::zip(self.epochs.len() as Index, epoch, self.backend); + self.epochs.push(epoch); id } } } pub fn free(&mut self, id: I) { - let (index, epoch) = (id.index(), id.epoch()); + 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)); @@ -106,31 +110,35 @@ pub struct Storage { impl ops::Index for Storage { type Output = T; fn index(&self, id: I) -> &T { - let (ref value, epoch) = self.map[id.index() as usize]; - assert_eq!(epoch, id.epoch()); + let (index, epoch, _) = id.unzip(); + let (ref value, storage_epoch) = self.map[index as usize]; + assert_eq!(epoch, storage_epoch); value } } impl ops::IndexMut for Storage { fn index_mut(&mut self, id: I) -> &mut T { - let (ref mut value, epoch) = self.map[id.index() as usize]; - assert_eq!(epoch, id.epoch()); + let (index, epoch, _) = id.unzip(); + let (ref mut value, storage_epoch) = self.map[index as usize]; + assert_eq!(epoch, storage_epoch); value } } impl Storage { pub fn contains(&self, id: I) -> bool { - match self.map.get(id.index() as usize) { - Some(&(_, epoch)) if epoch == id.epoch() => true, - _ => false, + let (index, epoch, _) = id.unzip(); + match self.map.get(index as usize) { + Some(&(_, storage_epoch)) => epoch == storage_epoch, + None => false, } } pub fn remove(&mut self, id: I) -> T { - let (value, epoch) = self.map.remove(id.index() as usize).unwrap(); - assert_eq!(epoch, id.epoch()); + let (index, epoch, _) = id.unzip(); + let (value, storage_epoch) = self.map.remove(index as usize).unwrap(); + assert_eq!(epoch, storage_epoch); value } } @@ -149,55 +157,57 @@ 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 {} -#[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 Root {} +impl Access for Root {} +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! { @@ -221,9 +231,7 @@ impl<'a, T> Token<'a, T> { assert_ne!(old, 0, "Root token was dropped"); active.set(old + 1); }); - Token { - level: PhantomData, - } + Token { level: PhantomData } } } @@ -234,9 +242,7 @@ impl Token<'static, Root> { assert_eq!(0, active.replace(1), "Root token is already active"); }); - Token { - level: PhantomData, - } + Token { level: PhantomData } } } @@ -253,90 +259,194 @@ 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, } } } impl Registry { - pub fn register>( - &self, id: I, value: T, _token: &mut Token - ) { - let old = self - .data - .write() - .map - .insert(id.index() as usize, (value, id.epoch())); + pub fn register>(&self, id: I, value: T, _token: &mut Token) { + let (index, epoch, backend) = id.unzip(); + debug_assert_eq!(backend, self.backend); + let old = self.data.write().map.insert(index as usize, (value, epoch)); 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(); - self.register(id, value, token); - id + (id, id) } - pub fn unregister>( - &self, id: I, _token: &mut Token - ) -> (T, Token) { + #[cfg(feature = "remote")] + pub fn new_identity(&self, id_in: Input) -> (I, Output) { + //TODO: 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); + output + } + + pub fn unregister>(&self, id: I, _token: &mut Token) -> (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()) } pub fn read>( - &self, _token: &mut Token + &self, + _token: &mut Token, ) -> (RwLockReadGuard>, Token) { (self.data.read(), Token::new()) } pub fn write>( - &self, _token: &mut Token + &self, + _token: &mut Token, ) -> (RwLockWriteGuard>, Token) { (self.data.write(), Token::new()) } } -#[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, + #[cfg(windows)] + dx12: Hub, + #[cfg(windows)] + dx11: 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 backend::Vulkan { + 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 backend::Metal { + 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 + } +} + +#[cfg(windows)] +impl GfxBackend for backend::Dx12 { + const VARIANT: Backend = Backend::Dx12; + fn hub() -> &'static Hub { + &GLOBAL.hubs.dx12 + } + fn get_surface_mut(surface: &mut Surface) -> &mut Self::Surface { + surface.dx12.as_mut().unwrap() + } +} + +#[cfg(windows)] +impl GfxBackend for backend::Dx11 { + const VARIANT: Backend = Backend::Dx11; + fn hub() -> &'static Hub { + &GLOBAL.hubs.dx11 + } + fn get_surface_mut(surface: &mut Surface) -> &mut Self::Surface { + &mut surface.dx11 + } } diff --git a/wgpu-native/src/id.rs b/wgpu-native/src/id.rs index 53cf77b0c..90aa67fbc 100644 --- a/wgpu-native/src/id.rs +++ b/wgpu-native/src/id.rs @@ -1,142 +1,125 @@ -use crate::{Epoch, Index}; -use std::{ - fmt, - marker::PhantomData, -}; +use crate::{Backend, Epoch, Index}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; +use std::{fmt, marker::PhantomData}; -#[repr(C)] -#[derive(Clone, Copy, Debug, Hash, PartialEq)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -pub struct Id(Index, Epoch); +const BACKEND_BITS: usize = 3; +const EPOCH_MASK: u32 = (1 << (32 - BACKEND_BITS)) - 1; +type Dummy = crate::backend::Empty; #[repr(transparent)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -pub struct GenericId(Id, PhantomData); +pub struct Id(u64, PhantomData); -impl Copy for GenericId {} +impl Id { + pub fn backend(&self) -> Backend { + match self.0 >> (64 - BACKEND_BITS) as u8 { + 0 => Backend::Empty, + 1 => Backend::Vulkan, + 2 => Backend::Metal, + 3 => Backend::Dx12, + 4 => Backend::Dx11, + 5 => Backend::Gl, + _ => unreachable!(), + } + } +} -impl Clone for GenericId { +impl Copy for Id {} + +impl Clone for Id { fn clone(&self) -> Self { Self(self.0, PhantomData) } } -impl fmt::Debug for GenericId { +impl fmt::Debug for Id { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(formatter) } } -impl std::hash::Hash for GenericId { +impl std::hash::Hash for Id { fn hash(&self, state: &mut H) { self.0.hash(state); } } -impl PartialEq for GenericId { +impl PartialEq for Id { fn eq(&self, other: &Self) -> bool { self.0 == other.0 } } pub trait TypedId { - fn new(index: Index, epoch: Epoch) -> Self; - fn index(&self) -> Index; - fn epoch(&self) -> Epoch; + fn zip(index: Index, epoch: Epoch, backend: Backend) -> Self; + fn unzip(self) -> (Index, Epoch, Backend); } -impl GenericId { - fn raw(self) -> Id { - self.0 +impl TypedId for Id { + 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 & EPOCH_MASK, + self.backend(), + ) } } -impl TypedId for GenericId { - fn new(index: Index, epoch: Epoch) -> Self { - Self(Id(index, epoch), PhantomData) - } +#[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; - fn index(&self) -> Index { - (self.raw()).0 - } - - fn epoch(&self) -> Epoch { - (self.raw()).1 - } -} - -#[cfg(not(feature = "gfx-backend-gl"))] -pub type InstanceId = GenericId; - -#[cfg(feature = "gfx-backend-gl")] -pub type InstanceId = SurfaceId; - -#[cfg(not(feature = "gfx-backend-gl"))] -pub type InstanceHandle = back::Instance; - -pub type AdapterId = GenericId; -pub type AdapterHandle = hal::Adapter; - -pub type DeviceId = GenericId; -pub type DeviceHandle = crate::Device; +pub type AdapterId = Id>; +pub type DeviceId = Id>; pub type QueueId = DeviceId; - // Resource -pub type BufferId = GenericId; -pub type BufferHandle = crate::Buffer; - -pub type TextureViewId = GenericId; -pub type TextureViewHandle = crate::TextureView; - -pub type TextureId = GenericId; -pub type TextureHandle = crate::Texture; - -pub type SamplerId = GenericId; -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 = GenericId; -pub type BindGroupLayoutHandle = crate::BindGroupLayout; - -pub type PipelineLayoutId = GenericId; -pub type PipelineLayoutHandle = crate::PipelineLayout; - -pub type BindGroupId = GenericId; -pub type BindGroupHandle = crate::BindGroup; - +pub type BindGroupLayoutId = Id>; +pub type PipelineLayoutId = Id>; +pub type BindGroupId = Id>; // Pipeline -pub type InputStateId = GenericId; -pub enum InputStateHandle {} - -pub type ShaderModuleId = GenericId; -pub type ShaderModuleHandle = crate::ShaderModule; - -pub type RenderPipelineId = GenericId; -pub type RenderPipelineHandle = crate::RenderPipeline; - -pub type ComputePipelineId = GenericId; -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 = GenericId; -pub type CommandBufferHandle = crate::CommandBuffer; - +pub type CommandBufferId = Id>; pub type CommandEncoderId = CommandBufferId; - -pub type RenderBundleId = GenericId; -pub enum RenderBundleHandle {} - -pub type RenderPassId = GenericId; -pub type RenderPassHandle = crate::RenderPass; - -pub type ComputePassId = GenericId; -pub type ComputePassHandle = crate::ComputePass; - +pub type RenderBundleId = Id>; +pub type RenderPassId = Id>; +pub type ComputePassId = Id>; // Swap chain -pub type SurfaceId = GenericId; -pub type SurfaceHandle = crate::Surface; +pub type SurfaceId = Id; +pub type SwapChainId = Id>; -pub type SwapChainId = SurfaceId; +#[test] +fn test_id_backend() { + for &b in &[ + Backend::Empty, + Backend::Vulkan, + Backend::Metal, + Backend::Dx12, + Backend::Dx11, + Backend::Gl, + ] { + let id: Id<()> = Id::zip(0, 0, b); + assert_eq!(id.backend(), b); + } +} diff --git a/wgpu-native/src/instance.rs b/wgpu-native/src/instance.rs index 64875aa37..3e106bb31 100644 --- a/wgpu-native/src/instance.rs +++ b/wgpu-native/src/instance.rs @@ -1,21 +1,78 @@ use crate::{ + backend, binding_model::MAX_BIND_GROUPS, - hub::{HUB, Root, Token}, - AdapterHandle, + device::BIND_BUFFER_ALIGNMENT, + hub::{GfxBackend, Token, GLOBAL}, + 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")] +#[cfg(not(feature = "remote"))] +use bitflags::bitflags; 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)] +pub struct Instance { + vulkan: Option, + #[cfg(any(target_os = "ios", target_os = "macos"))] + metal: gfx_backend_metal::Instance, + #[cfg(windows)] + dx12: Option, + #[cfg(windows)] + dx11: gfx_backend_dx11::Instance, +} + +impl Instance { + pub(crate) fn new(name: &str, version: u32) -> Self { + Instance { + //TODO: reconsider once `create` returns a `Result` + vulkan: if cfg!(all(unix, not(target_os = "ios"), not(target_os = "macos"))) { + Some(gfx_backend_vulkan::Instance::create(name, version)) + } else { + None + }, + #[cfg(any(target_os = "ios", target_os = "macos"))] + metal: gfx_backend_metal::Instance::create(name, version), + #[cfg(windows)] + dx12: Some(gfx_backend_dx12::Instance::create(name, version)), + #[cfg(windows)] + dx11: gfx_backend_dx11::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, + #[cfg(windows)] + pub(crate) dx12: Option>, + #[cfg(windows)] + pub(crate) dx11: GfxSurface, +} + +#[derive(Debug)] +pub struct Adapter { + pub(crate) raw: hal::Adapter, +} + #[repr(C)] #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] @@ -26,17 +83,44 @@ pub enum PowerPreference { HighPerformance = 2, } -impl Default for PowerPreference { - fn default() -> Self { - PowerPreference::Default +#[cfg(not(feature = "remote"))] +bitflags! { + #[repr(transparent)] + pub struct BackendBit: u32 { + const VULKAN = 1 << Backend::Vulkan as u32; + const GL = 1 << Backend::Gl as u32; + const METAL = 1 << Backend::Metal as u32; + const DX12 = 1 << Backend::Dx12 as u32; + const DX11 = 1 << Backend::Dx11 as u32; + const PRIMARY = Self::VULKAN.bits | Self::METAL.bits | Self::DX12.bits; + const SECONDARY = Self::GL.bits | Self::DX11.bits; + } +} + +#[cfg(not(feature = "remote"))] +impl From for BackendBit { + fn from(backend: Backend) -> Self { + BackendBit::from_bits(1 << backend as u32).unwrap() } } #[repr(C)] -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug)] #[cfg_attr(feature = "remote", derive(Serialize, Deserialize))] pub struct RequestAdapterOptions { pub power_preference: PowerPreference, + #[cfg(not(feature = "remote"))] + pub backends: BackendBit, +} + +impl Default for RequestAdapterOptions { + fn default() -> Self { + RequestAdapterOptions { + power_preference: PowerPreference::Default, + #[cfg(not(feature = "remote"))] + backends: BackendBit::PRIMARY, + } + } } #[repr(C)] @@ -69,286 +153,308 @@ pub struct DeviceDescriptor { pub limits: Limits, } -#[cfg(not(feature = "gfx-backend-gl"))] -pub fn create_instance() -> ::back::Instance { - ::back::Instance::create("wgpu", 1) -} +#[cfg(not(feature = "remote"))] +pub fn wgpu_create_surface(raw_handle: raw_window_handle::RawWindowHandle) -> SurfaceId { + use raw_window_handle::RawWindowHandle as Rwh; -#[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 { - let raw = back::Surface::from_context(windowed_context); - let surface = SurfaceHandle::new(raw); - HUB.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, - 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", - ))] + 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(all(unix, not(target_os = "ios"), not(target_os = "macos")))] + 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(all(unix, not(target_os = "ios"), not(target_os = "macos")))] + 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)), + dx12: instance + .dx12 + .as_ref() + .map(|inst| inst.create_surface_from_hwnd(h.hwnd)), + dx11: instance.dx11.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, not(target_os = "ios"), not(target_os = "macos")))] #[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, - 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) +pub extern "C" fn wgpu_create_surface_from_metal_layer(layer: *mut std::ffi::c_void) -> SurfaceId { + let surface = Surface { + swap_chain: None, + vulkan: None, //TODO: currently requires `NSView` + metal: GLOBAL + .instance + .metal + .create_surface_from_layer(layer as *mut _, 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::WindowsHandle; + wgpu_create_surface(raw_window_handle::RawWindowHandle::Windows( + raw_window_handle::windows::WindowsHandle { + hwnd, + ..WindowsHandle::empty() + }, + )) } -#[cfg(all(feature = "local", feature = "gfx-backend-gl"))] -pub fn wgpu_instance_get_gl_surface(instance_id: InstanceId) -> 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 = |b: Backend| { + let _ = input_ids; + if desc.backends.contains(b.into()) { + Some(PhantomData) + } else { + 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 { + let id_vulkan = find_input(Backend::Vulkan); + let id_metal = find_input(Backend::Metal); + let id_dx12 = find_input(Backend::Dx12); + let id_dx11 = find_input(Backend::Dx11); + + let mut adapters_vk = match instance.vulkan { + Some(ref inst) if id_vulkan.is_some() => { + let adapters = inst.enumerate_adapters(); + device_types.extend(adapters.iter().map(|ad| ad.info.device_type.clone())); + adapters + } + _ => Vec::new(), + }; + #[cfg(any(target_os = "ios", target_os = "macos"))] + let mut adapters_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() + }; + #[cfg(windows)] + let mut adapters_dx12 = match instance.dx12 { + Some(ref inst) if id_dx12.is_some() => { + let adapters = inst.enumerate_adapters(); + device_types.extend(adapters.iter().map(|ad| ad.info.device_type.clone())); + adapters + } + _ => Vec::new(), + }; + #[cfg(windows)] + let mut adapters_dx11 = if id_dx11.is_some() { + let adapters = instance.dx11.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, mut discrete, mut other) = (None, None, None); + + for (i, ty) in device_types.into_iter().enumerate() { + match ty { hal::adapter::DeviceType::IntegratedGpu => { - integrated_first = integrated_first.or(Some(i)); + integrated = integrated.or(Some(i)); } hal::adapter::DeviceType::DiscreteGpu => { - discrete_first = discrete_first.or(Some(i)); - discrete_last = Some(i); + discrete = discrete.or(Some(i)); + } + _ => { + other = other.or(Some(i)); } - _ => alternative = Some(i), } } let preferred_gpu = match desc.power_preference { - // If `LowPower`, prefer lowest power `DiscreteGPU` - PowerPreference::LowPower => integrated_first.or(discrete_last), - PowerPreference::HighPerformance | PowerPreference::Default => { - discrete_first.or(integrated_first) - } + PowerPreference::Default => integrated.or(discrete).or(other), + PowerPreference::LowPower => integrated.or(other).or(discrete), + PowerPreference::HighPerformance => discrete.or(other).or(integrated), }; - - 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() -} - -#[cfg(feature = "local")] -#[no_mangle] -pub extern "C" fn wgpu_instance_request_adapter( - instance_id: InstanceId, - 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) + 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 = backend::Vulkan::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 = backend::Metal::hub().adapters.register_identity( + id_metal.unwrap(), + adapter, + &mut token, + ); + return Some(id_out); + } + selected -= adapters_mtl.len(); + } + #[cfg(windows)] + { + if selected < adapters_dx12.len() { + let adapter = Adapter { + raw: adapters_dx12.swap_remove(selected), + }; + info!("Adapter Dx12 {:?}", adapter.raw.info); + let id_out = backend::Dx12::hub().adapters.register_identity( + id_dx12.unwrap(), + adapter, + &mut token, + ); + return Some(id_out); + } + selected -= adapters_dx12.len(); + if selected < adapters_dx11.len() { + let adapter = Adapter { + raw: adapters_dx11.swap_remove(selected), + }; + info!("Adapter Dx11 {:?}", adapter.raw.info); + let id_out = backend::Dx11::hub().adapters.register_identity( + id_dx11.unwrap(), + adapter, + &mut token, + ); + return Some(id_out); + } + selected -= adapters_dx11.len(); + } + let _ = (selected, id_metal, id_dx12, id_dx11); + None } -pub fn adapter_create_device( +#[cfg(not(feature = "remote"))] +#[no_mangle] +pub extern "C" fn wgpu_request_adapter(desc: Option<&RequestAdapterOptions>) -> AdapterId { + request_adapter(&desc.cloned().unwrap_or_default(), &[]).unwrap() +} + +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 9c88414b5..de10e2a27 100644 --- a/wgpu-native/src/lib.rs +++ b/wgpu-native/src/lib.rs @@ -1,49 +1,38 @@ -#[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 { + #[cfg(windows)] + pub use gfx_backend_dx11::Backend as Dx11; + #[cfg(windows)] + pub use gfx_backend_dx12::Backend as Dx12; + pub use gfx_backend_empty::Backend as Empty; + #[cfg(any(target_os = "ios", target_os = "macos"))] + pub use gfx_backend_metal::Backend as Metal; + pub use gfx_backend_vulkan::Backend as Vulkan; +} mod binding_model; mod command; mod conv; mod device; mod hub; +mod id; mod instance; mod pipeline; mod resource; mod swap_chain; mod track; -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::id::*; pub use self::instance::*; pub use self::pipeline::*; pub use self::resource::*; pub use self::swap_chain::*; -pub use self::id::*; pub use hal::pso::read_spirv; -#[cfg(feature = "glutin")] -pub use back::glutin; - use std::{ os::raw::c_char, ptr, @@ -51,8 +40,19 @@ use std::{ }; type SubmissionIndex = usize; -pub(crate) type Index = u32; -pub(crate) type Epoch = u32; +type Index = u32; +type Epoch = u32; + +#[repr(u8)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Backend { + Empty = 0, + Vulkan = 1, + Metal = 2, + Dx12 = 3, + Dx11 = 4, + Gl = 5, +} pub type BufferAddress = u64; pub type RawString = *const c_char; @@ -194,3 +194,22 @@ 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),+ ), + #[cfg(windows)] + $crate::Backend::Dx12 => $function::<$crate::backend::Dx12>( $($param),+ ), + #[cfg(windows)] + $crate::Backend::Dx11 => $function::<$crate::backend::Dx11>( $($param),+ ), + _ => unreachable!() + } + }; +} diff --git a/wgpu-native/src/pipeline.rs b/wgpu-native/src/pipeline.rs index 7f72c33a3..9c4a65189 100644 --- a/wgpu-native/src/pipeline.rs +++ b/wgpu-native/src/pipeline.rs @@ -2,10 +2,10 @@ use crate::{ device::RenderPassContext, resource, BufferAddress, - U32Array, PipelineLayoutId, RawString, ShaderModuleId, + U32Array, }; use bitflags::bitflags; diff --git a/wgpu-native/src/resource.rs b/wgpu-native/src/resource.rs index 418dc8ac2..8eb191998 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,19 +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 => { - panic!("Expected swap chain link!") - } + TexturePlacement::Memory(_) => panic!("Expected swap chain link!"), } } } @@ -274,7 +286,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..8bae0179c 100644 --- a/wgpu-native/src/swap_chain.rs +++ b/wgpu-native/src/swap_chain.rs @@ -1,7 +1,8 @@ use crate::{ conv, device::all_image_stages, - hub::{HUB, Token}, + gfx_select, + 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,33 @@ 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 +151,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 +173,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 +192,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 +219,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(); @@ -245,7 +227,8 @@ pub extern "C" fn wgpu_swap_chain_present(swap_chain_id: SwapChainId) { trace!("transit {:?} to present", frame.texture_id.value); let mut trackers = device.trackers.lock(); - let barriers = trackers.textures + let barriers = trackers + .textures .change_replace( frame.texture_id.value, &texture.life_guard.ref_count, @@ -292,3 +275,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 7fb2cb215..b2db9ad02 100644 --- a/wgpu-native/src/track/buffer.rs +++ b/wgpu-native/src/track/buffer.rs @@ -1,9 +1,5 @@ -use crate::{ - conv, - resource::BufferUsage, - BufferId, -}; use super::{PendingTransition, ResourceState, Stitch, Unit}; +use crate::{conv, resource::BufferUsage, BufferId}; use std::ops::Range; //TODO: store `hal::buffer::State` here to avoid extra conversions @@ -12,8 +8,7 @@ pub type BufferState = Unit; impl PendingTransition { /// Produce the gfx-hal buffer states corresponding to the transition. pub fn to_states(&self) -> Range { - conv::map_buffer_state(self.usage.start) .. - conv::map_buffer_state(self.usage.end) + conv::map_buffer_state(self.usage.start) .. conv::map_buffer_state(self.usage.end) } } @@ -31,10 +26,7 @@ impl ResourceState for BufferState { type Selector = (); type Usage = BufferUsage; - fn query( - &self, - _selector: Self::Selector, - ) -> Option { + fn query(&self, _selector: Self::Selector) -> Option { Some(self.last) } @@ -57,10 +49,10 @@ impl ResourceState for BufferState { transitions.push(pending); usage } - None => { - if !old.is_empty() && - old != usage && - BufferUsage::WRITE_ALL.intersects(old | usage) + None => { + if !old.is_empty() + && old != usage + && BufferUsage::WRITE_ALL.intersects(old | usage) { return Err(pending); } @@ -93,7 +85,7 @@ impl ResourceState for BufferState { transitions.push(pending); other.last } - None => { + None => { if !old.is_empty() && BufferUsage::WRITE_ALL.intersects(old | new) { return Err(pending); } @@ -104,14 +96,13 @@ impl ResourceState for BufferState { Ok(()) } - fn optimize(&mut self) { - } + fn optimize(&mut self) {} } #[cfg(test)] mod test { - use crate::TypedId; use super::*; + use crate::{Backend, TypedId}; #[test] fn change() { @@ -119,9 +110,10 @@ mod test { init: BufferUsage::INDEX, last: BufferUsage::STORAGE, }; - let id = TypedId::new(0, 0); + 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::VERTEX, Some(&mut Vec::new())) + .unwrap(); bs.change(id, (), BufferUsage::INDEX, None).unwrap(); assert_eq!(bs.last, BufferUsage::VERTEX | BufferUsage::INDEX); } diff --git a/wgpu-native/src/track/mod.rs b/wgpu-native/src/track/mod.rs index fddc1b0a0..03d26dd97 100644 --- a/wgpu-native/src/track/mod.rs +++ b/wgpu-native/src/track/mod.rs @@ -2,15 +2,7 @@ mod buffer; mod range; mod texture; -use crate::{ - hub::Storage, - Epoch, - Index, - RefCount, - TextureViewId, - TypedId, - BindGroupId, -}; +use crate::{hub::Storage, Backend, BindGroupId, Epoch, Index, RefCount, TextureViewId, TypedId}; use hal::backend::FastHashMap; @@ -83,10 +75,7 @@ pub trait ResourceState: Clone + Default { /// Returns `None` if no sub-resources /// are intersecting with the selector, or their usage /// isn't consistent. - fn query( - &self, - selector: Self::Selector, - ) -> Option; + fn query(&self, selector: Self::Selector) -> Option; /// Change the last usage of the selected sub-resources. /// @@ -157,22 +146,27 @@ 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, } } /// Remove an id from the tracked map. pub fn remove(&mut self, id: S::Id) -> bool { - match self.map.remove(&id.index()) { + let (index, epoch, backend) = id.unzip(); + debug_assert_eq!(backend, self.backend); + match self.map.remove(&index) { Some(resource) => { - assert_eq!(resource.epoch, id.epoch()); + assert_eq!(resource.epoch, epoch); true } None => false, @@ -188,9 +182,10 @@ impl ResourceTracker { /// Return an iterator over used resources keys. pub fn used<'a>(&'a self) -> impl 'a + Iterator { + let backend = self.backend; self.map .iter() - .map(|(&index, resource)| S::Id::new(index, resource.epoch)) + .map(move |(&index, resource)| S::Id::zip(index, resource.epoch, backend)) } /// Clear the tracked contents. @@ -209,21 +204,22 @@ impl ResourceTracker { default: S::Usage, ) -> bool { let mut state = S::default(); - match state.change( - id, - selector, - default, - None, - ) { + match state.change(id, selector, default, None) { Ok(()) => (), Err(_) => unreachable!(), } + + let (index, epoch, backend) = id.unzip(); + debug_assert_eq!(backend, self.backend); self.map - .insert(id.index(), Resource { - ref_count: ref_count.clone(), - state, - epoch: id.epoch(), - }) + .insert( + index, + Resource { + ref_count: ref_count.clone(), + state, + epoch, + }, + ) .is_none() } @@ -231,33 +227,32 @@ impl ResourceTracker { /// /// Returns `Some(Usage)` only if this usage is consistent /// across the given selector. - pub fn query( - &mut self, - id: S::Id, - selector: S::Selector, - ) -> Option { - let res = self.map.get(&id.index())?; - assert_eq!(res.epoch, id.epoch()); + pub fn query(&mut self, id: S::Id, selector: S::Selector) -> Option { + 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) } /// 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 { - match map.entry(id.index()) { - Entry::Vacant(e) => { - e.insert(Resource { - ref_count: ref_count.clone(), - state: S::default(), - epoch: id.epoch(), - }) - } + let (index, epoch, backend) = id.unzip(); + debug_assert_eq!(self_backend, backend); + match map.entry(index) { + Entry::Vacant(e) => e.insert(Resource { + ref_count: ref_count.clone(), + state: S::default(), + epoch, + }), Entry::Occupied(e) => { - assert_eq!(e.get().epoch, id.epoch()); + assert_eq!(e.get().epoch, epoch); e.into_mut() } } @@ -273,8 +268,9 @@ impl ResourceTracker { selector: S::Selector, usage: S::Usage, ) -> Result<(), PendingTransition> { - Self::get_or_insert(&mut self.map, id, ref_count) - .state.change(id, selector, usage, None) + Self::get_or_insert(self.backend, &mut self.map, id, ref_count) + .state + .change(id, selector, usage, None) } /// Replace the usage of a specified resource. @@ -285,17 +281,17 @@ impl ResourceTracker { selector: S::Selector, usage: S::Usage, ) -> Drain> { - let res = Self::get_or_insert(&mut self.map, id, ref_count); - res.state.change(id, selector, usage, Some(&mut self.temp)) + 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(..) } /// Merge another tracker into `self` by extending the current states /// without any transitions. - pub fn merge_extend( - &mut self, other: &Self, - ) -> Result<(), PendingTransition> { + 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) => { @@ -303,8 +299,10 @@ impl ResourceTracker { } Entry::Occupied(e) => { assert_eq!(e.get().epoch, new.epoch); - let id = S::Id::new(index, new.epoch); - e.into_mut().state.merge(id, &new.state, Stitch::Last, None)?; + let id = S::Id::zip(index, new.epoch, self.backend); + e.into_mut() + .state + .merge(id, &new.state, Stitch::Last, None)?; } } } @@ -325,8 +323,9 @@ impl ResourceTracker { } Entry::Occupied(e) => { assert_eq!(e.get().epoch, new.epoch); - let id = S::Id::new(index, new.epoch); - e.into_mut().state + let id = S::Id::zip(index, new.epoch, self.backend); + e.into_mut() + .state .merge(id, &new.state, stitch, Some(&mut self.temp)) .ok(); //TODO: unwrap? } @@ -376,10 +375,7 @@ impl ResourceState for PhantomData { type Selector = (); type Usage = (); - fn query( - &self, - _selector: Self::Selector, - ) -> Option { + fn query(&self, _selector: Self::Selector) -> Option { Some(()) } @@ -403,8 +399,7 @@ impl ResourceState for PhantomData { Ok(()) } - fn optimize(&mut self) { - } + fn optimize(&mut self) {} } @@ -420,12 +415,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), } } @@ -453,4 +448,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-native/src/track/range.rs b/wgpu-native/src/track/range.rs index 4d50d7b6f..c26df0d52 100644 --- a/wgpu-native/src/track/range.rs +++ b/wgpu-native/src/track/range.rs @@ -1,10 +1,4 @@ -use std::{ - cmp::Ordering, - fmt::Debug, - iter::Peekable, - ops::Range, - slice::Iter, -}; +use std::{cmp::Ordering, fmt::Debug, iter::Peekable, ops::Range, slice::Iter}; /// Structure that keeps track of a I -> T mapping, /// optimized for a case where keys of the same values @@ -18,9 +12,7 @@ pub struct RangedStates { impl Default for RangedStates { fn default() -> Self { - RangedStates { - ranges: Vec::new(), - } + RangedStates { ranges: Vec::new() } } } @@ -56,7 +48,7 @@ impl RangedStates { for a in self.ranges.iter() { assert!(a.0.start < a.0.end); } - for (a, b) in self.ranges.iter().zip(self.ranges[1..].iter()) { + for (a, b) in self.ranges.iter().zip(self.ranges[1 ..].iter()) { assert!(a.0.end <= b.0.start); } } @@ -88,14 +80,16 @@ impl RangedStates { /// Returns `None` if no intersections are detected. /// Returns `Some(Err)` if the intersected values are inconsistent. pub fn query( - &self, index: &Range, fun: impl Fn(&T) -> U + &self, + index: &Range, + fun: impl Fn(&T) -> U, ) -> Option> { let mut result = None; for &(ref range, ref value) in self.ranges.iter() { if range.end > index.start && range.start < index.end { let old = result.replace(fun(value)); if old.is_some() && old != result { - return Some(Err(())) + return Some(Err(())); } } } @@ -111,10 +105,7 @@ impl RangedStates { // 1. scan the ranges to figure out how many extra ones need to be inserted // 2. go through the ranges by moving them them to the right and inserting the missing ones - let mut start_pos = match self.ranges - .iter() - .position(|pair| pair.0.end > index.start) - { + let mut start_pos = match self.ranges.iter().position(|pair| pair.0.end > index.start) { Some(pos) => pos, None => { let pos = self.ranges.len(); @@ -127,7 +118,8 @@ impl RangedStates { let (range, value) = self.ranges[start_pos].clone(); if range.start < index.start { self.ranges[start_pos].0.start = index.start; - self.ranges.insert(start_pos, (range.start .. index.start, value)); + self.ranges + .insert(start_pos, (range.start .. index.start, value)); start_pos += 1; } } @@ -203,23 +195,30 @@ impl<'a, I: Copy + Debug + Ord, T: Copy + Debug> Iterator for Merge<'a, I, T> { match (self.sa.peek(), self.sb.peek()) { // we have both streams (Some(&(ref ra, va)), Some(&(ref rb, vb))) => { - let (range, usage) = if ra.start < self.base { // in the middle of the left stream - if self.base == rb.start { // right stream is starting + let (range, usage) = if ra.start < self.base { + // in the middle of the left stream + if self.base == rb.start { + // right stream is starting debug_assert!(self.base < ra.end); (self.base .. ra.end.min(rb.end), Some(*va) .. Some(*vb)) - } else { // right hasn't started yet + } else { + // right hasn't started yet debug_assert!(self.base < rb.start); (self.base .. rb.start, Some(*va) .. None) } - } else if rb.start < self.base { // in the middle of the right stream - if self.base == ra.start { // left stream is starting + } else if rb.start < self.base { + // in the middle of the right stream + if self.base == ra.start { + // left stream is starting debug_assert!(self.base < rb.end); (self.base .. ra.end.min(rb.end), Some(*va) .. Some(*vb)) - } else { // left hasn't started yet + } else { + // left hasn't started yet debug_assert!(self.base < ra.start); (self.base .. ra.start, None .. Some(*vb)) } - } else { // no active streams + } else { + // no active streams match ra.start.cmp(&rb.start) { // both are starting Ordering::Equal => (ra.start .. ra.end.min(rb.end), Some(*va) .. Some(*vb)), @@ -262,160 +261,111 @@ impl<'a, I: Copy + Debug + Ord, T: Copy + Debug> Iterator for Merge<'a, I, T> { mod test { //TODO: randomized/fuzzy testing use super::RangedStates; - use std::{ fmt::Debug, ops::Range }; + use std::{fmt::Debug, ops::Range}; fn easy_merge( - ra: Vec<(Range, T)>, rb: Vec<(Range, T)> + ra: Vec<(Range, T)>, + rb: Vec<(Range, T)>, ) -> Vec<(Range, Range>)> { - RangedStates { ranges: ra }.merge(&RangedStates { ranges: rb }, 0).collect() + RangedStates { ranges: ra } + .merge(&RangedStates { ranges: rb }, 0) + .collect() } #[test] fn sane_good() { - let rs = RangedStates { ranges: vec![ - (1..4, 9u8), - (4..5, 9), - ]}; + let rs = RangedStates { + ranges: vec![(1 .. 4, 9u8), (4 .. 5, 9)], + }; rs.check_sanity(); } #[test] #[should_panic] fn sane_empty() { - let rs = RangedStates { ranges: vec![ - (1..4, 9u8), - (5..5, 9), - ]}; + let rs = RangedStates { + ranges: vec![(1 .. 4, 9u8), (5 .. 5, 9)], + }; rs.check_sanity(); } #[test] #[should_panic] fn sane_intersect() { - let rs = RangedStates { ranges: vec![ - (1..4, 9u8), - (3..5, 9), - ]}; + let rs = RangedStates { + ranges: vec![(1 .. 4, 9u8), (3 .. 5, 9)], + }; rs.check_sanity(); } #[test] fn coalesce() { - let mut rs = RangedStates { ranges: vec![ - (1..4, 9u8), - (4..5, 9), - (5..7, 1), - (8..9, 1), - ]}; + let mut rs = RangedStates { + ranges: vec![(1 .. 4, 9u8), (4 .. 5, 9), (5 .. 7, 1), (8 .. 9, 1)], + }; rs.coalesce(); rs.check_sanity(); - assert_eq!(rs.ranges, vec![ - (1..5, 9), - (5..7, 1), - (8..9, 1), - ]); + assert_eq!(rs.ranges, vec![(1 .. 5, 9), (5 .. 7, 1), (8 .. 9, 1),]); } #[test] fn query() { - let rs = RangedStates { ranges: vec![ - (1..4, 1u8), - (5..7, 2), - ]}; - assert_eq!(rs.query(&(0..1), |v| *v), None); - assert_eq!(rs.query(&(1..3), |v| *v), Some(Ok(1))); - assert_eq!(rs.query(&(1..6), |v| *v), Some(Err(()))); + let rs = RangedStates { + ranges: vec![(1 .. 4, 1u8), (5 .. 7, 2)], + }; + assert_eq!(rs.query(&(0 .. 1), |v| *v), None); + assert_eq!(rs.query(&(1 .. 3), |v| *v), Some(Ok(1))); + assert_eq!(rs.query(&(1 .. 6), |v| *v), Some(Err(()))); } #[test] fn isolate() { - let rs = RangedStates { ranges: vec![ - (1..4, 9u8), - (4..5, 9), - (5..7, 1), - (8..9, 1), - ]}; - assert_eq!(&rs.sanely_isolated(4..5, 0), &[ - (4..5, 9u8), - ]); - assert_eq!(&rs.sanely_isolated(0..6, 0), &[ - (0..1, 0), - (1..4, 9u8), - (4..5, 9), - (5..6, 1), - ]); - assert_eq!(&rs.sanely_isolated(8..10, 1), &[ - (8..9, 1), - (9..10, 1), - ]); - assert_eq!(&rs.sanely_isolated(6..9, 0), &[ - (6..7, 1), - (7..8, 0), - (8..9, 1), - ]); + let rs = RangedStates { + ranges: vec![(1 .. 4, 9u8), (4 .. 5, 9), (5 .. 7, 1), (8 .. 9, 1)], + }; + assert_eq!(&rs.sanely_isolated(4 .. 5, 0), &[(4 .. 5, 9u8),]); + assert_eq!( + &rs.sanely_isolated(0 .. 6, 0), + &[(0 .. 1, 0), (1 .. 4, 9u8), (4 .. 5, 9), (5 .. 6, 1),] + ); + assert_eq!( + &rs.sanely_isolated(8 .. 10, 1), + &[(8 .. 9, 1), (9 .. 10, 1),] + ); + assert_eq!( + &rs.sanely_isolated(6 .. 9, 0), + &[(6 .. 7, 1), (7 .. 8, 0), (8 .. 9, 1),] + ); } #[test] fn merge_same() { assert_eq!( - easy_merge( - vec![ - (1..4, 0u8), - ], - vec![ - (1..4, 2u8), - ], - ), - vec![ - (1..4, Some(0)..Some(2)), - ] + easy_merge(vec![(1 .. 4, 0u8),], vec![(1 .. 4, 2u8),],), + vec![(1 .. 4, Some(0) .. Some(2)),] ); } #[test] fn merge_empty() { assert_eq!( - easy_merge( - vec![ - (1..2, 0u8), - ], - vec![ - ], - ), - vec![ - (1..2, Some(0)..None), - ] + easy_merge(vec![(1 .. 2, 0u8),], vec![],), + vec![(1 .. 2, Some(0) .. None),] ); assert_eq!( - easy_merge( - vec![ - ], - vec![ - (3..4, 1u8), - ], - ), - vec![ - (3..4, None..Some(1)), - ] + easy_merge(vec![], vec![(3 .. 4, 1u8),],), + vec![(3 .. 4, None .. Some(1)),] ); } #[test] fn merge_separate() { assert_eq!( - easy_merge( - vec![ - (1..2, 0u8), - (5..6, 1u8), - ], - vec![ - (2..4, 2u8), - ], - ), + easy_merge(vec![(1 .. 2, 0u8), (5 .. 6, 1u8),], vec![(2 .. 4, 2u8),],), vec![ - (1..2, Some(0)..None), - (2..4, None..Some(2)), - (5..6, Some(1)..None), + (1 .. 2, Some(0) .. None), + (2 .. 4, None .. Some(2)), + (5 .. 6, Some(1) .. None), ] ); } @@ -423,33 +373,16 @@ mod test { #[test] fn merge_subset() { assert_eq!( - easy_merge( - vec![ - (1..6, 0u8), - ], - vec![ - (2..4, 2u8), - ], - ), + easy_merge(vec![(1 .. 6, 0u8),], vec![(2 .. 4, 2u8),],), vec![ - (1..2, Some(0)..None), - (2..4, Some(0)..Some(2)), - (4..6, Some(0)..None), + (1 .. 2, Some(0) .. None), + (2 .. 4, Some(0) .. Some(2)), + (4 .. 6, Some(0) .. None), ] ); assert_eq!( - easy_merge( - vec![ - (2..4, 0u8), - ], - vec![ - (1..4, 2u8), - ], - ), - vec![ - (1..2, None..Some(2)), - (2..4, Some(0)..Some(2)), - ] + easy_merge(vec![(2 .. 4, 0u8),], vec![(1 .. 4, 2u8),],), + vec![(1 .. 2, None .. Some(2)), (2 .. 4, Some(0) .. Some(2)),] ); } @@ -457,23 +390,17 @@ mod test { fn merge_all() { assert_eq!( easy_merge( - vec![ - (1..4, 0u8), - (5..8, 1u8), - ], - vec![ - (2..6, 2u8), - (7..9, 3u8), - ], + vec![(1 .. 4, 0u8), (5 .. 8, 1u8),], + vec![(2 .. 6, 2u8), (7 .. 9, 3u8),], ), vec![ - (1..2, Some(0)..None), - (2..4, Some(0)..Some(2)), - (4..5, None..Some(2)), - (5..6, Some(1)..Some(2)), - (6..7, Some(1)..None), - (7..8, Some(1)..Some(3)), - (8..9, None..Some(3)), + (1 .. 2, Some(0) .. None), + (2 .. 4, Some(0) .. Some(2)), + (4 .. 5, None .. Some(2)), + (5 .. 6, Some(1) .. Some(2)), + (6 .. 7, Some(1) .. None), + (7 .. 8, Some(1) .. Some(3)), + (8 .. 9, None .. Some(3)), ] ); } diff --git a/wgpu-native/src/track/texture.rs b/wgpu-native/src/track/texture.rs index 5dc8147c1..b7ea45ded 100644 --- a/wgpu-native/src/track/texture.rs +++ b/wgpu-native/src/track/texture.rs @@ -1,10 +1,5 @@ -use crate::{ - conv, - device::MAX_MIP_LEVELS, - resource::TextureUsage, - TextureId, -}; use super::{range::RangedStates, PendingTransition, ResourceState, Stitch, Unit}; +use crate::{conv, device::MAX_MIP_LEVELS, resource::TextureUsage, TextureId}; use arrayvec::ArrayVec; @@ -30,8 +25,8 @@ pub struct TextureState { impl PendingTransition { /// Produce the gfx-hal image states corresponding to the transition. pub fn to_states(&self) -> Range { - conv::map_texture_state(self.usage.start, self.selector.aspects) .. - conv::map_texture_state(self.usage.end, self.selector.aspects) + conv::map_texture_state(self.usage.start, self.selector.aspects) + .. conv::map_texture_state(self.usage.end, self.selector.aspects) } //TODO: make this less awkward! @@ -42,7 +37,9 @@ impl PendingTransition { /// /// When a transition is generated, returns the specified `replace` usage. fn record( - self, output: Option<&mut &mut Vec>, replace: TextureUsage + self, + output: Option<&mut &mut Vec>, + replace: TextureUsage, ) -> Result { let u = self.usage.clone(); match output { @@ -51,9 +48,9 @@ impl PendingTransition { Ok(replace) } None => { - if !u.start.is_empty() && - u.start != u.end && - TextureUsage::WRITE_ALL.intersects(u.start | u.end) + if !u.start.is_empty() + && u.start != u.end + && TextureUsage::WRITE_ALL.intersects(u.start | u.end) { Err(self) } else { @@ -69,10 +66,7 @@ impl ResourceState for TextureState { type Selector = hal::image::SubresourceRange; type Usage = TextureUsage; - fn query( - &self, - selector: Self::Selector, - ) -> Option { + fn query(&self, selector: Self::Selector) -> Option { let mut result = None; let num_levels = self.mips.len(); let mip_start = num_levels.min(selector.levels.start as usize); @@ -84,7 +78,7 @@ impl ResourceState for TextureState { (hal::format::Aspects::STENCIL, &mip.stencil), ] { if !selector.aspects.contains(aspect) { - continue + continue; } match plane_states.query(&selector.layers, |unit| unit.last) { None => {} @@ -92,8 +86,7 @@ impl ResourceState for TextureState { Some(Ok(usage)) if result.is_none() => { result = Some(usage); } - Some(Ok(_)) | - Some(Err(())) => return None, + Some(Ok(_)) | Some(Err(())) => return None, } } } @@ -110,8 +103,8 @@ impl ResourceState for TextureState { while self.mips.len() < selector.levels.end as usize { self.mips.push(MipState::default()); } - for (mip_id, mip) in self - .mips[selector.levels.start as usize .. selector.levels.end as usize] + for (mip_id, mip) in self.mips + [selector.levels.start as usize .. selector.levels.end as usize] .iter_mut() .enumerate() { @@ -122,12 +115,12 @@ impl ResourceState for TextureState { (hal::format::Aspects::STENCIL, &mut mip.stencil), ] { if !selector.aspects.contains(aspect) { - continue + continue; } let layers = plane_states.isolate(&selector.layers, Unit::new(usage)); for &mut (ref range, ref mut unit) in layers { if unit.last == usage && TextureUsage::ORDERED.contains(usage) { - continue + continue; } let pending = PendingTransition { id, @@ -159,28 +152,50 @@ impl ResourceState for TextureState { self.mips.push(MipState::default()); } - for (mip_id, (mip_self, mip_other)) in self.mips - .iter_mut() - .zip(&other.mips) - .enumerate() - { + for (mip_id, (mip_self, mip_other)) in self.mips.iter_mut().zip(&other.mips).enumerate() { let level = mip_id as hal::image::Level; for &mut (aspects, ref mut planes_self, planes_other) in &mut [ - (hal::format::Aspects::COLOR, &mut mip_self.color, &mip_other.color), - (hal::format::Aspects::DEPTH, &mut mip_self.depth, &mip_other.depth), - (hal::format::Aspects::STENCIL, &mut mip_self.stencil, &mip_other.stencil), + ( + hal::format::Aspects::COLOR, + &mut mip_self.color, + &mip_other.color, + ), + ( + hal::format::Aspects::DEPTH, + &mut mip_self.depth, + &mip_other.depth, + ), + ( + hal::format::Aspects::STENCIL, + &mut mip_self.stencil, + &mip_other.stencil, + ), ] { temp.extend(planes_self.merge(planes_other, 0)); planes_self.clear(); for (layers, states) in temp.drain(..) { let unit = match states { - Range { start: None, end: None } => unreachable!(), - Range { start: Some(start), end: None } => start, - Range { start: None, end: Some(end) } => end, - Range { start: Some(start), end: Some(end) } => { + Range { + start: None, + end: None, + } => unreachable!(), + Range { + start: Some(start), + end: None, + } => start, + Range { + start: None, + end: Some(end), + } => end, + Range { + start: Some(start), + end: Some(end), + } => { let mut final_usage = end.select(stitch); - if start.last != final_usage || !TextureUsage::ORDERED.contains(final_usage) { + if start.last != final_usage + || !TextureUsage::ORDERED.contains(final_usage) + { let pending = PendingTransition { id, selector: hal::image::SubresourceRange { @@ -221,10 +236,7 @@ mod test { //TODO: change() and merge() tests //use crate::TypedId; use super::*; - use hal::{ - format::Aspects, - image::SubresourceRange, - }; + use hal::{format::Aspects, image::SubresourceRange}; #[test] fn query() { @@ -232,15 +244,15 @@ mod test { ts.mips.push(MipState::default()); ts.mips.push(MipState::default()); ts.mips[1].color = PlaneStates::new(&[ - (1..3, Unit::new(TextureUsage::SAMPLED)), - (3..5, Unit::new(TextureUsage::SAMPLED)), - (5..6, Unit::new(TextureUsage::STORAGE)), + (1 .. 3, Unit::new(TextureUsage::SAMPLED)), + (3 .. 5, Unit::new(TextureUsage::SAMPLED)), + (5 .. 6, Unit::new(TextureUsage::STORAGE)), ]); assert_eq!( ts.query(SubresourceRange { aspects: Aspects::COLOR, - levels: 1..2, - layers: 2..5, + levels: 1 .. 2, + layers: 2 .. 5, }), // level 1 matches Some(TextureUsage::SAMPLED), @@ -248,8 +260,8 @@ mod test { assert_eq!( ts.query(SubresourceRange { aspects: Aspects::DEPTH, - levels: 1..2, - layers: 2..5, + levels: 1 .. 2, + layers: 2 .. 5, }), // no depth found None, @@ -257,8 +269,8 @@ mod test { assert_eq!( ts.query(SubresourceRange { aspects: Aspects::COLOR, - levels: 0..2, - layers: 2..5, + levels: 0 .. 2, + layers: 2 .. 5, }), // level 0 is empty, level 1 matches Some(TextureUsage::SAMPLED), @@ -266,8 +278,8 @@ mod test { assert_eq!( ts.query(SubresourceRange { aspects: Aspects::COLOR, - levels: 1..2, - layers: 1..5, + levels: 1 .. 2, + layers: 1 .. 5, }), // level 1 matches with gaps Some(TextureUsage::SAMPLED), @@ -275,8 +287,8 @@ mod test { assert_eq!( ts.query(SubresourceRange { aspects: Aspects::COLOR, - levels: 1..2, - layers: 4..6, + levels: 1 .. 2, + layers: 4 .. 6, }), // level 1 doesn't match None, 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..a157677f3 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,81 @@ 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, + #[cfg(windows)] + dx12: 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), + #[cfg(windows)] + dx12: IdentityHub::new(Backend::Dx12), + } + } + + 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, + #[cfg(windows)] + Backend::Dx12 => &mut self.dx12, + _ => 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 +108,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 +122,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 +131,28 @@ 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, - desc.clone(), - adapter_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(), + #[cfg(windows)] + identities.dx12.adapters.alloc(), + ]; + let msg = GlobalMessage::RequestAdapter(desc.clone(), ids); client.channel.send(msg).unwrap(); - adapter_id + unimplemented!() } #[no_mangle] @@ -133,12 +161,13 @@ 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( - adapter_id, - desc.clone(), - device_id, - )); + 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..ee38de4c4 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, }