diff --git a/.cargo/config.toml b/.cargo/config.toml index 4b0140061..16bb81503 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,2 +1,6 @@ [alias] -xtask = "run --manifest-path xtask/Cargo.toml --" +xtask = "run -p wgpu-xtask --" + +# Needed until https://github.com/rust-random/getrandom/issues/675 is resolved. +[target.wasm32-unknown-unknown] +rustflags = ["--cfg", "getrandom_backend=\"wasm_js\""] diff --git a/.config/nextest.toml b/.config/nextest.toml index 5a6b918d0..574ad1b37 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -1,10 +1,15 @@ # None of our tests should take longer than 45s, and if they've gone 2x that, # terminate them to prevent infinite run-on. [profile.default] +default-filter = "!test(~oom_test)" slow-timeout = { period = "45s", terminate-after = 2 } fail-fast = false retries = 0 +[profile.default-miri] +# Miri is very very slow, so give it a much longer timeout. +slow-timeout = { period = "120s", terminate-after = 4 } + # Use two threads for tests with "2 threads" in their name [[profile.default.overrides]] filter = 'test(~2_threads) | test(~2 threads)' @@ -26,6 +31,23 @@ threads-required = 8 # https://github.com/gfx-rs/wgpu/issues/7200 [[profile.default.overrides]] -filter = 'test(wgpu_gpu_test::image_atomics::image_32_atomics)' +filter = 'test(wgpu_gpu::image_atomics::image_32_atomics)' platform = 'cfg(target_vendor = "apple")' retries = 1 + +[[profile.default.overrides]] +filter = 'test(compile_fail)' +slow-timeout = { period = "3m", terminate-after = 2 } + +[[profile.default.overrides]] +filter = 'test(~oom_test)' +threads-required = "num-test-threads" + +# +# Priorities for slow tests so that they run first, increasing overall test suite speed. +# On software renderers, they can take 10-60 seconds. Compile fail can easily take 30+ +# seconds as it has to compile wgpu. +# +[[profile.default.overrides]] +priority = 1 +filter = 'test(clear_texture) | test(clear_buffer_range_respected) | test(compile_fail) | test(test_api)' diff --git a/.deny.toml b/.deny.toml index 77a3a58fa..af5635c22 100644 --- a/.deny.toml +++ b/.deny.toml @@ -1,35 +1,49 @@ [bans] multiple-versions = "deny" skip-tree = [ - # We never enable loom in any of our dependencies but it causes dupes - { name = "loom", version = "0.7.2" }, { name = "windows-sys", version = "0.45" }, { name = "winit", version = "0.29" }, - { name = "rustc_version", version = "0.2.3" }, - { name = "miniz_oxide", version = "0.7.4" }, + { name = "rustc-hash", version = "1.1.0" }, # introduced by Deno, to be investigated - { name = "strum_macros", version = "0.25.3" }, { name = "petgraph", version = "0.6.5" }, - { name = "base64-simd", version = "0.7.0" }, - { name = "bit-set", version = "0.5.3" }, - { name = "bit-vec", version = "0.6.3" }, - { name = "capacity_builder", version = "0.1.3" }, - { name = "itertools", version = "0.10.5" }, ] skip = [ - # Strum uses an old version - { name = "heck", version = "0.4.0" }, + # Flume uses an old version + { name = "nanorand", version = "0.7.0" }, + # Deno uses an old version - { name = "strum", version = "0.25.0" }, + { name = "bincode", version = "1.3.3" }, + { name = "which", version = "6.0.3" }, + + # Winit uses an old version + { name = "windows-sys", version = "0.52.0" }, + + # Loom uses a new windows version + { name = "windows", version = "0.61.1" }, + { name = "windows-core", version = "0.61.2" }, + { name = "windows-implement", version = "0.60.0" }, + { name = "windows-interface", version = "0.59.1" }, + { name = "windows-result", version = "0.3.4" }, + { name = "windows-strings", version = "0.4.2" }, ] wildcards = "deny" allow-wildcard-paths = true [advisories] -# `paste` crate is no longer maintained https://rustsec.org/advisories/RUSTSEC-2024-0436 -# It's a dependency of `metal` (which is to be replaced with `objc2`) and a transitive dependency of `deno`. -ignore = ["RUSTSEC-2024-0436"] +ignore = [ + # `paste` crate is no longer maintained https://rustsec.org/advisories/RUSTSEC-2024-0436 + # It's a dependency of `metal` (which is to be replaced with `objc2-metal`), and a + # transitive dependency of `deno`. https://github.com/gfx-rs/wgpu/issues/7873 + "RUSTSEC-2024-0436", + # `unic-*` crates are no longer maintained https://rustsec.org/advisories/RUSTSEC-2025-0100 + # These are used via `deno`. https://github.com/gfx-rs/wgpu/issues/8393 + "RUSTSEC-2025-0075", + "RUSTSEC-2025-0080", + "RUSTSEC-2025-0081", + "RUSTSEC-2025-0098", + "RUSTSEC-2025-0100", +] [licenses] allow = [ @@ -42,7 +56,6 @@ allow = [ "MPL-2.0", "MIT", "MIT-0", - "Unicode-DFS-2016", "Unicode-3.0", "Zlib", ] @@ -50,11 +63,11 @@ private = { ignore = true } [sources] allow-git = [ - # Waiting on releases; used in examples only + # Waiting on releases; used in examples/tests only ] unknown-registry = "deny" unknown-git = "deny" required-git-spec = "rev" [sources.allow-org] -github = ["gfx-rs"] +github = [] diff --git a/.envrc b/.envrc deleted file mode 100644 index 1d953f4bd..000000000 --- a/.envrc +++ /dev/null @@ -1 +0,0 @@ -use nix diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS deleted file mode 100644 index 1cae09787..000000000 --- a/.github/CODEOWNERS +++ /dev/null @@ -1,17 +0,0 @@ -* @gfx-rs/wgpu - -/cts_runner/ @crowlkats @gfx-rs/wgpu -/deno_webgpu/ @crowlkats @gfx-rs/wgpu -/naga/ @gfx-rs/naga -/naga-cli/ @gfx-rs/naga - -# Both wgpu and naga teams are owners of naga infrastructure so -# either team can review changes to deps and docs. -naga/Cargo.toml @gfx-rs/wgpu @gfx-rs/naga -naga/README.md @gfx-rs/wgpu @gfx-rs/naga -naga/CHANGELOG.md @gfx-rs/wgpu @gfx-rs/naga -naga-cli/Cargo.toml @gfx-rs/wgpu @gfx-rs/naga - -# We leave the codeowners empty for the changelog, so naga changes -# don't trigger wgpu reviews and vise versa. -/CHANGELOG.md diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index dc45ceff3..29ab84ed1 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,5 +1,5 @@ blank_issues_enabled: false contact_links: - name: Question about wgpu - url: https://github.com/gfx-rs/wgpu/discussions/new + url: https://github.com/gfx-rs/wgpu/discussions/new/choose about: Any questions about how to use wgpu should go here. diff --git a/.github/actions/install-dxc/action.yml b/.github/actions/install-dxc/action.yml new file mode 100644 index 000000000..92189db8a --- /dev/null +++ b/.github/actions/install-dxc/action.yml @@ -0,0 +1,17 @@ +name: "Install DXC" +description: "Install DXC" +runs: + using: "composite" + steps: + - shell: bash + run: | + set -e + + export DXC_RELEASE="v1.8.2505.1" + export DXC_FILENAME="dxc_2025_07_14.zip" + + curl.exe -L --retry 5 https://github.com/microsoft/DirectXShaderCompiler/releases/download/$DXC_RELEASE/$DXC_FILENAME -o dxc.zip + 7z.exe e dxc.zip -odxc bin/x64/{dxc.exe,dxcompiler.dll} + + # We need to use cygpath to convert PWD to a windows path as we're using bash. + cygpath --windows "$PWD/dxc" >> "$GITHUB_PATH" diff --git a/.github/actions/install-mesa/action.yml b/.github/actions/install-mesa/action.yml new file mode 100644 index 000000000..103c1e218 --- /dev/null +++ b/.github/actions/install-mesa/action.yml @@ -0,0 +1,61 @@ +name: 'Install Mesa' +description: 'Install Mesa' +inputs: + # Sourced from https://archive.mesa3d.org/. Bumping this requires + # updating the mesa build in https://github.com/gfx-rs/ci-build and creating a new release. + version: + default: '24.3.4' + # Corresponds to https://github.com/gfx-rs/ci-build/releases + ci-binary-build: + default: 'build20' +runs: + using: 'composite' + steps: + - name: (Linux) Install Mesa + if: runner.os == 'Linux' + shell: bash + env: + MESA_VERSION: ${{ inputs.version }} + CI_BINARY_BUILD: ${{ inputs.ci-binary-build }} + run: | + set -e + + curl -L --retry 5 https://github.com/gfx-rs/ci-build/releases/download/$CI_BINARY_BUILD/mesa-$MESA_VERSION-linux-x86_64.tar.xz -o mesa.tar.xz + mkdir mesa + tar xpf mesa.tar.xz -C mesa + + # The ICD provided by the mesa build is hardcoded to the build environment. + # + # We write out our own ICD file to point to the mesa vulkan + cat <<- EOF > icd.json + { + "ICD": { + "api_version": "1.1.255", + "library_path": "$PWD/mesa/lib/x86_64-linux-gnu/libvulkan_lvp.so" + }, + "file_format_version": "1.0.0" + } + EOF + + echo "VK_DRIVER_FILES=$PWD/icd.json" >> "$GITHUB_ENV" + echo "LD_LIBRARY_PATH=$PWD/mesa/lib/x86_64-linux-gnu/:$LD_LIBRARY_PATH" >> "$GITHUB_ENV" + echo "LIBGL_DRIVERS_PATH=$PWD/mesa/lib/x86_64-linux-gnu/dri" >> "$GITHUB_ENV" + + - name: (Windows) Install Mesa + if: runner.os == 'Windows' + shell: bash + env: + MESA_VERSION: ${{ inputs.version }} + CI_BINARY_BUILD: ${{ inputs.ci-binary-build }} + run: | + set -e + + curl.exe -L --retry 5 https://github.com/pal1000/mesa-dist-win/releases/download/$MESA_VERSION/mesa3d-$MESA_VERSION-release-msvc.7z -o mesa.7z + 7z.exe e mesa.7z -omesa x64/{opengl32.dll,libgallium_wgl.dll,libglapi.dll,vulkan_lvp.dll,lvp_icd.x86_64.json} + + cp -v mesa/* target/llvm-cov-target/debug/ + cp -v mesa/* target/llvm-cov-target/debug/deps + + # We need to use cygpath to convert PWD to a windows path as we're using bash. + echo "VK_DRIVER_FILES=`cygpath --windows $PWD/mesa/lvp_icd.x86_64.json`" >> "$GITHUB_ENV" + echo "GALLIUM_DRIVER=llvmpipe" >> "$GITHUB_ENV" diff --git a/.github/actions/install-vulkan-sdk/action.yml b/.github/actions/install-vulkan-sdk/action.yml new file mode 100644 index 000000000..3c726902f --- /dev/null +++ b/.github/actions/install-vulkan-sdk/action.yml @@ -0,0 +1,61 @@ +name: "Install Vulkan SDK" +description: "Install Vulkan SDK" +inputs: + # Sourced from https://vulkan.lunarg.com/sdk/home#linux + version: + default: "1.4.328" + full-version: + default: "1.4.328.1" +runs: + using: "composite" + steps: + - name: (Linux) Install Vulkan SDK + if: runner.os == 'Linux' + shell: bash + env: + VULKAN_SDK_VERSION: ${{ inputs.version }} + VULKAN_FULL_SDK_VERSION: ${{ inputs.full-version }} + run: | + set -e + + curl -L --retry 5 https://sdk.lunarg.com/sdk/download/${{ env.VULKAN_FULL_SDK_VERSION }}/linux/vulkansdk-linux-x86_64-${{ env.VULKAN_FULL_SDK_VERSION }}.tar.xz -o vulkan-sdk.tar.xz + mkdir vulkan-sdk + tar xpf vulkan-sdk.tar.xz -C vulkan-sdk + + mv ./vulkan-sdk/${{ env.VULKAN_FULL_SDK_VERSION }} $HOME/VulkanSDK + + echo "$HOME/VulkanSDK/x86_64/bin" >> "$GITHUB_PATH" + echo "LD_LIBRARY_PATH=$HOME/VulkanSDK/x86_64/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" >> "$GITHUB_ENV" + echo "VK_ADD_LAYER_PATH=$HOME/VulkanSDK/x86_64/share/vulkan/explicit_layer.d" >> "$GITHUB_ENV" + + - name: (Windows) Install Vulkan SDK + if: runner.os == 'Windows' + shell: bash + env: + VULKAN_SDK_VERSION: ${{ inputs.version }} + VULKAN_FULL_SDK_VERSION: ${{ inputs.full-version }} + run: | + set -e + + curl.exe -L --retry 5 https://sdk.lunarg.com/sdk/download/${{ env.VULKAN_FULL_SDK_VERSION }}/windows/vulkansdk-windows-X64-${{ env.VULKAN_FULL_SDK_VERSION }}.exe -o vulkan-sdk-installer.exe + + ./vulkan-sdk-installer.exe --accept-licenses --default-answer --confirm-command install + + echo "C:/VulkanSDK/${{ env.VULKAN_FULL_SDK_VERSION }}/Bin" >> "$GITHUB_PATH" + + - name: (Mac) Install Vulkan SDK + if: runner.os == 'macOS' + shell: bash + env: + VULKAN_SDK_VERSION: ${{ inputs.version }} + VULKAN_FULL_SDK_VERSION: ${{ inputs.full-version }} + run: | + set -e + + curl -L --retry 5 https://sdk.lunarg.com/sdk/download/${{ env.VULKAN_FULL_SDK_VERSION }}/mac/vulkansdk-macos-${{ env.VULKAN_FULL_SDK_VERSION }}.zip -o vulkan-sdk.zip + unzip vulkan-sdk.zip -d vulkan-sdk + + ls -l vulkan-sdk + sudo ./vulkan-sdk/vulkansdk-macOS-${{ env.VULKAN_FULL_SDK_VERSION }}.app/Contents/MacOS/vulkansdk-macOS-${{ env.VULKAN_FULL_SDK_VERSION }} --root "$HOME/VulkanSDK" --accept-licenses --default-answer --confirm-command install + + echo "$HOME/VulkanSDK/macOS/bin" >> "$GITHUB_PATH" diff --git a/.github/actions/install-warp/action.yml b/.github/actions/install-warp/action.yml new file mode 100644 index 000000000..66aa303ae --- /dev/null +++ b/.github/actions/install-warp/action.yml @@ -0,0 +1,25 @@ +name: "Install WARP" +description: "Install WARP" +inputs: + target-dirs: + description: "Space-separated list of directories into which to install the WARP DLL." + required: true +runs: + using: "composite" + steps: + - shell: bash + run: | + set -e + + export WARP_VERSION="1.0.13" + + # Make sure dxc is in path. + dxc --version + + curl.exe -L --retry 5 https://www.nuget.org/api/v2/package/Microsoft.Direct3D.WARP/$WARP_VERSION -o warp.zip + 7z.exe e warp.zip -owarp build/native/bin/x64/d3d10warp.dll + + for dir in ${{ inputs.target-dirs }}; do + mkdir -p "$dir" + cp -v warp/d3d10warp.dll "$dir" + done diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index dceafcc14..000000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,27 +0,0 @@ -version: 2 - -updates: - - package-ecosystem: cargo - directory: / - schedule: - interval: weekly - # This allows dependabot to update _all_ lockfile packages. - # - # These will be grouped into the existing group update PRs, so shouldn't generate additional jobs. - allow: - # Allow both direct and indirect updates for all packages - - dependency-type: "all" - # Waiting on https://github.com/dependabot/dependabot-core/issues/4009 to be resolved, shouldn't be long. - # versioning-strategy: increase-if-necessary - groups: - patch-updates: - patterns: - - "*" - update-types: - - "minor" - - "patch" - - - package-ecosystem: github-actions - directory: / - schedule: - interval: weekly diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cc5dce5cd..f61ec6e22 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,12 +3,13 @@ name: CI on: push: branches-ignore: [ - # We don't need to run on dependabot PRs. - "dependabot/**", - # This is the branch the merge queue creates. + # Renovate branches are always PRs, so they will be covered + # by the pull_request event. + "renovate/**", + # Branches with the `gh-readonly-queue` prefix are used by the + # merge queue, so they are already covered by the `merge_group` event. "gh-readonly-queue/**", ] - tags: [v0.*] pull_request: merge_group: @@ -17,26 +18,8 @@ env: # Dependency versioning # - # Sourced from https://vulkan.lunarg.com/sdk/home#linux - VULKAN_SDK_VERSION: "1.4.304" - VULKAN_FULL_SDK_VERSION: "1.4.304.1" - # Sourced from https://www.nuget.org/packages/Microsoft.Direct3D.WARP - WARP_VERSION: "1.0.13" - - # Sourced from https://github.com/microsoft/DirectXShaderCompiler/releases - # - # Must also be changed in shaders.yaml - DXC_RELEASE: "v1.8.2407" - DXC_FILENAME: "dxc_2024_07_31_clang_cl.zip" - - # Sourced from https://archive.mesa3d.org/. Bumping this requires - # updating the mesa build in https://github.com/gfx-rs/ci-build and creating a new release. - MESA_VERSION: "24.3.4" - # Corresponds to https://github.com/gfx-rs/ci-build/releases - CI_BINARY_BUILD: "build20" - # This is the MSRV used by `wgpu` itself and all surrounding infrastructure. - REPO_MSRV: "1.84" + REPO_MSRV: "1.88" # This is the MSRV used by the `wgpu-core`, `wgpu-hal`, and `wgpu-types` crates, # to ensure that they can be used with firefox. CORE_MSRV: "1.82.0" @@ -48,7 +31,7 @@ env: CARGO_INCREMENTAL: false CARGO_TERM_COLOR: always WGPU_DX12_COMPILER: dxc - RUST_LOG: debug + RUST_LOG: debug,wasm_bindgen_wasm_interpreter=warn,wasm_bindgen_cli_support=warn,walrus=warn,naga=info RUST_BACKTRACE: full PKG_CONFIG_ALLOW_CROSS: 1 # allow android to work RUSTFLAGS: -D warnings @@ -57,6 +40,13 @@ env: CACHE_SUFFIX: d # cache busting WGPU_CI: true +# Every time a PR is pushed to, cancel any previous jobs. This +# makes us behave nicer to github and get faster turnaround times +# on PRs that are pushed to multiple times in rapid succession. +concurrency: + group: ${{github.workflow}}-${{github.ref}} + cancel-in-progress: ${{github.event_name == 'pull_request'}} + # We distinguish the following kinds of builds: # - native: build for the same target as we compile on # - web: build for the Web @@ -126,60 +116,67 @@ jobs: # Linux - name: Linux x86_64 - os: ubuntu-22.04 + os: ubuntu-24.04 target: x86_64-unknown-linux-gnu tier: 1 kind: native - name: Linux aarch64 - os: ubuntu-22.04 + os: ubuntu-24.04 target: aarch64-unknown-linux-gnu tier: 1 kind: native + # FreeBSD + - name: FreeBSD x86_64 + os: ubuntu-24.04 + target: x86_64-unknown-freebsd + tier: 2 + kind: wgpu-only + # Android - name: Android aarch64 - os: ubuntu-22.04 + os: ubuntu-24.04 target: aarch64-linux-android tier: 2 kind: native # Android - name: Android ARMv7 - os: ubuntu-22.04 + os: ubuntu-24.04 target: armv7-linux-androideabi tier: 2 kind: wgpu-only # Android - name: Android x86_64 - os: ubuntu-22.04 + os: ubuntu-24.04 target: x86_64-linux-android tier: 2 kind: wgpu-only # OpenHarmony - name: OpenHarmony aarch64 - os: ubuntu-22.04 + os: ubuntu-24.04 target: aarch64-unknown-linux-ohos tier: 2 kind: native # WebGPU/WebGL - name: WebAssembly - os: ubuntu-22.04 + os: ubuntu-24.04 target: wasm32-unknown-unknown tier: 2 kind: web - name: Emscripten - os: ubuntu-22.04 + os: ubuntu-24.04 target: wasm32-unknown-emscripten tier: 2 kind: wgpu-only - name: WebAssembly Core 1.0 - os: ubuntu-22.04 + os: ubuntu-24.04 target: wasm32v1-none tier: 2 kind: no_std @@ -187,7 +184,7 @@ jobs: # 32-bit PowerPC Linux # Included to test support for `portable-atomic` - name: Linux ppc32 - os: ubuntu-22.04 + os: ubuntu-24.04 target: powerpc-unknown-linux-gnu tier: 2 kind: wgpu-only @@ -197,7 +194,7 @@ jobs: steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Install toolchain (repo MSRV - tier 1 or 2) if: matrix.tier == 1 || matrix.tier == 2 @@ -264,17 +261,19 @@ jobs: run: | set -e - # build for WebGPU - cargo clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} --tests --features glsl,spirv,fragile-send-sync-non-atomic-wasm - cargo clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} --tests --features glsl,spirv - cargo doc --target ${{ matrix.target }} ${{ matrix.extra-flags }} --no-deps --features glsl,spirv + export RUSTFLAGS="$RUSTFLAGS --cfg getrandom_backend=\"wasm_js\"" - # check with no features - cargo clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} --no-default-features + # build for WebGPU + cargo --locked clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} --tests --features glsl,spirv,fragile-send-sync-non-atomic-wasm + cargo --locked clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} --tests --features glsl,spirv + cargo --locked doc --target ${{ matrix.target }} ${{ matrix.extra-flags }} --no-deps --features glsl,spirv + + # check with only the web feature + cargo --locked clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} --no-default-features --features=web # all features - cargo clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} --tests --all-features - cargo doc --target ${{ matrix.target }} ${{ matrix.extra-flags }} --no-deps --all-features + cargo --locked clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} --tests --all-features + cargo --locked doc --target ${{ matrix.target }} ${{ matrix.extra-flags }} --no-deps --all-features # Building for platforms where the tests do not compile. - name: Check `wgpu` only @@ -284,15 +283,15 @@ jobs: set -e # check with no features - cargo clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} -p wgpu -p wgpu-hal --no-default-features + cargo --locked clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} -p wgpu -p wgpu-hal --no-default-features # Don't check samples since we use winit in our samples which has dropped support for Emscripten. # Check with all features. - cargo clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} -p wgpu-hal --all-features - cargo clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} -p wgpu --all-features + cargo --locked clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} -p wgpu-hal --all-features + cargo --locked clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} -p wgpu --all-features - # Building for no_std platforms where every feature is enabled except "std". + # Building for no_std platforms. - name: Check `no_std` if: matrix.kind == 'no_std' shell: bash @@ -300,10 +299,16 @@ jobs: set -e # check with no features - cargo clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} -p wgpu-types --no-default-features + cargo --locked clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} -p wgpu-types --no-default-features + cargo --locked clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} -p naga --no-default-features + cargo --locked clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} -p wgpu-hal --no-default-features + cargo --locked clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} -p wgpu --no-default-features - # Check with all features except "std". - cargo clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} -p wgpu-types --no-default-features --features strict_asserts,fragile-send-sync-non-atomic-wasm,serde,counters + # Check with all compatible features + cargo --locked clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} -p wgpu-types --no-default-features --features strict_asserts,fragile-send-sync-non-atomic-wasm,serde,counters + cargo --locked clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} -p naga --no-default-features --features dot-out,spv-in,spv-out + cargo --locked clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} -p wgpu-hal --no-default-features --features fragile-send-sync-non-atomic-wasm + cargo --locked clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} -p wgpu --no-default-features --features serde # Building for native platforms with standard tests. - name: Check native @@ -313,13 +318,17 @@ jobs: set -e # check with no features - cargo clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} --no-default-features + cargo --locked clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} --no-default-features # Check with all features. - cargo clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} --tests --benches --all-features + cargo --locked clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} --tests --benches --all-features + + # Check with all features and profiling macro code. + # If we don't check this then errors inside `profiling::scope!()` will not be caught. + cargo --locked clippy --target ${{ matrix.target }} ${{ matrix.extra-flags }} --tests --benches --all-features --features test-build-with-profiling # build docs - cargo doc --target ${{ matrix.target }} ${{ matrix.extra-flags }} --all-features --no-deps + cargo --locked doc --target ${{ matrix.target }} ${{ matrix.extra-flags }} --all-features --no-deps - name: Check private item docs if: matrix.kind == 'native' @@ -328,7 +337,7 @@ jobs: set -e # wgpu_core package - cargo doc --target ${{ matrix.target }} ${{ matrix.extra-flags }} \ + cargo --locked doc --target ${{ matrix.target }} ${{ matrix.extra-flags }} \ --package wgpu-core \ --package wgpu-hal \ --package naga \ @@ -358,7 +367,7 @@ jobs: # Linux - name: Linux x86_64 - os: ubuntu-22.04 + os: ubuntu-24.04 target: x86_64-unknown-linux-gnu name: MSRV Check ${{ matrix.name }} @@ -366,7 +375,7 @@ jobs: steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Install core MSRV toolchain run: | @@ -394,6 +403,8 @@ jobs: run: | set -e + # 1.23.2 requires bytemuck_derive 1.10.1 + cargo update -p bytemuck --precise 1.23.1 # 1.9.0 requires MSRV 1.84 cargo update -p bytemuck_derive --precise 1.8.1 @@ -405,32 +416,29 @@ jobs: # check `wgpu-core` with all features. This will also get `wgpu-hal` and `wgpu-types`. cargo check --target ${{ matrix.target }} --all-features -p wgpu-core - naga-minimal-versions: + # Check that the libraries build — but not that there are no warnings or that tests pass - + # with `-Zdirect-minimal-versions` which lowers all dependencies from the workspace packages + # to non-workspace packages to their minimum allowed version. + check-minimal-versions: # runtime is normally 2 minutes timeout-minutes: 10 - name: MSRV naga Minimal Versions - runs-on: ubuntu-22.04 + name: MSRV Minimal Versions + runs-on: ubuntu-24.04 + env: + # Override flags to NOT include `-D warnings`, because warnings may be due to harmless problems in deps. + # Also, allow unexpected_cfgs because it is very common and spammy when using old deps. + RUSTFLAGS: -A unexpected_cfgs steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v5 - - name: Install core MSRV toolchain - run: | - rustup toolchain install ${{ env.CORE_MSRV }} --no-self-update --profile=minimal --component clippy - rustup override set ${{ env.CORE_MSRV }} - cargo -V - - - name: Install Nightly toolchain + - name: Install toolchain run: | rustup toolchain install ${{ env.REPO_MSRV }} --no-self-update --profile=minimal - cargo +${{ env.REPO_MSRV }} -V - - - name: Install `cargo-hack` - uses: taiki-e/install-action@v2 - with: - tool: cargo-hack + rustup override set ${{ env.REPO_MSRV }} + cargo -V - name: Disable debug symbols shell: bash @@ -445,16 +453,16 @@ jobs: run: | set -e - cargo +${{ env.REPO_MSRV }} hack generate-lockfile --remove-dev-deps -Z minimal-versions -p naga -p naga-cli + cargo +${{ env.REPO_MSRV }} update -Zdirect-minimal-versions env: RUSTC_BOOTSTRAP: 1 - - name: Run Clippy + - name: Run cargo check shell: bash run: | set -e - cargo clippy --all-features -p naga -p naga-cli + cargo check --all-targets --all-features wasm-test: # runtime is normally 2 minutes @@ -465,7 +473,7 @@ jobs: steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Install repo MSRV toolchain run: | @@ -481,7 +489,10 @@ jobs: - name: Execute tests run: | cd wgpu - wasm-pack test --headless --chrome --no-default-features --features wgsl,webgl --workspace + + export RUSTFLAGS="$RUSTFLAGS --cfg getrandom_backend=\"wasm_js\"" + + wasm-pack test --headless --chrome --no-default-features --features wgsl,webgl,web --workspace gpu-test: # runtime is normally 5-15 minutes @@ -508,7 +519,7 @@ jobs: steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Install repo MSRV toolchain run: | @@ -538,120 +549,44 @@ jobs: key: test-${{ matrix.os }}-${{ env.CACHE_SUFFIX }} workspaces: | . -> target - xtask -> xtask/target - name: (Windows) Install DXC if: matrix.os == 'windows-2022' - shell: bash - run: | - set -e - - curl.exe -L --retry 5 https://github.com/microsoft/DirectXShaderCompiler/releases/download/$DXC_RELEASE/$DXC_FILENAME -o dxc.zip - 7z.exe e dxc.zip -odxc bin/x64/{dxc.exe,dxcompiler.dll,dxil.dll} - - # We need to use cygpath to convert PWD to a windows path as we're using bash. - cygpath --windows "$PWD/dxc" >> "$GITHUB_PATH" + uses: ./.github/actions/install-dxc - name: (Windows) Install WARP if: matrix.os == 'windows-2022' - shell: bash - run: | - set -e - - # Make sure dxc is in path. - dxc --version - - curl.exe -L --retry 5 https://www.nuget.org/api/v2/package/Microsoft.Direct3D.WARP/$WARP_VERSION -o warp.zip - 7z.exe e warp.zip -owarp build/native/bin/x64/d3d10warp.dll - - mkdir -p target/llvm-cov-target/debug/deps - - cp -v warp/d3d10warp.dll target/llvm-cov-target/debug/ - cp -v warp/d3d10warp.dll target/llvm-cov-target/debug/deps + uses: ./.github/actions/install-warp + with: + target-dirs: "target/llvm-cov-target/debug target/llvm-cov-target/debug/deps" - name: (Windows) Install Mesa if: matrix.os == 'windows-2022' - shell: bash - run: | - set -e - - curl.exe -L --retry 5 https://github.com/pal1000/mesa-dist-win/releases/download/$MESA_VERSION/mesa3d-$MESA_VERSION-release-msvc.7z -o mesa.7z - 7z.exe e mesa.7z -omesa x64/{opengl32.dll,libgallium_wgl.dll,libglapi.dll,vulkan_lvp.dll,lvp_icd.x86_64.json} - - cp -v mesa/* target/llvm-cov-target/debug/ - cp -v mesa/* target/llvm-cov-target/debug/deps - - # We need to use cygpath to convert PWD to a windows path as we're using bash. - echo "VK_DRIVER_FILES=`cygpath --windows $PWD/mesa/lvp_icd.x86_64.json`" >> "$GITHUB_ENV" - echo "GALLIUM_DRIVER=llvmpipe" >> "$GITHUB_ENV" + uses: ./.github/actions/install-mesa - name: (Windows) Install Vulkan SDK if: matrix.os == 'windows-2022' - shell: bash - run: | - set -e - - curl.exe -L --retry 5 https://sdk.lunarg.com/sdk/download/${{ env.VULKAN_FULL_SDK_VERSION }}/windows/VulkanSDK-${{ env.VULKAN_FULL_SDK_VERSION }}-Installer.exe -o vulkan-sdk-installer.exe - - ./vulkan-sdk-installer.exe --accept-licenses --default-answer --confirm-command install - - echo "C:/VulkanSDK/${{ env.VULKAN_FULL_SDK_VERSION }}/Bin" >> "$GITHUB_PATH" + uses: ./.github/actions/install-vulkan-sdk - name: (Mac) Install Vulkan SDK if: matrix.os == 'macos-14' - shell: bash - run: | - set -e - - curl -L --retry 5 https://sdk.lunarg.com/sdk/download/${{ env.VULKAN_FULL_SDK_VERSION }}/mac/vulkansdk-macos-${{ env.VULKAN_FULL_SDK_VERSION }}.zip -o vulkan-sdk.zip - unzip vulkan-sdk.zip -d vulkan-sdk - - ls -l vulkan-sdk - sudo ./vulkan-sdk/InstallVulkan-${{ env.VULKAN_FULL_SDK_VERSION }}.app/Contents/MacOS/InstallVulkan-${{ env.VULKAN_FULL_SDK_VERSION }} --root "$HOME/VulkanSDK" --accept-licenses --default-answer --confirm-command install - - echo "$HOME/VulkanSDK/macOS/bin" >> "$GITHUB_PATH" + uses: ./.github/actions/install-vulkan-sdk - name: (Linux) Install Vulkan SDK if: matrix.os == 'ubuntu-24.04' - shell: bash - run: | - set -e - - sudo apt-get update -y -qq - - # vulkan sdk - wget -qO - https://packages.lunarg.com/lunarg-signing-key-pub.asc | sudo apt-key add - - sudo wget -qO /etc/apt/sources.list.d/lunarg-vulkan-${{ env.VULKAN_SDK_VERSION }}-noble.list https://packages.lunarg.com/vulkan/${{ env.VULKAN_SDK_VERSION }}/lunarg-vulkan-$VULKAN_SDK_VERSION-noble.list - - sudo apt-get update - sudo apt install -y vulkan-sdk + uses: ./.github/actions/install-vulkan-sdk - name: (Linux) Install Mesa if: matrix.os == 'ubuntu-24.04' + uses: ./.github/actions/install-mesa + + - name: Delete Naga snapshots shell: bash run: | set -e - curl -L --retry 5 https://github.com/gfx-rs/ci-build/releases/download/$CI_BINARY_BUILD/mesa-$MESA_VERSION-linux-x86_64.tar.xz -o mesa.tar.xz - mkdir mesa - tar xpf mesa.tar.xz -C mesa - - # The ICD provided by the mesa build is hardcoded to the build environment. - # - # We write out our own ICD file to point to the mesa vulkan - cat <<- EOF > icd.json - { - "ICD": { - "api_version": "1.1.255", - "library_path": "$PWD/mesa/lib/x86_64-linux-gnu/libvulkan_lvp.so" - }, - "file_format_version": "1.0.0" - } - EOF - - echo "VK_DRIVER_FILES=$PWD/icd.json" >> "$GITHUB_ENV" - echo "LD_LIBRARY_PATH=$PWD/mesa/lib/x86_64-linux-gnu/:$LD_LIBRARY_PATH" >> "$GITHUB_ENV" - echo "LIBGL_DRIVERS_PATH=$PWD/mesa/lib/x86_64-linux-gnu/dri" >> "$GITHUB_ENV" + # Delete snapshots so we can ensure there aren't any excess output files. + rm -r naga/tests/out - name: Run `wgpu-info` shell: bash @@ -661,20 +596,20 @@ jobs: export RUST_LOG=trace # This needs to match the command in xtask/tests.rs - cargo llvm-cov --no-cfg-coverage --no-report run --bin wgpu-info -- -vv + cargo --locked llvm-cov --no-cfg-coverage --no-report run --bin wgpu-info -- -vv - name: Run tests shell: bash run: | set -e - cargo xtask test --llvm-cov + cargo --locked xtask test --llvm-cov - name: Check Naga snapshots # git diff doesn't check untracked files, we need to stage those then compare with HEAD. run: git add . && git diff --exit-code HEAD naga/tests/out - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v5 if: always() # We want artifacts even if the tests fail. with: name: comparison-images-${{ matrix.os }} @@ -689,10 +624,10 @@ jobs: run: | set -e - cargo llvm-cov report --lcov --output-path lcov.info + cargo --locked llvm-cov report --lcov --output-path lcov.info - name: Upload coverage report to Codecov - uses: codecov/codecov-action@v4 + uses: codecov/codecov-action@v5 if: steps.coverage.outcome == 'success' with: files: lcov.info @@ -707,7 +642,7 @@ jobs: steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Install repo MSRV toolchain run: | @@ -725,7 +660,7 @@ jobs: run: | set -e - cargo test --doc + cargo --locked test --doc fmt: # runtime is normally 15 seconds @@ -735,7 +670,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Install repo MSRV toolchain run: | @@ -745,9 +680,7 @@ jobs: - name: Run `cargo fmt` run: | - cargo fmt -- --check - cargo fmt --manifest-path xtask/Cargo.toml -- --check - cargo fmt --manifest-path naga/xtask/Cargo.toml -- --check + cargo --locked fmt -- --check - name: Install Taplo uses: uncenter/setup-taplo@v1 @@ -758,7 +691,7 @@ jobs: run: taplo format --check --diff - name: Check for typos - uses: crate-ci/typos@v1.30.2 + uses: crate-ci/typos@v1.38.1 check-cts-runner: # runtime is normally 2 minutes @@ -768,7 +701,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Install MSRV toolchain run: | @@ -793,7 +726,7 @@ jobs: - name: Build Deno run: | - cargo clippy --manifest-path cts_runner/Cargo.toml + cargo --locked clippy --manifest-path cts_runner/Cargo.toml # Separate job so that new advisories don't block CI. # @@ -806,13 +739,14 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Run `cargo deny check` uses: EmbarkStudios/cargo-deny-action@v2 with: command: check advisories arguments: --all-features --workspace + command-arguments: -Dwarnings -Aunmatched-organization rust-version: ${{ env.REPO_MSRV }} cargo-deny-check-rest: @@ -823,11 +757,12 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Run `cargo deny check` uses: EmbarkStudios/cargo-deny-action@v2 with: command: check bans licenses sources arguments: --all-features --workspace + command-arguments: -Dwarnings -Aunmatched-organization rust-version: ${{ env.REPO_MSRV }} diff --git a/.github/workflows/cts.yml b/.github/workflows/cts.yml new file mode 100644 index 000000000..36b1b4f98 --- /dev/null +++ b/.github/workflows/cts.yml @@ -0,0 +1,119 @@ +name: CTS + +on: + push: + branches-ignore: [ + # Renovate branches are always PRs, so they will be covered + # by the pull_request event. + "renovate/**", + # Branches with the `gh-readonly-queue` prefix are used by the + # merge queue, so they are already covered by the `merge_group` event. + "gh-readonly-queue/**", + ] + pull_request: + merge_group: + +env: + CARGO_INCREMENTAL: false + CARGO_TERM_COLOR: always + RUST_BACKTRACE: full + MSRV: "1.88" + +# Every time a PR is pushed to, cancel any previous jobs. This +# makes us behave nicer to github and get faster turnaround times +# on PRs that are pushed to multiple times in rapid succession. +concurrency: + group: ${{github.workflow}}-${{github.ref}} + cancel-in-progress: ${{github.event_name == 'pull_request'}} + +jobs: + cts: + strategy: + fail-fast: false + matrix: + include: + # Windows + - name: Windows x86_64 + os: windows-2022 + target: x86_64-pc-windows-msvc + backend: dx12 + + # Mac + - name: Mac aarch64 + os: macos-14 + target: x86_64-apple-darwin + backend: metal + + # Linux + - name: Linux x86_64 + os: ubuntu-24.04 + target: x86_64-unknown-linux-gnu + backend: vulkan + + name: CTS ${{ matrix.name }} + runs-on: ${{ matrix.os }} + + steps: + - name: checkout repo + uses: actions/checkout@v5 + + - name: Install Repo MSRV toolchain + run: | + rustup toolchain install ${{ env.MSRV }} --no-self-update --profile=minimal --target ${{ matrix.target }} --component llvm-tools + rustup override set ${{ env.MSRV }} + cargo -V + + - name: Install `cargo-llvm-cov` + uses: taiki-e/install-action@v2 + with: + tool: cargo-llvm-cov + + - name: caching + uses: Swatinem/rust-cache@v2 + with: + prefix-key: v2-rust # Increment version for cache busting + cache-directories: cts + + # We enable line numbers for panics, but that's it + - name: disable debug + shell: bash + run: | + mkdir -p .cargo + cat <> .cargo/config.toml + [profile.dev] + debug = "line-tables-only" + EOF + + - name: (Windows) Install DXC + if: matrix.os == 'windows-2022' + uses: ./.github/actions/install-dxc + + - name: (Windows) Install WARP + if: matrix.os == 'windows-2022' + uses: ./.github/actions/install-warp + with: + target-dirs: "target/llvm-cov-target/debug" + + - name: (Linux) Install Mesa + if: matrix.os == 'ubuntu-24.04' + uses: ./.github/actions/install-mesa + + - name: run CTS + shell: bash + run: cargo --locked xtask cts --llvm-cov --backend ${{ matrix.backend }} + + - name: Generate coverage report + id: coverage + shell: bash + continue-on-error: true + run: | + set -e + + cargo --locked llvm-cov report --lcov --output-path lcov.info + + - name: Upload coverage report to Codecov + uses: codecov/codecov-action@v5 + if: steps.coverage.outcome == 'success' + with: + files: lcov.info + token: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index d96ed0870..83adc7629 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -10,19 +10,26 @@ on: env: # This is the MSRV used by `wgpu` itself and all surrounding infrastructure. - REPO_MSRV: "1.84" + REPO_MSRV: "1.88" CARGO_INCREMENTAL: false CARGO_TERM_COLOR: always RUST_BACKTRACE: full +# Every time a PR is pushed to, cancel any previous jobs. This +# makes us behave nicer to github and get faster turnaround times +# on PRs that are pushed to multiple times in rapid succession. +concurrency: + group: ${{github.workflow}}-${{github.ref}} + cancel-in-progress: ${{github.event_name == 'pull_request'}} + jobs: build: runs-on: ubuntu-latest steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: persist-credentials: false diff --git a/.github/workflows/generate.yml b/.github/workflows/generate.yml index 0f758d4a8..cd2d4af90 100644 --- a/.github/workflows/generate.yml +++ b/.github/workflows/generate.yml @@ -2,8 +2,14 @@ name: cargo-generate on: push: - branches: ["*"] - tags: [v0.*] + branches-ignore: [ + # Renovate branches are always PRs, so they will be covered + # by the pull_request event. + "renovate/**", + # Branches with the `gh-readonly-queue` prefix are used by the + # merge queue, so they are already covered by the `merge_group` event. + "gh-readonly-queue/**", + ] pull_request: merge_group: @@ -13,9 +19,16 @@ env: # # This is the MSRV used by `wgpu` itself and all surrounding infrastructure. - REPO_MSRV: "1.84" + REPO_MSRV: "1.88" RUSTFLAGS: -D warnings +# Every time a PR is pushed to, cancel any previous jobs. This +# makes us behave nicer to github and get faster turnaround times +# on PRs that are pushed to multiple times in rapid succession. +concurrency: + group: ${{github.workflow}}-${{github.ref}} + cancel-in-progress: ${{github.event_name == 'pull_request'}} + jobs: cargo-generate: timeout-minutes: 5 @@ -36,7 +49,7 @@ jobs: name: "${{ matrix.name }}" steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 # We can't rely on an override here, as that would only set # the toolchain for the current directory, not the newly generated project. diff --git a/.github/workflows/lazy.yml b/.github/workflows/lazy.yml index d33f40423..d0e526799 100644 --- a/.github/workflows/lazy.yml +++ b/.github/workflows/lazy.yml @@ -3,7 +3,7 @@ name: Lazy on: pull_request: paths: - - '.github/workflows/lazy.yml' + - ".github/workflows/lazy.yml" push: branches: [trunk] @@ -12,12 +12,19 @@ env: CARGO_TERM_COLOR: always RUST_BACKTRACE: full +# Every time a PR is pushed to, cancel any previous jobs. This +# makes us behave nicer to github and get faster turnaround times +# on PRs that are pushed to multiple times in rapid succession. +concurrency: + group: ${{github.workflow}}-${{github.ref}} + cancel-in-progress: ${{github.event_name == 'pull_request'}} + jobs: parse-dota2: name: "Validate Shaders: Dota2" runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - run: mkdir naga/data @@ -43,7 +50,7 @@ jobs: name: "Validate Shaders: Sascha Willems Vulkan Tutorial" runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Download shaders run: cd naga && git clone https://github.com/SaschaWillems/Vulkan.git @@ -78,7 +85,7 @@ jobs: name: "Validate Shaders: dneto0 spirv-samples" runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Download shaders run: | @@ -98,58 +105,58 @@ jobs: - name: Compile `spv` from `spvasm` run: | - cd naga/spirv-samples - mkdir -p spv + cd naga/spirv-samples + mkdir -p spv - find "./spvasm" -name '*.spvasm' | while read fname; - do - echo "Convert to spv with spirv-as: $fname" - ../install/bin/spirv-as --target-env spv1.3 $(realpath ${fname}) -o ./spv/$(basename ${fname}).spv - done; + find "./spvasm" -name '*.spvasm' | while read fname; + do + echo "Convert to spv with spirv-as: $fname" + ../install/bin/spirv-as --target-env spv1.3 $(realpath ${fname}) -o ./spv/$(basename ${fname}).spv + done; - name: Validate `spv` and generate `wgsl` run: | - set +e - cd naga/spirv-samples - SUCCESS_RESULT_COUNT=0 - FILE_COUNT=0 - mkdir -p spv - mkdir -p wgsl + set +e + cd naga/spirv-samples + SUCCESS_RESULT_COUNT=0 + FILE_COUNT=0 + mkdir -p spv + mkdir -p wgsl - echo "==== Validate spv and generate wgsl ====" - rm -f counter - touch counter + echo "==== Validate spv and generate wgsl ====" + rm -f counter + touch counter - find "./spv" -name '*.spv' | while read fname; - do - echo "Convert: $fname" - FILE_COUNT=$((FILE_COUNT+1)) - ../../target/release/naga --validate 27 $(realpath ${fname}) ./wgsl/$(basename ${fname}).wgsl - if [[ $? -eq 0 ]]; then - SUCCESS_RESULT_COUNT=$((SUCCESS_RESULT_COUNT + 1)) - fi - echo "Result: $(expr $FILE_COUNT - $SUCCESS_RESULT_COUNT) / $FILE_COUNT" > counter - done - cat counter + find "./spv" -name '*.spv' | while read fname; + do + echo "Convert: $fname" + FILE_COUNT=$((FILE_COUNT+1)) + ../../target/release/naga --validate 27 $(realpath ${fname}) ./wgsl/$(basename ${fname}).wgsl + if [[ $? -eq 0 ]]; then + SUCCESS_RESULT_COUNT=$((SUCCESS_RESULT_COUNT + 1)) + fi + echo "Result: $(expr $FILE_COUNT - $SUCCESS_RESULT_COUNT) / $FILE_COUNT" > counter + done + cat counter - name: Validate output `wgsl` run: | - set +e - cd naga/spirv-samples - SUCCESS_RESULT_COUNT=0 - FILE_COUNT=0 + set +e + cd naga/spirv-samples + SUCCESS_RESULT_COUNT=0 + FILE_COUNT=0 - rm -f counter - touch counter + rm -f counter + touch counter - find "./wgsl" -name '*.wgsl' | while read fname; - do - echo "Validate: $fname" - FILE_COUNT=$((FILE_COUNT+1)) - ../../target/release/naga --validate 27 $(realpath ${fname}) - if [[ $? -eq 0 ]]; then - SUCCESS_RESULT_COUNT=$((SUCCESS_RESULT_COUNT + 1)) - fi - echo "Result: $(expr $FILE_COUNT - $SUCCESS_RESULT_COUNT) / $FILE_COUNT" > counter - done - cat counter + find "./wgsl" -name '*.wgsl' | while read fname; + do + echo "Validate: $fname" + FILE_COUNT=$((FILE_COUNT+1)) + ../../target/release/naga --validate 27 $(realpath ${fname}) + if [[ $? -eq 0 ]]; then + SUCCESS_RESULT_COUNT=$((SUCCESS_RESULT_COUNT + 1)) + fi + echo "Result: $(expr $FILE_COUNT - $SUCCESS_RESULT_COUNT) / $FILE_COUNT" > counter + done + cat counter diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 44326879b..1a4385da0 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -3,7 +3,7 @@ name: Publish on: pull_request: paths: - - '.github/workflows/publish.yml' + - ".github/workflows/publish.yml" push: branches: - trunk @@ -13,12 +13,19 @@ env: CARGO_TERM_COLOR: always RUST_BACKTRACE: full +# Every time a PR is pushed to, cancel any previous jobs. This +# makes us behave nicer to github and get faster turnaround times +# on PRs that are pushed to multiple times in rapid succession. +concurrency: + group: ${{github.workflow}}-${{github.ref}} + cancel-in-progress: ${{github.event_name == 'pull_request'}} + jobs: publish: runs-on: ubuntu-latest steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: persist-credentials: false diff --git a/.github/workflows/shaders.yml b/.github/workflows/shaders.yml index 16c13b25a..062d6ecb1 100644 --- a/.github/workflows/shaders.yml +++ b/.github/workflows/shaders.yml @@ -3,33 +3,29 @@ name: Shaders on: push: branches-ignore: [ - # We don't need to run on dependabot PRs. - "dependabot/**", - # This is the branch the merge queue creates. + # Renovate branches are always PRs, so they will be covered + # by the pull_request event. + "renovate/**", + # Branches with the `gh-readonly-queue` prefix are used by the + # merge queue, so they are already covered by the `merge_group` event. "gh-readonly-queue/**", ] - tags: [v0.*] pull_request: merge_group: -env: - # Sourced from https://vulkan.lunarg.com/sdk/home#linux - # - # We don't include the 4th version number, as it's not used in any URL. - VULKAN_SDK_VERSION: "1.4.304" - - # Sourced from https://github.com/microsoft/DirectXShaderCompiler/releases - # - # Must also be changed in ci.yaml - DXC_RELEASE: "v1.8.2407" - DXC_FILENAME: "dxc_2024_07_31_clang_cl.zip" +# Every time a PR is pushed to, cancel any previous jobs. This +# makes us behave nicer to github and get faster turnaround times +# on PRs that are pushed to multiple times in rapid succession. +concurrency: + group: ${{github.workflow}}-${{github.ref}} + cancel-in-progress: ${{github.event_name == 'pull_request'}} jobs: naga-validate-windows: name: "Validate: HLSL" runs-on: windows-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Debug symbols to `line-tables-only` shell: bash @@ -42,9 +38,6 @@ jobs: EOF - uses: Swatinem/rust-cache@v2 - with: - workspaces: | - naga/xtask -> naga/xtask/target # We must have the FXC job before the DXC job, so the DXC PATH has priority # over the FXC PATH. This is because the windows kits also include an older @@ -59,15 +52,7 @@ jobs: shell: powershell - name: Setup DXC - shell: bash - run: | - set -e - - curl.exe -L --retry 5 https://github.com/microsoft/DirectXShaderCompiler/releases/download/$DXC_RELEASE/$DXC_FILENAME -o dxc.zip - 7z.exe e dxc.zip -odxc bin/x64/{dxc.exe,dxcompiler.dll,dxil.dll} - - # We need to use cygpath to convert PWD to a windows path as we're using bash. - cygpath --windows "$PWD/dxc" >> "$GITHUB_PATH" + uses: ./.github/actions/install-dxc - name: Validate shell: bash @@ -82,9 +67,9 @@ jobs: naga-validate-macos: name: "Validate: MSL" - runs-on: macos-14 + runs-on: macos-15 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Debug symbols to line-tables-only shell: bash @@ -97,9 +82,6 @@ jobs: EOF - uses: Swatinem/rust-cache@v2 - with: - workspaces: | - naga/xtask -> naga/xtask/target - run: | cd naga @@ -109,21 +91,10 @@ jobs: name: "Validate: SPIR-V/GLSL/DOT/WGSL" runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Install Vulkan SDK - shell: bash - run: | - set -e - - sudo apt-get update -y -qq - - # vulkan sdk - wget -qO - https://packages.lunarg.com/lunarg-signing-key-pub.asc | sudo apt-key add - - sudo wget -qO /etc/apt/sources.list.d/lunarg-vulkan-$VULKAN_SDK_VERSION-noble.list https://packages.lunarg.com/vulkan/$VULKAN_SDK_VERSION/lunarg-vulkan-$VULKAN_SDK_VERSION-noble.list - - sudo apt-get update - sudo apt install -y vulkan-sdk + uses: ./.github/actions/install-vulkan-sdk - name: Install Graphviz run: sudo apt-get install graphviz @@ -139,9 +110,6 @@ jobs: EOF - uses: Swatinem/rust-cache@v2 - with: - workspaces: | - naga/xtask -> naga/xtask/target - run: cd naga; cargo xtask validate spv diff --git a/.gitignore b/.gitignore index 4383c6f58..a23fffc26 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,16 @@ +# Jujutsu +# +# When using the wgpu repository through [Jujutsu](https://github.com/martinvonz/jj), `.jj/` dirs. +# are ignored because Jujutsu writes a `.jj/.gitignore` file containing `/*`. Some tools, like +# `prettier`, don't handle nested `.gitgnore` properly, but they _do_ handle top-level `.gitignore` +# patterns properly. So, include it here, even though we shouldn't need it. :cry: +.jj/ + # Generated by Cargo # will have compiled files and executables target/ # Include the root lockfile but not the others */Cargo.lock -!xtask/Cargo.lock # These are backup files generated by rustfmt **/*.rs.bk @@ -27,7 +34,7 @@ wgpu/red.png **/*-difference.png # Readme says to check out CTS here -cts/ +/cts # Readme says to put angle in working directory *.dll @@ -36,4 +43,4 @@ cts/ .gpuconfig # Temporary clone location for wasm-bindgen mirroring -wgpu/src/backend/webgpu/webgpu_sys/wasm_bindgen_clone_tmp \ No newline at end of file +wgpu/src/backend/webgpu/webgpu_sys/wasm_bindgen_clone_tmp diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 000000000..0d9ae5763 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,4 @@ +**/*.frag +**/*.vert +naga/tests/in/ +naga/tests/out/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 54c4780f6..fe12edeb3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,7 +27,7 @@ Top level categories: Bottom level categories: -- Naga +- naga - General - DX12 - Vulkan @@ -40,8 +40,665 @@ Bottom level categories: ## Unreleased -- Added an example that shows how to handle datasets too large to fit in a single `GPUBuffer` by distributing it across many buffers, and then having the shader receive them as a `binding_array` of storage buffers. By @alphastrata in [#6138](https://github.com/gfx-rs/wgpu/pull/6138) +### Major Changes +#### `wgpu::Instance::enumerate_adapters` is now `async` & available on WebGPU + +BREAKING CHANGE: `enumerate_adapters` is now `async`: + +```diff +- pub fn enumerate_adapters(&self, backends: Backends) -> Vec { ++ pub fn enumerate_adapters(&self, backends: Backends) -> impl Future> { +``` + +This yields ([kek]) two benefits: + +- This method is now implemented on non-native using the standard `Adapter::request_adapter(…)`, making `enumerate_adapters` a portable surface. This was previously a nontrivial pain point when an application wanted to do some of its own filtering of adapters. +- This method can now be implemented in custom backends. + +By @R-Cramer4 in [#8230](https://github.com/gfx-rs/wgpu/pull/8230) + +[kek]: https://web.archive.org/web/20250923122958/https://knowyourmeme.com/memes/kek + +#### `MipmapFilterMode` is split from `FilterMode` + +This is a breaking change that aligns wgpu with spec. + +```diff +SamplerDescriptor { +... +- mipmap_filter: FilterMode::Nearest ++ mipmap_filter: MipmapFilterMode::Nearest +... +} +``` + +#### Multiview on all major platforms and support for multiview bitmasks + +Multiview is a feature that allows rendering the same content to multiple layers of a texture. This is useful primarily in VR where you wish to +display almost identical content to 2 views, just with a different perspective. Instead of using 2 draw calls or 2 instances for each object, you +can use this feature. + +Multiview is also called view instancing in DX12 land or vertex amplification in Metal land. + +Multiview has been reworked, adding support for Metal, and adding testing and validation to wgpu itself. +This change also introduces a view bitmask, a new field in `RenderPassDescriptor` that allows a render pass to render to multiple non-adjacent layers +when using the `SELECTIVE_MULTIVIEW` feature. Note that this also influences apps that don't use multiview, as they have to set this mask to `None`. +```diff +- wgpu::RenderPassDescriptor { +- label: None, +- color_attachments: &color_attachments, +- depth_stencil_attachment: None, +- timestamp_writes: None, +- occlusion_query_set: None, +- } ++ wgpu::RenderPassDescriptor { ++ label: None, ++ color_attachments: &color_attachments, ++ depth_stencil_attachment: None, ++ timestamp_writes: None, ++ occlusion_query_set: None, ++ multiview_mask: NonZero::new(3), ++ } +``` +One other breaking change worth noting is that in WGSL `@builtin(view_index)` now requires a type of `u32`, where previously it required `i32`. + +By @SupaMaggie70Incorporated in [#8206](https://github.com/gfx-rs/wgpu/pull/8206). + +### New Features + +- Added support for transient textures on Vulkan and Metal. By @opstic in [#8247](https://github.com/gfx-rs/wgpu/pull/8247) +- Implement shader triangle barycentric coordinate builtins. By @atlv24 in [#8320](https://github.com/gfx-rs/wgpu/pull/8320). + +### Changes + +#### General + +- Lower `max_blas_primitive_count` due to a bug in llvmpipe. By @Vecvec in [#8446](https://github.com/gfx-rs/wgpu/pull/8446). +- Texture now has `from_custom`. By @R-Cramer4 in [#8315](https://github.com/gfx-rs/wgpu/pull/8315). +- Using both the wgpu command encoding APIs and `CommandEncoder::as_hal_mut` on the same encoder will now result in a panic. +- Allow `include_spirv!` and `include_spirv_raw!` macros to be used in constants and statics. By @clarfonthey in [#8250](https://github.com/gfx-rs/wgpu/pull/8250). +- Added support for rendering onto multi-planar textures. By @noituri in [#8307](https://github.com/gfx-rs/wgpu/pull/8307). +- Validation errors from `CommandEncoder::finish()` will report the label of the invalid encoder. By @kpreid in [#8449](https://github.com/gfx-rs/wgpu/pull/8449). +- Corrected documentation of the minimum alignment of the *end* of a mapped range of a buffer (it is 4, not 8). By @kpreid in [#8450](https://github.com/gfx-rs/wgpu/pull/8450). +- `util::StagingBelt` now takes a `Device` when it is created instead of when it is used. By @kpreid in [#8462](https://github.com/gfx-rs/wgpu/pull/8462). + +### Bug Fixes + +#### naga + +- Fix a bug that resulted in the Metal error `program scope variable must reside in constant address space` in some cases. By @teoxoy in [#8311](https://github.com/gfx-rs/wgpu/pull/8311). + +#### General + +- Fixed a bug where mapping sub-ranges of a buffer on web would fail with `OperationError: GPUBuffer.getMappedRange: GetMappedRange range extends beyond buffer's mapped range`. By @ryankaplan in [#8349](https://github.com/gfx-rs/wgpu/pull/8349) +- Reject fragment shader output `location`s > `max_color_attachments` limit. By @ErichDonGubler in [#8316](https://github.com/gfx-rs/wgpu/pull/8316). +- WebGPU device requests now support the required limits `maxColorAttachments` and `maxColorAttachmentBytesPerSample`. By @evilpie in [#8328](https://github.com/gfx-rs/wgpu/pull/8328) +- Reject binding indices that exceed `wgpu_types::Limits::max_bindings_per_bind_group` when deriving a bind group layout for a pipeline. By @jimblandy in [#8325](https://github.com/gfx-rs/wgpu/pull/8325). +- Removed three features from `wgpu-hal` which did nothing useful: `"cargo-clippy"`, `"gpu-allocator"`, and `"rustc-hash"`. By @kpreid in [#8357](https://github.com/gfx-rs/wgpu/pull/8357). +- `wgpu_types::PollError` now always implements the `Error` trait. By @kpreid in [#8384](https://github.com/gfx-rs/wgpu/pull/8384). +- The texture subresources used by the color attachments of a render pass are no longer allowed to overlap when accessed via different texture views. By @andyleiserson in [#8402](https://github.com/gfx-rs/wgpu/pull/8402). +- Fixed a bug where the texture aspect was not passed through when calling `copy_texture_to_buffer` in WebGPU, causing the copy to fail for depth/stencil textures. By @Tim-Evans-Seequent in [#8445](https://github.com/gfx-rs/wgpu/pull/8445). + +#### DX12 + +- Align copies b/w textures and buffers via a single intermediate buffer per copy when `D3D12_FEATURE_DATA_D3D12_OPTIONS13.UnrestrictedBufferTextureCopyPitchSupported` is `false`. By @ErichDonGubler in [#7721](https://github.com/gfx-rs/wgpu/pull/7721). + +#### Vulkan + +- Fixed a validation error regarding atomic memory semantics. By @atlv24 in [#8391](https://github.com/gfx-rs/wgpu/pull/8391). + +#### hal + +- `DropCallback`s are now called after dropping all other fields of their parent structs. By @jerzywilczek in [#8353](https://github.com/gfx-rs/wgpu/pull/8353) + +## v27.0.4 (2025-10-23) + +This release includes `wgpu-hal` version `27.0.4`. All other crates remain at their previous versions. + +### Bug Fixes + +#### General + +- Remove fragile dependency constraint on `ordered-float` that prevented semver-compatible changes above `5.0.0`. By @kpreid in [#8371](https://github.com/gfx-rs/wgpu/pull/8371). + +#### Vulkan + +- Work around extremely poor frame pacing from AMD and Nvidia cards on Windows in `Fifo` and `FifoRelaxed` present modes. This is due to the drivers implicitly using a DXGI (Direct3D) swapchain to implement these modes and it having vastly different timing properties. See https://github.com/gfx-rs/wgpu/issues/8310 and https://github.com/gfx-rs/wgpu/issues/8354 for more information. By @cwfitzgerald in [#8420](https://github.com/gfx-rs/wgpu/pull/8420). + +## v27.0.3 (2025-10-22) + +This release includes `naga`, `wgpu-core` and `wgpu-hal` version `27.0.3`. All other crates remain at their previous versions. + +### Bug Fixes + +#### naga + +- Fix a bug that resulted in the Metal error `program scope variable must reside in constant address space` in some cases. Backport of [#8311](https://github.com/gfx-rs/wgpu/pull/8311) by @teoxoy. + +#### General + +- Remove an assertion that causes problems if `CommandEncoder::as_hal_mut` is used. By @andyleiserson in [#8387](https://github.com/gfx-rs/wgpu/pull/8387). + +#### DX12 + +- Align copies b/w textures and buffers via a single intermediate buffer per copy when `D3D12_FEATURE_DATA_D3D12_OPTIONS13.UnrestrictedBufferTextureCopyPitchSupported` is `false`. By @ErichDonGubler in [#7721](https://github.com/gfx-rs/wgpu/pull/7721), backported in [#8374](https://github.com/gfx-rs/wgpu/pull/8374). + +## v27.0.2 (2025-10-03) + +### Bug Fixes + +#### DX12 + +- Fix device creation failures for devices that do not support mesh shaders. By @vorporeal in [#8297](https://github.com/gfx-rs/wgpu/pull/8297). + +## v27.0.1 (2025-10-02) + +### Bug Fixes + +- Fixed the build on docs.rs. By @cwfitzgerald in [#8292](https://github.com/gfx-rs/wgpu/pull/8292). + +## v27.0.0 (2025-10-01) + +### Major Changes + +#### Deferred command buffer actions: `map_buffer_on_submit` and `on_submitted_work_done` + +You may schedule buffer mapping and a submission-complete callback to run automatically after you submit, directly from encoders, command buffers, and passes. + +```rust +// Record some GPU work so the submission isn't empty and touches `buffer`. +encoder.clear_buffer(&buffer, 0, None); + +// Defer mapping until this encoder is submitted. +encoder.map_buffer_on_submit(&buffer, wgpu::MapMode::Read, 0..size, |result| { .. }); + +// Fires after the command buffer's work is finished. +encoder.on_submitted_work_done(|| { .. }); + +// Automatically calls `map_async` and `on_submitted_work_done` after this submission finishes. +queue.submit([encoder.finish()]); +``` + +Available on `CommandEncoder`, `CommandBuffer`, `RenderPass`, and `ComputePass`. + +By @cwfitzgerald in [#8125](https://github.com/gfx-rs/wgpu/pull/8125). + +#### Builtin Support for DXGI swapchains on top of of DirectComposition Visuals in DX12 + +By enabling DirectComposition support, the dx12 backend can now support transparent windows. + +This creates a single `IDCompositionVisual` over the entire window that is used by the mf`Surface`. If a user wants to manage the composition tree themselves, they should create their own device and composition, and pass the relevant visual down into `wgpu` via `SurfaceTargetUnsafe::CompositionVisual`. + +```rust +let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor { + backend_options: wgpu::BackendOptions { + dx12: wgpu::Dx12BackendOptions { + presentation_system: wgpu::Dx12SwapchainKind::DxgiFromVisual, + .. + }, + .. + }, + .. +}); +``` + +By @n1ght-hunter in [#7550](https://github.com/gfx-rs/wgpu/pull/7550). + +#### `EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE` has been merged into `EXPERIMENTAL_RAY_QUERY` + +We have merged the acceleration structure feature into the `RayQuery` feature. This is to help work around an AMD driver bug and reduce the feature complexity of ray tracing. In the future when ray tracing pipelines are implemented, if either feature is enabled, acceleration structures will be available. + +```diff +- Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE ++ Features::EXPERIMENTAL_RAY_QUERY +``` + +By @Vecvec in [#7913](https://github.com/gfx-rs/wgpu/pull/7913). + +#### New `EXPERIMENTAL_PRECOMPILED_SHADERS` API + +We have added `Features::EXPERIMENTAL_PRECOMPILED_SHADERS`, replacing existing passthrough types with a unified `CreateShaderModuleDescriptorPassthrough` which allows passing multiple shader codes for different backends. By @SupaMaggie70Incorporated in [#7834](https://github.com/gfx-rs/wgpu/pull/7834) + +Difference for SPIR-V passthrough: + +```diff +- device.create_shader_module_passthrough(wgpu::ShaderModuleDescriptorPassthrough::SpirV( +- wgpu::ShaderModuleDescriptorSpirV { +- label: None, +- source: spirv_code, +- }, +- )) ++ device.create_shader_module_passthrough(wgpu::ShaderModuleDescriptorPassthrough { ++ entry_point: "main".into(), ++ label: None, ++ spirv: Some(spirv_code), ++ ..Default::default() +}) +``` + +This allows using precompiled shaders without manually checking which backend's code to pass, for example if you have shaders precompiled for both DXIL and SPIR-V. + +#### Buffer mapping apis no longer have lifetimes + +`Buffer::get_mapped_range()`, `Buffer::get_mapped_range_mut()`, and `Queue::write_buffer_with()` now return guard objects without any lifetimes. This +makes it significantly easier to store these types in structs, which is useful for building utilities that build the contents of a buffer over time. + +```diff +- let buffer_mapping_ref: wgpu::BufferView<'_> = buffer.get_mapped_range(..); +- let buffer_mapping_mut: wgpu::BufferViewMut<'_> = buffer.get_mapped_range_mut(..); +- let queue_write_with: wgpu::QueueWriteBufferView<'_> = queue.write_buffer_with(..); ++ let buffer_mapping_ref: wgpu::BufferView = buffer.get_mapped_range(..); ++ let buffer_mapping_mut: wgpu::BufferViewMut = buffer.get_mapped_range_mut(..); ++ let queue_write_with: wgpu::QueueWriteBufferView = queue.write_buffer_with(..); +``` + +By @sagudev in [#8046](https://github.com/gfx-rs/wgpu/pull/8046) and @cwfitzgerald in [#8070](https://github.com/gfx-rs/wgpu/pull/8161). + +#### `EXPERIMENTAL_*` features now require unsafe code to enable + +We want to be able to expose potentially experimental features to our users before we have ensured that they are fully sound to use. +As such, we now require any feature that is prefixed with `EXPERIMENTAL` to have a special unsafe token enabled in the device descriptor +acknowledging that the features may still have bugs in them and to report any they find. + +```rust +adapter.request_device(&wgpu::DeviceDescriptor { + features: wgpu::Features::EXPERIMENTAL_MESH_SHADER, + experimental_features: unsafe { wgpu::ExperimentalFeatures::enabled() } + .. +}) +``` + +By @cwfitzgerald in [#8163](https://github.com/gfx-rs/wgpu/pull/8163). + +#### Multi-draw indirect is now unconditionally supported when indirect draws are supported + +We have removed `Features::MULTI_DRAW_INDIRECT` as it was unconditionally available on all platforms. +`RenderPass::multi_draw_indirect` is now available if the device supports downlevel flag `DownlevelFlags::INDIRECT_EXECUTION`. + +If you are using spirv-passthrough with multi-draw indirect and `gl_DrawID`, you can know if `MULTI_DRAW_INDIRECT` is being emulated +by if the `Feature::MULTI_DRAW_INDIRECT_COUNT` feature is available on the device, this feature cannot be emulated efficicently. + +By @cwfitzgerald in [#8162](https://github.com/gfx-rs/wgpu/pull/8162). + +#### `wgpu::PollType::Wait` has now an optional timeout + +We removed `wgpu::PollType::WaitForSubmissionIndex` and added fields to `wgpu::PollType::Wait` in order to express timeouts. + +Before/after for `wgpu::PollType::Wait`: + +```diff +-device.poll(wgpu::PollType::Wait).unwrap(); +-device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); ++device.poll(wgpu::PollType::Wait { ++ submission_index: None, // Wait for most recent submission ++ timeout: Some(std::time::Duration::from_secs(60)), // Previous behavior, but more likely you want `None` instead. ++ }) ++ .unwrap(); +``` + +Before/after for `wgpu::PollType::WaitForSubmissionIndex`: + +```diff +-device.poll(wgpu::PollType::WaitForSubmissionIndex(index_to_wait_on)) ++device.poll(wgpu::PollType::Wait { ++ submission_index: Some(index_to_wait_on), ++ timeout: Some(std::time::Duration::from_secs(60)), // Previous behavior, but more likely you want `None` instead. ++ }) ++ .unwrap(); +``` + +⚠️ Previously, both `wgpu::PollType::WaitForSubmissionIndex` and `wgpu::PollType::Wait` had a hard-coded timeout of 60 seconds. + +To wait indefinitely on the latest submission, you can also use the `wait_indefinitely` convenience function: + +```rust +device.poll(wgpu::PollType::wait_indefinitely()); +``` + +By @wumpf in [#8282](https://github.com/gfx-rs/wgpu/pull/8282), [#8285](https://github.com/gfx-rs/wgpu/pull/8285) + +### New Features + +#### General + +- Added mesh shader support to `wgpu`, with examples. Requires passthrough. By @SupaMaggie70Incorporated in [#7345](https://github.com/gfx-rs/wgpu/pull/7345). +- Added support for external textures based on WebGPU's [`GPUExternalTexture`](https://www.w3.org/TR/webgpu/#gpuexternaltexture). These allow shaders to transparently operate on potentially multiplanar source texture data in either RGB or YCbCr formats via WGSL's `texture_external` type. This is gated behind the `Features::EXTERNAL_TEXTURE` feature, which is currently only supported on DX12. By @jamienicol in [#4386](https://github.com/gfx-rs/wgpu/issues/4386). +- `wgpu::Device::poll` can now specify a timeout via `wgpu::PollType::Wait`. By @wumpf in [#8282](https://github.com/gfx-rs/wgpu/pull/8282) & [#8285](https://github.com/gfx-rs/wgpu/pull/8285) + +#### naga + +- Expose `naga::front::wgsl::UnimplementedEnableExtension`. By @ErichDonGubler in [#8237](https://github.com/gfx-rs/wgpu/pull/8237). + +### Changes + +#### General + +- Command encoding now happens when `CommandEncoder::finish` is called, not when the individual operations are requested. This does not affect the API, but may affect performance characteristics. By @andyleiserson in [#8220](https://github.com/gfx-rs/wgpu/pull/8220). +- Prevent resources for acceleration structures being created if acceleration structures are not enabled. By @Vecvec in [#8036](https://github.com/gfx-rs/wgpu/pull/8036). +- Validate that each `push_debug_group` pairs with exactly one `pop_debug_group`. By @andyleiserson in [#8048](https://github.com/gfx-rs/wgpu/pull/8048). +- `set_viewport` now requires that the supplied minimum depth value is less than the maximum depth value. By @andyleiserson in [#8040](https://github.com/gfx-rs/wgpu/pull/8040). +- Validation of `copy_texture_to_buffer`, `copy_buffer_to_texture`, and `copy_texture_to_texture` operations more closely follows the WebGPU specification. By @andyleiserson in various PRs. + - Copies within the same texture must not overlap. + - Copies of multisampled or depth/stencil formats must span an entire subresource (layer). + - Copies of depth/stencil formats must be 4B aligned. + - For texture-buffer copies, `bytes_per_row` on the buffer side must be 256B-aligned, even if the transfer is a single row. +- The offset for `set_vertex_buffer` and `set_index_buffer` must be 4B aligned. By @andyleiserson in [#7929](https://github.com/gfx-rs/wgpu/pull/7929). +- The offset and size of bindings are validated as fitting within the underlying buffer in more cases. By @andyleiserson in [#7911](https://github.com/gfx-rs/wgpu/pull/7911). +- The function you pass to `Device::on_uncaptured_error()` must now implement `Sync` in addition to `Send`, and be wrapped in `Arc` instead of `Box`. + In exchange for this, it is no longer possible for calling `wgpu` functions while in that callback to cause a deadlock (not that we encourage you to actually do that). + By @kpreid in [#8011](https://github.com/gfx-rs/wgpu/pull/8011). +- Make a compacted hal acceleration structure inherit a label from the base BLAS. By @Vecvec in [#8103](https://github.com/gfx-rs/wgpu/pull/8103). +- The limits requested for a device must now satisfy `min_subgroup_size <= max_subgroup_size`. By @andyleiserson in [#8085](https://github.com/gfx-rs/wgpu/pull/8085). +- Improve errors when buffer mapping is done incorrectly. Allow aliasing immutable [`BufferViews`]. By @cwfitzgerald in [#8150](https://github.com/gfx-rs/wgpu/pull/8150). +- Require new `F16_IN_F32` downlevel flag for `quantizeToF16`, `pack2x16float`, and `unpack2x16float` in WGSL input. By @aleiserson in [#8130](https://github.com/gfx-rs/wgpu/pull/8130). +- The error message for non-copyable depth/stencil formats no longer mentions the aspect when it is not relevant. By @reima in [#8156](https://github.com/gfx-rs/wgpu/pull/8156). +- Track the initialization status of buffer memory correctly when `copy_texture_to_buffer` skips over padding space between rows or layers, or when the start/end of a texture-buffer transfer is not 4B aligned. By @andyleiserson in [#8099](https://github.com/gfx-rs/wgpu/pull/8099). + +#### naga + +- naga now requires that no type be larger than 1 GB. This limit may be lowered in the future; feedback on an appropriate value for the limit is welcome. By @andyleiserson in [#7950](https://github.com/gfx-rs/wgpu/pull/7950). +- If the shader source contains control characters, naga now replaces them with U+FFFD ("replacement character") in diagnostic output. By @andyleiserson in [#8049](https://github.com/gfx-rs/wgpu/pull/8049). +- Add f16 IO polyfill on Vulkan backend to enable SHADER_F16 use without requiring `storageInputOutput16`. By @cryvosh in [#7884](https://github.com/gfx-rs/wgpu/pull/7884). +- For custom Naga backend authors: `naga::proc::Namer` now accepts reserved keywords using two new dedicated types, `proc::{KeywordSet, CaseInsensitiveKeywordSet}`. By @kpreid in [#8136](https://github.com/gfx-rs/wgpu/pull/8136). +- **BREAKING**: Previously the WGSL storage-texture format `rg11b10float` was incorrectly accepted and generated by naga, but now only accepts the the correct name `rg11b10ufloat` instead. By @ErikWDev in [#8219](https://github.com/gfx-rs/wgpu/pull/8219). +- The [`source()`](https://doc.rust-lang.org/std/error/trait.Error.html#method.source) method of `ShaderError` no longer reports the error as its own source. By @andyleiserson in [#8258](https://github.com/gfx-rs/wgpu/pull/8258). +- naga correctly ingests SPIR-V that use descriptor runtime indexing, which in turn is correctly converted into WGSLs binding array. By @hasenbanck in [8256](https://github.com/gfx-rs/wgpu/pull/8256). +- naga correctly ingests SPIR-V that loads from multi-sampled textures, which in turn is correctly converted into WGSLs texture_multisampled_2d and load operations. By @hasenbanck in [8270](https://github.com/gfx-rs/wgpu/pull/8270). +- naga implement OpImageGather and OpImageDrefGather operations when ingesting SPIR-V. By @hasenbanck in [8280](https://github.com/gfx-rs/wgpu/pull/8280). + +#### DX12 + +- Allow disabling waiting for latency waitable object. By @marcpabst in [#7400](https://github.com/gfx-rs/wgpu/pull/7400) +- Add mesh shader support, including to the example. By @SupaMaggie70Incorporated in [#8110](https://github.com/gfx-rs/wgpu/issues/8110) + +### Bug Fixes + +#### General + +- Validate that effective buffer binding size is aligned to 4 when creating bind groups with buffer entries.. By @ErichDonGubler in [8041](https://github.com/gfx-rs/wgpu/pull/8041). + +#### DX12 + +- Create an event per wait to prevent 60 second hangs in certain multithreaded scenarios. By @Vecvec in [#8273](https://github.com/gfx-rs/wgpu/pull/8273). +- Fixed a bug where access to matrices with 2 rows would not work in some cases. By @andyleiserson in [#7438](https://github.com/gfx-rs/wgpu/pull/7438). + +##### EGL + +- Fixed unwrap failed in context creation for some Android devices. By @uael in [#8024](https://github.com/gfx-rs/wgpu/pull/8024). + +##### Vulkan + +- Fixed wrong color format+space being reported versus what is hardcoded in `create_swapchain()`. By @MarijnS95 in [#8226](https://github.com/gfx-rs/wgpu/pull/8226). + +#### naga + +- [wgsl-in] Allow a trailing comma in `@blend_src(…)` attributes. By @ErichDonGubler in [#8137](https://github.com/gfx-rs/wgpu/pull/8137). +- [wgsl-in] Allow a trailing comma in the list of `case` values inside a `switch`. By @reima in [#8165](https://github.com/gfx-rs/wgpu/pull/8165). +- Escape, rather than strip, identifiers with Unicode. By @ErichDonGubler in [7995](https://github.com/gfx-rs/wgpu/pull/7995). + +### Documentation + +#### General + +- Clarify that subgroup barriers require both the `SUBGROUP` and `SUBGROUP_BARRIER` features / capabilities. By @andyleiserson in [#8203](https://github.com/gfx-rs/wgpu/pull/8203). + +# v26.0.6 (2025-10-23) + +This release includes `wgpu-hal` version `26.0.6`. All other crates remain at their previous versions. + +### Bug Fixes + +#### Vulkan + +- Work around extremely poor frame pacing from AMD and Nvidia cards on Windows in `Fifo` and `FifoRelaxed` present modes. This is due to the drivers implicitly using a DXGI (Direct3D) swapchain to implement these modes and it having vastly different timing properties. See https://github.com/gfx-rs/wgpu/issues/8310 and https://github.com/gfx-rs/wgpu/issues/8354 for more information. By @cwfitzgerald in [#8420](https://github.com/gfx-rs/wgpu/pull/8420). + +## v26.0.5 (2025-10-21) + +This release includes `wgpu-hal` version `26.0.5`. All other crates remain at their previous versions. + +### Bug Fixes + +#### DX12 + +- Align copies b/w textures and buffers via a single intermediate buffer per copy when `D3D12_FEATURE_DATA_D3D12_OPTIONS13.UnrestrictedBufferTextureCopyPitchSupported` is `false`. By @ErichDonGubler in [#7721](https://github.com/gfx-rs/wgpu/pull/7721), backported in [#8375](https://github.com/gfx-rs/wgpu/pull/8375). + +## v26.0.4 (2025-08-07) + +### Bug Fixes + +#### Vulkan + +- Fix `STATUS_HEAP_CORRUPTION` crash when concurrently calling `create_sampler`. By @atlv24 in [#8043](https://github.com/gfx-rs/wgpu/pull/8043), [#8056](https://github.com/gfx-rs/wgpu/pull/8056). + +## v26.0.3 (2025-07-30) + +### Bug Fixes + +- Fixed memory leak in vulkan backend. By @cwfitzgerald in [#8031](https://github.com/gfx-rs/wgpu/pull/8031). + +### Bug Fixes + +#### naga + +- Fix empty `if` statements causing errors on spirv 1.6+. By @Vecvec in [#7883](https://github.com/gfx-rs/wgpu/pull/7883). + +## v26.0.2 (2025-07-23) + +### Bug Fixes + +- Fixed vulkan validation error regarding the swapchain in latest SDK. By @cwfitzgerald in [#7971](https://github.com/gfx-rs/wgpu/pull/7971). +- Fixed flickering on AMD devices and crashes inside Renderdoc due to incorrect caching of `VkFramebuffer`s when the driver re-used image view handles. By @cwfitzgerald in [#7972](https://github.com/gfx-rs/wgpu/pull/7972). + +> [!WARNING] +> There is formally a breaking change in `wgpu_hal::vulkan::Device::texture_from_raw` as there is now a `&self` receiver where +> there previously wasn't one. This will not affect you unless you explicitly use this api. We have gone ahead with the release +> as the bug was pervasive and made wgpu unusable for the affected people on v26. + +## v26.0.1 (2025-07-10) + +### Bug Fixes + +- Fixed build error inside `wgpu::util::initialize_adapter_from_env` when `std` feature is not enabled. By @kpreid in [#7918](https://github.com/gfx-rs/wgpu/pull/7918). +- Fixed build error occurring when the `profiling` dependency is configured to have profiling active. By @kpreid in [#7916](https://github.com/gfx-rs/wgpu/pull/7916). +- Emit a validation error instead of panicking when a query set index is OOB. By @ErichDonGubler in [#7908](https://github.com/gfx-rs/wgpu/pull/7908). + +## v26.0.0 (2025-07-09) + +### Major Features + +#### New method `TextureView::texture` + +You can now call `texture_view.texture()` to get access to the texture that +a given texture view points to. + +By @cwfitzgerald and @Wumpf in [#7907](https://github.com/gfx-rs/wgpu/pull/7907). + +#### `as_hal` calls now return guards instead of using callbacks. + +Previously, if you wanted to get access to the wgpu-hal or underlying api types, you would call `as_hal` and get the hal type as a callback. Now the function returns a guard which dereferences to the hal type. + +```diff +- device.as_hal::(|hal_device| {...}); ++ let hal_device: impl Deref = device.as_hal::(); +``` + +By @cwfitzgerald in [#7863](https://github.com/gfx-rs/wgpu/pull/7863). + +#### Enabling Vulkan Features/Extensions + +For those who are doing vulkan/wgpu interop or passthrough and need to enable features/extensions that wgpu does not expose, there is a new `wgpu_hal::vulkan::Adapter::open_with_callback` that allows the user to modify the pnext chains and extension lists populated by wgpu before we create a vulkan device. This should vastly simplify the experience, as previously you needed to create a device yourself. + +Underlying api interop is a quickly evolving space, so we welcome all feedback! + +```rust +type VkApi = wgpu::hal::api::Vulkan; +let adapter: wgpu::Adapter = ...; + +let mut buffer_device_address_create_info = ash::vk::PhysicalDeviceBufferDeviceAddressFeatures { .. }; +let hal_device: wgpu::hal::OpenDevice = adapter + .as_hal::() + .unwrap() + .open_with_callback( + wgpu::Features::empty(), + &wgpu::MemoryHints::Performance, + Some(Box::new(|args| { + // Add the buffer device address extension. + args.extensions.push(ash::khr::buffer_device_address::NAME); + // Extend the create info with the buffer device address create info. + *args.create_info = args + .create_info + .push_next(&mut buffer_device_address_create_info); + // We also have access to the queue create infos if we need them. + let _ = args.queue_create_infos; + })), + ) + .unwrap(); + +let (device, queue) = adapter + .create_device_from_hal(hal_device, &wgpu::DeviceDescriptor { .. }) + .unwrap(); +``` + +By @Vecvec in [#7829](https://github.com/gfx-rs/wgpu/pull/7829). + +### naga + +- Added `no_std` support with default features disabled. By @Bushrat011899 in [#7585](https://github.com/gfx-rs/wgpu/pull/7585). +- [wgsl-in,ir] Add support for parsing rust-style doc comments via `naga::front::glsl::Frontend::new_with_options`. By @Vrixyz in [#6364](https://github.com/gfx-rs/wgpu/pull/6364). +- When emitting GLSL, Uniform and Storage Buffer memory layouts are now emitted even if no explicit binding is given. By @cloone8 in [#7579](https://github.com/gfx-rs/wgpu/pull/7579). +- Diagnostic rendering methods (i.e., `naga::{front::wgsl::ParseError,WithSpan}::emit_error_to_string_with_path`) now accept more types for their `path` argument via a new sealed `AsDiagnosticFilePath` trait. By @atlv24, @bushrat011899, and @ErichDonGubler in [#7643](https://github.com/gfx-rs/wgpu/pull/7643). +- Add support for [quad operations](https://www.w3.org/TR/WGSL/#quad-builtin-functions) (requires `SUBGROUP` feature to be enabled). By @dzamkov and @valaphee in [#7683](https://github.com/gfx-rs/wgpu/pull/7683). +- Add support for `atomicCompareExchangeWeak` in HLSL and GLSL backends. By @cryvosh in [#7658](https://github.com/gfx-rs/wgpu/pull/7658) + +### General + +- Add support for astc-sliced-3d feature. By @mehmetoguzderin in [#7577](https://github.com/gfx-rs/wgpu/issues/7577) +- Added `wgpu_hal::dx12::Adapter::as_raw()`. By @tronical in [##7852](https://github.com/gfx-rs/wgpu/pull/7852) +- Add support for rendering to slices of 3D texture views and single layered 2D-Array texture views (this requires `VK_KHR_maintenance1` which should be widely available on newer drivers). By @teoxoy in [#7596](https://github.com/gfx-rs/wgpu/pull/7596) +- Add extra acceleration structure vertex formats. By @Vecvec in [#7580](https://github.com/gfx-rs/wgpu/pull/7580). +- Add acceleration structure limits. By @Vecvec in [#7845](https://github.com/gfx-rs/wgpu/pull/7845). +- Add support for clip-distances feature for Vulkan and GL backends. By @dzamkov in [#7730](https://github.com/gfx-rs/wgpu/pull/7730) +- Added `wgpu_types::error::{ErrorType, WebGpuError}` for classification of errors according to WebGPU's [`GPUError`]'s classification scheme, and implement `WebGpuError` for existing errors. This allows users of `wgpu-core` to offload error classification onto the wgpu ecosystem, rather than having to do it themselves without sufficient information. By @ErichDonGubler in [#6547](https://github.com/gfx-rs/wgpu/pull/6547). + +[`GPUError`]: https://www.w3.org/TR/webgpu/#gpuerror + +### Bug Fixes + +#### General + +- Fix error message for sampler array limit. By @LPGhatguy in [#7704](https://github.com/gfx-rs/wgpu/pull/7704). +- Fix bug where using `BufferSlice::get_mapped_range_as_array_buffer()` on a buffer would prevent you from ever unmapping it. Note that this API has changed and is now `BufferView::as_uint8array()`. + +#### naga + +- naga now infers the correct binding layout when a resource appears only in an assignment to `_`. By @andyleiserson in [#7540](https://github.com/gfx-rs/wgpu/pull/7540). +- Implement `dot4U8Packed` and `dot4I8Packed` for all backends, using specialized intrinsics on SPIR-V, HLSL, and Metal if available, and polyfills everywhere else. By @robamler in [#7494](https://github.com/gfx-rs/wgpu/pull/7494), [#7574](https://github.com/gfx-rs/wgpu/pull/7574), and [#7653](https://github.com/gfx-rs/wgpu/pull/7653). +- Add polyfilled `pack4x{I,U}8Clamped` built-ins to all backends and WGSL frontend. By @ErichDonGubler in [#7546](https://github.com/gfx-rs/wgpu/pull/7546). +- Allow textureLoad's sample index arg to be unsigned. By @jimblandy in [#7625](https://github.com/gfx-rs/wgpu/pull/7625). +- Properly convert arguments to atomic operations. By @jimblandy in [#7573](https://github.com/gfx-rs/wgpu/pull/7573). +- Apply necessary automatic conversions to the `value` argument of `textureStore`. By @jimblandy in [#7567](https://github.com/gfx-rs/wgpu/pull/7567). +- Properly apply WGSL's automatic conversions to the arguments to texture sampling functions. By @jimblandy in [#7548](https://github.com/gfx-rs/wgpu/pull/7548). +- Properly evaluate `abs(most negative abstract int)`. By @jimblandy in [#7507](https://github.com/gfx-rs/wgpu/pull/7507). +- Generate vectorized code for `[un]pack4x{I,U}8[Clamp]` on SPIR-V and MSL 2.1+. By @robamler in [#7664](https://github.com/gfx-rs/wgpu/pull/7664). +- Fix typing for `select`, which had issues particularly with a lack of automatic type conversion. By @ErichDonGubler in [#7572](https://github.com/gfx-rs/wgpu/pull/7572). +- Allow scalars as the first argument of the `distance` built-in function. By @bernhl in [#7530](https://github.com/gfx-rs/wgpu/pull/7530). +- Don't panic when handling `f16` for pipeline constants, i.e., `override`s in WGSL. By @ErichDonGubler in [#7801](https://github.com/gfx-rs/wgpu/pull/7801). +- Prevent aliased ray queries crashing naga when writing SPIR-V out. By @Vecvec in [#7759](https://github.com/gfx-rs/wgpu/pull/7759). + +#### DX12 + +- Get `vertex_index` & `instance_index` builtins working for indirect draws. By @teoxoy in [#7535](https://github.com/gfx-rs/wgpu/pull/7535) + +#### Vulkan + +- Fix OpenBSD compilation of `wgpu_hal::vulkan::drm`. By @ErichDonGubler in [#7810](https://github.com/gfx-rs/wgpu/pull/7810). +- Fix warnings for unrecognized present mode. By @Wumpf in [#7850](https://github.com/gfx-rs/wgpu/pull/7850). + +#### Metal + +- Remove extraneous main thread warning in `fn surface_capabilities()`. By @jamesordner in [#7692](https://github.com/gfx-rs/wgpu/pull/7692) + +#### WebGPU + +- Fix setting unclipped_depth. By @atlv24 in [#7841](https://github.com/gfx-rs/wgpu/pull/7841) +- Implement `on_submitted_work_done` for WebGPU backend. By @drewcrawford in [#7864](https://github.com/gfx-rs/wgpu/pull/7864) + +### Changes + +- Loosen Viewport validation requirements to match the [new specs](https://github.com/gpuweb/gpuweb/pull/5025). By @ebbdrop in [#7564](https://github.com/gfx-rs/wgpu/pull/7564) +- `wgpu` and `deno_webgpu` now use `wgpu-types::error::WebGpuError` to classify errors. Any changes here are likely to be regressions; please report them if you find them! By @ErichDonGubler in [#6547](https://github.com/gfx-rs/wgpu/pull/6547). + +#### General + +- Support BLAS compaction in wgpu. By @Vecvec in [#7285](https://github.com/gfx-rs/wgpu/pull/7285). +- Removed `MaintainBase` in favor of using `PollType`. By @waywardmonkeys in [#7508](https://github.com/gfx-rs/wgpu/pull/7508). +- The `destroy` functions for buffers and textures in wgpu-core are now infallible. Previously, they returned an error if called multiple times for the same object. This only affects the wgpu-core API; the wgpu API already allowed multiple `destroy` calls. By @andyleiserson in [#7686](https://github.com/gfx-rs/wgpu/pull/7686) and [#7720](https://github.com/gfx-rs/wgpu/pull/7720). +- Remove `CommandEncoder::build_acceleration_structures_unsafe_tlas` in favour of `as_hal` and apply + simplifications allowed by this. By @Vecvec in [#7513](https://github.com/gfx-rs/wgpu/pull/7513) +- The type of the `size` parameter to `copy_buffer_to_buffer` has changed from `BufferAddress` to `impl Into>`. This achieves the spec-defined behavior of the value being optional, while still accepting existing calls without changes. By @andyleiserson in [#7659](https://github.com/gfx-rs/wgpu/pull/7659). +- To bring wgpu's error reporting into compliance with the WebGPU specification, the error type returned from some functions has changed, and some errors may be raised at a different time than they were previously. + - The error type returned by many methods on `CommandEncoder`, `RenderPassEncoder`, `ComputePassEncoder`, and `RenderBundleEncoder` has changed to `EncoderStateError` or `PassStateError`. These functions will return the `Ended` variant of these errors if called on an encoder that is no longer active. Reporting of all other errors is deferred until a call to `finish()`. + - Variants holding a `CommandEncoderError` in the error enums `ClearError`, `ComputePassErrorInner`, `QueryError`, and `RenderPassErrorInner` have been replaced with variants holding an `EncoderStateError`. + - The definition of `enum CommandEncoderError` has changed significantly, to reflect which errors can be raised by `CommandEncoder.finish()`. There are also some errors that no longer appear directly in `CommandEncoderError`, and instead appear nested within the `RenderPass` or `ComputePass` variants. + - `CopyError` has been removed. Errors that were previously a `CopyError` are now a `CommandEncoderError` returned by `finish()`. (The detailed reasons for copies to fail were and still are described by `TransferError`, which was previously a variant of `CopyError`, and is now a variant of `CommandEncoderError`). + +#### naga + +- Mark `readonly_and_readwrite_storage_textures` & `packed_4x8_integer_dot_product` language extensions as implemented. By @teoxoy in [#7543](https://github.com/gfx-rs/wgpu/pull/7543) +- `naga::back::hlsl::Writer::new` has a new `pipeline_options` argument. `hlsl::PipelineOptions::default()` can be passed as a default. The `shader_stage` and `entry_point` members of `pipeline_options` can be used to write only a single entry point when using the HLSL and MSL backends (GLSL and SPIR-V already had this functionality). The Metal and DX12 HALs now write only a single entry point when loading shaders. By @andyleiserson in [#7626](https://github.com/gfx-rs/wgpu/pull/7626). +- Implemented `early_depth_test` for SPIR-V backend, enabling `SHADER_EARLY_DEPTH_TEST` for Vulkan. Additionally, fixed conservative depth optimizations when using `early_depth_test`. The syntax for forcing early depth tests is now `@early_depth_test(force)` instead of `@early_depth_test`. By @dzamkov in [#7676](https://github.com/gfx-rs/wgpu/pull/7676). +- `ImplementedLanguageExtension::VARIANTS` is now implemented manually rather than derived using `strum` (allowing `strum` to become a dev-only dependency) so it is no longer a member of the `strum::VARIANTS` trait. Unless you are using this trait as a bound this should have no effect. +- Compaction changes, by @andyleiserson in [#7703](https://github.com/gfx-rs/wgpu/pull/7703): + - [`process_overrides`](https://docs.rs/naga/latest/naga/back/pipeline_constants/fn.process_overrides.html) now compacts the module to remove unused items. It is no longer necessary to supply values for overrides that are not used by the active entry point. + - The `compact` Cargo feature has been removed. It is no longer possible to exclude compaction support from the build. + - [`compact`](https://docs.rs/naga/latest/naga/compact/fn.compact.html) now has an additional argument that specifies whether to remove unused functions, globals, and named types and overrides. For the previous behavior, pass `KeepUnused::Yes`. + +#### D3D12 + +- Remove the need for dxil.dll. By @teoxoy in [#7566](https://github.com/gfx-rs/wgpu/pull/7566) +- Ability to get the raw `IDXGIFactory4` from `Instance`. By @MendyBerger in [#7827](https://github.com/gfx-rs/wgpu/pull/7827) + +#### Vulkan + +- Use highest SPIR-V version supported by Vulkan API version. By @robamler in [#7595](https://github.com/gfx-rs/wgpu/pull/7595) + +#### HAL + +- Added initial `no_std` support to `wgpu-hal`. By @bushrat011899 in [#7599](https://github.com/gfx-rs/wgpu/pull/7599) + +### Documentation + +#### General + +- Remove outdated information about `Adapter::request_device`. By @tesselode in [#7768](https://github.com/gfx-rs/wgpu/pull/7768) + +## v25.0.2 (2025-05-24) + +### Bug Fixes + +#### General + +- Fix a possible deadlock within `Queue::write_buffer`. By @RedMindZ in [#7582](https://github.com/gfx-rs/wgpu/pull/7582) +- Fix `raw-window-handle` dependency being too lenient. By @kpreid in [#7526](https://github.com/gfx-rs/wgpu/pull/7526) + +#### WebGPU + +- Insert fragment pipeline constants into fragment descriptor instead of vertex descriptor. By @DerSchmale in [#7621](https://github.com/gfx-rs/wgpu/pull/7621) + +## v25.0.1 (2025-04-11) + +### Bug Fixes + +- Fix typos in various documentation. By @waywardmonkeys in [#7510](https://github.com/gfx-rs/wgpu/pull/7510). +- Fix compile error when building with `profiling/profile-with-*` feature enabled. By @waywardmonkeys in [#7509](https://github.com/gfx-rs/wgpu/pull/7509). +- Use `once_cell::race::OnceBox` instead of `std::sync::LazyLock` to allow `naga::proc::Namer::default()` to be available without backend features being enabled. By @cwfitzgerald in [#7517](https://github.com/gfx-rs/wgpu/pull/7517). + +#### DX12 + +- Fix validation error when creating a non-mappable buffer using the committed allocation scheme. By @cwfitzgerald and @ErichDonGubler in [#7519](https://github.com/gfx-rs/wgpu/pull/7519). + +## v25.0.0 (2025-04-10) ### Major Features @@ -58,6 +715,14 @@ By @cwfitzgerald in [#7133](https://github.com/gfx-rs/wgpu/pull/7133) Previously, the `vulkan` and `gles` backends were non-optional on windows, linux, and android and there was no way to disable them. We have now figured out how to properly make them disablable! Additionally, if you turn on the `webgl` feature, you will only get the GLES backend on WebAssembly, it won't leak into native builds, like previously it might have. +> [!WARNING] +> If you use wgpu with `default-features = false` and you want to retain the `vulkan` and `gles` backends, you will need to add them to your feature list. +> +> ```diff +> -wgpu = { version = "24", default-features = false, features = ["metal", "wgsl", "webgl"] } +> +wgpu = { version = "25", default-features = false, features = ["metal", "wgsl", "webgl", "vulkan", "gles"] } +> ``` + By @cwfitzgerald in [#7076](https://github.com/gfx-rs/wgpu/pull/7076). #### `device.poll` Api Reworked @@ -117,12 +782,23 @@ pub enum PollError { > > You will lose the ability to know exactly when a submission has completed, but `device.poll(Wait)` will behave the same as it does on native. -By @cwfitzgerald in [#6942](https://github.com/gfx-rs/wgpu/pull/6942). -By @cwfitzgerald in [#7030](https://github.com/gfx-rs/wgpu/pull/7030). +By @cwfitzgerald in [#6942](https://github.com/gfx-rs/wgpu/pull/6942) and [#7030](https://github.com/gfx-rs/wgpu/pull/7030). -#### Naga +#### `wgpu::Device::start_capture` renamed, documented, and made unsafe -##### Ensure loops generated by SPIR-V and HLSL Naga backends are bounded +```diff +- device.start_capture(); ++ unsafe { device.start_graphics_debugger_capture() } +// Your code here +- device.stop_capture(); ++ unsafe { device.stop_graphics_debugger_capture() } +``` + +There is now documentation to describe how this maps to the various debuggers' apis. + +By @cwfitzgerald in [#7470](https://github.com/gfx-rs/wgpu/pull/7470) + +##### Ensure loops generated by SPIR-V and HLSL naga backends are bounded Make sure that all loops in shaders generated by these naga backends are bounded to avoid undefined behaviour due to infinite loops. Note that this may have a @@ -133,7 +809,7 @@ By @jamienicol in [#6929](https://github.com/gfx-rs/wgpu/pull/6929) and [#7080]( #### Split up `Features` internally -Internally split up the `Features` struct and recombine them internally using a macro. There should be no breaking +Internally split up the `Features` struct and recombine them internally using a macro. There should be no breaking changes from this. This means there are also namespaces (as well as the old `Features::*`) for all wgpu specific features and webgpu feature (`FeaturesWGPU` and `FeaturesWebGPU` respectively) and `Features::from_internal_flags` which allow you to be explicit about whether features you need are available on the web too. @@ -157,9 +833,11 @@ struct FragmentOutput{ } ``` + With that `wgpu::Features::DUAL_SOURCE_BLENDING` is now available on WebGPU. Furthermore, GLSL shaders now support dual source blending as well via the `index` layout qualifier: + ```c layout(location = 0, index = 0) out vec4 output0; layout(location = 0, index = 1) out vec4 output1; @@ -167,30 +845,87 @@ layout(location = 0, index = 1) out vec4 output1; By @wumpf in [#7144](https://github.com/gfx-rs/wgpu/pull/7144) +#### Unify interface for SpirV shader passthrough + +Replace device `create_shader_module_spirv` function with a generic `create_shader_module_passthrough` function +taking a `ShaderModuleDescriptorPassthrough` enum as parameter. + +Update your calls to `create_shader_module_spirv` and use `create_shader_module_passthrough` instead: + +```diff +- device.create_shader_module_spirv( +- wgpu::ShaderModuleDescriptorSpirV { +- label: Some(&name), +- source: Cow::Borrowed(&source), +- } +- ) ++ device.create_shader_module_passthrough( ++ wgpu::ShaderModuleDescriptorPassthrough::SpirV( ++ wgpu::ShaderModuleDescriptorSpirV { ++ label: Some(&name), ++ source: Cow::Borrowed(&source), ++ }, ++ ), ++ ) +``` + +By @syl20bnr in [#7326](https://github.com/gfx-rs/wgpu/pull/7326). + +#### Noop Backend + +It is now possible to create a dummy `wgpu` device even when no GPU is available. This may be useful for testing of code which manages graphics resources. Currently, it supports reading and writing buffers, and other resource types can be created but do nothing. + +To use it, enable the `noop` feature of `wgpu`, and either call `Device::noop()`, or add `NoopBackendOptions { enable: true }` to the backend options of your `Instance` (this is an additional safeguard beyond the `Backends` bits). + +By @kpreid in [#7063](https://github.com/gfx-rs/wgpu/pull/7063) and [#7342](https://github.com/gfx-rs/wgpu/pull/7342). + +#### `SHADER_F16` feature is now available with naga shaders + +Previously this feature only allowed you to use `f16` on SPIR-V passthrough shaders. Now you can use it on all shaders, including WGSL, SPIR-V, and GLSL! + +```wgsl +enable f16; + +fn hello_world(a: f16) -> f16 { + return a + 1.0h; +} +``` + +By @FL33TW00D, @ErichDonGubler, and @cwfitzgerald in [#5701](https://github.com/gfx-rs/wgpu/pull/5701) + +#### Bindless support improved and validation rules changed. + +Metal support for bindless has significantly improved and the limits for binding arrays have been increased. + +Previously, all resources inside binding arrays contributed towards the standard limit of their type (`texture_2d` arrays for example would contribute to `max_sampled_textures_per_shader_stage`). Now these resources will only contribute towards binding-array specific limits: + +- `max_binding_array_elements_per_shader_stage` for all non-sampler resources +- `max_binding_array_sampler_elements_per_shader_stage` for sampler resources. + +This change has allowed the metal binding array limits to go from between 32 and 128 resources, all the way 500,000 sampled textures. Additionally binding arrays are now bound more efficiently on Metal. + +This change also enabled legacy Intel GPUs to support 1M bindless resources, instead of the previous 1800. + +To facilitate this change, there was an additional validation rule put in place: if there is a binding array in a bind group, you may not use dynamic offset buffers or uniform buffers in that bind group. This requirement comes from vulkan rules on `UpdateAfterBind` descriptors. +By @cwfitzgerald in [#6811](https://github.com/gfx-rs/wgpu/pull/6811), [#6815](https://github.com/gfx-rs/wgpu/pull/6815), and [#6952](https://github.com/gfx-rs/wgpu/pull/6952). + ### New Features -- Added mesh shader support to `wgpu_hal`. By @SupaMaggie70Incorporated in [#7089](https://github.com/gfx-rs/wgpu/pull/7089) - #### General -- It is now possible to create a dummy `wgpu` device even when no GPU is available. This may be useful for testing of code which manages graphics resources. Currently, it supports reading and writing buffers, and other resource types can be created but do nothing. - - To use it, enable the `noop` feature of `wgpu`, and either call `Device::noop()`, or add `NoopBackendOptions { enable: true }` to the backend options of your `Instance` (this is an additional safeguard beyond the `Backends` bits). - - By @kpreid in [#7063](https://github.com/gfx-rs/wgpu/pull/7063) and [#7342](https://github.com/gfx-rs/wgpu/pull/7342). - - Add `Buffer` methods corresponding to `BufferSlice` methods, so you can skip creating a `BufferSlice` when it offers no benefit, and `BufferSlice::slice()` for sub-slicing a slice. By @kpreid in [#7123](https://github.com/gfx-rs/wgpu/pull/7123). - Add `BufferSlice::buffer()`, `BufferSlice::offset()` and `BufferSlice::size()`. By @kpreid in [#7148](https://github.com/gfx-rs/wgpu/pull/7148). - Add `impl From for BufferBinding` and `impl From for BindingResource`, allowing `BufferSlice`s to be easily used in creating bind groups. By @kpreid in [#7148](https://github.com/gfx-rs/wgpu/pull/7148). - - Add `util::StagingBelt::allocate()` so the staging belt can be used to write textures. By @kpreid in [#6900](https://github.com/gfx-rs/wgpu/pull/6900). - Added `CommandEncoder::transition_resources()` for native API interop, and allowing users to slightly optimize barriers. By @JMS55 in [#6678](https://github.com/gfx-rs/wgpu/pull/6678). - Add `wgpu_hal::vulkan::Adapter::texture_format_as_raw` for native API interop. By @JMS55 in [#7228](https://github.com/gfx-rs/wgpu/pull/7228). +- Support getting vertices of the hit triangle when raytracing. By @Vecvec in [#7183](https://github.com/gfx-rs/wgpu/pull/7183). +- Add `as_hal` for both acceleration structures. By @Vecvec in [#7303](https://github.com/gfx-rs/wgpu/pull/7303). +- Add Metal compute shader passthrough. Use `create_shader_module_passthrough` on device. By @syl20bnr in [#7326](https://github.com/gfx-rs/wgpu/pull/7326). +- new `Features::MSL_SHADER_PASSTHROUGH` run-time feature allows providing pass-through MSL Metal shaders. By @syl20bnr in [#7326](https://github.com/gfx-rs/wgpu/pull/7326). +- Added mesh shader support to `wgpu_hal`. By @SupaMaggie70Incorporated in [#7089](https://github.com/gfx-rs/wgpu/pull/7089) -- Support getting vertices of the hit triangle when raytracing. By @Vecvec in [#7183](https://github.com/gfx-rs/wgpu/pull/7183) . - - -#### Naga +#### naga - Add support for unsigned types when calling textureLoad with the level parameter. By @ygdrasil-io in [#7058](https://github.com/gfx-rs/wgpu/pull/7058). - Support @must_use attribute on function declarations. By @turbocrime in [#6801](https://github.com/gfx-rs/wgpu/pull/6801). @@ -199,6 +934,10 @@ By @wumpf in [#7144](https://github.com/gfx-rs/wgpu/pull/7144) - Add support for texture memory barriers. By @Devon7925 in [#7173](https://github.com/gfx-rs/wgpu/pull/7173). - Add polyfills for `unpackSnorm4x8`, `unpackUnorm4x8`, `unpackSnorm2x16`, `unpackUnorm2x16` for GLSL versions they aren't supported in. By @DJMcNab in [#7408](https://github.com/gfx-rs/wgpu/pull/7408). +#### Examples + +- Added an example that shows how to handle datasets too large to fit in a single `GPUBuffer` by distributing it across many buffers, and then having the shader receive them as a `binding_array` of storage buffers. By @alphastrata in [#6138](https://github.com/gfx-rs/wgpu/pull/6138) + ### Changes #### General @@ -211,15 +950,15 @@ By @wumpf in [#7144](https://github.com/gfx-rs/wgpu/pull/7144) - Rename `instance_id` and `instance_custom_index` to `instance_index` and `instance_custom_data` by @Vecvec in [#6780](https://github.com/gfx-rs/wgpu/pull/6780) +#### naga -#### Naga - -- Naga IR types are now available in the module `naga::ir` (e.g. `naga::ir::Module`). +- naga IR types are now available in the module `naga::ir` (e.g. `naga::ir::Module`). The original names (e.g. `naga::Module`) remain present for compatibility. By @kpreid in [#7365](https://github.com/gfx-rs/wgpu/pull/7365). - Refactored `use` statements to simplify future `no_std` support. By @bushrat011899 in [#7256](https://github.com/gfx-rs/wgpu/pull/7256) -- Naga's WGSL frontend no longer allows using the `&` operator to take the address of a component of a vector, +- naga's WGSL frontend no longer allows using the `&` operator to take the address of a component of a vector, which is not permitted by the WGSL specification. By @andyleiserson in [#7284](https://github.com/gfx-rs/wgpu/pull/7284) +- naga's use of `termcolor` and `stderr` are now optional behind features of the same names. By @bushrat011899 in [#7482](https://github.com/gfx-rs/wgpu/pull/7482) #### Vulkan @@ -229,7 +968,7 @@ By @wumpf in [#7144](https://github.com/gfx-rs/wgpu/pull/7144) ### Bug Fixes -#### Naga +#### naga - Fix some instances of functions which have a return type but don't return a value being incorrectly validated. By @jamienicol in [#7013](https://github.com/gfx-rs/wgpu/pull/7013). - Allow abstract expressions to be used in WGSL function return statements. By @jamienicol in [#7035](https://github.com/gfx-rs/wgpu/pull/7035). @@ -239,26 +978,29 @@ By @wumpf in [#7144](https://github.com/gfx-rs/wgpu/pull/7144) - Allow WGSL const declarations to have abstract types. By @jamienicol in [#7055](https://github.com/gfx-rs/wgpu/pull/7055) and [#7222](https://github.com/gfx-rs/wgpu/pull/7222). - Allows override-sized arrays to resolve to the same size without causing the type arena to panic. By @KentSlaney in [#7082](https://github.com/gfx-rs/wgpu/pull/7082). - Allow abstract types to be used for WGSL switch statement selector and case selector expressions. By @jamienicol in [#7250](https://github.com/gfx-rs/wgpu/pull/7250). +- Apply automatic conversions to `let` declarations, and accept `vecN()` as a constructor for vectors (in any context). By @andyleiserson in [#7367](https://github.com/gfx-rs/wgpu/pull/7367). +- The `&&` and `||` operators are no longer allowed on vectors. By @andyleiserson in [#7368](https://github.com/gfx-rs/wgpu/pull/7368). +- Prevent ray intersection function overwriting each other. By @Vecvec in [#7497](https://github.com/gfx-rs/wgpu/pull/7497). +- Require that the level operand of an ImageQuery::Size expression is i32 or u32, per spec. By @jimblandy in [#7426](https://github.com/gfx-rs/wgpu/pull/7426). +- Implement constant evaluation for the cross builtin. By @jimblandy in [#7404](https://github.com/gfx-rs/wgpu/pull/7404). +- Properly handle automatic type conversions in calls to `MathFunction` builtins. By @jimblandy in [#6833](https://github.com/gfx-rs/wgpu/pull/6833). #### General +- Fix some validation errors when building acceleration + structures. By @Vecvec in [#7486](https://github.com/gfx-rs/wgpu/pull/7486). - Avoid overflow in query set bounds check validation. By @ErichDonGubler in [#6933](https://github.com/gfx-rs/wgpu/pull/6933). - Add Flush to GL Queue::submit. By @cwfitzgerald in [#6941](https://github.com/gfx-rs/wgpu/pull/6941). -- Fix `wgpu` not building with `--no-default-features` on when targeting `wasm32-unknown-unknown`. By @wumpf in [#6946](https://github.com/gfx-rs/wgpu/pull/6946). -- Fix `CopyExternalImageDestInfo` not exported on `wgpu`. By @wumpf in [#6962](https://github.com/gfx-rs/wgpu/pull/6962). - Reduce downlevel `max_color_attachments` limit from 8 to 4 for better GLES compatibility. By @adrian17 in [#6994](https://github.com/gfx-rs/wgpu/pull/6994). -- Fix drop order in `Surface`. By @ed-2100 in [#6997](https://github.com/gfx-rs/wgpu/pull/6997) -- Fix a possible deadlock within `Queue::write_texture`. By @metamuffin in [#7004](https://github.com/gfx-rs/wgpu/pull/7004) - Fix building a BLAS with a transform buffer by adding a flag to indicate usage of the transform buffer. By @Vecvec in -[#7062](https://github.com/gfx-rs/wgpu/pull/7062). + [#7062](https://github.com/gfx-rs/wgpu/pull/7062). +- Move incrementation of `Device::last_acceleration_structure_build_command_index` into queue submit. By @Vecvec in [#7462](https://github.com/gfx-rs/wgpu/pull/7462). +- Implement indirect draw validation. By @teoxoy in [#7140](https://github.com/gfx-rs/wgpu/pull/7140) #### Vulkan - Stop naga causing undefined behavior when a ray query misses. By @Vecvec in [#6752](https://github.com/gfx-rs/wgpu/pull/6752). - -#### Metal - -- Use resize observers for smoother resizing. By @madsmtm in [#7026](https://github.com/gfx-rs/wgpu/pull/7026). +- In naga's SPIR-V backend, avoid duplicating SPIR-V OpTypePointer instructions. By @jimblandy in [#7246](https://github.com/gfx-rs/wgpu/pull/7246). #### Gles @@ -269,6 +1011,8 @@ By @wumpf in [#7144](https://github.com/gfx-rs/wgpu/pull/7144) - Fix HLSL storage format generation. By @Vecvec in [#6993](https://github.com/gfx-rs/wgpu/pull/6993) and [#7104](https://github.com/gfx-rs/wgpu/pull/7104) - Fix 3D storage texture bindings. By @SparkyPotato in [#7071](https://github.com/gfx-rs/wgpu/pull/7071) - Fix DX12 composite alpha modes. By @amrbashir in [#7117](https://github.com/gfx-rs/wgpu/pull/7117) +- Bound check dynamic buffers. By @teoxoy in [#6931](https://github.com/gfx-rs/wgpu/pull/6931) +- Fix size of buffer. By @teoxoy in [#7310](https://github.com/gfx-rs/wgpu/pull/7310) #### WebGPU @@ -276,7 +1020,7 @@ By @wumpf in [#7144](https://github.com/gfx-rs/wgpu/pull/7144) ### Performance -#### Naga +#### naga - Replace `unicode-xid` with `unicode-ident`. By @CrazyboyQCD in [#7135](https://github.com/gfx-rs/wgpu/pull/7135) @@ -291,6 +1035,46 @@ By @wumpf in [#7144](https://github.com/gfx-rs/wgpu/pull/7144) - Call `pre_present_notify()` before presenting. By @kjarosh in [#7074](https://github.com/gfx-rs/wgpu/pull/7074). +## v24.0.5 (2025-05-24) + +### Bug Fixes + +#### General + +- Fix a possible deadlock within `Queue::write_buffer`. By @RedMindZ in [#7582](https://github.com/gfx-rs/wgpu/pull/7582) + +#### WebGPU + +- Insert fragment pipeline constants into fragment descriptor instead of vertex descriptor. By @DerSchmale in [#7621](https://github.com/gfx-rs/wgpu/pull/7621) + +## v24.0.4 (2025-04-03) + +### Metal + +- Use resize observers for smoother resizing. By @madsmtm in [#7026](https://github.com/gfx-rs/wgpu/pull/7026). + +## v24.0.3 (2025-03-19) + +### Bug Fixes + +- Fix drop order in `Surface`, solving segfaults on exit on some systems. By @ed-2100 in [#6997](https://github.com/gfx-rs/wgpu/pull/6997) + +## v24.0.2 (2025-02-26) + +### Bug Fixes + +- Fix GLES renderpass clears causing violation of `max_color_attachments` limit. By @adrian17 in [#6994](https://github.com/gfx-rs/wgpu/pull/6994). +- Fix a possible deadlock within `Queue::write_texture`. By @metamuffin in [#7004](https://github.com/gfx-rs/wgpu/pull/7004) +- Decrement `max_storage_buffer_binding_size` by 1 to match `max_buffer_size`. By @minus1ms in [#7217](https://github.com/gfx-rs/wgpu/pull/7217) + +## v24.0.1 (2025-01-22) + +### Bug Fixes + +- Fix `wgpu` not building with `--no-default-features` on when targeting `wasm32-unknown-unknown`. By @wumpf in [#6946](https://github.com/gfx-rs/wgpu/pull/6946). +- Implement `Clone` on `ShaderModule`. By @a1phyr in [#6937](https://github.com/gfx-rs/wgpu/pull/6937). +- Fix `CopyExternalImageDestInfo` not exported on `wgpu`. By @wumpf in [#6962](https://github.com/gfx-rs/wgpu/pull/6962). + ## v24.0.0 (2025-01-15) ### Major changes @@ -409,7 +1193,7 @@ By @cwfitzgerald in [#6895](https://github.com/gfx-rs/wgpu/pull/6895) #### The `diagnostic(…);` directive is now supported in WGSL -Naga now parses `diagnostic(…);` directives according to the WGSL spec. This allows users to control certain lints, similar to Rust's `allow`, `warn`, and `deny` attributes. For example, in standard WGSL (but, notably, not Naga yet—see ) this snippet would emit a uniformity error: +naga now parses `diagnostic(…);` directives according to the WGSL spec. This allows users to control certain lints, similar to Rust's `allow`, `warn`, and `deny` attributes. For example, in standard WGSL (but, notably, not naga yet—see ) this snippet would emit a uniformity error: ```wgsl @group(0) @binding(0) var s : sampler; @@ -451,15 +1235,15 @@ fn main(@builtin(position) p : vec4f) -> @location(0) vec4f { There are some limitations to keep in mind with this new functionality: - We support `@diagnostic(…)` rules as `fn` attributes, but prioritization for rules in statement positions (i.e., `if (…) @diagnostic(…) { … }` is unclear. If you are blocked by not being able to parse `diagnostic(…)` rules in statement positions, please let us know in , so we can determine how to prioritize it! -- Standard WGSL specifies `error`, `warning`, `info`, and `off` severity levels. These are all technically usable now! A caveat, though: warning- and info-level are only emitted to `stderr` via the `log` façade, rather than being reported through a `Result::Err` in Naga or the `CompilationInfo` interface in `wgpu{,-core}`. This will require breaking changes in Naga to fix, and is being tracked by . -- Not all lints can be controlled with `diagnostic(…)` rules. In fact, only the `derivative_uniformity` triggering rule exists in the WGSL standard. That said, Naga contributors are excited to see how this level of control unlocks a new ecosystem of configurable diagnostics. +- Standard WGSL specifies `error`, `warning`, `info`, and `off` severity levels. These are all technically usable now! A caveat, though: warning- and info-level are only emitted to `stderr` via the `log` façade, rather than being reported through a `Result::Err` in naga or the `CompilationInfo` interface in `wgpu{,-core}`. This will require breaking changes in naga to fix, and is being tracked by . +- Not all lints can be controlled with `diagnostic(…)` rules. In fact, only the `derivative_uniformity` triggering rule exists in the WGSL standard. That said, naga contributors are excited to see how this level of control unlocks a new ecosystem of configurable diagnostics. - Finally, `diagnostic(…)` rules are not yet emitted in WGSL output. This means that `wgsl-in` → `wgsl-out` is currently a lossy process. We felt that it was important to unblock users who needed `diagnostic(…)` rules (i.e., ) before we took significant effort to fix this (tracked in ). By @ErichDonGubler in [#6456](https://github.com/gfx-rs/wgpu/pull/6456), [#6148](https://github.com/gfx-rs/wgpu/pull/6148), [#6533](https://github.com/gfx-rs/wgpu/pull/6533), [#6353](https://github.com/gfx-rs/wgpu/pull/6353), [#6537](https://github.com/gfx-rs/wgpu/pull/6537). #### New Features -##### Naga +##### naga - Support atomic operations on fields of global structs in the SPIR-V frontend. By @schell in [#6693](https://github.com/gfx-rs/wgpu/pull/6693). - Clean up tests for atomic operations support in SPIR-V frontend. By @schell in [#6692](https://github.com/gfx-rs/wgpu/pull/6692) @@ -505,7 +1289,7 @@ By @ErichDonGubler in [#6456](https://github.com/gfx-rs/wgpu/pull/6456), [#6148] #### Changes -##### Naga +##### naga - Show types of LHS and RHS in binary operation type mismatch errors. By @ErichDonGubler in [#6450](https://github.com/gfx-rs/wgpu/pull/6450). - The GLSL parser now uses less expressions for function calls. By @magcius in [#6604](https://github.com/gfx-rs/wgpu/pull/6604). @@ -558,7 +1342,7 @@ By @ErichDonGubler in [#6456](https://github.com/gfx-rs/wgpu/pull/6456), [#6148] - Fix `wgpu-info` not showing dx12 adapters. By @wumpf in [#6844](https://github.com/gfx-rs/wgpu/pull/6844). - Use `transform_buffer_offset` when initialising `transform_buffer`. By @Vecvec in [#6864](https://github.com/gfx-rs/wgpu/pull/6864). -#### Naga +#### naga - Fix crash when a texture argument is missing. By @aedm in [#6486](https://github.com/gfx-rs/wgpu/pull/6486) - Emit an error in constant evaluation, rather than crash, in certain cases where `vecN` constructors have less than N arguments. By @ErichDonGubler in [#6508](https://github.com/gfx-rs/wgpu/pull/6508). @@ -585,7 +1369,6 @@ By @ErichDonGubler in [#6456](https://github.com/gfx-rs/wgpu/pull/6456), [#6148] - Add multiple render targets example. By @kaphula in [#5297](https://github.com/gfx-rs/wgpu/pull/5313) - ### Testing - Tests the early returns in the acceleration structure build calls with empty calls. By @Vecvec in [#6651](https://github.com/gfx-rs/wgpu/pull/6651). @@ -613,7 +1396,7 @@ Below changes were cherry-picked from 24.0.0 development line. ### Themes of this release -This release's theme is one that is likely to repeat for a few releases: convergence with the WebGPU specification! WGPU's design and base functionality are actually determined by two specifications: one for WebGPU, and one for the WebGPU Shading Language. +This release's theme is one that is likely to repeat for a few releases: convergence with the WebGPU specification! wgpu's design and base functionality are actually determined by two specifications: one for WebGPU, and one for the WebGPU Shading Language. This may not sound exciting, but let us convince you otherwise! All major web browsers have committed to offering WebGPU in their environment. Even JS runtimes like [Node][nodejs-webgpu-interest] and [Deno][deno_webgpu-crate-manifest] have communities that are very interested in providing WebGPU! WebGPU is slowly [eating the world][eat-the-world-meaning], as it were. 😀 It's really important, then, that WebGPU implementations behave in ways that one would expect across all platforms. For example, if Firefox's WebGPU implementation were to break when running scripts and shaders that worked just fine in Chrome, that would mean sad users for both application authors _and_ browser authors. @@ -621,23 +1404,23 @@ This may not sound exciting, but let us convince you otherwise! All major web br [deno_webgpu-crate-manifest]: https://github.com/gfx-rs/wgpu/tree/64a61ee5c69569bbb3db03563997e88a229eba17/deno_webgpu#deno_webgpu [eat-the-world-meaning]: https://www.quora.com/What-did-Marc-Andreessen-mean-when-he-said-that-software-is-eating-the-world -WGPU also benefits from standard, portable behavior in the same way as web browsers. Because of this behavior, it's generally fairly easy to port over usage of WebGPU in JavaScript to WGPU. It is also what lets WGPU go full circle: WGPU can be an implementation of WebGPU on native targets, but _also_ it can use _other implementations of WebGPU_ as a backend in JavaScript when compiled to WASM. Therefore, the same dynamic applies: if WGPU's own behavior were significantly different, then WGPU and end users would be _sad, sad humans_ as soon as they discover places where their nice apps are breaking, right? +wgpu also benefits from standard, portable behavior in the same way as web browsers. Because of this behavior, it's generally fairly easy to port over usage of WebGPU in JavaScript to wgpu. It is also what lets wgpu go full circle: wgpu can be an implementation of WebGPU on native targets, but _also_ it can use _other implementations of WebGPU_ as a backend in JavaScript when compiled to WASM. Therefore, the same dynamic applies: if wgpu's own behavior were significantly different, then wgpu and end users would be _sad, sad humans_ as soon as they discover places where their nice apps are breaking, right? -The answer is: yes, we _do_ have sad, sad humans that really want their WGPU code to work _everywhere_. As Firefox and others use WGPU to implement WebGPU, the above example of Firefox diverging from standard is, unfortunately, today's reality. It _mostly_ behaves the same as a standards-compliant WebGPU, but it still doesn't in many important ways. Of particular note is Naga, its implementation of the WebGPU Shader Language. Shaders are pretty much a black-and-white point of failure in GPU programming; if they don't compile, then you can't use the rest of the API! And yet, it's extremely easy to run into a case like that from : +The answer is: yes, we _do_ have sad, sad humans that really want their wgpu code to work _everywhere_. As Firefox and others use wgpu to implement WebGPU, the above example of Firefox diverging from standard is, unfortunately, today's reality. It _mostly_ behaves the same as a standards-compliant WebGPU, but it still doesn't in many important ways. Of particular note is naga, its implementation of the WebGPU Shader Language. Shaders are pretty much a black-and-white point of failure in GPU programming; if they don't compile, then you can't use the rest of the API! And yet, it's extremely easy to run into a case like that from : ```wgsl fn gimme_a_float() -> f32 { - return 42; // fails in Naga, but standard WGSL happily converts to `f32` + return 42; // fails in naga, but standard WGSL happily converts to `f32` } ``` -We intend to continue making visible strides in converging with specifications for WebGPU and WGSL, as this release has. This is, unfortunately, one of the major reasons that WGPU has no plans to work hard at keeping a SemVer-stable interface for the foreseeable future; we have an entire platform of GPU programming functionality we have to catch up with, and SemVer stability is unfortunately in tension with that. So, for now, you're going to keep seeing major releases and breaking changes. Where possible, we'll try to make that painless, but compromises to do so don't always make sense with our limited resources. +We intend to continue making visible strides in converging with specifications for WebGPU and WGSL, as this release has. This is, unfortunately, one of the major reasons that wgpu has no plans to work hard at keeping a SemVer-stable interface for the foreseeable future; we have an entire platform of GPU programming functionality we have to catch up with, and SemVer stability is unfortunately in tension with that. So, for now, you're going to keep seeing major releases and breaking changes. Where possible, we'll try to make that painless, but compromises to do so don't always make sense with our limited resources. This is also the last planned major version release of 2024; the next milestone is set for January 1st, 2025, according to our regular 12-week cadence (offset from the originally planned date of 2024-10-09 for _this_ release 😅). We'll see you next year! ### Contributor spotlight: @sagudev -This release, we'd like to spotlight the work of @sagudev, who has made significant contributions to the WGPU ecosystem this release. Among other things, they contributed a particularly notable feature where runtime-known indices are finally allowed for use with `const` array values. For example, this WGSL shader previously wasn't allowed: +This release, we'd like to spotlight the work of @sagudev, who has made significant contributions to the wgpu ecosystem this release. Among other things, they contributed a particularly notable feature where runtime-known indices are finally allowed for use with `const` array values. For example, this WGSL shader previously wasn't allowed: ```wgsl const arr: array = array(1, 2, 3, 4); @@ -649,7 +1432,7 @@ fn what_number_should_i_use(idx: u32) -> u32 { …but now it works! This is significant because this sort of shader rejection was one of the most impactful issues we are aware of for converging with the WGSL specification. There are more still to go—some of which we expect to even more drastically change how folks author shaders—but we suspect that many more will come in the next few releases, including with @sagudev's help. -We're excited for more of @sagudev's contributions via the Servo community. Oh, did we forget to mention that these contributions were motivated by their work on Servo? That's right, a _third_ well-known JavaScript runtime is now using WGPU to implement its WebGPU implementation. We're excited to support Servo to becoming another fully fledged browsing environment this way. +We're excited for more of @sagudev's contributions via the Servo community. Oh, did we forget to mention that these contributions were motivated by their work on Servo? That's right, a _third_ well-known JavaScript runtime is now using wgpu to implement its WebGPU implementation. We're excited to support Servo to becoming another fully fledged browsing environment this way. ### Major Changes @@ -724,9 +1507,9 @@ fn fs_main() { /* … */ } [optional-entrypoint-in-spec]: https://github.com/gpuweb/gpuweb/issues/4342 -#### WGPU's DX12 backend is now based on the `windows` crate ecosystem, instead of the `d3d12` crate +#### wgpu's DX12 backend is now based on the `windows` crate ecosystem, instead of the `d3d12` crate -WGPU has retired the `d3d12` crate (based on `winapi`), and now uses the `windows` crate for interfacing with Windows. For many, this may not be a change that affects day-to-day work. However, for users who need to vet their dependencies, or who may vendor in dependencies, this may be a nontrivial migration. +wgpu has retired the `d3d12` crate (based on `winapi`), and now uses the `windows` crate for interfacing with Windows. For many, this may not be a change that affects day-to-day work. However, for users who need to vet their dependencies, or who may vendor in dependencies, this may be a nontrivial migration. By @MarijnS95 in [#6006](https://github.com/gfx-rs/wgpu/pull/6006). @@ -736,7 +1519,7 @@ By @MarijnS95 in [#6006](https://github.com/gfx-rs/wgpu/pull/6006). - Added initial acceleration structure and ray query support into wgpu. By @expenses @daniel-keitel @Vecvec @JMS55 @atlv24 in [#6291](https://github.com/gfx-rs/wgpu/pull/6291) -#### Naga +#### naga - Support constant evaluation for `firstLeadingBit` and `firstTrailingBit` numeric built-ins in WGSL. Front-ends that translate to these built-ins also benefit from constant evaluation. By @ErichDonGubler in [#5101](https://github.com/gfx-rs/wgpu/pull/5101). - Add `first` and `either` sampling types for `@interpolate(flat, …)` in WGSL. By @ErichDonGubler in [#6181](https://github.com/gfx-rs/wgpu/pull/6181). @@ -746,7 +1529,7 @@ By @MarijnS95 in [#6006](https://github.com/gfx-rs/wgpu/pull/6006). - Support polyfilling `inverse` in WGSL. By @chyyran in [#6385](https://github.com/gfx-rs/wgpu/pull/6385). - Add base support for parsing `requires`, `enable`, and `diagnostic` directives. No extensions or diagnostic filters are yet supported, but diagnostics have improved dramatically. By @ErichDonGubler in [#6352](https://github.com/gfx-rs/wgpu/pull/6352), [#6424](https://github.com/gfx-rs/wgpu/pull/6424), [#6437](https://github.com/gfx-rs/wgpu/pull/6437). - Include error chain information as a message and notes in shader compilation messages. By @ErichDonGubler in [#6436](https://github.com/gfx-rs/wgpu/pull/6436). -- Unify Naga CLI error output with the format of shader compilation messages. By @ErichDonGubler in [#6436](https://github.com/gfx-rs/wgpu/pull/6436). +- Unify naga CLI error output with the format of shader compilation messages. By @ErichDonGubler in [#6436](https://github.com/gfx-rs/wgpu/pull/6436). #### General @@ -766,7 +1549,7 @@ By @MarijnS95 in [#6006](https://github.com/gfx-rs/wgpu/pull/6006). - Fix incorrect hlsl image output type conversion. By @atlv24 in [#6123](https://github.com/gfx-rs/wgpu/pull/6123). -#### Naga +#### naga - SPIR-V frontend splats depth texture sample and load results. Fixes [issue #4551](https://github.com/gfx-rs/wgpu/issues/4551). By @schell in [#6384](https://github.com/gfx-rs/wgpu/pull/6384). - Accept only `vec3` (not `vecN`) for the `cross` built-in. By @ErichDonGubler in [#6171](https://github.com/gfx-rs/wgpu/pull/6171). @@ -790,7 +1573,7 @@ By @MarijnS95 in [#6006](https://github.com/gfx-rs/wgpu/pull/6006). - Deduplicate bind group layouts that are created from pipelines with "auto" layouts. By @teoxoy [#6049](https://github.com/gfx-rs/wgpu/pull/6049). - Document `wgpu_hal` bounds-checking promises, and adapt `wgpu_core`'s lazy initialization logic to the slightly weaker-than-expected guarantees. By @jimblandy in [#6201](https://github.com/gfx-rs/wgpu/pull/6201). - Raise validation error instead of panicking in `{Render,Compute}Pipeline::get_bind_group_layout` on native / WebGL. By @bgr360 in [#6280](https://github.com/gfx-rs/wgpu/pull/6280). -- **BREAKING**: Remove the last exposed C symbols in project, located in `wgpu_core::render::bundle::bundle_ffi`, to allow multiple versions of WGPU to compile together. By @ErichDonGubler in [#6272](https://github.com/gfx-rs/wgpu/pull/6272). +- **BREAKING**: Remove the last exposed C symbols in project, located in `wgpu_core::render::bundle::bundle_ffi`, to allow multiple versions of wgpu to compile together. By @ErichDonGubler in [#6272](https://github.com/gfx-rs/wgpu/pull/6272). - Call `flush_mapped_ranges` when unmapping write-mapped buffers. By @teoxoy in [#6089](https://github.com/gfx-rs/wgpu/pull/6089). - When mapping buffers for reading, mark buffers as initialized only when they have `MAP_WRITE` usage. By @teoxoy in [#6178](https://github.com/gfx-rs/wgpu/pull/6178). - Add a separate pipeline constants error. By @teoxoy in [#6094](https://github.com/gfx-rs/wgpu/pull/6094). @@ -862,7 +1645,7 @@ This release includes `wgpu`, `wgpu-core` and `naga`. All other crates remain at ### Added -#### Naga +#### naga - Added back implementations of PartialEq for more IR types. By @teoxoy in [#6045](https://github.com/gfx-rs/wgpu/pull/6045) @@ -883,21 +1666,21 @@ This release includes `wgpu`, `wgpu-core` and `naga`. All other crates remain at ### Our first major version release! -For the first time ever, WGPU is being released with a major version (i.e., 22.\* instead of 0.22.\*)! Maintainership has decided to fully adhere to [Semantic Versioning](https://semver.org/)'s recommendations for versioning production software. According to [SemVer 2.0.0's Q&A about when to use 1.0.0 versions (and beyond)](https://semver.org/spec/v2.0.0.html#how-do-i-know-when-to-release-100): +For the first time ever, wgpu is being released with a major version (i.e., 22.\* instead of 0.22.\*)! Maintainership has decided to fully adhere to [Semantic Versioning](https://semver.org/)'s recommendations for versioning production software. According to [SemVer 2.0.0's Q&A about when to use 1.0.0 versions (and beyond)](https://semver.org/spec/v2.0.0.html#how-do-i-know-when-to-release-100): > ### How do I know when to release 1.0.0? > > If your software is being used in production, it should probably already be 1.0.0. If you have a stable API on which users have come to depend, you should be 1.0.0. If you’re worrying a lot about backward compatibility, you should probably already be 1.0.0. -It is a well-known fact that WGPU has been used for applications and platforms already in production for years, at this point. We are often concerned with tracking breaking changes, and affecting these consumers' ability to ship. By releasing our first major version, we publicly acknowledge that this is the case. We encourage other projects in the Rust ecosystem to follow suit. +It is a well-known fact that wgpu has been used for applications and platforms already in production for years, at this point. We are often concerned with tracking breaking changes, and affecting these consumers' ability to ship. By releasing our first major version, we publicly acknowledge that this is the case. We encourage other projects in the Rust ecosystem to follow suit. -Note that while we start to use the major version number, WGPU is _not_ "going stable", as many Rust projects do. We anticipate many breaking changes before we fully comply with the WebGPU spec., which we expect to take a small number of years. +Note that while we start to use the major version number, wgpu is _not_ "going stable", as many Rust projects do. We anticipate many breaking changes before we fully comply with the WebGPU spec., which we expect to take a small number of years. ### Overview -A major ([pun intended](#our-first-major-version-release)) theme of this release is incremental improvement. Among the typically large set of bug fixes, new features, and other adjustments to WGPU by the many contributors listed below, @wumpf and @teoxoy have merged a series of many simplifications to WGPU's internals and, in one case, to the render and compute pass recording APIs. Many of these change WGPU to use atomically reference-counted resource tracking (i.e., `Arc<…>`), rather than using IDs to manage the lifetimes of platform-specific graphics resources in a registry of separate reference counts. This has led us to diagnose and fix many long-standing bugs, and net some neat performance improvements on the order of 40% or more of some workloads. +A major ([pun intended](#our-first-major-version-release)) theme of this release is incremental improvement. Among the typically large set of bug fixes, new features, and other adjustments to wgpu by the many contributors listed below, @wumpf and @teoxoy have merged a series of many simplifications to wgpu's internals and, in one case, to the render and compute pass recording APIs. Many of these change wgpu to use atomically reference-counted resource tracking (i.e., `Arc<…>`), rather than using IDs to manage the lifetimes of platform-specific graphics resources in a registry of separate reference counts. This has led us to diagnose and fix many long-standing bugs, and net some neat performance improvements on the order of 40% or more of some workloads. -While the above is exciting, we acknowledge already finding and fixing some (easy-to-fix) regressions from the above work. If you migrate to WGPU 22 and encounter such bugs, please engage us in the issue tracker right away! +While the above is exciting, we acknowledge already finding and fixing some (easy-to-fix) regressions from the above work. If you migrate to wgpu 22 and encounter such bugs, please engage us in the issue tracker right away! ### Major Changes @@ -917,18 +1700,20 @@ pipelines.push(/* ... */); // Continue pass recording. cpass.set_bindgroup(...); ``` + Previously, a set pipeline (or other resource) had to outlive pass recording which often affected wider systems, meaning that users needed to prove to the borrow checker that `Vec` (or similar constructs) aren't accessed mutably for the duration of pass recording. - Furthermore, you can now opt out of `wgpu::RenderPass`/`wgpu::ComputePass`'s lifetime dependency on its parent `wgpu::CommandEncoder` using `wgpu::RenderPass::forget_lifetime`/`wgpu::ComputePass::forget_lifetime`: + ```rust fn independent_cpass<'enc>(encoder: &'enc mut wgpu::CommandEncoder) -> wgpu::ComputePass<'static> { let cpass: wgpu::ComputePass<'enc> = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor::default()); cpass.forget_lifetime() } ``` + ⚠️ As long as a `wgpu::RenderPass`/`wgpu::ComputePass` is pending for a given `wgpu::CommandEncoder`, creation of a compute or render pass is an error and invalidates the `wgpu::CommandEncoder`. `forget_lifetime` can be very useful for library authors, but opens up an easy way for incorrect use, so use with care. This method doesn't add any additional overhead and has no side effects on pass recording. @@ -972,7 +1757,7 @@ Add the following flags to `wgpu_types::Features`: atomic operations available on Metal as of 3.1. Add corresponding flags to `naga::valid::Capabilities`. These are supported by the -WGSL front end, and all Naga backends. +WGSL front end, and all naga backends. Platform support: @@ -1011,13 +1796,13 @@ By @teoxoy in [#5901](https://github.com/gfx-rs/wgpu/pull/5901) - Added `as_hal` for `Buffer` to access wgpu created buffers form wgpu-hal. By @JasondeWolff in [#5724](https://github.com/gfx-rs/wgpu/pull/5724) - `include_wgsl!` is now callable in const contexts by @9SMTM6 in [#5872](https://github.com/gfx-rs/wgpu/pull/5872) - Added memory allocation hints to `DeviceDescriptor` by @nical in [#5875](https://github.com/gfx-rs/wgpu/pull/5875) - - `MemoryHints::Performance`, the default, favors performance over memory usage and will likely cause large amounts of VRAM to be allocated up-front. This hint is typically good for games. - - `MemoryHints::MemoryUsage` favors memory usage over performance. This hint is typically useful for smaller applications or UI libraries. - - `MemoryHints::Manual` allows the user to specify parameters for the underlying GPU memory allocator. These parameters are subject to change. - - These hints may be ignored by some backends. Currently only the Vulkan and D3D12 backends take them into account. + - `MemoryHints::Performance`, the default, favors performance over memory usage and will likely cause large amounts of VRAM to be allocated up-front. This hint is typically good for games. + - `MemoryHints::MemoryUsage` favors memory usage over performance. This hint is typically useful for smaller applications or UI libraries. + - `MemoryHints::Manual` allows the user to specify parameters for the underlying GPU memory allocator. These parameters are subject to change. + - These hints may be ignored by some backends. Currently only the Vulkan and D3D12 backends take them into account. - Add `HTMLImageElement` and `ImageData` as external source for copying images. By @Valaphee in [#5668](https://github.com/gfx-rs/wgpu/pull/5668) -#### Naga +#### naga - Added -D, --defines option to naga CLI to define preprocessor macros by @theomonnom in [#5859](https://github.com/gfx-rs/wgpu/pull/5859) - Added type upgrades to SPIR-V atomic support. Added related infrastructure. Tracking issue is [here](https://github.com/gfx-rs/wgpu/issues/4489). By @schell in [#5775](https://github.com/gfx-rs/wgpu/pull/5775). @@ -1031,6 +1816,7 @@ By @teoxoy in [#5901](https://github.com/gfx-rs/wgpu/pull/5901) -writer.write(&module, &module_info); +writer.write(&module, &module_info, None); ``` + - HLSL & MSL output can now be added conditionally on the target via the `msl-out-if-target-apple` and `hlsl-out-if-target-windows` features. This is used in wgpu-hal to no longer compile with MSL output when `metal` is enabled & MacOS isn't targeted and no longer compile with HLSL output when `dx12` is enabled & Windows isn't targeted. By @wumpf in [#5919](https://github.com/gfx-rs/wgpu/pull/5919) #### Vulkan @@ -1053,13 +1839,16 @@ By @teoxoy in [#5901](https://github.com/gfx-rs/wgpu/pull/5901) - The `trace` wgpu feature has been temporarily removed. By @teoxoy in [#5975](https://github.com/gfx-rs/wgpu/pull/5975) #### Metal + - Removed the `link` Cargo feature. This was used to allow weakly linking frameworks. This can be achieved with putting something like the following in your `.cargo/config.toml` instead: + ```toml [target.'cfg(target_vendor = "apple")'] rustflags = ["-C", "link-args=-weak_framework Metal -weak_framework QuartzCore -weak_framework CoreGraphics"] ``` + By @madsmtm in [#5752](https://github.com/gfx-rs/wgpu/pull/5752) ### Bug Fixes @@ -1081,7 +1870,7 @@ By @teoxoy in [#5901](https://github.com/gfx-rs/wgpu/pull/5901) - Replace `glClear` with `glClearBufferF` because `glDrawBuffers` requires that the ith buffer must be `COLOR_ATTACHMENTi` or `NONE` [#5666](https://github.com/gfx-rs/wgpu/pull/5666) - Return the unmodified version in driver_info. By @Valaphee in [#5753](https://github.com/gfx-rs/wgpu/pull/5753) -#### Naga +#### naga - In spv-out don't decorate a `BindingArray`'s type with `Block` if the type is a struct with a runtime array by @Vecvec in [#5776](https://github.com/gfx-rs/wgpu/pull/5776) - Add `packed` as a keyword for GLSL by @kjarosh in [#5855](https://github.com/gfx-rs/wgpu/pull/5855) @@ -1094,11 +1883,11 @@ This release force-bumps transitive dependencies of `wgpu` on `wgpu-core` and `w #### General -* Fix a `CommandBuffer` leak. By @cwfitzgerald and @nical in [#5141](https://github.com/gfx-rs/wgpu/pull/5141) +- Fix a `CommandBuffer` leak. By @cwfitzgerald and @nical in [#5141](https://github.com/gfx-rs/wgpu/pull/5141) #### DX12 -* Do not feed `&""` to `D3DCompile`, by @workingjubilee in [#5812](https://github.com/gfx-rs/wgpu/issues/5812). +- Do not feed `&""` to `D3DCompile`, by @workingjubilee in [#5812](https://github.com/gfx-rs/wgpu/issues/5812). ## v0.20.1 (2024-06-12) @@ -1121,12 +1910,11 @@ This release fixes the validation errors whenever a surface is used with the vul - Fix enablement of subgroup ops extension on Vulkan devices that don't support Vulkan 1.3. By @cwfitzgerald in [#5624](https://github.com/gfx-rs/wgpu/pull/5624). - #### GLES / OpenGL - Fix regression on OpenGL (EGL) where non-sRGB still used sRGB [#5642](https://github.com/gfx-rs/wgpu/pull/5642) -#### Naga +#### naga - Work around shader consumers that have bugs handling `switch` statements with a single body for all cases. These are now written as `do {} while(false);` loops in hlsl-out and glsl-out. By @Imberflur in [#5654](https://github.com/gfx-rs/wgpu/pull/5654) - In hlsl-out, defer `continue` statements in switches by setting a flag and breaking from the switch. This allows such constructs to work with FXC which does not support `continue` within a switch. By @Imberflur in [#5654](https://github.com/gfx-rs/wgpu/pull/5654) @@ -1140,10 +1928,13 @@ This release fixes the validation errors whenever a surface is used with the vul Wgpu supports now [pipeline-overridable constants](https://www.w3.org/TR/webgpu/#dom-gpuprogrammablestage-constants) This allows you to define constants in wgsl like this: + ```rust override some_factor: f32 = 42.1337; // Specifies a default of 42.1337 if it's not set. ``` + And then set them at runtime like so on your pipeline consuming this shader: + ```rust // ... fragment: Some(wgpu::FragmentState { @@ -1165,7 +1956,6 @@ Due to a specification change `write_timestamp` is no longer supported on WebGPU By @wumpf in [#5188](https://github.com/gfx-rs/wgpu/pull/5188) - #### Wgsl const evaluation for many more built-ins Many numeric built-ins have had a constant evaluation implementation added for them, which allows them to be used in a `const` context: @@ -1182,11 +1972,11 @@ The following subgroup operations are available in wgsl now: `subgroupBallot`, `subgroupAll`, `subgroupAny`, `subgroupAdd`, `subgroupMul`, `subgroupMin`, `subgroupMax`, `subgroupAnd`, `subgroupOr`, `subgroupXor`, `subgroupExclusiveAdd`, `subgroupExclusiveMul`, `subgroupInclusiveAdd`, `subgroupInclusiveMul`, `subgroupBroadcastFirst`, `subgroupBroadcast`, `subgroupShuffle`, `subgroupShuffleDown`, `subgroupShuffleUp`, `subgroupShuffleXor` - Availability is governed by the following feature flags: -* `wgpu::Features::SUBGROUP` for all operations except `subgroupBarrier` in fragment & compute, supported on Vulkan, DX12 and Metal. -* `wgpu::Features::SUBGROUP_VERTEX`, for all operations except `subgroupBarrier` general operations in vertex shaders, supported on Vulkan -* `wgpu::Features::SUBGROUP_BARRIER`, for support of the `subgroupBarrier` operation, supported on Vulkan & Metal + +- `wgpu::Features::SUBGROUP` for all operations except `subgroupBarrier` in fragment & compute, supported on Vulkan, DX12 and Metal. +- `wgpu::Features::SUBGROUP_VERTEX`, for all operations except `subgroupBarrier` general operations in vertex shaders, supported on Vulkan +- `wgpu::Features::SUBGROUP_BARRIER`, for support of the `subgroupBarrier` operation, supported on Vulkan & Metal Note that there currently [some differences](https://github.com/gfx-rs/wgpu/issues/5555) between wgpu's native-only implementation and the [open WebGPU proposal](https://github.com/gpuweb/gpuweb/blob/main/proposals/subgroups.md). @@ -1223,9 +2013,9 @@ By @atlv24 and @cwfitzgerald in [#5154](https://github.com/gfx-rs/wgpu/pull/5154 - Added `wgpu::TextureView::as_hal` - `wgpu::Texture::as_hal` now returns a user-defined type to match the other as_hal functions -#### Naga +#### naga -- Allow user to select which MSL version to use via `--metal-version` with Naga CLI. By @pcleavelin in [#5392](https://github.com/gfx-rs/wgpu/pull/5392) +- Allow user to select which MSL version to use via `--metal-version` with naga CLI. By @pcleavelin in [#5392](https://github.com/gfx-rs/wgpu/pull/5392) - Support `arrayLength` for runtime-sized arrays inside binding arrays (for WGSL input and SPIR-V output). By @kvark in [#5428](https://github.com/gfx-rs/wgpu/pull/5428) - Added `--shader-stage` and `--input-kind` options to naga-cli for specifying vertex/fragment/compute shaders, and frontend. by @ratmice in [#5411](https://github.com/gfx-rs/wgpu/pull/5411) - Added a `create_validator` function to wgpu_core `Device` to create naga `Validator`s. By @atlv24 [#5606](https://github.com/gfx-rs/wgpu/pull/5606) @@ -1271,6 +2061,7 @@ By @atlv24 and @cwfitzgerald in [#5154](https://github.com/gfx-rs/wgpu/pull/5154 ### Bug Fixes #### General + - Fix `serde` feature not compiling for `wgpu-types`. By @KirmesBude in [#5149](https://github.com/gfx-rs/wgpu/pull/5149) - Fix the validation of vertex and index ranges. By @nical in [#5144](https://github.com/gfx-rs/wgpu/pull/5144) and [#5156](https://github.com/gfx-rs/wgpu/pull/5156) - Fix panic when creating a surface while no backend is available. By @wumpf [#5166](https://github.com/gfx-rs/wgpu/pull/5166) @@ -1283,7 +2074,7 @@ By @atlv24 and @cwfitzgerald in [#5154](https://github.com/gfx-rs/wgpu/pull/5154 - Remove exposed C symbols (`extern "C"` + [no_mangle]) from RenderPass & ComputePass recording. By @wumpf in [#5409](https://github.com/gfx-rs/wgpu/pull/5409). - Fix surfaces being only compatible with first backend enabled on an instance, causing failures when manually specifying an adapter. By @Wumpf in [#5535](https://github.com/gfx-rs/wgpu/pull/5535). -#### Naga +#### naga - In spv-in, remove unnecessary "gl_PerVertex" name check so unused builtins will always be skipped. Prevents validation errors caused by capability requirements of these builtins [#4915](https://github.com/gfx-rs/wgpu/issues/4915). By @Imberflur in [#5227](https://github.com/gfx-rs/wgpu/pull/5227). - In spv-out, check for acceleration and ray-query types when enabling ray-query extension to prevent validation error. By @Vecvec in [#5463](https://github.com/gfx-rs/wgpu/pull/5463) @@ -1335,6 +2126,7 @@ for DX12. - Fix deadlock in certain situations when mapping buffers using `wgpu-profiler`. By @cwfitzgerald in [#5517](https://github.com/gfx-rs/wgpu/pull/5517) #### WebGPU + - Correctly pass through timestamp queries to WebGPU. By @cwfitzgerald in [#5527](https://github.com/gfx-rs/wgpu/pull/5527). ## v0.19.3 (2024-03-01) @@ -1361,8 +2153,8 @@ By @cwfitzgerald in [#5325](https://github.com/gfx-rs/wgpu/pull/5325). - Fix incorrect validation causing all indexed draws on render bundles to fail. By @wumpf in [#5430](https://github.com/gfx-rs/wgpu/pull/5340). #### Android -- Fix linking error when targeting android without `winit`. By @ashdnazg in [#5326](https://github.com/gfx-rs/wgpu/pull/5326). +- Fix linking error when targeting android without `winit`. By @ashdnazg in [#5326](https://github.com/gfx-rs/wgpu/pull/5326). ## v0.19.2 (2024-02-29) @@ -1371,15 +2163,19 @@ This release includes `wgpu`, `wgpu-core`, `wgpu-hal`, `wgpu-types`, and `naga`. ### Added/New Features #### General + - `wgpu::Id` now implements `PartialOrd`/`Ord` allowing it to be put in `BTreeMap`s. By @cwfitzgerald and @9291Sam in [#5176](https://github.com/gfx-rs/wgpu/pull/5176) #### OpenGL + - Log an error when OpenGL texture format heuristics fail. By @PolyMeilex in [#5266](https://github.com/gfx-rs/wgpu/issues/5266) #### `wgsl-out` + - Learned to generate acceleration structure types. By @JMS55 in [#5261](https://github.com/gfx-rs/wgpu/pull/5261) ### Documentation + - Fix link in `wgpu::Instance::create_surface` documentation. By @HexoKnight in [#5280](https://github.com/gfx-rs/wgpu/pull/5280). - Fix typo in `wgpu::CommandEncoder::clear_buffer` documentation. By @PWhiddy in [#5281](https://github.com/gfx-rs/wgpu/pull/5281). - `Surface` configuration incorrectly claimed that `wgpu::Instance::create_surface` was unsafe. By @hackaugusto in [#5265](https://github.com/gfx-rs/wgpu/pull/5265). @@ -1387,6 +2183,7 @@ This release includes `wgpu`, `wgpu-core`, `wgpu-hal`, `wgpu-types`, and `naga`. ### Bug Fixes #### General + - Device lost callbacks are invoked when replaced and when global is dropped. By @bradwerth in [#5168](https://github.com/gfx-rs/wgpu/pull/5168) - Fix performance regression when allocating a large amount of resources of the same type. By @nical in [#5229](https://github.com/gfx-rs/wgpu/pull/5229) - Fix docs.rs wasm32 builds. By @cwfitzgerald in [#5310](https://github.com/gfx-rs/wgpu/pull/5310) @@ -1395,9 +2192,11 @@ This release includes `wgpu`, `wgpu-core`, `wgpu-hal`, `wgpu-types`, and `naga`. - Fix missing validation for `Device::clear_buffer` where `offset + size > buffer.size` was not checked when `size` was omitted. By @ErichDonGubler in [#5282](https://github.com/gfx-rs/wgpu/pull/5282). #### DX12 + - Fix `panic!` when dropping `Instance` without `InstanceFlags::VALIDATION`. By @hakolao in [#5134](https://github.com/gfx-rs/wgpu/pull/5134) #### OpenGL + - Fix internal format for the `Etc2Rgba8Unorm` format. By @andristarr in [#5178](https://github.com/gfx-rs/wgpu/pull/5178) - Try to load `libX11.so.6` in addition to `libX11.so` on linux. [#5307](https://github.com/gfx-rs/wgpu/pull/5307) - Make use of `GL_EXT_texture_shadow_lod` to support sampling a cube depth texture with an explicit LOD. By @cmrschwarz in #[5171](https://github.com/gfx-rs/wgpu/pull/5171). @@ -1406,7 +2205,6 @@ This release includes `wgpu`, `wgpu-core`, `wgpu-hal`, `wgpu-types`, and `naga`. - Fix code generation from nested loops. By @cwfitzgerald and @teoxoy in [#5311](https://github.com/gfx-rs/wgpu/pull/5311) - ## v0.19.1 (2024-01-22) This release includes `wgpu` and `wgpu-hal`. The rest of the crates are unchanged since 0.19.0. @@ -1431,10 +2229,10 @@ This release includes `wgpu` and `wgpu-hal`. The rest of the crates are unchange - Document Wayland specific behavior related to `SurfaceTexture::present`. By @i509VCB in [#5093](https://github.com/gfx-rs/wgpu/pull/5093). - ## v0.19.0 (2024-01-17) This release includes: + - `wgpu` - `wgpu-core` - `wgpu-hal` @@ -1456,6 +2254,7 @@ By @gents83 in [#3626](https://github.com/gfx-rs/wgpu/pull/3626) and thanks also All of wgpu's public dependencies are now re-exported at the top level so that users don't need to take their own dependencies. This includes: + - wgpu-core - wgpu-hal - naga @@ -1502,6 +2301,7 @@ By @i509VCB in [#4754](https://github.com/gfx-rs/wgpu/pull/4754). ### `DeviceExt::create_texture_with_data` allows Mip-Major Data Previously, `DeviceExt::create_texture_with_data` only allowed data to be provided in layer major order. There is now a `order` parameter which allows you to specify if the data is in layer major or mip major order. + ```diff let tex = ctx.device.create_texture_with_data( &queue, @@ -1521,6 +2321,7 @@ Passing an owned value `window` to `Surface` will return a `wgpu::Surface<'stati All possible safe variants (owned windows and web canvases) are grouped using `wgpu::SurfaceTarget`. Conversion to `wgpu::SurfaceTarget` is automatic for any type implementing `raw-window-handle`'s `HasWindowHandle` & `HasDisplayHandle` traits, i.e. most window types. For web canvas types this has to be done explicitly: + ```rust let surface: wgpu::Surface<'static> = instance.create_surface(wgpu::SurfaceTarget::Canvas(my_canvas))?; ``` @@ -1530,12 +2331,15 @@ All unsafe variants are now grouped under `wgpu::Instance::create_surface_unsafe In order to create a `wgpu::Surface<'static>` without passing ownership of the window use `wgpu::SurfaceTargetUnsafe::from_window`: + ```rust let surface = unsafe { instance.create_surface_unsafe(wgpu::SurfaceTargetUnsafe::from_window(&my_window))? }; ``` + The easiest way to make this code safe is to use shared ownership: + ```rust let window: Arc; // ... @@ -1554,32 +2358,38 @@ Abstract types make numeric literals easier to use, by automatically converting literals and other constant expressions from abstract numeric types to concrete types when safe and necessary. For example, to build a vector of floating-point -numbers, Naga previously made you write: +numbers, naga previously made you write: + ```rust vec3(1.0, 2.0, 3.0) ``` + With this change, you can now simply write: + ```rust vec3(1, 2, 3) ``` -Even though the literals are abstract integers, Naga recognizes + +Even though the literals are abstract integers, naga recognizes that it is safe and necessary to convert them to `f32` values in order to build the vector. You can also use abstract values as initializers for global constants and global and local variables, like this: + ```rust var unit_x: vec2 = vec2(1, 0); ``` + The literals `1` and `0` are abstract integers, and the expression -`vec2(1, 0)` is an abstract vector. However, Naga recognizes that +`vec2(1, 0)` is an abstract vector. However, naga recognizes that it can convert that to the concrete type `vec2` to satisfy the given type of `unit_x`. The WGSL specification permits abstract integers and -floating-point values in almost all contexts, but Naga's support +floating-point values in almost all contexts, but naga's support for this is still incomplete. Many WGSL operators and builtin functions are specified to produce abstract results when applied -to abstract inputs, but for now Naga simply concretizes them all -before applying the operation. We will expand Naga's abstract type +to abstract inputs, but for now naga simply concretizes them all +before applying the operation. We will expand naga's abstract type support in subsequent pull requests. As part of this work, the public types `naga::ScalarKind` and `naga::Literal` now have new variants, `AbstractInt` and `AbstractFloat`. @@ -1612,6 +2422,7 @@ By @cwfitzgerald in [#5053](https://github.com/gfx-rs/wgpu/pull/5053) ### New Features #### General + - Added `DownlevelFlags::VERTEX_AND_INSTANCE_INDEX_RESPECTS_RESPECTIVE_FIRST_VALUE_IN_INDIRECT_DRAW` to know if `@builtin(vertex_index)` and `@builtin(instance_index)` will respect the `first_vertex` / `first_instance` in indirect calls. If this is not present, both will always start counting from 0. Currently enabled on all backends except DX12. By @cwfitzgerald in [#4722](https://github.com/gfx-rs/wgpu/pull/4722). - Added support for the `FLOAT32_FILTERABLE` feature (web and native, corresponds to WebGPU's `float32-filterable`). By @almarklein in [#4759](https://github.com/gfx-rs/wgpu/pull/4759). - GPU buffer memory is released during "lose the device". By @bradwerth in [#4851](https://github.com/gfx-rs/wgpu/pull/4851). @@ -1626,18 +2437,19 @@ By @cwfitzgerald in [#5053](https://github.com/gfx-rs/wgpu/pull/5053) - `SurfaceConfiguration` now exposes `desired_maximum_frame_latency` which was previously hard-coded to 2. By setting it to 1 you can reduce latency under the risk of making GPU & CPU work sequential. Currently, on DX12 this affects the `MaximumFrameLatency`, on all other backends except OpenGL the size of the swapchain (on OpenGL this has no effect). By @emilk & @wumpf in [#4899](https://github.com/gfx-rs/wgpu/pull/4899) #### OpenGL + - `@builtin(instance_index)` now properly reflects the range provided in the draw call instead of always counting from 0. By @cwfitzgerald in [#4722](https://github.com/gfx-rs/wgpu/pull/4722). - Desktop GL now supports `POLYGON_MODE_LINE` and `POLYGON_MODE_POINT`. By @valaphee in [#4836](https://github.com/gfx-rs/wgpu/pull/4836). -#### Naga +#### naga -- Naga's WGSL front end now allows operators to produce values with abstract types, rather than concretizing their operands. By @jimblandy in [#4850](https://github.com/gfx-rs/wgpu/pull/4850) and [#4870](https://github.com/gfx-rs/wgpu/pull/4870). -- Naga's WGSL front and back ends now have experimental support for 64-bit floating-point literals: `1.0lf` denotes an `f64` value. There has been experimental support for an `f64` type for a while, but until now there was no syntax for writing literals with that type. As before, Naga module validation rejects `f64` values unless `naga::valid::Capabilities::FLOAT64` is requested. By @jimblandy in [#4747](https://github.com/gfx-rs/wgpu/pull/4747). -- Naga constant evaluation can now process binary operators whose operands are both vectors. By @jimblandy in [#4861](https://github.com/gfx-rs/wgpu/pull/4861). -- Add `--bulk-validate` option to Naga CLI. By @jimblandy in [#4871](https://github.com/gfx-rs/wgpu/pull/4871). -- Naga's `cargo xtask validate` now runs validation jobs in parallel, using the [jobserver](https://crates.io/crates/jobserver) protocol to limit concurrency, and offers a `validate all` subcommand, which runs all available validation types. By @jimblandy in [#4902](https://github.com/gfx-rs/wgpu/pull/4902). +- naga's WGSL front end now allows operators to produce values with abstract types, rather than concretizing their operands. By @jimblandy in [#4850](https://github.com/gfx-rs/wgpu/pull/4850) and [#4870](https://github.com/gfx-rs/wgpu/pull/4870). +- naga's WGSL front and back ends now have experimental support for 64-bit floating-point literals: `1.0lf` denotes an `f64` value. There has been experimental support for an `f64` type for a while, but until now there was no syntax for writing literals with that type. As before, naga module validation rejects `f64` values unless `naga::valid::Capabilities::FLOAT64` is requested. By @jimblandy in [#4747](https://github.com/gfx-rs/wgpu/pull/4747). +- naga constant evaluation can now process binary operators whose operands are both vectors. By @jimblandy in [#4861](https://github.com/gfx-rs/wgpu/pull/4861). +- Add `--bulk-validate` option to naga CLI. By @jimblandy in [#4871](https://github.com/gfx-rs/wgpu/pull/4871). +- naga's `cargo xtask validate` now runs validation jobs in parallel, using the [jobserver](https://crates.io/crates/jobserver) protocol to limit concurrency, and offers a `validate all` subcommand, which runs all available validation types. By @jimblandy in [#4902](https://github.com/gfx-rs/wgpu/pull/4902). - Remove `span` and `validate` features. Always fully validate shader modules, and always track source positions for use in error messages. By @teoxoy in [#4706](https://github.com/gfx-rs/wgpu/pull/4706). -- Introduce a new `Scalar` struct type for use in Naga's IR, and update all frontend, middle, and backend code appropriately. By @jimblandy in [#4673](https://github.com/gfx-rs/wgpu/pull/4673). +- Introduce a new `Scalar` struct type for use in naga's IR, and update all frontend, middle, and backend code appropriately. By @jimblandy in [#4673](https://github.com/gfx-rs/wgpu/pull/4673). - Add more metal keywords. By @fornwall in [#4707](https://github.com/gfx-rs/wgpu/pull/4707). - Add a new `naga::Literal` variant, `I64`, for signed 64-bit literals. [#4711](https://github.com/gfx-rs/wgpu/pull/4711). - Emit and init `struct` member padding always. By @ErichDonGubler in [#4701](https://github.com/gfx-rs/wgpu/pull/4701). @@ -1671,14 +2483,14 @@ By @cwfitzgerald in [#5053](https://github.com/gfx-rs/wgpu/pull/5053) - Create a hidden window per `wgpu::Instance` instead of sharing a global one. By @Zoxc in [#4603](https://github.com/gfx-rs/wgpu/issues/4603) -#### Naga +#### naga - Make module compaction preserve the module's named types, even if they are unused. By @jimblandy in [#4734](https://github.com/gfx-rs/wgpu/pull/4734). - Improve algorithm used by module compaction. By @jimblandy in [#4662](https://github.com/gfx-rs/wgpu/pull/4662). - When reading GLSL, fix the argument types of the double-precision floating-point overloads of the `dot`, `reflect`, `distance`, and `ldexp` builtin functions. Correct the WGSL generated for constructing 64-bit floating-point matrices. Add tests for all the above. By @jimblandy in [#4684](https://github.com/gfx-rs/wgpu/pull/4684). -- Allow Naga's IR types to represent matrices with elements elements of any scalar kind. This makes it possible for Naga IR types to represent WGSL abstract matrices. By @jimblandy in [#4735](https://github.com/gfx-rs/wgpu/pull/4735). +- Allow naga's IR types to represent matrices with elements elements of any scalar kind. This makes it possible for naga IR types to represent WGSL abstract matrices. By @jimblandy in [#4735](https://github.com/gfx-rs/wgpu/pull/4735). - Preserve the source spans for constants and expressions correctly across module compaction. By @jimblandy in [#4696](https://github.com/gfx-rs/wgpu/pull/4696). -- Record the names of WGSL `alias` declarations in Naga IR `Type`s. By @jimblandy in [#4733](https://github.com/gfx-rs/wgpu/pull/4733). +- Record the names of WGSL `alias` declarations in naga IR `Type`s. By @jimblandy in [#4733](https://github.com/gfx-rs/wgpu/pull/4733). #### Metal @@ -1696,7 +2508,8 @@ This release includes `naga` version 0.14.2. The crates `wgpu-core`, `wgpu-hal` ### Bug Fixes -#### Naga +#### naga + - When evaluating const-expressions and generating SPIR-V, properly handle `Compose` expressions whose operands are `Splat` expressions. Such expressions are created and marked as constant by the constant evaluator. By @jimblandy in [#4695](https://github.com/gfx-rs/wgpu/pull/4695). ## v0.18.1 (2023-11-15) @@ -1706,15 +2519,18 @@ This release includes `naga` version 0.14.2. The crates `wgpu-core`, `wgpu-hal` ### Bug Fixes #### General + - Fix panic in `Surface::configure` in debug builds. By @cwfitzgerald in [#4635](https://github.com/gfx-rs/wgpu/pull/4635) - Fix crash when all the following are true: By @teoxoy in #[#4642](https://github.com/gfx-rs/wgpu/pull/4642) - Passing a naga module directly to `Device::create_shader_module`. - `InstanceFlags::DEBUG` is enabled. #### DX12 + - Always use HLSL 2018 when using DXC to compile HLSL shaders. By @daxpedda in [#4629](https://github.com/gfx-rs/wgpu/pull/4629) #### Metal + - In Metal Shading Language output, fix issue where local variables were sometimes using variable names from previous functions. By @DJMcNab in [#4594](https://github.com/gfx-rs/wgpu/pull/4594) ## v0.18.0 (2023-10-25) @@ -1886,7 +2702,7 @@ By @teoxoy in [#4185](https://github.com/gfx-rs/wgpu/pull/4185) ### Added/New Features -- Re-export Naga. By @exrook in [#4172](https://github.com/gfx-rs/wgpu/pull/4172) +- Re-export naga. By @exrook in [#4172](https://github.com/gfx-rs/wgpu/pull/4172) - Add WinUI 3 SwapChainPanel support. By @ddrboxman in [#4191](https://github.com/gfx-rs/wgpu/pull/4191) ### Changes @@ -1910,7 +2726,6 @@ By @teoxoy in [#4185](https://github.com/gfx-rs/wgpu/pull/4185) - Allow filtering labels out before they are passed to GPU drivers by @nical in [https://github.com/gfx-rs/wgpu/pull/4246](4246) - `DeviceLostClosure` callback mechanism provided so user agents can resolve `GPUDevice.lost` Promises at the appropriate time by @bradwerth in [#4645](https://github.com/gfx-rs/wgpu/pull/4645) - #### Vulkan - Rename `wgpu_hal::vulkan::Instance::required_extensions` to `desired_extensions`. By @jimblandy in [#4115](https://github.com/gfx-rs/wgpu/pull/4115) @@ -2039,7 +2854,6 @@ By @fornwall in [#3904](https://github.com/gfx-rs/wgpu/pull/3904) and [#3905](ht - Added support for importing external buffers using `buffer_from_raw` (Dx12, Metal, Vulkan) and `create_buffer_from_hal`. By @AdrianEddy in [#3355](https://github.com/gfx-rs/wgpu/pull/3355) - #### Vulkan - Work around [Vulkan-ValidationLayers#5671](https://github.com/KhronosGroup/Vulkan-ValidationLayers/issues/5671) by ignoring reports of violations of [VUID-vkCmdEndDebugUtilsLabelEXT-commandBuffer-01912](https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-vkCmdEndDebugUtilsLabelEXT-commandBuffer-01912). By @jimblandy in [#3809](https://github.com/gfx-rs/wgpu/pull/3809). @@ -2128,7 +2942,7 @@ By @fornwall in [#3904](https://github.com/gfx-rs/wgpu/pull/3904) and [#3905](ht #### WebGPU -* Fix crash when calling `create_surface_from_canvas`. By @grovesNL in [#3718](https://github.com/gfx-rs/wgpu/pull/3718) +- Fix crash when calling `create_surface_from_canvas`. By @grovesNL in [#3718](https://github.com/gfx-rs/wgpu/pull/3718) ## v0.16.0 (2023-04-19) @@ -2147,7 +2961,6 @@ By @fornwall in [#3904](https://github.com/gfx-rs/wgpu/pull/3904) and [#3905](ht The `TextureFormat::describe` function was removed in favor of separate functions: `block_dimensions`, `is_compressed`, `is_srgb`, `required_features`, `guaranteed_format_features`, `sample_type` and `block_size`. - ```diff - let block_dimensions = format.describe().block_dimensions; + let block_dimensions = format.block_dimensions(); @@ -2240,6 +3053,7 @@ By @cwfitzgerald in [#3671](https://github.com/gfx-rs/wgpu/pull/3671). ### Added/New Features #### General + - Added feature flags for ray-tracing (currently only hal): `RAY_QUERY` and `RAY_TRACING` @daniel-keitel (started by @expenses) in [#3507](https://github.com/gfx-rs/wgpu/pull/3507) #### Vulkan @@ -2250,7 +3064,6 @@ By @cwfitzgerald in [#3671](https://github.com/gfx-rs/wgpu/pull/3671). - Added basic ray-tracing api for acceleration structures, and ray-queries @daniel-keitel (started by @expenses) in [#3507](https://github.com/gfx-rs/wgpu/pull/3507) - ### Changes #### General @@ -2277,12 +3090,14 @@ By @cwfitzgerald in [#3671](https://github.com/gfx-rs/wgpu/pull/3671). - Add support for `Features::RG11B10UFLOAT_RENDERABLE`. By @mockersf in [#3689](https://github.com/gfx-rs/wgpu/pull/3689) #### Vulkan + - Set `max_memory_allocation_size` via `PhysicalDeviceMaintenance3Properties`. By @jinleili in [#3567](https://github.com/gfx-rs/wgpu/pull/3567) - Silence false-positive validation error about surface resizing. By @seabassjh in [#3627](https://github.com/gfx-rs/wgpu/pull/3627) ### Bug Fixes #### General + - `copyTextureToTexture` src/dst aspects must both refer to all aspects of src/dst format. By @teoxoy in [#3431](https://github.com/gfx-rs/wgpu/pull/3431) - Validate before extracting texture selectors. By @teoxoy in [#3487](https://github.com/gfx-rs/wgpu/pull/3487) - Fix fatal errors (those which panic even if an error handler is set) not including all of the details. By @kpreid in [#3563](https://github.com/gfx-rs/wgpu/pull/3563) @@ -2290,27 +3105,33 @@ By @cwfitzgerald in [#3671](https://github.com/gfx-rs/wgpu/pull/3671). - Fix surfaces not being dropped until exit. By @benjaminschaaf in [#3647](https://github.com/gfx-rs/wgpu/pull/3647) #### WebGPU + - Fix handling of `None` values for `depth_ops` and `stencil_ops` in `RenderPassDescriptor::depth_stencil_attachment`. By @niklaskorz in [#3660](https://github.com/gfx-rs/wgpu/pull/3660) - Avoid using `WasmAbi` functions for WebGPU backend. By @grovesNL in [#3657](https://github.com/gfx-rs/wgpu/pull/3657) #### DX12 + - Use typeless formats for textures that might be viewed as srgb or non-srgb. By @teoxoy in [#3555](https://github.com/gfx-rs/wgpu/pull/3555) #### GLES + - Set FORCE_POINT_SIZE if it is vertex shader with mesh consist of point list. By @REASY in [3440](https://github.com/gfx-rs/wgpu/pull/3440) - Remove unwraps inside `surface.configure`. By @cwfitzgerald in [#3585](https://github.com/gfx-rs/wgpu/pull/3585) - Fix `copy_external_image_to_texture`, `copy_texture_to_texture` and `copy_buffer_to_texture` not taking the specified index into account if the target texture is a cube map, 2D texture array or cube map array. By @daxpedda [#3641](https://github.com/gfx-rs/wgpu/pull/3641) - Fix disabling of vertex attributes with non-consecutive locations. By @Azorlogh in [#3706](https://github.com/gfx-rs/wgpu/pull/3706) #### Metal + - Fix metal erroring on an `array_stride` of 0. By @teoxoy in [#3538](https://github.com/gfx-rs/wgpu/pull/3538) - `create_texture` returns an error if `new_texture` returns NULL. By @jinleili in [#3554](https://github.com/gfx-rs/wgpu/pull/3554) - Fix shader bounds checking being ignored. By @FL33TW00D in [#3603](https://github.com/gfx-rs/wgpu/pull/3603) #### Vulkan + - Treat `VK_SUBOPTIMAL_KHR` as `VK_SUCCESS` on Android due to rotation issues. By @James2022-rgb in [#3525](https://github.com/gfx-rs/wgpu/pull/3525) ### Examples + - Use `BufferUsages::QUERY_RESOLVE` instead of `BufferUsages::COPY_DST` for buffers used in `CommandEncoder::resolve_query_set` calls in `mipmap` example. By @JolifantoBambla in [#3489](https://github.com/gfx-rs/wgpu/pull/3489) ## v0.15.3 (2023-03-22) @@ -2318,22 +3139,25 @@ By @cwfitzgerald in [#3671](https://github.com/gfx-rs/wgpu/pull/3671). ### Bug Fixes #### Metal + - Fix incorrect mipmap being sampled when using `MinLod <= 0.0` and `MaxLod >= 32.0` or when the fragment shader samples different Lods in the same quad. By @cwfitzgerald in [#3610](https://github.com/gfx-rs/wgpu/pull/3610). #### GLES + - Fix `Vertex buffer is not big enough for the draw call.` for ANGLE/Web when rendering with instance attributes on a single instance. By @wumpf in [#3596](https://github.com/gfx-rs/wgpu/pull/3596) - Reset all queue state between command buffers in a submit. By @jleibs [#3589](https://github.com/gfx-rs/wgpu/pull/3589) - Reset the state of `SAMPLE_ALPHA_TO_COVERAGE` on queue reset. By @jleibs [#3589](https://github.com/gfx-rs/wgpu/pull/3589) - ## wgpu-0.15.2 (2023-03-08) ### Bug Fixes #### Metal + - Fix definition of `NSOperatingSystemVersion` to avoid potential crashes. By @grovesNL in [#3557](https://github.com/gfx-rs/wgpu/pull/3557) #### GLES + - Enable `WEBGL_debug_renderer_info` before querying unmasked vendor/renderer to avoid crashing on emscripten in [#3519](https://github.com/gfx-rs/wgpu/pull/3519) ## wgpu-0.15.1 (2023-02-09) @@ -2341,29 +3165,37 @@ By @cwfitzgerald in [#3671](https://github.com/gfx-rs/wgpu/pull/3671). ### Changes #### General + - Fix for some minor issues in comments on some features. By @Wumpf in [#3455](https://github.com/gfx-rs/wgpu/pull/3455) #### Vulkan + - Improve format MSAA capabilities detection. By @jinleili in [#3429](https://github.com/gfx-rs/wgpu/pull/3429) #### DX12 + - Update gpu allocator to 0.22. By @Elabajaba in [#3447](https://github.com/gfx-rs/wgpu/pull/3447) #### WebGPU + - Implement `CommandEncoder::clear_buffer`. By @raphlinus in [#3426](https://github.com/gfx-rs/wgpu/pull/3426) ### Bug Fixes #### General + - Re-sort supported surface formats based on srgb-ness. By @cwfitzgerald in [#3444](https://github.com/gfx-rs/wgpu/pull/3444) #### Vulkan + - Fix surface view formats validation error. By @jinleili in [#3432](https://github.com/gfx-rs/wgpu/pull/3432) #### DX12 + - Fix DXC validation issues when using a custom `dxil_path`. By @Elabajaba in [#3434](https://github.com/gfx-rs/wgpu/pull/3434) #### GLES + - Unbind vertex buffers at end of renderpass. By @cwfitzgerald in [#3459](https://github.com/gfx-rs/wgpu/pull/3459) #### WebGPU @@ -2373,14 +3205,13 @@ By @cwfitzgerald in [#3671](https://github.com/gfx-rs/wgpu/pull/3671). ### Documentation #### General -- Build for Wasm on docs.rs. By @daxpedda in [#3462](https://github.com/gfx-rs/wgpu/pull/3428) +- Build for Wasm on docs.rs. By @daxpedda in [#3462](https://github.com/gfx-rs/wgpu/pull/3428) ## wgpu-0.15.0 (2023-01-25) ### Major Changes - #### WGSL Top-Level `let` is now `const` All top level constants are now declared with `const`, catching up with the wgsl spec. @@ -2560,7 +3391,6 @@ By @jimblandy in [#3254](https://github.com/gfx-rs/wgpu/pull/3254). - Implement `queue_validate_write_buffer` by @jinleili in [#3098](https://github.com/gfx-rs/wgpu/pull/3098) - Sync depth/stencil copy restrictions with the spec by @teoxoy in [#3314](https://github.com/gfx-rs/wgpu/pull/3314) - ### Added/New Features #### General @@ -2593,6 +3423,7 @@ By @jimblandy in [#3254](https://github.com/gfx-rs/wgpu/pull/3254). - Sync `TextureFormat.describe` with the spec. By @teoxoy in [3312](https://github.com/gfx-rs/wgpu/pull/3312) #### Metal + - Add a way to create `Device` and `Queue` from raw Metal resources in wgpu-hal. By @AdrianEddy in [#3338](https://github.com/gfx-rs/wgpu/pull/3338) ### Bug Fixes @@ -2617,6 +3448,7 @@ By @jimblandy in [#3254](https://github.com/gfx-rs/wgpu/pull/3254). - Make `make_spirv_raw` and `make_spirv` handle big-endian binaries. By @1e1001 in [#3411](https://github.com/gfx-rs/wgpu/pull/3411). #### Vulkan + - Update ash to 0.37.1+1.3.235 to fix CI breaking by changing a call to the deprecated `debug_utils_set_object_name()` function to `set_debug_utils_object_name()` by @elabajaba in [#3273](https://github.com/gfx-rs/wgpu/pull/3273) - Document and improve extension detection. By @teoxoy in [#3327](https://github.com/gfx-rs/wgpu/pull/3327) - Don't use a pointer to a local copy of a `PhysicalDeviceDriverProperties` struct after it has gone out of scope. In fact, don't make a local copy at all. Introduce a helper function for building `CStr`s from C character arrays, and remove some `unsafe` blocks. By @jimblandy in [#3076](https://github.com/gfx-rs/wgpu/pull/3076). @@ -2627,6 +3459,7 @@ By @jimblandy in [#3254](https://github.com/gfx-rs/wgpu/pull/3254). - Don't re-use `GraphicsCommandList` when `close` or `reset` fails. By @xiaopengli89 in [#3204](https://github.com/gfx-rs/wgpu/pull/3204) #### Metal + - Fix texture view creation with full-resource views when using an explicit `mip_level_count` or `array_layer_count`. By @cwfitzgerald in [#3323](https://github.com/gfx-rs/wgpu/pull/3323) #### GLES @@ -2755,7 +3588,7 @@ both `raw_window_handle::HasRawWindowHandle` and `raw_window_handle::HasRawDispl #### Vulkan - Fix `astc_hdr` formats support by @jinleili in [#2971]](https://github.com/gfx-rs/wgpu/pull/2971) -- Update to Naga b209d911 (2022-9-1) to avoid generating SPIR-V that +- Update to naga b209d911 (2022-9-1) to avoid generating SPIR-V that violates Vulkan valid usage rules `VUID-StandaloneSpirv-Flat-06202` and `VUID-StandaloneSpirv-Flat-04744`. By @jimblandy in [#3008](https://github.com/gfx-rs/wgpu/pull/3008) @@ -2783,7 +3616,7 @@ both `raw_window_handle::HasRawWindowHandle` and `raw_window_handle::HasRawDispl - Update Winit to version 0.27 and raw-window-handle to 0.5 by @wyatt-herkamp in [#2918](https://github.com/gfx-rs/wgpu/pull/2918) - Address Clippy 0.1.63 complaints. By @jimblandy in [#2977](https://github.com/gfx-rs/wgpu/pull/2977) - Don't use `PhantomData` for `IdentityManager`'s `Input` type. By @jimblandy in [#2972](https://github.com/gfx-rs/wgpu/pull/2972) -- Changed Naga variant in ShaderSource to `Cow<'static, Module>`, to allow loading global variables by @daxpedda in [#2903](https://github.com/gfx-rs/wgpu/pull/2903) +- Changed naga variant in ShaderSource to `Cow<'static, Module>`, to allow loading global variables by @daxpedda in [#2903](https://github.com/gfx-rs/wgpu/pull/2903) - Updated the maximum binding index to match the WebGPU specification by @nical in [#2957](https://github.com/gfx-rs/wgpu/pull/2957) - Add `unsafe_op_in_unsafe_fn` to Clippy lints in the entire workspace. By @ErichDonGubler in [#3044](https://github.com/gfx-rs/wgpu/pull/3044). @@ -3116,7 +3949,7 @@ DeviceDescriptor { - [WebGL] Add a downlevel capability for rendering to floating point textures by @expenses in [#2729](https://github.com/gfx-rs/wgpu/pull/2729) - allow creating wgpu::Instance from wgpu_core::Instance by @i509VCB in [#2763](https://github.com/gfx-rs/wgpu/pull/2763) - Force binding sizes to be multiples of 16 on webgl by @cwfitzgerald in [#2808](https://github.com/gfx-rs/wgpu/pull/2808) -- Add Naga variant to ShaderSource by @rttad in [#2801](https://github.com/gfx-rs/wgpu/pull/2801) +- Add naga variant to ShaderSource by @rttad in [#2801](https://github.com/gfx-rs/wgpu/pull/2801) - Implement Queue::write_buffer_with by @teoxoy in [#2777](https://github.com/gfx-rs/wgpu/pull/2777) #### Vulkan @@ -3262,7 +4095,7 @@ DeviceDescriptor { - Explicitly set Vulkan debug message types instead of !empty() by @victorvde in [#2321](https://github.com/gfx-rs/wgpu/pull/2321) - Use stencil read/write masks by @kvark in [#2382](https://github.com/gfx-rs/wgpu/pull/2382) -- Vulkan: correctly set INDEPENDENT_BLEND,make runable on Android 8.x by @jinleili in [#2498](https://github.com/gfx-rs/wgpu/pull/2498) +- Vulkan: correctly set INDEPENDENT_BLEND,make runnable on Android 8.x by @jinleili in [#2498](https://github.com/gfx-rs/wgpu/pull/2498) - Fix ASTC format mapping by @kvark in [#2476](https://github.com/gfx-rs/wgpu/pull/2476) - Support flipped Y on VK 1.1 devices by @cwfitzgerald in [#2512](https://github.com/gfx-rs/wgpu/pull/2512) - Fixed builtin(primitive_index) for vulkan backend by @kwillemsen in [#2716](https://github.com/gfx-rs/wgpu/pull/2716) @@ -3553,7 +4386,7 @@ DeviceDescriptor { - new `PARTIALLY_BOUND_BINDING_ARRAY` - `NON_FILL_POLYGON_MODE` is split into `POLYGON_MODE_LINE` and `POLYGON_MODE_POINT` - fixes: - - many shader-related fixes in Naga-0.7 + - many shader-related fixes in naga-0.7 - fix a panic in resource cleanup happening when they are dropped on another thread - Vulkan: - create SPIR-V per entry point to work around driver bugs @@ -3703,7 +4536,7 @@ DeviceDescriptor { ## v0.8 (2021-04-29) -- Naga is used by default to translate shaders, SPIRV-Cross is optional behind `cross` feature +- naga is used by default to translate shaders, SPIRV-Cross is optional behind `cross` feature - Features: - buffers are zero-initialized - downlevel limits for DX11/OpenGL support @@ -3802,7 +4635,7 @@ DeviceDescriptor { - all transfer operations - all resource creation - bind group matching to the layout - - experimental shader interface matching with Naga + - experimental shader interface matching with naga ### wgpu-core-0.5.6 (2020-07-09) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index be0bddfc1..04aaf6fb9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,18 +1,18 @@ -This document is a guide for contributions to the WGPU project. +This document is a guide for contributions to the wgpu project. ## Welcome! -First of all, welcome to the WGPU community! 👋 We're glad you want to -contribute. If you are unfamiliar with the WGPU project, we recommend you read +First of all, welcome to the wgpu community! 👋 We're glad you want to +contribute. If you are unfamiliar with the wgpu project, we recommend you read [`GOVERNANCE.md`] for an overview of its goals, and how it's governed. ## Documentation Overview: -- [`GOVERNANCE.md`]: An overview of the WGPU project's goals and governance. -- [`CODE_OF_CONDUCT.md`]: The code of conduct for the WGPU project. -- [`docs/release-checklist.md`]: Checklist for creating a new release of WGPU. -- [`docs/review-checklist.md`]: Checklist for reviewing a pull request in WGPU. -- [`docs/testing.md`]: Information on the test suites in WGPU and Naga. +- [`GOVERNANCE.md`]: An overview of the wgpu project's goals and governance. +- [`CODE_OF_CONDUCT.md`]: The code of conduct for the wgpu project. +- [`docs/release-checklist.md`]: Checklist for creating a new release of wgpu. +- [`docs/review-checklist.md`]: Checklist for reviewing a pull request in wgpu. +- [`docs/testing.md`]: Information on the test suites in wgpu and naga. [`GOVERNANCE.md`]: ./GOVERNANCE.md [`CODE_OF_CONDUCT.md`]: ./CODE_OF_CONDUCT.md @@ -20,9 +20,9 @@ contribute. If you are unfamiliar with the WGPU project, we recommend you read [`docs/review-checklist.md`]: ./docs/review-checklist.md [`docs/testing.md`]: ./docs/testing.md -## Talking to other humans in the WGPU project +## Talking to other humans in the wgpu project -The WGPU project has multiple official platforms for community engagement: +The wgpu project has multiple official platforms for community engagement: - The Matrix channel [`wgpu:matrix.org`](https://matrix.to/#/#wgpu:matrix.org) is dedicated to informal chat about contributions the project. It is @@ -73,10 +73,10 @@ The WGPU project has multiple official platforms for community engagement: [Meeting Link]: https://meet.google.com/ubo-ztcw-gwf [`CODE_OF_CONDUCT.md`]: ./CODE_OF_CONDUCT.md -## Contributing to WGPU +## Contributing to wgpu Community response to contributions are, in general, prioritized based on their -relevance to WGPU's mission and decision-making groups' interest (see +relevance to wgpu's mission and decision-making groups' interest (see [`GOVERNANCE.md`]). ### "What can I work on?" as a new contributor @@ -84,24 +84,24 @@ relevance to WGPU's mission and decision-making groups' interest (see TODO We discourage new contributors from submitting large changes or opinionated -refactors unless they have been specifically validated by WGPU maintainership. +refactors unless they have been specifically validated by wgpu maintainership. These are likely to be rejected on basis of needing discussion before a formal review. -### Setting up a WGPU development environment +### Setting up a wgpu development environment -We use the following components in a WGPU development environment: +We use the following components in a wgpu development environment: - [A Rust toolchain][install-rust] matching the version specified in - [`rust-toolchain.toml`](./rust-toolchain.toml), to compile WGPU's code. If you + [`rust-toolchain.toml`](./rust-toolchain.toml), to compile wgpu's code. If you use `rustup`, this will be automatically installed when you first run a `cargo` command in the repository. - [Taplo](https://taplo.tamasfe.dev/) to keep TOML files formatted. - [Vulkan SDK](https://vulkan.lunarg.com/) to provide Vulkan validation layers and other Vulkan/SPIR-V tools for testing. -Once these are done, you should be ready to hack on WGPU! Drop into your -favorite editor, make some changes to the repository's code, and test that WGPU +Once these are done, you should be ready to hack on wgpu! Drop into your +favorite editor, make some changes to the repository's code, and test that wgpu has been changed the way you expect. Take a look at [`docs/testing.md`] for more info on testing. @@ -111,8 +111,8 @@ and a [`git` dependency][git-deps] pointing to your own fork to share changes with other contributors. Once you are ready to request a review of your changes so they become part of -WGPU public history, create a pull request with your changes committed to a -branch in your own fork of WGPU in GitHub. See documentation for that +wgpu public history, create a pull request with your changes committed to a +branch in your own fork of wgpu in GitHub. See documentation for that [here](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request-from-a-fork). [install-rust]: https://www.rust-lang.org/tools/install @@ -157,9 +157,9 @@ assignment is simply to ensure that pull requests don't get neglected. #### Designing new features -As an open source project, WGPU wants to serve a broad audience. This +As an open source project, wgpu wants to serve a broad audience. This helps us cast a wide net for contributors, and widens the impact of -their work. However, WGPU does not promise to incorporate every +their work. However, wgpu does not promise to incorporate every proposed feature. Large efforts that are ultimately rejected tend to burn contributors @@ -176,11 +176,11 @@ Contributors should anticipate that the larger and more complex a pull request is, the less likely it is that reviewers will accept it, regardless of its merits. -The WGPU project has had poor experiences with large, complex pull +The wgpu project has had poor experiences with large, complex pull requests: - Complex pull requests are difficult to review effectively. It is - common for us to debug a problem in WGPU and find that it was + common for us to debug a problem in wgpu and find that it was introduced by some massive pull request that we had reviewed and accepted, showing that we obviously hadn't understood it as well as we'd thought. @@ -190,7 +190,7 @@ requests: stressful to question its design decisions, knowing that changing them will require the author to essentially reimplement the project from scratch. Such pull requests make it hard for maintainers to - uphold their responsibility to keep WGPU maintainable. Incremental + uphold their responsibility to keep wgpu maintainable. Incremental changes are easier to discuss and revise without drama. These problems are serious enough that maintainers may choose to @@ -199,7 +199,7 @@ feature or the technical merit of the code. The problem isn't really the *size* of the pull request: a simple rename, with no changes to functionality, might touch hundreds of -files, but be easy to review. Or, a change to Naga might affect dozens +files, but be easy to review. Or, a change to naga might affect dozens of snapshot test output files, without being hard to understand. Rather, the problem is the *complexity* of the pull request: how many diff --git a/Cargo.lock b/Cargo.lock index f92b10a82..4ad8ea59b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 3 [[package]] name = "ab_glyph" -version = "0.2.29" +version = "0.2.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec3672c180e71eeaaac3a541fbbc5f5ad4def8b747c595ad30d674e43049f7b0" +checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" dependencies = [ "ab_glyph_rasterizer", "owned_ttf_parser", @@ -14,39 +14,33 @@ dependencies = [ [[package]] name = "ab_glyph_rasterizer" -version = "0.1.8" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c71b1793ee61086797f5c80b6efa2b8ffa6d5dd703f118545808a7f2e27f7046" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" [[package]] name = "addr2line" -version = "0.24.2" +version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1" +checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b" dependencies = [ "gimli", ] -[[package]] -name = "adler" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" - [[package]] name = "adler2" -version = "2.0.0" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "ahash" -version = "0.8.11" +version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" dependencies = [ "cfg-if", - "getrandom 0.2.15", + "getrandom 0.3.4", "once_cell", "version_check", "zerocopy", @@ -54,9 +48,9 @@ dependencies = [ [[package]] name = "aho-corasick" -version = "1.1.3" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" dependencies = [ "memchr", ] @@ -68,7 +62,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee91c0c2905bae44f84bfa4e044536541df26b7703fd0888deeb9060fcc44289" dependencies = [ "android-properties", - "bitflags 2.9.0", + "bitflags 2.10.0", "cc", "cesu8", "jni", @@ -89,7 +83,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ef6978589202a00cd7e118380c448a08b6ed394c3a8df3a430d0898e3a42d046" dependencies = [ "android-properties", - "bitflags 2.9.0", + "bitflags 2.10.0", "cc", "cesu8", "jni", @@ -126,9 +120,9 @@ checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" [[package]] name = "anstream" -version = "0.6.18" +version = "0.6.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8acc5369981196006228e28809f761875c0327210a891e941f4c683b3a99529b" +checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" dependencies = [ "anstyle", "anstyle-parse", @@ -141,44 +135,44 @@ dependencies = [ [[package]] name = "anstyle" -version = "1.0.10" +version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" +checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" [[package]] name = "anstyle-parse" -version = "0.2.6" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b2d16507662817a6a20a9ea92df6652ee4f94f914589377d69f3b21bc5798a9" +checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" -version = "1.1.2" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79947af37f4177cfead1110013d678905c37501914fba0efea834c3fe9a8d60c" +checksum = "9e231f6134f61b71076a3eab506c379d4f36122f2af15a9ff04415ea4c3339e2" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.60.2", ] [[package]] name = "anstyle-wincon" -version = "3.0.7" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca3534e77181a9cc07539ad51f2141fe32f6c3ffd4df76db8ad92346b003ae4e" +checksum = "3e0633414522a32ffaac8ac6cc8f748e090c5717661fddeea04219e2344f5f2a" dependencies = [ "anstyle", - "once_cell", - "windows-sys 0.59.0", + "once_cell_polyfill", + "windows-sys 0.60.2", ] [[package]] name = "anyhow" -version = "1.0.97" +version = "1.0.100" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f" +checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61" [[package]] name = "approx" @@ -191,9 +185,9 @@ dependencies = [ [[package]] name = "arbitrary" -version = "1.4.1" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dde20b3d026af13f561bdd0f15edf01fc734f0dafcedbaf42bba506a9517f223" +checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" dependencies = [ "derive_arbitrary", ] @@ -262,9 +256,9 @@ dependencies = [ [[package]] name = "async-trait" -version = "0.1.88" +version = "0.1.89" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e539d3fca749fcee5236ab05e93a52867dd549cc157c8cb7f99595f3cedffdb5" +checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" dependencies = [ "proc-macro2", "quote", @@ -279,9 +273,9 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] name = "autocfg" -version = "1.4.0" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "az" @@ -291,17 +285,17 @@ checksum = "7b7e4c2464d97fe331d41de9d5db0def0a96f4d823b8b32a2efd503578988973" [[package]] name = "backtrace" -version = "0.3.74" +version = "0.3.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a" +checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6" dependencies = [ "addr2line", "cfg-if", "libc", - "miniz_oxide 0.8.3", + "miniz_oxide", "object", "rustc-demangle", - "windows-targets 0.52.6", + "windows-link 0.2.1", ] [[package]] @@ -310,22 +304,13 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" -[[package]] -name = "base64-simd" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "781dd20c3aff0bd194fe7d2a977dd92f21c173891f3a03b677359e5fa457e5d5" -dependencies = [ - "simd-abstraction", -] - [[package]] name = "base64-simd" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "339abbe78e73178762e23bea9dfd08e697eb3f3301cd4be981c0f78ba5859195" dependencies = [ - "outref 0.5.2", + "outref", "vsimd", ] @@ -339,12 +324,32 @@ dependencies = [ ] [[package]] -name = "bindgen" -version = "0.70.1" +name = "bincode" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f" +checksum = "36eaf5d7b090263e8150820482d5d93cd964a81e4019913c972f4edcc6edb740" dependencies = [ - "bitflags 2.9.0", + "bincode_derive", + "serde", + "unty", +] + +[[package]] +name = "bincode_derive" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf95709a440f45e986983918d0e8a1f30a9b1df04918fc828670606804ac3c09" +dependencies = [ + "virtue", +] + +[[package]] +name = "bindgen" +version = "0.71.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3" +dependencies = [ + "bitflags 2.10.0", "cexpr", "clang-sys", "itertools 0.13.0", @@ -353,35 +358,20 @@ dependencies = [ "proc-macro2", "quote", "regex", - "rustc-hash", + "rustc-hash 2.1.1", "shlex", "syn", ] -[[package]] -name = "bit-set" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1" -dependencies = [ - "bit-vec 0.6.3", -] - [[package]] name = "bit-set" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" dependencies = [ - "bit-vec 0.8.0", + "bit-vec", ] -[[package]] -name = "bit-vec" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" - [[package]] name = "bit-vec" version = "0.8.0" @@ -396,12 +386,12 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.9.0" +version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" +checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" dependencies = [ "arbitrary", - "serde", + "serde_core", ] [[package]] @@ -451,25 +441,35 @@ dependencies = [ ] [[package]] -name = "bumpalo" -version = "3.17.0" +name = "boxed_error" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1628fb46dfa0b37568d12e5edd512553eccf6a22a78e8bde00bb4aed84d5bdbf" +checksum = "17d4f95e880cfd28c4ca5a006cf7f6af52b4bcb7b5866f573b2faa126fb7affb" +dependencies = [ + "quote", + "syn", +] + +[[package]] +name = "bumpalo" +version = "3.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" [[package]] name = "bytemuck" -version = "1.22.0" +version = "1.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6b1fc10dbac614ebc03540c9dbd60e83887fda27794998c6528f1782047d540" +checksum = "1fbdf580320f38b612e485521afda1ee26d10cc9884efaaa750d383e13e3c5f4" dependencies = [ "bytemuck_derive", ] [[package]] name = "bytemuck_derive" -version = "1.9.2" +version = "1.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ff22c2722516255d1823ce3cc4bc0b154dbc9364be5c905d6baa6eccbbc8774" +checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff" dependencies = [ "proc-macro2", "quote", @@ -477,10 +477,10 @@ dependencies = [ ] [[package]] -name = "byteorder" -version = "1.5.0" +name = "byteorder-lite" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" [[package]] name = "bytes" @@ -494,10 +494,10 @@ version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fba7adb4dd5aa98e5553510223000e7148f621165ec5f9acd7113f6ca4995298" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "log", "polling", - "rustix", + "rustix 0.38.44", "slab", "thiserror 1.0.69", ] @@ -508,10 +508,10 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "log", "polling", - "rustix", + "rustix 0.38.44", "slab", "thiserror 1.0.69", ] @@ -523,7 +523,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0f0ea9b9476c7fad82841a8dbb380e2eae480c21910feba80725b46931ed8f02" dependencies = [ "calloop 0.12.4", - "rustix", + "rustix 0.38.44", "wayland-backend", "wayland-client", ] @@ -535,27 +535,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" dependencies = [ "calloop 0.13.0", - "rustix", + "rustix 0.38.44", "wayland-backend", "wayland-client", ] [[package]] name = "camino" -version = "1.1.9" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b96ec4966b5813e2c0507c1f86115c8c5abaadc3980879c3424042a02fd1ad3" +checksum = "276a59bf2b2c967788139340c9f0c5b12d7fd6630315c15c217e559de85d2609" dependencies = [ - "serde", -] - -[[package]] -name = "capacity_builder" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58ec49028cb308564429cd8fac4ef21290067a0afe8f5955330a8d487d0d790c" -dependencies = [ - "itoa", + "serde_core", ] [[package]] @@ -580,25 +571,25 @@ dependencies = [ [[package]] name = "cargo-platform" -version = "0.1.9" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea" +checksum = "122ec45a44b270afd1402f351b782c676b173e3c3fb28d86ff7ebfb4d86a4ee4" dependencies = [ "serde", ] [[package]] name = "cargo_metadata" -version = "0.19.2" +version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba" +checksum = "981a6f317983eec002839b90fae7411a85621410ae591a9cab2ecf5cb5744873" dependencies = [ "camino", "cargo-platform", - "semver 1.0.25", + "semver", "serde", "serde_json", - "thiserror 2.0.12", + "thiserror 2.0.17", ] [[package]] @@ -609,10 +600,11 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.2.17" +version = "1.2.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fcb57c740ae1daf453ae85f16e37396f672b039e00d9d866e07ddb24e328e3a" +checksum = "37521ac7aabe3d13122dc382493e20c9416f299d2ccd5b3a5340a2570cdeb0f3" dependencies = [ + "find-msvc-tools", "jobserver", "libc", "shlex", @@ -635,9 +627,9 @@ dependencies = [ [[package]] name = "cfg-if" -version = "1.0.0" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "cfg_aliases" @@ -700,9 +692,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.33" +version = "4.5.51" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2c80cae4c3350dd8f1272c73e83baff9a6ba550b8bfbe651b3c45b78cd1751e" +checksum = "4c26d721170e0295f191a69bd9a1f93efcdb0aff38684b61ab5750468972e5f5" dependencies = [ "clap_builder", "clap_derive", @@ -710,9 +702,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.33" +version = "4.5.51" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0123e386f691c90aa228219b5b1ee72d465e8e231c79e9c82324f016a62a741c" +checksum = "75835f0c7bf681bfd05abe44e965760fea999a5286c6eb2d59883634fd02011a" dependencies = [ "anstream", "anstyle", @@ -722,11 +714,11 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.32" +version = "4.5.49" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09176aae279615badda0765c0c0b3f6ed53f4709118af73cf4655d85d1530cd7" +checksum = "2a0b5487afeab2deb2ff4e03a807ad1a03ac532ff5a2cee5d86884440c7f7671" dependencies = [ - "heck 0.5.0", + "heck", "proc-macro2", "quote", "syn", @@ -734,9 +726,9 @@ dependencies = [ [[package]] name = "clap_lex" -version = "0.7.4" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6" +checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d" [[package]] name = "codespan-reporting" @@ -749,17 +741,11 @@ dependencies = [ "unicode-width", ] -[[package]] -name = "color_quant" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" - [[package]] name = "colorchoice" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" +checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" [[package]] name = "combine" @@ -780,6 +766,19 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "console" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b430743a6eb14e9764d4260d4c0d8123087d504eeb9c48f2b2a5e810dd369df4" +dependencies = [ + "encode_unicode", + "libc", + "once_cell", + "unicode-width", + "windows-sys 0.61.2", +] + [[package]] name = "console_error_panic_hook" version = "0.1.7" @@ -802,9 +801,12 @@ dependencies = [ [[package]] name = "const_panic" -version = "0.2.12" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2459fc9262a1aa204eb4b5764ad4f189caec88aea9634389c0a25f8be7f6265e" +checksum = "e262cdaac42494e3ae34c43969f9cdeb7da178bdb4b66fa6a1ea2edb4c8ae652" +dependencies = [ + "typewit", +] [[package]] name = "cooked-waker" @@ -822,6 +824,16 @@ dependencies = [ "libc", ] +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -835,8 +847,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" dependencies = [ "bitflags 1.3.2", - "core-foundation", - "core-graphics-types", + "core-foundation 0.9.4", + "core-graphics-types 0.1.3", "foreign-types", "libc", ] @@ -848,40 +860,48 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" dependencies = [ "bitflags 1.3.2", - "core-foundation", + "core-foundation 0.9.4", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" +dependencies = [ + "bitflags 2.10.0", + "core-foundation 0.10.1", "libc", ] [[package]] name = "crc32fast" -version = "1.4.2" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" dependencies = [ "cfg-if", ] [[package]] name = "criterion" -version = "0.5.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f" +checksum = "e1c047a62b0cc3e145fa84415a3191f628e980b194c2755aa12300a4e6cbd928" dependencies = [ "anes", "cast", "ciborium", "clap", "criterion-plot", - "is-terminal", - "itertools 0.10.5", + "itertools 0.13.0", "num-traits", - "once_cell", "oorandom", "plotters", "rayon", "regex", "serde", - "serde_derive", "serde_json", "tinytemplate", "walkdir", @@ -889,12 +909,12 @@ dependencies = [ [[package]] name = "criterion-plot" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1" +checksum = "9b1bcc0dc7dfae599d84ad0b1a55f80cde8af3725da8313b528da95ef783e338" dependencies = [ "cast", - "itertools 0.10.5", + "itertools 0.13.0", ] [[package]] @@ -924,45 +944,54 @@ checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" [[package]] name = "crunchy" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43da5946c66ffcc7745f48db692ffbb10a83bfe0afd96235c5c2a4fb23994929" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" [[package]] name = "ctor" -version = "0.2.9" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a2785755761f3ddc1492979ce1e48d2c00d09311c39e4466429188f3dd6501" +checksum = "59c9b8bdf64ee849747c1b12eb861d21aa47fa161564f48332f1afe2373bf899" dependencies = [ - "quote", - "syn", + "ctor-proc-macro", + "dtor", ] +[[package]] +name = "ctor-proc-macro" +version = "0.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52560adf09603e58c9a7ee1fe1dcb95a16927b17c127f0ac02d6e768a0e25bc1" + [[package]] name = "cts_runner" -version = "0.1.0" +version = "27.0.0" dependencies = [ "deno_console", "deno_core", + "deno_features", "deno_url", "deno_web", "deno_webgpu", "deno_webidl", + "env_logger", + "tempfile", "termcolor", "tokio", ] [[package]] name = "cursor-icon" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96a6ac251f4a2aca6b3f91340350eab87ae57c3f127ffeb585e92bd336717991" +checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" [[package]] name = "data-encoding" -version = "2.8.0" +version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "575f75dfd25738df5b91b8e43e14d44bda14637a58fae779fd2b064f8bf3e010" +checksum = "2a2330da5de22e8a3cb63252ce2abb30116bf5265e89c0e01bc17015ce30a476" [[package]] name = "debugid" @@ -976,26 +1005,27 @@ dependencies = [ [[package]] name = "deno_console" -version = "0.190.0" +version = "0.214.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94352b8d75c288a26ef748ad0ddae07e181109374a02c547850f96eef76b5389" +checksum = "74189b98d1245bcef3a7565cbfe5cad4ab3d2ad9393aa48067fab89efe85a99b" dependencies = [ "deno_core", ] [[package]] name = "deno_core" -version = "0.336.0" +version = "0.355.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdd50476c4325d5fa52bb906804a1e35b127d2a1dcf674e3447b53dcf25525bf" +checksum = "775d2fde80a2ec3116d179703b38346a931bb9626f4a826148d5fe8631cab29f" dependencies = [ "anyhow", "az", - "bincode", - "bit-set 0.5.3", - "bit-vec 0.6.3", + "bincode 1.3.3", + "bit-set", + "bit-vec", + "boxed_error", "bytes", - "capacity_builder 0.1.3", + "capacity_builder", "cooked-waker", "deno_core_icudata", "deno_error", @@ -1005,7 +1035,6 @@ dependencies = [ "futures", "indexmap", "libc", - "memoffset", "parking_lot", "percent-encoding", "pin-project", @@ -1015,7 +1044,7 @@ dependencies = [ "smallvec", "sourcemap", "static_assertions", - "thiserror 2.0.12", + "thiserror 2.0.17", "tokio", "url", "v8", @@ -1030,9 +1059,9 @@ checksum = "fe4dccb6147bb3f3ba0c7a48e993bfeb999d2c2e47a81badee80e2b370c8d695" [[package]] name = "deno_error" -version = "0.5.5" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c23dbc46d5804814b08b4675838f9884e3a52916987ec5105af36d42f9911b5" +checksum = "dde60bd153886964234c5012d3d9caf788287f28d81fb24a884436904101ef10" dependencies = [ "deno_error_macro", "libc", @@ -1044,9 +1073,9 @@ dependencies = [ [[package]] name = "deno_error_macro" -version = "0.5.5" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "babccedee31ce7e57c3e6dff2cb3ab8d68c49d0df8222fe0d11d628e65192790" +checksum = "409f265785bd946d3006756955aaf40b0e4deb25752eae6a990afe54a31cfd83" dependencies = [ "proc-macro2", "quote", @@ -1054,55 +1083,73 @@ dependencies = [ ] [[package]] -name = "deno_ops" -version = "0.212.0" +name = "deno_features" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2d328067139909aa81522a5d90f119368b541fbddd73ab630e4d9f777865f0d" +checksum = "ea79a01229bd5f8ee4ba784811f421a90a1ac241da4dc015a3f58380167c9944" +dependencies = [ + "deno_core", + "serde", + "serde_json", +] + +[[package]] +name = "deno_ops" +version = "0.231.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ca530772bbcbc9ad389ad7bcd86623b2ec555f68a2d062d23cc008915cbe781" dependencies = [ "indexmap", "proc-macro-rules", "proc-macro2", "quote", "stringcase", - "strum 0.25.0", - "strum_macros 0.25.3", + "strum", + "strum_macros", "syn", - "thiserror 2.0.12", + "thiserror 2.0.17", ] [[package]] name = "deno_path_util" -version = "0.3.1" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c87b8996966ae1b13ee9c20219b1d10fc53905b9570faae6adfa34614fd15224" +checksum = "bfe02936964b2910719bd488841f6e884349360113c7abf6f4c6b28ca9cd7a19" dependencies = [ "deno_error", "percent-encoding", "sys_traits", - "thiserror 2.0.12", + "thiserror 2.0.17", "url", ] [[package]] name = "deno_permissions" -version = "0.49.0" +version = "0.73.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abf879dff0b3de4dbcb78d6dda3a55e711369d5b9f479270a82853ef106c4176" +checksum = "656d8cc364ca906e12fb83d379202983052c6aa3e7420e385559e903d2773f61" dependencies = [ - "capacity_builder 0.5.0", - "deno_core", + "capacity_builder", "deno_error", "deno_path_util", "deno_terminal", + "deno_unsync", "fqdn", + "ipnetwork", "libc", "log", + "nix", "once_cell", + "parking_lot", "percent-encoding", "serde", - "thiserror 2.0.12", - "which", + "serde_json", + "sys_traits", + "thiserror 2.0.17", + "url", + "which 8.0.0", "winapi", + "windows-sys 0.59.0", ] [[package]] @@ -1117,35 +1164,34 @@ dependencies = [ [[package]] name = "deno_unsync" -version = "0.4.2" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d774fd83f26b24f0805a6ab8b26834a0d06ceac0db517b769b1e4633c96a2057" +checksum = "6742a724e8becb372a74c650a1aefb8924a5b8107f7d75b3848763ea24b27a87" dependencies = [ - "futures", + "futures-util", "parking_lot", "tokio", ] [[package]] name = "deno_url" -version = "0.190.0" +version = "0.214.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d79e743ad841f7826d46c6944580f5ba665fe9ab4c31a68c4eed8b5a78225da3" +checksum = "a4f02fd80dda41f1e278c69170b802004c0094ceef2dde68bc117a69dc5702cf" dependencies = [ "deno_core", "deno_error", - "thiserror 2.0.12", "urlpattern", ] [[package]] name = "deno_web" -version = "0.221.0" +version = "0.245.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8041ba73bb2f238c61b5e4ed341d2fe1f9464a71115a240ab3390480b3c10e12" +checksum = "56fbbfb92fa76a4e0873d1b02f5e9947562e70ac7ec065ba794b08aca3760564" dependencies = [ "async-trait", - "base64-simd 0.8.0", + "base64-simd", "bytes", "deno_core", "deno_error", @@ -1154,14 +1200,14 @@ dependencies = [ "flate2", "futures", "serde", - "thiserror 2.0.12", + "thiserror 2.0.17", "tokio", "uuid", ] [[package]] name = "deno_webgpu" -version = "0.157.0" +version = "0.181.0" dependencies = [ "deno_core", "deno_error", @@ -1170,7 +1216,7 @@ dependencies = [ "raw-window-handle 0.6.2", "serde", "serde_json", - "thiserror 2.0.12", + "thiserror 2.0.17", "tokio", "wgpu-core", "wgpu-types", @@ -1178,18 +1224,18 @@ dependencies = [ [[package]] name = "deno_webidl" -version = "0.190.0" +version = "0.214.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4ff81a990196bf3a80fe5d339b4eb8b411ef17634d60d399a63bae6e71a37c9" +checksum = "b29a947a96dc0f672741669470f0260eba20d198436143b40afb9bda97723f07" dependencies = [ "deno_core", ] [[package]] name = "derive_arbitrary" -version = "1.4.1" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30542c1ad912e0e3d22a1935c290e12e8a29d704a420177a31faad4a601a0800" +checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" dependencies = [ "proc-macro2", "quote", @@ -1230,9 +1276,9 @@ dependencies = [ [[package]] name = "document-features" -version = "0.2.11" +version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95249b50c6c185bee49034bcb378a49dc2b5dff0be90ff6616d31d64febab05d" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" dependencies = [ "litrs", ] @@ -1245,9 +1291,24 @@ checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" [[package]] name = "dpi" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f25c0e292a7ca6d6498557ff1df68f32c99850012b6ea401cf8daf771f22ff53" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" + +[[package]] +name = "dtor" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e58a0764cddb55ab28955347b45be00ade43d4d6f3ba4bf3dc354e4ec9432934" +dependencies = [ + "dtor-proc-macro", +] + +[[package]] +name = "dtor-proc-macro" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f678cf4a922c215c63e0de95eb1ff08a958a81d47e485cf9da1e27bf6305cfa5" [[package]] name = "either" @@ -1257,30 +1318,29 @@ checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" [[package]] name = "encase" -version = "0.10.0" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0a05902cf601ed11d564128448097b98ebe3c6574bd7b6a653a3d56d54aa020" +checksum = "6e3e0ff2ee0b7aa97428308dd9e1e42369cb22f5fb8dc1c55546637443a60f1e" dependencies = [ "const_panic", "encase_derive", - "glam", - "thiserror 1.0.69", + "thiserror 2.0.17", ] [[package]] name = "encase_derive" -version = "0.10.0" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "181d475b694e2dd56ae919ce7699d344d1fd259292d590c723a50d1189a2ea85" +checksum = "a4d90c5d7d527c6cb8a3b114efd26a6304d9ab772656e73d8f4e32b1f3d601a2" dependencies = [ "encase_derive_impl", ] [[package]] name = "encase_derive_impl" -version = "0.10.0" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f97b51c5cc57ef7c5f7a0c57c250251c49ee4c28f819f87ac32f4aceabc36792" +checksum = "c8bad72d8308f7a382de2391ec978ddd736e0103846b965d7e2a63a75768af30" dependencies = [ "proc-macro2", "quote", @@ -1288,29 +1348,41 @@ dependencies = [ ] [[package]] -name = "encoding_rs" -version = "0.8.33" +name = "encode_unicode" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7268b386296a025e474d5140678f75d6de9493ae55a5d709eeb9dd08149945e1" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" dependencies = [ "cfg-if", ] [[package]] name = "env_filter" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "186e05a59d4c50738528153b83b0b0194d3a29507dfec16eccd4b342903397d0" +checksum = "1bf3c259d255ca70051b30e2e95b5446cdb8949ac4cd22c0d7fd634d89f568e2" dependencies = [ "log", "regex", ] [[package]] -name = "env_logger" -version = "0.11.7" +name = "env_home" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3716d7a920fb4fac5d84e9d4bce8ceb321e9414b4409da61b07b75c1e3d0697" +checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe" + +[[package]] +name = "env_logger" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c863f0904021b108aa8b2f55046443e6b1ebde8fd4a15c399893aae4fa069f" dependencies = [ "anstream", "anstyle", @@ -1327,12 +1399,12 @@ checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] name = "errno" -version = "0.3.10" +version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -1365,6 +1437,12 @@ dependencies = [ "log", ] +[[package]] +name = "find-msvc-tools" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52051878f80a721bb68ebfbc930e07b65ba72f2da88968ea5c06fd6ca3d3a127" + [[package]] name = "fixedbitset" version = "0.4.2" @@ -1379,12 +1457,12 @@ checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" [[package]] name = "flate2" -version = "1.0.35" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c936bfdafb507ebbf50b8074c54fa31c5be9a1e7e5f467dd659697041407d07c" +checksum = "bfe33edd8e85a12a67454e37f8c75e730830d83e313556ab9ebf9ee7fbeb3bfb" dependencies = [ "crc32fast", - "miniz_oxide 0.8.3", + "miniz_oxide", ] [[package]] @@ -1395,15 +1473,21 @@ checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095" dependencies = [ "futures-core", "futures-sink", - "nanorand", + "nanorand 0.7.0", "spin", ] [[package]] name = "foldhash" -version = "0.1.4" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0d2fde1f7b3d48b8395d5f2de76c18a528bd6a9cdde438df747bfcba3e05d6f" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "foreign-types" @@ -1434,9 +1518,9 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" [[package]] name = "form_urlencoded" -version = "1.2.1" +version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" dependencies = [ "percent-encoding", ] @@ -1513,9 +1597,9 @@ checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" [[package]] name = "futures-lite" -version = "2.6.0" +version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5edaec856126859abb19ed65f39e90fea3a9574b9707f13539acf4abf7eb532" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" dependencies = [ "fastrand", "futures-core", @@ -1567,57 +1651,60 @@ dependencies = [ [[package]] name = "generator" -version = "0.8.4" +version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc6bd114ceda131d3b1d665eba35788690ad37f5916457286b32ab6fd3c438dd" +checksum = "605183a538e3e2a9c1038635cc5c2d194e2ee8fd0d1b66b8349fad7dbacce5a2" dependencies = [ + "cc", "cfg-if", "libc", "log", "rustversion", - "windows", + "windows 0.61.3", ] [[package]] name = "gethostname" -version = "0.4.3" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0176e0459c2e4a1fe232f984bca6890e681076abb9934f6cea7c326f3fc47818" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ - "libc", - "windows-targets 0.48.5", + "rustix 1.1.2", + "windows-link 0.2.1", ] [[package]] name = "getrandom" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" +checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" dependencies = [ "cfg-if", "js-sys", "libc", - "wasi 0.11.0+wasi-snapshot-preview1", + "wasi", "wasm-bindgen", ] [[package]] name = "getrandom" -version = "0.3.1" +version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43a49c392881ce6d5c3b8cb70f98717b7c07aabbdff06687b9030dbfbe2725f8" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", + "js-sys", "libc", - "wasi 0.13.3+wasi-0.2.2", - "windows-targets 0.52.6", + "r-efi", + "wasip2", + "wasm-bindgen", ] [[package]] name = "gimli" -version = "0.31.1" +version = "0.32.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" +checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" [[package]] name = "gl_generator" @@ -1632,18 +1719,19 @@ dependencies = [ [[package]] name = "glam" -version = "0.29.2" +version = "0.30.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc46dd3ec48fdd8e693a98d2b8bafae273a2d54c1de02a2a7e3d57d501f39677" +checksum = "bd47b05dddf0005d850e5644cae7f2b14ac3df487979dbfff3b56f20b1a6ae46" dependencies = [ "bytemuck", + "encase", ] [[package]] name = "glob" -version = "0.3.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2" +checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" [[package]] name = "glow" @@ -1663,10 +1751,10 @@ version = "0.31.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "18fcd4ae4e86d991ad1300b8f57166e5be0c95ef1f63f3f5b827f8a164548746" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "cfg_aliases 0.1.1", "cgl", - "core-foundation", + "core-foundation 0.9.4", "dispatch", "glutin_egl_sys", "glutin_wgl_sys 0.5.0", @@ -1726,7 +1814,7 @@ version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fbcd2dba93594b227a1f57ee09b8b9da8892c34d55aa332e034a228d0fe6a171" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "gpu-alloc-types", ] @@ -1736,7 +1824,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "98ff03b468aa837d70984d55f5d3f846f6ec31fe34bbb97c4f85219caeee1ca4" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", ] [[package]] @@ -1748,18 +1836,18 @@ dependencies = [ "log", "presser", "thiserror 1.0.69", - "windows", + "windows 0.58.0", ] [[package]] name = "gpu-descriptor" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcf29e94d6d243368b7a56caa16bc213e4f9f8ed38c4d9557069527b5d5281ca" +checksum = "b89c83349105e3732062a895becfc71a8f921bb71ecbbdd8ff99263e3b53a0ca" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "gpu-descriptor-types", - "hashbrown", + "hashbrown 0.15.5", ] [[package]] @@ -1768,7 +1856,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fdf242682df893b86f33a73828fb09ca4b2d3bb6cc95249707fc684d27484b91" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", ] [[package]] @@ -1782,9 +1870,9 @@ dependencies = [ [[package]] name = "half" -version = "2.5.0" +version = "2.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7db2ff139bba50379da6aa0766b52fdcb62cb5b263009b09ed58ba604e14bbd1" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" dependencies = [ "arbitrary", "bytemuck", @@ -1792,23 +1880,27 @@ dependencies = [ "crunchy", "num-traits", "serde", + "zerocopy", ] [[package]] name = "hashbrown" -version = "0.15.2" +version = "0.15.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf151400ff0baff5465007dd2f3e717f3fe502074ca563069ce3a6629d07b289" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" dependencies = [ - "foldhash", - "serde", + "foldhash 0.1.5", ] [[package]] -name = "heck" -version = "0.4.1" +name = "hashbrown" +version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" +checksum = "5419bdc4f6a9207fbeba6d11b604d481addf78ecd10c11ad51e76c2f6482748d" +dependencies = [ + "foldhash 0.2.0", + "serde", +] [[package]] name = "heck" @@ -1818,15 +1910,9 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "hermit-abi" -version = "0.4.0" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" - -[[package]] -name = "hermit-abi" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbd780fe5cc30f81464441920d82ac8740e2e46b29a6fad543ddd075229ce37e" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" [[package]] name = "hexf-parse" @@ -1836,7 +1922,7 @@ checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df" [[package]] name = "hlsl-snapshots" -version = "0.1.0" +version = "27.0.0" dependencies = [ "anyhow", "nanoserde", @@ -1844,11 +1930,11 @@ dependencies = [ [[package]] name = "home" -version = "0.5.11" +version = "0.5.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589533453244b0995c858700322199b2becb13b627df2851f64a2775d024abcf" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -1864,21 +1950,22 @@ dependencies = [ [[package]] name = "icu_collections" -version = "1.5.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db2fa452206ebee18c4b5c2274dbf1de17008e874b4dc4f0aea9d01ca79e4526" +checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" dependencies = [ "displaydoc", + "potential_utf", "yoke", "zerofrom", "zerovec", ] [[package]] -name = "icu_locid" -version = "1.5.0" +name = "icu_locale_core" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13acbb8371917fc971be86fc8057c41a64b521c184808a698c02acc242dbf637" +checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" dependencies = [ "displaydoc", "litemap", @@ -1887,104 +1974,66 @@ dependencies = [ "zerovec", ] -[[package]] -name = "icu_locid_transform" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01d11ac35de8e40fdeda00d9e1e9d92525f3f9d887cdd7aa81d727596788b54e" -dependencies = [ - "displaydoc", - "icu_locid", - "icu_locid_transform_data", - "icu_provider", - "tinystr", - "zerovec", -] - -[[package]] -name = "icu_locid_transform_data" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7515e6d781098bf9f7205ab3fc7e9709d34554ae0b21ddbcb5febfa4bc7df11d" - [[package]] name = "icu_normalizer" -version = "1.5.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19ce3e0da2ec68599d193c93d088142efd7f9c5d6fc9b803774855747dc6a84f" +checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" dependencies = [ - "displaydoc", "icu_collections", "icu_normalizer_data", "icu_properties", "icu_provider", "smallvec", - "utf16_iter", - "utf8_iter", - "write16", "zerovec", ] [[package]] name = "icu_normalizer_data" -version = "1.5.1" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5e8338228bdc8ab83303f16b797e177953730f601a96c25d10cb3ab0daa0cb7" +checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" [[package]] name = "icu_properties" -version = "1.5.1" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93d6020766cfc6302c15dbbc9c8778c37e62c14427cb7f6e601d849e092aeef5" +checksum = "e93fcd3157766c0c8da2f8cff6ce651a31f0810eaa1c51ec363ef790bbb5fb99" dependencies = [ - "displaydoc", "icu_collections", - "icu_locid_transform", + "icu_locale_core", "icu_properties_data", "icu_provider", - "tinystr", + "zerotrie", "zerovec", ] [[package]] name = "icu_properties_data" -version = "1.5.1" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85fb8799753b75aee8d2a21d7c14d9f38921b54b3dbda10f5a3c7a7b82dba5e2" +checksum = "02845b3647bb045f1100ecd6480ff52f34c35f82d9880e029d329c21d1054899" [[package]] name = "icu_provider" -version = "1.5.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ed421c8a8ef78d3e2dbc98a973be2f3770cb42b606e3ab18d6237c4dfde68d9" +checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" dependencies = [ "displaydoc", - "icu_locid", - "icu_provider_macros", - "stable_deref_trait", - "tinystr", + "icu_locale_core", "writeable", "yoke", "zerofrom", + "zerotrie", "zerovec", ] -[[package]] -name = "icu_provider_macros" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "idna" -version = "1.0.3" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "686f825264d630750a544639377bae737628043f20d38bbc029e8f29ea968a7e" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" dependencies = [ "idna_adapter", "smallvec", @@ -1993,9 +2042,9 @@ dependencies = [ [[package]] name = "idna_adapter" -version = "1.2.0" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "daca1df1c957320b2cf139ac61e7bd64fed304c5040df000a745aa1de3b4ef71" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" dependencies = [ "icu_normalizer", "icu_properties", @@ -2003,60 +2052,63 @@ dependencies = [ [[package]] name = "if_chain" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb56e1aa765b4b4f3aadfab769793b7087bb03a4ea4920644a6d238e2df5b9ed" +checksum = "cd62e6b5e86ea8eeeb8db1de02880a6abc01a397b2ebb64b5d74ac255318f5cb" [[package]] name = "image" -version = "0.24.9" +version = "0.25.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5690139d2f55868e080017335e4b94cb7414274c74f1669c84fb5feba2c9f69d" +checksum = "529feb3e6769d234375c4cf1ee2ce713682b8e76538cb13f9fc23e1400a591e7" dependencies = [ "bytemuck", - "byteorder", - "color_quant", + "byteorder-lite", + "moxcms", "num-traits", "png", ] [[package]] name = "indexmap" -version = "2.7.1" +version = "2.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c9c992b02b5b4c94ea26e32fe5bccb7aa7d9f390ab5c1221ff895bc7ea8b652" +checksum = "6717a8d2a5a929a1a2eb43a12812498ed141a0bcfb7e8f7844fbdbe4303bba9f" dependencies = [ "arbitrary", "equivalent", - "hashbrown", + "hashbrown 0.16.0", + "serde", + "serde_core", +] + +[[package]] +name = "indicatif" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ade6dfcba0dfb62ad59e59e7241ec8912af34fd29e0e743e3db992bd278e8b65" +dependencies = [ + "console", + "portable-atomic", + "unicode-width", + "unit-prefix", + "web-time 1.1.0", +] + +[[package]] +name = "ipnetwork" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf466541e9d546596ee94f9f69590f89473455f88372423e0008fc1a7daf100e" +dependencies = [ "serde", ] -[[package]] -name = "is-terminal" -version = "0.4.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9" -dependencies = [ - "hermit-abi 0.5.0", - "libc", - "windows-sys 0.52.0", -] - [[package]] name = "is_terminal_polyfill" -version = "1.70.1" +version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" - -[[package]] -name = "itertools" -version = "0.10.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" -dependencies = [ - "either", -] +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" [[package]] name = "itertools" @@ -2067,6 +2119,15 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.15" @@ -2075,9 +2136,9 @@ checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] name = "jiff" -version = "0.2.5" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c102670231191d07d37a35af3eb77f1f0dbf7a71be51a962dcd57ea607be7260" +checksum = "be1f93b8b1eb69c77f24bbb0afdf66f54b632ee39af40ca21c4365a1d7347e49" dependencies = [ "jiff-static", "log", @@ -2088,9 +2149,9 @@ dependencies = [ [[package]] name = "jiff-static" -version = "0.2.5" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cdde31a9d349f1b1f51a0b3714a5940ac022976f4b49485fc04be052b183b4c" +checksum = "03343451ff899767262ec32146f6d559dd759fdadf42ff0e227c7c48f72594b4" dependencies = [ "proc-macro2", "quote", @@ -2121,18 +2182,19 @@ checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" [[package]] name = "jobserver" -version = "0.1.32" +version = "0.1.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48d1dbcbbeb6a7fec7e059840aa538bd62aaccf972c7346c4d9d2059312853d0" +checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" dependencies = [ + "getrandom 0.3.4", "libc", ] [[package]] name = "js-sys" -version = "0.3.77" +version = "0.3.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f" +checksum = "b011eec8cc36da2aab2d5cff675ec18454fad408585853910a202391cf9f8e65" dependencies = [ "once_cell", "wasm-bindgen", @@ -2157,11 +2219,11 @@ checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" [[package]] name = "ktx2" -version = "0.3.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87d65e08a9ec02e409d27a0139eaa6b9756b4d81fe7cde71f6941a83730ce838" +checksum = "ff7f53bdf698e7aa7ec916411bbdc8078135da11b66db5182675b2227f6c0d07" dependencies = [ - "bitflags 1.3.2", + "bitflags 2.10.0", ] [[package]] @@ -2172,9 +2234,9 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" -version = "0.2.171" +version = "0.2.177" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c19937216e9d3aa9956d9bb8dfc0b0c8beb6058fc4f7a4dc4d850edf86a237d6" +checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976" [[package]] name = "libfuzzer-sys" @@ -2189,29 +2251,29 @@ dependencies = [ [[package]] name = "libloading" -version = "0.8.6" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" dependencies = [ "cfg-if", - "windows-targets 0.48.5", + "windows-link 0.2.1", ] [[package]] name = "libm" -version = "0.2.11" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8355be11b20d696c8f18f6cc018c4e372165b1fa8126cef092399c9951984ffa" +checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de" [[package]] name = "libredox" -version = "0.1.3" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" +checksum = "416f7e718bdb06000964960ffa43b4335ad4012ae8b99060261aa4a8088d5ccb" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "libc", - "redox_syscall 0.5.8", + "redox_syscall 0.5.18", ] [[package]] @@ -2233,20 +2295,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" [[package]] -name = "litemap" -version = "0.7.5" +name = "linux-raw-sys" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23fb14cb19457329c82206317a5663005a4d404783dc74f4252769b0d5f42856" +checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" + +[[package]] +name = "litemap" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" [[package]] name = "litrs" -version = "0.4.1" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ce301924b7887e9d637144fdade93f9dfff9b60981d4ac161db09720d39aa5" +checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" [[package]] name = "lock-analyzer" -version = "24.0.0" +version = "27.0.0" dependencies = [ "anyhow", "ron", @@ -2255,19 +2323,18 @@ dependencies = [ [[package]] name = "lock_api" -version = "0.4.12" +version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" dependencies = [ - "autocfg", "scopeguard", ] [[package]] name = "log" -version = "0.4.27" +version = "0.4.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94" +checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432" [[package]] name = "loom" @@ -2288,6 +2355,22 @@ version = "0.1.4+2024.11.22-df583a3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e3cd67e8ea2ba061339150970542cf1c60ba44c6d17e31279cbc133a4b018f8" +[[package]] +name = "macro_rules_attribute" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65049d7923698040cd0b1ddcced9b0eb14dd22c5f86ae59c3740eab64a676520" +dependencies = [ + "macro_rules_attribute-proc_macro", + "paste", +] + +[[package]] +name = "macro_rules_attribute-proc_macro" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "670fdfda89751bc4a84ac13eaa63e205cf0fd22b4c9a5fbfa085b63c1f1d3a30" + [[package]] name = "malloc_buf" version = "0.0.6" @@ -2299,46 +2382,37 @@ dependencies = [ [[package]] name = "matchers" -version = "0.1.0" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" dependencies = [ - "regex-automata 0.1.10", + "regex-automata", ] [[package]] name = "memchr" -version = "2.7.4" +version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" +checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" [[package]] name = "memmap2" -version = "0.9.5" +version = "0.9.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd3f7eed9d3848f8b98834af67102b720745c4ec028fcd0aa0239277e7de374f" +checksum = "744133e4a0e0a658e1374cf3bf8e415c4052a15a111acd372764c55b4177d490" dependencies = [ "libc", ] -[[package]] -name = "memoffset" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" -dependencies = [ - "autocfg", -] - [[package]] name = "metal" -version = "0.31.0" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f569fb946490b5743ad69813cb19629130ce9374034abe31614a36402d18f99e" +checksum = "00c15a6f673ff72ddcc22394663290f870fb224c1bfce55734a75c414150e605" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "block", - "core-graphics-types", + "core-graphics-types 0.2.0", "foreign-types", "log", "objc", @@ -2363,18 +2437,9 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.7.4" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08" -dependencies = [ - "adler", -] - -[[package]] -name = "miniz_oxide" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8402cab7aefae129c6977bb0ff1b8fd9a04eb5b51efc50a70bea51cda0c7924" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" dependencies = [ "adler2", "simd-adler32", @@ -2382,56 +2447,69 @@ dependencies = [ [[package]] name = "mio" -version = "1.0.3" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2886843bf800fba2e3377cff24abf6379b4c4d5c6681eaf9ea5b0d15090450bd" +checksum = "69d83b0086dc8ecf3ce9ae2874b2d1290252e2a30720bea58a5c6639b0092873" dependencies = [ "libc", - "wasi 0.11.0+wasi-snapshot-preview1", - "windows-sys 0.52.0", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "moxcms" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fbdd3d7436f8b5e892b8b7ea114271ff0fa00bc5acae845d53b07d498616ef6" +dependencies = [ + "num-traits", + "pxfm", ] [[package]] name = "naga" -version = "24.0.0" +version = "27.0.0" dependencies = [ "arbitrary", "arrayvec", - "bit-set 0.8.0", - "bitflags 2.9.0", + "bit-set", + "bitflags 2.10.0", + "cfg-if", "cfg_aliases 0.2.1", "codespan-reporting", "diff", "env_logger", "half", - "hashbrown", + "hashbrown 0.16.0", "hexf-parse", "hlsl-snapshots", "indexmap", - "itertools 0.13.0", + "itertools 0.14.0", + "libm", "log", + "naga-test", "num-traits", - "petgraph 0.7.1", + "once_cell", + "petgraph 0.8.3", "pp-rs", "ron", "rspirv", - "rustc-hash", + "rustc-hash 1.1.0", "serde", - "spirv 0.3.0+sdk-1.3.268.0", - "strum 0.26.3", - "thiserror 2.0.12", - "toml", + "spirv", + "strum", + "thiserror 2.0.17", "unicode-ident", "walkdir", ] [[package]] name = "naga-cli" -version = "24.0.0" +version = "27.0.0" dependencies = [ "anyhow", "argh", - "bincode", + "bincode 2.0.1", "codespan-reporting", "env_logger", "log", @@ -2440,7 +2518,7 @@ dependencies = [ [[package]] name = "naga-fuzz" -version = "0.0.0" +version = "27.0.0" dependencies = [ "arbitrary", "cfg_aliases 0.2.1", @@ -2448,13 +2526,52 @@ dependencies = [ "naga", ] +[[package]] +name = "naga-test" +version = "27.0.0" +dependencies = [ + "bitflags 2.10.0", + "naga", + "ron", + "serde", + "serde_json", + "spirv", + "toml", +] + +[[package]] +name = "naga-xtask" +version = "0.1.0" +dependencies = [ + "anyhow", + "env_logger", + "glob", + "hlsl-snapshots", + "indicatif", + "jobserver", + "log", + "num_cpus", + "pico-args", + "shell-words", + "which 8.0.0", +] + [[package]] name = "nanorand" version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a51313c5820b0b02bd422f4b44776fbf47961755c74ce64afc73bfad10226c3" dependencies = [ - "getrandom 0.2.15", + "getrandom 0.2.16", +] + +[[package]] +name = "nanorand" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e3d189da485332e96ba8a5ef646a311871abd7915bf06ac848a9117f19cf6e4" +dependencies = [ + "getrandom 0.3.4", ] [[package]] @@ -2478,7 +2595,7 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2076a31b7010b17a38c01907c45b945e8f11495ee4dd588309718901b1f7a5b7" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "jni-sys", "log", "ndk-sys 0.5.0+25.2.9519653", @@ -2494,7 +2611,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "jni-sys", "log", "ndk-sys 0.6.0+11769913", @@ -2527,6 +2644,17 @@ dependencies = [ "jni-sys", ] +[[package]] +name = "nix" +version = "0.27.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2eb04e9c688eff1c89d72b407f168cf79bb9e867a9d3323ed6c01519eb9cc053" +dependencies = [ + "bitflags 2.10.0", + "cfg-if", + "libc", +] + [[package]] name = "noise" version = "0.9.0" @@ -2550,12 +2678,11 @@ dependencies = [ [[package]] name = "nu-ansi-term" -version = "0.46.0" +version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "overload", - "winapi", + "windows-sys 0.61.2", ] [[package]] @@ -2589,19 +2716,30 @@ dependencies = [ ] [[package]] -name = "num_enum" -version = "0.7.3" +name = "num_cpus" +version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e613fc340b2220f734a8595782c551f1250e969d87d3be1ae0579e8d4065179" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "num_enum" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1207a7e20ad57b847bbddc6776b968420d38292bbfe2089accff5e19e82454c" dependencies = [ "num_enum_derive", + "rustversion", ] [[package]] name = "num_enum_derive" -version = "0.7.3" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af1844ef2428cc3e1cb900be36181049ef3d3193c63e43026cfe202983b27a56" +checksum = "ff32365de1b6743cb203b710788263c44a03de03802daf96092f2da4fe6ba4d7" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2674,7 +2812,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "block2 0.5.1", "libc", "objc2 0.5.2", @@ -2690,7 +2828,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "block2 0.5.1", "objc2 0.5.2", "objc2-core-location", @@ -2714,7 +2852,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "block2 0.5.1", "objc2 0.5.2", "objc2-foundation", @@ -2762,7 +2900,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "block2 0.5.1", "dispatch", "libc", @@ -2787,7 +2925,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "block2 0.5.1", "objc2 0.5.2", "objc2-foundation", @@ -2799,7 +2937,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "block2 0.5.1", "objc2 0.5.2", "objc2-foundation", @@ -2822,7 +2960,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "block2 0.5.1", "objc2 0.5.2", "objc2-cloud-kit", @@ -2854,7 +2992,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "block2 0.5.1", "objc2 0.5.2", "objc2-core-location", @@ -2863,18 +3001,24 @@ dependencies = [ [[package]] name = "object" -version = "0.36.7" +version = "0.37.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87" +checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" dependencies = [ "memchr", ] [[package]] name = "once_cell" -version = "1.21.1" +version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d75b0bedcc4fe52caa0e03d9f1151a323e4aa5e2d78ba3580400cd3c9e2bc4bc" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" [[package]] name = "oorandom" @@ -2893,36 +3037,24 @@ dependencies = [ [[package]] name = "ordered-float" -version = "4.6.0" +version = "5.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bb71e1b3fa6ca1c61f383464aaf2bb0e2f8e772a1f01d486832464de363b951" +checksum = "7f4779c6901a562440c3786d08192c6fbda7c1c2060edd10006b05ee35d10f2d" dependencies = [ "num-traits", ] -[[package]] -name = "outref" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f222829ae9293e33a9f5e9f440c6760a3d450a64affe1846486b140db81c1f4" - [[package]] name = "outref" version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" -[[package]] -name = "overload" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" - [[package]] name = "owned_ttf_parser" -version = "0.25.0" +version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22ec719bbf3b2a81c109a4e20b1f129b5566b7dce654bc3872f6a05abf82b2c4" +checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" dependencies = [ "ttf-parser", ] @@ -2935,9 +3067,9 @@ checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" [[package]] name = "parking_lot" -version = "0.12.3" +version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" dependencies = [ "lock_api", "parking_lot_core", @@ -2945,18 +3077,17 @@ dependencies = [ [[package]] name = "parking_lot_core" -version = "0.9.10" +version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ "backtrace", "cfg-if", "libc", "petgraph 0.6.5", - "redox_syscall 0.5.8", + "redox_syscall 0.5.18", "smallvec", - "thread-id", - "windows-targets 0.52.6", + "windows-link 0.2.1", ] [[package]] @@ -2967,9 +3098,9 @@ checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" [[package]] name = "percent-encoding" -version = "2.3.1" +version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" [[package]] name = "petgraph" @@ -2983,11 +3114,12 @@ dependencies = [ [[package]] name = "petgraph" -version = "0.7.1" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" dependencies = [ "fixedbitset 0.5.7", + "hashbrown 0.15.5", "indexmap", ] @@ -3037,9 +3169,11 @@ checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" [[package]] name = "player" -version = "24.0.0" +version = "27.0.0" dependencies = [ + "bytemuck", "env_logger", + "hashbrown 0.16.0", "log", "raw-window-handle 0.6.2", "ron", @@ -3079,30 +3213,29 @@ dependencies = [ [[package]] name = "png" -version = "0.17.16" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" +checksum = "97baced388464909d42d89643fe4361939af9b7ce7a31ee32a168f832a70f2a0" dependencies = [ - "bitflags 1.3.2", + "bitflags 2.10.0", "crc32fast", "fdeflate", "flate2", - "miniz_oxide 0.8.3", + "miniz_oxide", ] [[package]] name = "polling" -version = "3.7.4" +version = "3.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a604568c3202727d1507653cb121dbd627a58684eb09a820fd746bee38b4442f" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" dependencies = [ "cfg-if", "concurrent-queue", - "hermit-abi 0.4.0", + "hermit-abi", "pin-project-lite", - "rustix", - "tracing", - "windows-sys 0.59.0", + "rustix 1.1.2", + "windows-sys 0.61.2", ] [[package]] @@ -3127,9 +3260,9 @@ dependencies = [ [[package]] name = "portable-atomic" -version = "1.11.0" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "350e9b48cbc6b0e028b0473b114454c6316e57336ee184ceab6e53f72c178b3e" +checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483" [[package]] name = "portable-atomic-util" @@ -3140,6 +3273,15 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "potential_utf" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" +dependencies = [ + "zerovec", +] + [[package]] name = "pp-rs" version = "0.2.1" @@ -3157,9 +3299,9 @@ checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" [[package]] name = "prettyplease" -version = "0.2.31" +version = "0.2.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5316f57387668042f561aae71480de936257848f9c43ce528e311d89a07cadeb" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" dependencies = [ "proc-macro2", "syn", @@ -3167,9 +3309,9 @@ dependencies = [ [[package]] name = "proc-macro-crate" -version = "3.3.0" +version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edce586971a4dfaa28950c6f18ed55e0406c1ab88bbce2c6f6293a7aaba73d35" +checksum = "219cb19e96be00ab2e37d6e299658a0cfa83e52429179969b0f0121b4ac46983" dependencies = [ "toml_edit", ] @@ -3199,37 +3341,52 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.94" +version = "1.0.103" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84" +checksum = "5ee95bc4ef87b8d5ba32e8b7714ccc834865276eab0aed5c9958d00ec45f49e8" dependencies = [ "unicode-ident", ] [[package]] name = "profiling" -version = "1.0.16" +version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afbdc74edc00b6f6a218ca6a5364d6226a259d4b8ea1af4a0ea063f27e179f4d" +checksum = "3eb8486b569e12e2c32ad3e204dbaba5e4b5b216e9367044f25f1dba42341773" + +[[package]] +name = "pxfm" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3cbdf373972bf78df4d3b518d07003938e2c7d1fb5891e55f9cb6df57009d84" +dependencies = [ + "num-traits", +] [[package]] name = "quick-xml" -version = "0.37.3" +version = "0.37.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf763ab1c7a3aa408be466efc86efe35ed1bd3dd74173ed39d6b0d0a6f0ba148" +checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb" dependencies = [ "memchr", ] [[package]] name = "quote" -version = "1.0.40" +version = "1.0.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" +checksum = "ce25767e7b499d1b604768e7cde645d14cc8584231ea6b295e9c9eb22c02e1d1" dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + [[package]] name = "radium" version = "0.7.0" @@ -3280,9 +3437,9 @@ checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" [[package]] name = "rayon" -version = "1.10.0" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b418a60154510ca1a002a752ca9714984e21e4241e804d32555251faf8b78ffa" +checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f" dependencies = [ "either", "rayon-core", @@ -3290,9 +3447,9 @@ dependencies = [ [[package]] name = "rayon-core" -version = "1.12.1" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" dependencies = [ "crossbeam-deque", "crossbeam-utils", @@ -3318,56 +3475,47 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.5.8" +version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03a862b389f93e68874fbf580b9de08dd02facb9a788ebadaf4a3fd33cf58834" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", ] [[package]] name = "regex" -version = "1.11.1" +version = "1.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" +checksum = "843bc0191f75f3e22651ae5f1e72939ab2f72a4bc30fa80a066bd66edefc24d4" dependencies = [ "aho-corasick", "memchr", - "regex-automata 0.4.9", - "regex-syntax 0.8.5", + "regex-automata", + "regex-syntax", ] [[package]] name = "regex-automata" -version = "0.1.10" +version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" -dependencies = [ - "regex-syntax 0.6.29", -] - -[[package]] -name = "regex-automata" -version = "0.4.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" +checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c" dependencies = [ "aho-corasick", "memchr", - "regex-syntax 0.8.5", + "regex-syntax", ] [[package]] -name = "regex-syntax" -version = "0.6.29" +name = "regex-lite" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" +checksum = "8d942b98df5e658f56f20d592c7f868833fe38115e65c33003d8cd224b0155da" [[package]] name = "regex-syntax" -version = "0.8.5" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" +checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" [[package]] name = "renderdoc-sys" @@ -3377,12 +3525,12 @@ checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" [[package]] name = "ron" -version = "0.9.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63f3aa105dea217ef30d89581b65a4d527a19afc95ef5750be3890e8d3c5b837" +checksum = "db09040cc89e461f1a265139777a2bde7f8d8c67c4936f700c63ce3e2904d468" dependencies = [ "base64", - "bitflags 2.9.0", + "bitflags 2.10.0", "serde", "serde_derive", "unicode-ident", @@ -3390,11 +3538,12 @@ dependencies = [ [[package]] name = "rspirv" -version = "0.11.0+sdk-1.2.198" -source = "git+https://github.com/gfx-rs/rspirv?rev=b969f175d5663258b4891e44b76c1544da9661ab#b969f175d5663258b4891e44b76c1544da9661ab" +version = "0.12.0+sdk-1.3.268.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cf3a93856b6e5946537278df0d3075596371b1950ccff012f02b0f7eafec8d" dependencies = [ - "rustc-hash", - "spirv 0.2.0+sdk-1.2.198", + "rustc-hash 1.1.0", + "spirv", ] [[package]] @@ -3405,9 +3554,9 @@ checksum = "a157657054ffe556d8858504af8a672a054a6e0bd9e8ee531059100c0fa11bb2" [[package]] name = "rustc-demangle" -version = "0.1.24" +version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" +checksum = "56f7d92ca342cea22a06f2121d944b4fd82af56988c270852495420f961d4ace" [[package]] name = "rustc-hash" @@ -3416,13 +3565,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" [[package]] -name = "rustc_version" -version = "0.2.3" +name = "rustc-hash" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" -dependencies = [ - "semver 0.9.0", -] +checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" [[package]] name = "rustix" @@ -3430,18 +3576,31 @@ version = "0.38.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "errno", "libc", - "linux-raw-sys", - "windows-sys 0.52.0", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e" +dependencies = [ + "bitflags 2.10.0", + "errno", + "libc", + "linux-raw-sys 0.11.0", + "windows-sys 0.61.2", ] [[package]] name = "rustversion" -version = "1.0.20" +version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eded382c5f5f786b989652c49544c4877d9f015cc22e145a5ea8ea66c2921cd2" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" [[package]] name = "ryu" @@ -3498,42 +3657,38 @@ dependencies = [ [[package]] name = "semver" -version = "0.9.0" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" -dependencies = [ - "semver-parser", -] - -[[package]] -name = "semver" -version = "1.0.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f79dfe2d285b0488816f30e700a7438c5a73d816b5b7d3ac72fbc48b0d185e03" +checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" dependencies = [ "serde", + "serde_core", ] -[[package]] -name = "semver-parser" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" - [[package]] name = "serde" -version = "1.0.219" +version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.219" +version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", @@ -3542,37 +3697,38 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.140" +version = "1.0.145" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" +checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c" dependencies = [ "indexmap", "itoa", "memchr", "ryu", "serde", + "serde_core", ] [[package]] name = "serde_spanned" -version = "0.6.8" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87607cb1398ed59d48732e575a4c28a7a8ebf2454b964fe3f224f2afc07909e1" +checksum = "e24345aa0fe688594e73770a5f6d1b216508b4f93484c0026d521acd30134392" dependencies = [ - "serde", + "serde_core", ] [[package]] name = "serde_v8" -version = "0.245.0" +version = "0.264.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "945f93c91e0c7e4799b5fefff076756141aae92e262c4dc4833310dd3d2d845e" +checksum = "c34707712f3815e73e1c8319bba06e5bc105bb65fe812ea2e7279ffb905f6312" dependencies = [ "deno_error", "num-bigint", "serde", "smallvec", - "thiserror 2.0.12", + "thiserror 2.0.17", "v8", ] @@ -3585,6 +3741,12 @@ dependencies = [ "lazy_static", ] +[[package]] +name = "shell-words" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24188a676b6ae68c3b2cb3a01be17fbf7240ce009799bb56d5b1409051e78fde" + [[package]] name = "shlex" version = "1.3.0" @@ -3593,22 +3755,13 @@ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] name = "signal-hook-registry" -version = "1.4.2" +version = "1.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" +checksum = "b2a4719bff48cee6b39d12c020eeb490953ad2443b7055bd0b21fca26bd8c28b" dependencies = [ "libc", ] -[[package]] -name = "simd-abstraction" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cadb29c57caadc51ff8346233b5cec1d240b68ce55cf1afc764818791876987" -dependencies = [ - "outref 0.1.0", -] - [[package]] name = "simd-adler32" version = "0.3.7" @@ -3617,12 +3770,9 @@ checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe" [[package]] name = "slab" -version = "0.4.9" +version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" -dependencies = [ - "autocfg", -] +checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" [[package]] name = "slotmap" @@ -3635,9 +3785,12 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.14.0" +version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fcf8323ef1faaee30a44a340193b1ac6814fd9b7b4e88e9d4519a3e4abe1cfd" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +dependencies = [ + "serde", +] [[package]] name = "smithay-client-toolkit" @@ -3645,14 +3798,14 @@ version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "922fd3eeab3bd820d76537ce8f582b1cf951eceb5475c28500c7457d9d17f53a" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "calloop 0.12.4", "calloop-wayland-source 0.2.0", "cursor-icon", "libc", "log", "memmap2", - "rustix", + "rustix 0.38.44", "thiserror 1.0.69", "wayland-backend", "wayland-client", @@ -3670,21 +3823,21 @@ version = "0.19.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "calloop 0.13.0", "calloop-wayland-source 0.3.0", "cursor-icon", "libc", "log", "memmap2", - "rustix", + "rustix 0.38.44", "thiserror 1.0.69", "wayland-backend", "wayland-client", "wayland-csd-frame", "wayland-cursor", - "wayland-protocols 0.32.5", - "wayland-protocols-wlr 0.3.5", + "wayland-protocols 0.32.9", + "wayland-protocols-wlr 0.3.9", "wayland-scanner", "xkeysym", ] @@ -3700,27 +3853,26 @@ dependencies = [ [[package]] name = "socket2" -version = "0.5.8" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c970269d99b64e60ec3bd6ad27270092a5394c4e309314b18ae3fe575695fbe8" +checksum = "17129e116933cf371d018bb80ae557e889637989d8638274fb25622827b03881" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] name = "sourcemap" -version = "8.0.1" +version = "9.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "208d40b9e8cad9f93613778ea295ed8f3c2b1824217c6cfc7219d3f6f45b96d4" +checksum = "e22afbcb92ce02d23815b9795523c005cb9d3c214f8b7a66318541c240ea7935" dependencies = [ - "base64-simd 0.7.0", + "base64-simd", "bitvec", "data-encoding", "debugid", "if_chain", - "rustc-hash", - "rustc_version", + "rustc-hash 2.1.1", "serde", "serde_json", "unicode-id-start", @@ -3736,29 +3888,21 @@ dependencies = [ "lock_api", ] -[[package]] -name = "spirv" -version = "0.2.0+sdk-1.2.198" -source = "git+https://github.com/gfx-rs/rspirv?rev=b969f175d5663258b4891e44b76c1544da9661ab#b969f175d5663258b4891e44b76c1544da9661ab" -dependencies = [ - "bitflags 1.3.2", -] - [[package]] name = "spirv" version = "0.3.0+sdk-1.3.268.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eda41003dc44290527a59b13432d4a0379379fa074b70174882adfbdfd917844" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "serde", ] [[package]] name = "stable_deref_trait" -version = "1.2.0" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" [[package]] name = "static_assertions" @@ -3774,9 +3918,9 @@ checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" [[package]] name = "stringcase" -version = "0.3.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04028eeb851ed08af6aba5caa29f2d59a13ed168cee4d6bd753aeefcf1d636b0" +checksum = "72abeda133c49d7bddece6c154728f83eec8172380c80ab7096da9487e20d27c" [[package]] name = "strsim" @@ -3786,53 +3930,30 @@ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] name = "strum" -version = "0.25.0" +version = "0.27.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "290d54ea6f91c969195bdbcd7442c8c2a2ba87da8bf60a7ee86a235d4bc1e125" +checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" dependencies = [ - "strum_macros 0.25.3", -] - -[[package]] -name = "strum" -version = "0.26.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" -dependencies = [ - "strum_macros 0.26.4", + "strum_macros", ] [[package]] name = "strum_macros" -version = "0.25.3" +version = "0.27.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23dc1fa9ac9c169a78ba62f0b841814b7abae11bdd047b9c58f893439e309ea0" +checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7" dependencies = [ - "heck 0.4.1", + "heck", "proc-macro2", "quote", - "rustversion", - "syn", -] - -[[package]] -name = "strum_macros" -version = "0.26.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" -dependencies = [ - "heck 0.5.0", - "proc-macro2", - "quote", - "rustversion", "syn", ] [[package]] name = "syn" -version = "2.0.100" +version = "2.0.108" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0" +checksum = "da58917d35242480a05c2897064da0a80589a2a0476c9a3f2fdc83b53502e917" dependencies = [ "proc-macro2", "quote", @@ -3841,9 +3962,9 @@ dependencies = [ [[package]] name = "synstructure" -version = "0.13.1" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" dependencies = [ "proc-macro2", "quote", @@ -3852,9 +3973,23 @@ dependencies = [ [[package]] name = "sys_traits" -version = "0.1.8" +version = "0.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "638f0e61b5134e56b2abdf4c704fd44672603f15ca09013f314649056f3fee4d" +checksum = "4f74a2c95f72e36fa6bd04a40d15623a9904bab1cc2fa6c6135b09d774a65088" +dependencies = [ + "sys_traits_macros", +] + +[[package]] +name = "sys_traits_macros" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "181f22127402abcf8ee5c83ccd5b408933fec36a6095cf82cda545634692657e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] [[package]] name = "tap" @@ -3864,9 +3999,22 @@ checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" [[package]] name = "target-triple" -version = "0.1.4" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ac9aa371f599d22256307c24a9d748c041e548cbf599f35d890f9d365361790" +checksum = "591ef38edfb78ca4771ee32cf494cb8771944bee237a9b91fc9c1424ac4b777b" + +[[package]] +name = "tempfile" +version = "3.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d31c77bdf42a745371d260a26ca7163f1e0924b64afa0b688e61b5a9fa02f16" +dependencies = [ + "fastrand", + "getrandom 0.3.4", + "once_cell", + "rustix 1.1.2", + "windows-sys 0.61.2", +] [[package]] name = "termcolor" @@ -3888,11 +4036,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.12" +version = "2.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "567b8a2dae586314f7be2a752ec7474332959c6460e02bde30d702a66d488708" +checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8" dependencies = [ - "thiserror-impl 2.0.12", + "thiserror-impl 2.0.17", ] [[package]] @@ -3908,33 +4056,22 @@ dependencies = [ [[package]] name = "thiserror-impl" -version = "2.0.12" +version = "2.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f7cf42b4507d8ea322120659672cf1b9dbb93f8f2d4ecfd6e51350ff5b17a1d" +checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913" dependencies = [ "proc-macro2", "quote", "syn", ] -[[package]] -name = "thread-id" -version = "4.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfe8f25bbdd100db7e1d34acf7fd2dc59c4bf8f7483f505eaa7d4f12f76cc0ea" -dependencies = [ - "libc", - "winapi", -] - [[package]] name = "thread_local" -version = "1.1.8" +version = "1.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" dependencies = [ "cfg-if", - "once_cell", ] [[package]] @@ -3964,9 +4101,9 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.7.6" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9117f5d4db391c1cf6927e7bea3db74b9a1c1add8f7eda9ffd5364f40f57b82f" +checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" dependencies = [ "displaydoc", "zerovec", @@ -3984,11 +4121,10 @@ dependencies = [ [[package]] name = "tokio" -version = "1.44.1" +version = "1.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f382da615b842244d4b8738c82ed1275e6c5dd90c459a30941cd07080b06c91a" +checksum = "ff360e02eab121e0bc37a2d3b4d4dc622e6eda3a8e5253d5435ecf5bd4c68408" dependencies = [ - "backtrace", "bytes", "libc", "mio", @@ -3997,14 +4133,14 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] name = "tokio-macros" -version = "2.5.0" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8" +checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" dependencies = [ "proc-macro2", "quote", @@ -4013,38 +4149,55 @@ dependencies = [ [[package]] name = "toml" -version = "0.8.20" +version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd87a5cdd6ffab733b2f74bc4fd7ee5fff6634124999ac278c35fc78c6120148" +checksum = "f0dc8b1fb61449e27716ec0e1bdf0f6b8f3e8f6b05391e8497b8b6d7804ea6d8" dependencies = [ - "serde", + "indexmap", + "serde_core", "serde_spanned", "toml_datetime", - "toml_edit", + "toml_parser", + "toml_writer", + "winnow", ] [[package]] name = "toml_datetime" -version = "0.6.8" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dd7358ecb8fc2f8d014bf86f6f638ce72ba252a2c3a2572f2a795f1d23efb41" +checksum = "f2cdb639ebbc97961c51720f858597f7f24c4fc295327923af55b74c3c724533" dependencies = [ - "serde", + "serde_core", ] [[package]] name = "toml_edit" -version = "0.22.24" +version = "0.23.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17b4795ff5edd201c7cd6dca065ae59972ce77d1b80fa0a84d94950ece7d1474" +checksum = "6485ef6d0d9b5d0ec17244ff7eb05310113c3f316f2d14200d4de56b3cb98f8d" dependencies = [ "indexmap", - "serde", - "serde_spanned", "toml_datetime", + "toml_parser", "winnow", ] +[[package]] +name = "toml_parser" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0cbe268d35bdb4bb5a56a2de88d0ad0eb70af5384a99d648cd4b3d04039800e" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df8b2b54733674ad286d16267dcfc7a71ed5c776e4ac7aa3c3e2561f7c637bf2" + [[package]] name = "tracing" version = "0.1.41" @@ -4057,9 +4210,9 @@ dependencies = [ [[package]] name = "tracing-core" -version = "0.1.33" +version = "0.1.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e672c95779cf947c5311f83787af4fa8fffd12fb27e4993211a84bdfd9610f9c" +checksum = "b9d12581f227e93f094d3af2ae690a574abb8a2b9b7a96e7cfe9647b2b617678" dependencies = [ "once_cell", "valuable", @@ -4078,14 +4231,14 @@ dependencies = [ [[package]] name = "tracing-subscriber" -version = "0.3.19" +version = "0.3.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8189decb5ac0fa7bc8b96b7cb9b2701d60d48805aca84a238004d665fcc4008" +checksum = "2054a14f5307d601f88daf0553e1cbf472acc4f2c51afab632431cdcd72124d5" dependencies = [ "matchers", "nu-ansi-term", "once_cell", - "regex", + "regex-automata", "sharded-slab", "smallvec", "thread_local", @@ -4096,9 +4249,9 @@ dependencies = [ [[package]] name = "tracy-client" -version = "0.17.6" +version = "0.18.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73202d787346a5418f8222eddb5a00f29ea47caf3c7d38a8f2f69f8455fa7c7e" +checksum = "ef54005d3d760186fd662dad4b7bb27ecd5531cdef54d1573ebd3f20a9205ed7" dependencies = [ "loom", "once_cell", @@ -4107,19 +4260,19 @@ dependencies = [ [[package]] name = "tracy-client-sys" -version = "0.24.3" +version = "0.26.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69fff37da548239c3bf9e64a12193d261e8b22b660991c6fd2df057c168f435f" +checksum = "319c70195101a93f56db4c74733e272d720768e13471f400c78406a326b172b0" dependencies = [ "cc", - "windows-targets 0.48.5", + "windows-targets 0.52.6", ] [[package]] name = "trybuild" -version = "1.0.104" +version = "1.0.113" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ae08be68c056db96f0e6c6dd820727cca756ced9e1f4cc7fdd20e2a55e23898" +checksum = "559b6a626c0815c942ac98d434746138b4f89ddd6a1b8cbb168c6845fb3376c5" dependencies = [ "glob", "serde", @@ -4136,6 +4289,12 @@ version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +[[package]] +name = "typewit" +version = "1.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8c1ae7cc0fdb8b842d65d127cb981574b0d2b249b74d1c7a2986863dc134f71" + [[package]] name = "unic-char-property" version = "0.9.0" @@ -4179,15 +4338,15 @@ dependencies = [ [[package]] name = "unicode-id-start" -version = "1.3.1" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f322b60f6b9736017344fa0635d64be2f458fbc04eef65f6be22976dd1ffd5b" +checksum = "81b79ad29b5e19de4260020f8919b443b2ef0277d242ce532ec7b7a2cc8b6007" [[package]] name = "unicode-ident" -version = "1.0.18" +version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" +checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5" [[package]] name = "unicode-segmentation" @@ -4197,9 +4356,9 @@ checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" [[package]] name = "unicode-width" -version = "0.2.0" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" [[package]] name = "unicode-xid" @@ -4208,10 +4367,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" [[package]] -name = "url" -version = "2.5.4" +name = "unit-prefix" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32f8b686cadd1473f4bd0117a5d28d36b1ade384ea9b5069a1c40aefed7fda60" +checksum = "323402cff2dd658f39ca17c789b502021b3f18707c91cdf22e3838e1b4023817" + +[[package]] +name = "unty" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d49784317cd0d1ee7ec5c716dd598ec5b4483ea832a2dced265471cc0f690ae" + +[[package]] +name = "url" +version = "2.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08bc136a29a3d1758e07a9cca267be308aeebf5cfd5a10f3f67ab2097683ef5b" dependencies = [ "form_urlencoded", "idna", @@ -4231,12 +4402,6 @@ dependencies = [ "url", ] -[[package]] -name = "utf16_iter" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" - [[package]] name = "utf8_iter" version = "1.0.4" @@ -4251,29 +4416,30 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.16.0" +version = "1.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "458f7a779bf54acc9f347480ac654f68407d3aab21269a6e3c9f922acd9e2da9" +checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2" dependencies = [ - "getrandom 0.3.1", + "getrandom 0.3.4", + "js-sys", "serde", + "wasm-bindgen", ] [[package]] name = "v8" -version = "130.0.7" +version = "137.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a511192602f7b435b0a241c1947aa743eb7717f20a9195f4b5e8ed1952e01db1" +checksum = "33995a1fee055ff743281cde33a41f0d618ee0bdbe8bdf6859e11864499c2595" dependencies = [ "bindgen", - "bitflags 2.9.0", + "bitflags 2.10.0", "fslock", "gzip-header", "home", - "miniz_oxide 0.7.4", - "once_cell", + "miniz_oxide", "paste", - "which", + "which 6.0.3", ] [[package]] @@ -4288,6 +4454,12 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "virtue" +version = "0.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "051eb1abcf10076295e815102942cc58f9d5e3b4560e46e53c21e8ff6f3af7b1" + [[package]] name = "vsimd" version = "0.8.0" @@ -4306,50 +4478,37 @@ dependencies = [ [[package]] name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" +version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] -name = "wasi" -version = "0.13.3+wasi-0.2.2" +name = "wasip2" +version = "1.0.1+wasi-0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26816d2e1a4a36a2940b96c5296ce403917633dff8f3440e9b236ed6f6bacad2" +checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" dependencies = [ - "wit-bindgen-rt", + "wit-bindgen", ] [[package]] name = "wasm-bindgen" -version = "0.2.100" +version = "0.2.105" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5" +checksum = "da95793dfc411fbbd93f5be7715b0578ec61fe87cb1a42b12eb625caa5c5ea60" dependencies = [ "cfg-if", "once_cell", "rustversion", "wasm-bindgen-macro", -] - -[[package]] -name = "wasm-bindgen-backend" -version = "0.2.100" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6" -dependencies = [ - "bumpalo", - "log", - "proc-macro2", - "quote", - "syn", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.50" +version = "0.4.55" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "555d470ec0bc3bb57890405e5d4322cc9ea83cebb085523ced7be4144dac1e61" +checksum = "551f88106c6d5e7ccc7cd9a16f312dd3b5d36ea8b4954304657d5dfba115d4a0" dependencies = [ "cfg-if", "js-sys", @@ -4360,9 +4519,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.100" +version = "0.2.105" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407" +checksum = "04264334509e04a7bf8690f2384ef5265f05143a4bff3889ab7a3269adab59c2" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -4370,31 +4529,31 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.100" +version = "0.2.105" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de" +checksum = "420bc339d9f322e562942d52e115d57e950d12d88983a14c79b86859ee6c7ebc" dependencies = [ + "bumpalo", "proc-macro2", "quote", "syn", - "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.100" +version = "0.2.105" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d" +checksum = "76f218a38c84bcb33c25ec7059b07847d465ce0e0a76b995e134a45adcb6af76" dependencies = [ "unicode-ident", ] [[package]] name = "wasm-bindgen-test" -version = "0.3.50" +version = "0.3.55" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66c8d5e33ca3b6d9fa3b4676d774c5778031d27a578c2b007f905acf816152c3" +checksum = "bfc379bfb624eb59050b509c13e77b4eb53150c350db69628141abce842f2373" dependencies = [ "js-sys", "minicov", @@ -4405,9 +4564,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-test-macro" -version = "0.3.50" +version = "0.3.55" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17d5042cc5fa009658f9a7333ef24291b1291a25b6382dd68862a7f3b969f69b" +checksum = "085b2df989e1e6f9620c1311df6c996e83fe16f57792b272ce1e024ac16a90f1" dependencies = [ "proc-macro2", "quote", @@ -4416,23 +4575,23 @@ dependencies = [ [[package]] name = "wasm_dep_analyzer" -version = "0.2.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2eeee3bdea6257cc36d756fa745a70f9d393571e47d69e0ed97581676a5369ca" +checksum = "a10e6b67c951a84de7029487e0e0a496860dae49f6699edd279d5ff35b8fbf54" dependencies = [ "deno_error", - "thiserror 2.0.12", + "thiserror 2.0.17", ] [[package]] name = "wayland-backend" -version = "0.3.8" +version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7208998eaa3870dad37ec8836979581506e0c5c64c20c9e79e9d2a10d6f47bf" +checksum = "673a33c33048a5ade91a6b139580fa174e19fb0d23f396dca9fa15f2e1e49b35" dependencies = [ "cc", "downcast-rs", - "rustix", + "rustix 1.1.2", "scoped-tls", "smallvec", "wayland-sys", @@ -4440,12 +4599,12 @@ dependencies = [ [[package]] name = "wayland-client" -version = "0.31.8" +version = "0.31.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2120de3d33638aaef5b9f4472bff75f07c56379cf76ea320bd3a3d65ecaf73f" +checksum = "c66a47e840dc20793f2264eb4b3e4ecb4b75d91c0dd4af04b456128e0bdd449d" dependencies = [ - "bitflags 2.9.0", - "rustix", + "bitflags 2.10.0", + "rustix 1.1.2", "wayland-backend", "wayland-scanner", ] @@ -4456,18 +4615,18 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "cursor-icon", "wayland-backend", ] [[package]] name = "wayland-cursor" -version = "0.31.8" +version = "0.31.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a93029cbb6650748881a00e4922b076092a6a08c11e7fbdb923f064b23968c5d" +checksum = "447ccc440a881271b19e9989f75726d60faa09b95b0200a9b7eb5cc47c3eeb29" dependencies = [ - "rustix", + "rustix 1.1.2", "wayland-client", "xcursor", ] @@ -4478,7 +4637,7 @@ version = "0.31.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f81f365b8b4a97f422ac0e8737c438024b5951734506b0e1d775c73030561f4" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "wayland-backend", "wayland-client", "wayland-scanner", @@ -4486,11 +4645,11 @@ dependencies = [ [[package]] name = "wayland-protocols" -version = "0.32.5" +version = "0.32.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd0ade57c4e6e9a8952741325c30bf82f4246885dca8bf561898b86d0c1f58e" +checksum = "efa790ed75fbfd71283bd2521a1cfdc022aabcc28bdcff00851f9e4ae88d9901" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "wayland-backend", "wayland-client", "wayland-scanner", @@ -4502,7 +4661,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23803551115ff9ea9bce586860c5c5a971e360825a0309264102a9495a5ff479" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "wayland-backend", "wayland-client", "wayland-protocols 0.31.2", @@ -4511,14 +4670,14 @@ dependencies = [ [[package]] name = "wayland-protocols-plasma" -version = "0.3.5" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b31cab548ee68c7eb155517f2212049dc151f7cd7910c2b66abfd31c3ee12bd" +checksum = "a07a14257c077ab3279987c4f8bb987851bf57081b93710381daea94f2c2c032" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "wayland-backend", "wayland-client", - "wayland-protocols 0.32.5", + "wayland-protocols 0.32.9", "wayland-scanner", ] @@ -4528,7 +4687,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ad1f61b76b6c2d8742e10f9ba5c3737f6530b4c243132c2a2ccc8aa96fe25cd6" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "wayland-backend", "wayland-client", "wayland-protocols 0.31.2", @@ -4537,22 +4696,22 @@ dependencies = [ [[package]] name = "wayland-protocols-wlr" -version = "0.3.5" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "782e12f6cd923c3c316130d56205ebab53f55d6666b7faddfad36cecaeeb4022" +checksum = "efd94963ed43cf9938a090ca4f7da58eb55325ec8200c3848963e98dc25b78ec" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "wayland-backend", "wayland-client", - "wayland-protocols 0.32.5", + "wayland-protocols 0.32.9", "wayland-scanner", ] [[package]] name = "wayland-scanner" -version = "0.31.6" +version = "0.31.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "896fdafd5d28145fce7958917d69f2fd44469b1d4e861cb5961bcbeebc6d1484" +checksum = "54cb1e9dc49da91950bdfd8b848c49330536d9d1fb03d4bfec8cae50caa50ae3" dependencies = [ "proc-macro2", "quick-xml", @@ -4561,9 +4720,9 @@ dependencies = [ [[package]] name = "wayland-sys" -version = "0.31.6" +version = "0.31.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbcebb399c77d5aa9fa5db874806ee7b4eba4e73650948e8f93963f128896615" +checksum = "34949b42822155826b41db8e5d0c1be3a2bd296c747577a43a3e6daefc296142" dependencies = [ "dlib", "log", @@ -4573,9 +4732,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.77" +version = "0.3.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33b6dd2ef9186f1f2072e409e99cd22a975331a6b3591b12c764e0e55c60d5d2" +checksum = "3a1f95c0d03a47f4ae1f7a64643a6bb97465d9b740f0fa8f90ea33915c99a9a1" dependencies = [ "js-sys", "wasm-bindgen", @@ -4603,14 +4762,14 @@ dependencies = [ [[package]] name = "wgpu" -version = "24.0.0" +version = "27.0.0" dependencies = [ "arrayvec", - "bitflags 2.9.0", + "bitflags 2.10.0", "bytemuck", + "cfg-if", "cfg_aliases 0.2.1", "document-features", - "hashbrown", "js-sys", "log", "naga", @@ -4630,13 +4789,14 @@ dependencies = [ [[package]] name = "wgpu-benchmark" -version = "24.0.0" +version = "27.0.0" dependencies = [ - "bincode", + "bincode 2.0.1", "bytemuck", "criterion", "naga", - "nanorand", + "naga-test", + "nanorand 0.8.0", "pollster", "profiling", "rayon", @@ -4646,18 +4806,19 @@ dependencies = [ [[package]] name = "wgpu-core" -version = "24.0.0" +version = "27.0.0" dependencies = [ "arrayvec", - "bit-set 0.8.0", - "bit-vec 0.8.0", - "bitflags 2.9.0", + "bit-set", + "bit-vec", + "bitflags 2.10.0", "bytemuck", "cfg_aliases 0.2.1", "document-features", - "hashbrown", + "hashbrown 0.16.0", "indexmap", "log", + "macro_rules_attribute", "naga", "once_cell", "parking_lot", @@ -4665,10 +4826,10 @@ dependencies = [ "profiling", "raw-window-handle 0.6.2", "ron", - "rustc-hash", + "rustc-hash 1.1.0", "serde", "smallvec", - "thiserror 2.0.12", + "thiserror 2.0.17", "wgpu-core-deps-apple", "wgpu-core-deps-emscripten", "wgpu-core-deps-wasm", @@ -4679,28 +4840,28 @@ dependencies = [ [[package]] name = "wgpu-core-deps-apple" -version = "24.0.0" +version = "27.0.0" dependencies = [ "wgpu-hal", ] [[package]] name = "wgpu-core-deps-emscripten" -version = "24.0.0" +version = "27.0.0" dependencies = [ "wgpu-hal", ] [[package]] name = "wgpu-core-deps-wasm" -version = "24.0.0" +version = "27.0.0" dependencies = [ "wgpu-hal", ] [[package]] name = "wgpu-core-deps-windows-linux-android" -version = "24.0.0" +version = "27.0.0" dependencies = [ "wgpu-hal", ] @@ -4722,7 +4883,7 @@ dependencies = [ "env_logger", "pollster", "wgpu", - "winit 0.30.8", + "winit 0.30.12", ] [[package]] @@ -4735,7 +4896,7 @@ dependencies = [ [[package]] name = "wgpu-examples" -version = "24.0.0" +version = "27.0.0" dependencies = [ "bytemuck", "cfg-if", @@ -4745,10 +4906,11 @@ dependencies = [ "env_logger", "fern", "flume", + "getrandom 0.3.4", "glam", "ktx2", "log", - "nanorand", + "nanorand 0.8.0", "noise", "obj", "png", @@ -4766,18 +4928,18 @@ dependencies = [ [[package]] name = "wgpu-hal" -version = "24.0.0" +version = "27.0.0" dependencies = [ "android_system_properties", "arrayvec", "ash", - "bit-set 0.8.0", - "bitflags 2.9.0", + "bit-set", + "bitflags 2.10.0", "block", "bytemuck", "cfg-if", "cfg_aliases 0.2.1", - "core-graphics-types", + "core-graphics-types 0.2.0", "env_logger", "glam", "glow", @@ -4787,7 +4949,7 @@ dependencies = [ "gpu-alloc", "gpu-allocator", "gpu-descriptor", - "hashbrown", + "hashbrown 0.16.0", "js-sys", "khronos-egl", "libc", @@ -4796,37 +4958,38 @@ dependencies = [ "mach-dxcompiler-rs", "metal", "naga", - "ndk-sys 0.5.0+25.2.9519653", + "ndk-sys 0.6.0+11769913", "objc", "once_cell", "ordered-float", "parking_lot", "portable-atomic", + "portable-atomic-util", "profiling", "range-alloc", "raw-window-handle 0.5.2", "raw-window-handle 0.6.2", "renderdoc-sys", - "rustc-hash", "smallvec", - "thiserror 2.0.12", + "thiserror 2.0.17", "wasm-bindgen", "web-sys", "wgpu-types", - "windows", - "windows-core", + "windows 0.58.0", + "windows-core 0.58.0", "winit 0.29.15", ] [[package]] name = "wgpu-info" -version = "24.0.0" +version = "27.0.0" dependencies = [ "anyhow", - "bitflags 2.9.0", + "bitflags 2.10.0", "env_logger", - "hashbrown", + "hashbrown 0.16.0", "pico-args", + "pollster", "serde", "serde_json", "wgpu", @@ -4834,21 +4997,21 @@ dependencies = [ [[package]] name = "wgpu-macros" -version = "24.0.0" +version = "27.0.0" dependencies = [ - "heck 0.5.0", + "heck", "quote", "syn", ] [[package]] name = "wgpu-test" -version = "24.0.0" +version = "27.0.0" dependencies = [ "anyhow", "approx", "arrayvec", - "bitflags 2.9.0", + "bitflags 2.10.0", "bytemuck", "cargo_metadata", "cfg-if", @@ -4859,10 +5022,11 @@ dependencies = [ "glam", "half", "image", - "itertools 0.13.0", + "itertools 0.14.0", "js-sys", "libtest-mimic", "log", + "nanorand 0.8.0", "nv-flip", "parking_lot", "png", @@ -4870,30 +5034,42 @@ dependencies = [ "profiling", "serde", "serde_json", - "strum 0.26.3", + "strum", "trybuild", "wasm-bindgen", "wasm-bindgen-futures", "wasm-bindgen-test", "web-sys", "wgpu", + "wgpu-hal", "wgpu-macros", ] [[package]] name = "wgpu-types" -version = "24.0.0" +version = "27.0.0" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "bytemuck", "js-sys", "log", "serde", "serde_json", - "thiserror 2.0.12", "web-sys", ] +[[package]] +name = "wgpu-xtask" +version = "0.1.0" +dependencies = [ + "anyhow", + "env_logger", + "log", + "pico-args", + "regex-lite", + "xshell", +] + [[package]] name = "which" version = "6.0.3" @@ -4902,7 +5078,18 @@ checksum = "b4ee928febd44d98f2f459a4a79bd4d928591333a494a10a868418ac1b39cf1f" dependencies = [ "either", "home", - "rustix", + "rustix 0.38.44", + "winsafe", +] + +[[package]] +name = "which" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fabb953106c3c8eea8306e4393700d7657561cb43122571b172bbfb7c7ba1d" +dependencies = [ + "env_home", + "rustix 1.1.2", "winsafe", ] @@ -4924,11 +5111,11 @@ checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-util" -version = "0.1.9" +version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.61.2", ] [[package]] @@ -4943,23 +5130,69 @@ version = "0.58.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6" dependencies = [ - "windows-core", + "windows-core 0.58.0", "windows-targets 0.52.6", ] +[[package]] +name = "windows" +version = "0.61.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" +dependencies = [ + "windows-collections", + "windows-core 0.61.2", + "windows-future", + "windows-link 0.1.3", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8" +dependencies = [ + "windows-core 0.61.2", +] + [[package]] name = "windows-core" version = "0.58.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99" dependencies = [ - "windows-implement", - "windows-interface", - "windows-result", - "windows-strings", + "windows-implement 0.58.0", + "windows-interface 0.58.0", + "windows-result 0.2.0", + "windows-strings 0.1.0", "windows-targets 0.52.6", ] +[[package]] +name = "windows-core" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" +dependencies = [ + "windows-implement 0.60.2", + "windows-interface 0.59.3", + "windows-link 0.1.3", + "windows-result 0.3.4", + "windows-strings 0.4.2", +] + +[[package]] +name = "windows-future" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", + "windows-threading", +] + [[package]] name = "windows-implement" version = "0.58.0" @@ -4971,6 +5204,17 @@ dependencies = [ "syn", ] +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "windows-interface" version = "0.58.0" @@ -4982,6 +5226,39 @@ dependencies = [ "syn", ] +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-link" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", +] + [[package]] name = "windows-result" version = "0.2.0" @@ -4991,16 +5268,34 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-result" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" +dependencies = [ + "windows-link 0.1.3", +] + [[package]] name = "windows-strings" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" dependencies = [ - "windows-result", + "windows-result 0.2.0", "windows-targets 0.52.6", ] +[[package]] +name = "windows-strings" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" +dependencies = [ + "windows-link 0.1.3", +] + [[package]] name = "windows-sys" version = "0.45.0" @@ -5037,6 +5332,24 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link 0.2.1", +] + [[package]] name = "windows-targets" version = "0.42.2" @@ -5076,13 +5389,39 @@ dependencies = [ "windows_aarch64_gnullvm 0.52.6", "windows_aarch64_msvc 0.52.6", "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm", + "windows_i686_gnullvm 0.52.6", "windows_i686_msvc 0.52.6", "windows_x86_64_gnu 0.52.6", "windows_x86_64_gnullvm 0.52.6", "windows_x86_64_msvc 0.52.6", ] +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link 0.2.1", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows-threading" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6" +dependencies = [ + "windows-link 0.1.3", +] + [[package]] name = "windows_aarch64_gnullvm" version = "0.42.2" @@ -5101,6 +5440,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + [[package]] name = "windows_aarch64_msvc" version = "0.42.2" @@ -5119,6 +5464,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + [[package]] name = "windows_i686_gnu" version = "0.42.2" @@ -5137,12 +5488,24 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + [[package]] name = "windows_i686_msvc" version = "0.42.2" @@ -5161,6 +5524,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + [[package]] name = "windows_x86_64_gnu" version = "0.42.2" @@ -5179,6 +5548,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + [[package]] name = "windows_x86_64_gnullvm" version = "0.42.2" @@ -5197,6 +5572,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + [[package]] name = "windows_x86_64_msvc" version = "0.42.2" @@ -5215,6 +5596,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + [[package]] name = "winit" version = "0.29.15" @@ -5224,11 +5611,11 @@ dependencies = [ "ahash", "android-activity 0.5.2", "atomic-waker", - "bitflags 2.9.0", + "bitflags 2.10.0", "bytemuck", "calloop 0.12.4", "cfg_aliases 0.1.1", - "core-foundation", + "core-foundation 0.9.4", "core-graphics", "cursor-icon", "icrate", @@ -5245,7 +5632,7 @@ dependencies = [ "raw-window-handle 0.5.2", "raw-window-handle 0.6.2", "redox_syscall 0.3.5", - "rustix", + "rustix 0.38.44", "sctk-adwaita 0.8.3", "smithay-client-toolkit 0.18.1", "smol_str", @@ -5266,20 +5653,20 @@ dependencies = [ [[package]] name = "winit" -version = "0.30.8" +version = "0.30.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5d74280aabb958072864bff6cfbcf9025cf8bfacdde5e32b5e12920ef703b0f" +checksum = "c66d4b9ed69c4009f6321f762d6e61ad8a2389cd431b97cb1e146812e9e6c732" dependencies = [ "ahash", "android-activity 0.6.0", "atomic-waker", - "bitflags 2.9.0", + "bitflags 2.10.0", "block2 0.5.1", "bytemuck", "calloop 0.13.0", "cfg_aliases 0.2.1", "concurrent-queue", - "core-foundation", + "core-foundation 0.9.4", "core-graphics", "cursor-icon", "dpi", @@ -5296,7 +5683,7 @@ dependencies = [ "pin-project", "raw-window-handle 0.6.2", "redox_syscall 0.4.1", - "rustix", + "rustix 0.38.44", "sctk-adwaita 0.10.1", "smithay-client-toolkit 0.19.2", "smol_str", @@ -5306,8 +5693,8 @@ dependencies = [ "wasm-bindgen-futures", "wayland-backend", "wayland-client", - "wayland-protocols 0.32.5", - "wayland-protocols-plasma 0.3.5", + "wayland-protocols 0.32.9", + "wayland-protocols-plasma 0.3.9", "web-sys", "web-time 1.1.0", "windows-sys 0.52.0", @@ -5318,9 +5705,9 @@ dependencies = [ [[package]] name = "winnow" -version = "0.7.4" +version = "0.7.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e97b544156e9bebe1a0ffbc03484fc1ffe3100cbce3ffb17eac35f7cdd7ab36" +checksum = "21a0236b59786fed61e2a80582dd500fe61f18b5dca67a4a067d0bc9039339cf" dependencies = [ "memchr", ] @@ -5332,25 +5719,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" [[package]] -name = "wit-bindgen-rt" -version = "0.33.0" +name = "wit-bindgen" +version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3268f3d866458b787f390cf61f4bbb563b922d091359f9608842999eaee3943c" -dependencies = [ - "bitflags 2.9.0", -] - -[[package]] -name = "write16" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" +checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" [[package]] name = "writeable" -version = "0.5.5" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51" +checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" [[package]] name = "wyz" @@ -5374,30 +5752,30 @@ dependencies = [ [[package]] name = "x11rb" -version = "0.13.1" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d91ffca73ee7f68ce055750bf9f6eca0780b8c85eff9bc046a3b0da41755e12" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" dependencies = [ "as-raw-xcb-connection", "gethostname", "libc", "libloading", "once_cell", - "rustix", + "rustix 1.1.2", "x11rb-protocol", ] [[package]] name = "x11rb-protocol" -version = "0.13.1" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec107c4503ea0b4a98ef47356329af139c0a4f7750e621cf2973cd3385ebcb3d" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" [[package]] name = "xcursor" -version = "0.3.8" +version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ef33da6b1660b4ddbfb3aef0ade110c8b8a781a3b6382fa5f2b5b040fd55f61" +checksum = "bec9e4a500ca8864c5b47b8b482a73d62e4237670e5b5f1d6b9e3cae50f28f2b" [[package]] name = "xkbcommon-dl" @@ -5405,7 +5783,7 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.10.0", "dlib", "log", "once_cell", @@ -5420,17 +5798,31 @@ checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" [[package]] name = "xml-rs" -version = "0.8.25" +version = "0.8.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5b940ebc25896e71dd073bad2dbaa2abfe97b0a391415e22ad1326d9c54e3c4" +checksum = "3ae8337f8a065cfc972643663ea4279e04e7256de865aa66fe25cec5fb912d3f" + +[[package]] +name = "xshell" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e7290c623014758632efe00737145b6867b66292c42167f2ec381eb566a373d" +dependencies = [ + "xshell-macros", +] + +[[package]] +name = "xshell-macros" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32ac00cd3f8ec9c1d33fb3e7958a82df6989c42d747bd326c822b1d625283547" [[package]] name = "yoke" -version = "0.7.5" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "120e6aef9aa629e3d4f52dc8cc43a015c7724194c97dfaf45180d2daf2b77f40" +checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" dependencies = [ - "serde", "stable_deref_trait", "yoke-derive", "zerofrom", @@ -5438,9 +5830,9 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.7.5" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154" +checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" dependencies = [ "proc-macro2", "quote", @@ -5450,18 +5842,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.7.35" +version = "0.8.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" +checksum = "0894878a5fa3edfd6da3f88c4805f4c8558e2b996227a3d864f47fe11e38282c" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.7.35" +version = "0.8.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" +checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831" dependencies = [ "proc-macro2", "quote", @@ -5490,10 +5882,21 @@ dependencies = [ ] [[package]] -name = "zerovec" -version = "0.10.4" +name = "zerotrie" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa2b893d79df23bfb12d5461018d408ea19dfafe76c2c7ef6d4eba614f8ff079" +checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" dependencies = [ "yoke", "zerofrom", @@ -5502,9 +5905,9 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.10.3" +version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" +checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 566bdfdaf..335dddaa6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,9 +10,11 @@ members = [ "examples/standalone/*", "lock-analyzer", "naga-cli", + "naga-test", "naga", "naga/fuzz", "naga/hlsl-snapshots", + "naga/xtask", "player", "tests", "wgpu-core", @@ -22,6 +24,7 @@ members = [ "wgpu-macros", "wgpu-types", "wgpu", + "xtask", ] exclude = [] default-members = [ @@ -30,9 +33,11 @@ default-members = [ "examples/standalone/*", "lock-analyzer", "naga-cli", + "naga-test", "naga", "naga/fuzz", "naga/hlsl-snapshots", + "naga/xtask", "player", "tests", "wgpu-core", @@ -42,6 +47,7 @@ default-members = [ "wgpu-macros", "wgpu-types", "wgpu", + "xtask", ] [workspace.lints.clippy] @@ -50,17 +56,18 @@ ref_as_ptr = "warn" [workspace.package] edition = "2021" -rust-version = "1.84" +rust-version = "1.88" keywords = ["graphics"] license = "MIT OR Apache-2.0" homepage = "https://wgpu.rs/" repository = "https://github.com/gfx-rs/wgpu" -version = "24.0.0" +version = "27.0.0" authors = ["gfx-rs developers"] [workspace.dependencies] -naga = { version = "24.0.0", path = "./naga" } -wgpu = { version = "24.0.0", path = "./wgpu", default-features = false, features = [ +naga = { version = "27.0.0", path = "./naga" } +naga-test = { path = "./naga-test" } +wgpu = { version = "27.0.0", path = "./wgpu", default-features = false, features = [ "serde", "wgsl", "vulkan", @@ -68,25 +75,30 @@ wgpu = { version = "24.0.0", path = "./wgpu", default-features = false, features "dx12", "metal", "static-dxc", - "webgl", "noop", # This should be removed if we ever have non-test crates that depend on wgpu ] } -wgpu-core = { version = "24.0.0", path = "./wgpu-core" } -wgpu-hal = { version = "24.0.0", path = "./wgpu-hal" } -wgpu-macros = { version = "24.0.0", path = "./wgpu-macros" } -wgpu-test = { version = "24.0.0", path = "./tests" } -wgpu-types = { version = "24.0.0", path = "./wgpu-types" } +wgpu-core = { version = "27.0.0", path = "./wgpu-core" } +wgpu-hal = { version = "27.0.0", path = "./wgpu-hal" } +wgpu-macros = { version = "27.0.0", path = "./wgpu-macros" } +wgpu-test = { version = "27.0.0", path = "./tests" } +wgpu-types = { version = "27.0.0", path = "./wgpu-types", default-features = false } -wgpu-core-deps-windows-linux-android = { version = "24.0.0", path = "./wgpu-core/platform-deps/windows-linux-android" } -wgpu-core-deps-apple = { version = "24.0.0", path = "./wgpu-core/platform-deps/apple" } -wgpu-core-deps-wasm = { version = "24.0.0", path = "./wgpu-core/platform-deps/wasm" } -wgpu-core-deps-emscripten = { version = "24.0.0", path = "./wgpu-core/platform-deps/emscripten" } +# These _cannot_ have a version specified. If it does, crates.io will look +# for a version of the package on crates when we publish naga. Path dependencies +# are allowed through though. +hlsl-snapshots = { path = "naga/hlsl-snapshots" } -anyhow = { version = "1.0.97", default-features = false } +wgpu-core-deps-windows-linux-android = { version = "27.0.0", path = "./wgpu-core/platform-deps/windows-linux-android" } +wgpu-core-deps-apple = { version = "27.0.0", path = "./wgpu-core/platform-deps/apple" } +wgpu-core-deps-wasm = { version = "27.0.0", path = "./wgpu-core/platform-deps/wasm" } +wgpu-core-deps-emscripten = { version = "27.0.0", path = "./wgpu-core/platform-deps/emscripten" } + +anyhow = { version = "1.0.87", default-features = false } approx = "0.5" +arbitrary = "1.4.2" argh = "0.1.13" -arrayvec = { version = "0.7.6", default-features = false } -bincode = "1" +arrayvec = { version = "0.7.1", default-features = false } +bincode = "2" bit-set = { version = "0.8", default-features = false } bit-vec = { version = "0.8", default-features = false } bitflags = "2.9" @@ -94,81 +106,110 @@ bytemuck = { version = "1.22", features = [ "extern_crate_alloc", "min_const_generics", ] } -cargo_metadata = "0.19" +cargo_metadata = "0.23" cfg_aliases = "0.2.1" cfg-if = "1" -criterion = "0.5" +criterion = "0.7" codespan-reporting = { version = "0.12", default-features = false } -ctor = "0.2" -document-features = "0.2.11" -encase = "0.10.0" -env_logger = "0.11" +ctor = "0.6" +diff = "0.1" +document-features = "0.2.10" +encase = "0.12" +env_logger = { version = "0.11", default-features = false } fern = "0.7" flume = "0.11" futures-lite = "2" -glam = "0.29" -half = "2.5" # We require 2.5 to have `Arbitrary` support. -hashbrown = { version = "0.15.2", default-features = false, features = [ +getrandom = "0.3" +glam = "0.30.7" +glob = "0.3" +half = { version = "2.5", default-features = false } # We require 2.5 to have `Arbitrary` support. +hashbrown = { version = "0.16", default-features = false, features = [ "default-hasher", "inline-more", ] } -heck = "0.5.0" -image = { version = "0.24", default-features = false, features = ["png"] } -indexmap = { version = "2.7.1", default-features = false } -itertools = { version = "0.13.0" } -ktx2 = "0.3" -libc = { version = "0.2", default-features = false } +heck = "0.5" +hexf-parse = "0.2" +image = { version = "0.25", default-features = false, features = ["png"] } +indexmap = { version = "2.8", default-features = false } +indicatif = "0.18" +itertools = { version = "0.14" } +jobserver = "0.1" +ktx2 = "0.4" +libc = { version = "0.2.171", default-features = false } +# See https://github.com/rust-fuzz/libfuzzer/issues/126 +libfuzzer-sys = ">0.4.0,<=0.4.7" libloading = "0.8" -libtest-mimic = "0.8.1" -log = "0.4" -nanorand = { version = "0.7", default-features = false, features = ["wyrand"] } +libm = { version = "0.2.6", default-features = false } +libtest-mimic = "0.8" +log = "0.4.21" +macro_rules_attribute = "0.2" +nanoserde = "0.2" +nanorand = { version = "0.8", default-features = false, features = ["wyrand"] } noise = "0.9" +num_cpus = "1" +# `half` requires 0.2.16 for `FromBytes` and `ToBytes`. +num-traits = { version = "0.2.16", default-features = false } nv-flip = "0.1" obj = "0.10" # NOTE: once_cell/std is *required* for some commonly-used features, selecting this per crate -once_cell = { version = "1.21.1", default-features = false } +once_cell = { version = "1.21", default-features = false } # Firefox has 3.4.0 vendored, so we allow that version in our dependencies -ordered-float = { version = ">=3,<=4.6", default-features = false } -parking_lot = "0.12.1" -pico-args = { version = "0.5.0", features = [ +ordered-float = { version = ">=3, <6.0", default-features = false } +parking_lot = "0.12.3" +petgraph = { version = "0.8", default-features = false } +pico-args = { version = "0.5", features = [ "eq-separator", "short-space-opt", "combined-flags", ] } -png = "0.17.16" +png = "0.18" pollster = "0.4" -portable-atomic = "1" -profiling = { version = "1", default-features = false } -raw-window-handle = { version = "0.6", default-features = false } -rayon = "1" -renderdoc-sys = "1.1.0" -ron = "0.9" +portable-atomic = "1.8" +portable-atomic-util = "0.2.4" +pp-rs = "0.2.1" +profiling = { version = "1.0.1", default-features = false } +quote = "1.0.38" +raw-window-handle = { version = "0.6.2", default-features = false } +rwh_05 = { version = "0.5.2", package = "raw-window-handle" } # temporary compatibility for glutin-winit +rayon = "1.3" +regex-lite = "0.1" +renderdoc-sys = "1" +rspirv = "0.12" +ron = "0.11" # NOTE: rustc-hash v2 is a completely different hasher with different performance characteristics # see discussion here (including with some other alternatives): https://github.com/gfx-rs/wgpu/issues/6999 # (using default-features = false to support no-std build, avoiding any extra features that may require std::collections) -rustc-hash = { version = "1", default-features = false } -serde_json = "1.0.140" -serde = { version = "1", default-features = false } -smallvec = "1" -static_assertions = "1.1.0" -strum = { version = "0.26.3", default-features = false, features = ["derive"] } +rustc-hash = { version = "1.1", default-features = false } +serde_json = "1.0.143" +serde = { version = "1.0.219", default-features = false } +shell-words = "1" +smallvec = "1.14" +spirv = "0.3" +static_assertions = "1.1" +strum = { version = "0.27.1", default-features = false, features = ["derive"] } +syn = "2.0.98" +tempfile = "3" +toml = "0.9.0" trybuild = "1" -tracy-client = "0.17" -thiserror = { version = "2", default-features = false } -walkdir = "2" +tracy-client = "0.18" +thiserror = { version = "2.0.12", default-features = false } +unicode-ident = "1.0.5" +walkdir = "2.3" winit = { version = "0.29", features = ["android-native-activity"] } +which = "8" +xshell = "0.2.2" # Metal dependencies -metal = "0.31.0" -block = "0.1" -core-graphics-types = "0.1" +metal = "0.32" +block = "0.1.6" +core-graphics-types = "0.2" objc = "0.2.5" # Vulkan dependencies android_system_properties = "0.1.1" -ash = "0.38.0" +ash = "0.38" gpu-alloc = "0.6" -gpu-descriptor = "0.3" +gpu-descriptor = "0.3.2" # DX12 dependencies gpu-allocator = { version = "0.27", default-features = false } @@ -187,29 +228,30 @@ glutin_wgl_sys = "0.6" windows = { version = "0.58", default-features = false } # wasm32 dependencies -console_error_panic_hook = "0.1.7" +console_error_panic_hook = "0.1.5" console_log = "1" -js-sys = { version = "0.3.70", default-features = false } -wasm-bindgen = "0.2.97" -wasm-bindgen-futures = "0.4.45" +js-sys = { version = "0.3.77", default-features = false } +wasm-bindgen = "0.2.100" +wasm-bindgen-futures = "0.4.43" wasm-bindgen-test = "0.3" -web-sys = { version = "0.3.74", default-features = false } +web-sys = { version = "0.3.77", default-features = false } web-time = "1.1.0" # deno dependencies -deno_console = "0.190.0" -deno_core = "0.336.0" -deno_url = "0.190.0" -deno_web = "0.221.0" -deno_webidl = "0.190.0" -deno_webgpu = { version = "0.157.0", path = "./deno_webgpu" } -deno_unsync = "0.4.2" -deno_error = "0.5.5" -tokio = "1.44.1" -termcolor = "1.4.1" +deno_console = "0.214.0" +deno_core = "0.355.0" +deno_features = "0.11.0" +deno_url = "0.214.0" +deno_web = "0.245.0" +deno_webidl = "0.214.0" +deno_webgpu = { version = "0.181.0", path = "./deno_webgpu" } +deno_unsync = "0.4.4" +deno_error = "0.7.0" +tokio = "1.45.1" +termcolor = "1.1.3" # android dependencies -ndk-sys = "0.5.0" +ndk-sys = "0.6" # These overrides allow our examples to explicitly depend on release crates [patch.crates-io] diff --git a/GOVERNANCE.md b/GOVERNANCE.md index 73205cc41..b3e7a4086 100644 --- a/GOVERNANCE.md +++ b/GOVERNANCE.md @@ -1,15 +1,15 @@ -The **WGPU project** is a set of open-source libraries that _enables application +The **wgpu project** is a set of open-source libraries that _enables application authors to write portable and performant graphics programs_. It was originally conceived to provide an implementation of WebGPU for Firefox as the standard evolved, and settled into something that could be shipped on all web browsers. -WGPU has also enjoyed much contribution and use from other projects that require +wgpu has also enjoyed much contribution and use from other projects that require graphics programming. We expect that these sorts of users will continue for the lifetime of project, and we embrace these contributors' needs and effort as the -lifeblood of WGPU. +lifeblood of wgpu. ## Mission -The WGPU community seeks to realize the following directives through the +The wgpu community seeks to realize the following directives through the project: it… 1. …provides libraries for the WebGPU API that… @@ -28,7 +28,7 @@ project: it… ## Decision-making -The WGPU community's decision-making is influenced by the following +The wgpu community's decision-making is influenced by the following groups: * Community leadership: @@ -38,18 +38,18 @@ groups: * Firefox's WebGPU team (@jimblandy, @nical, @teoxoy, @ErichDonGubler, and others) * Deno's WebGPU contributors (@crowlKats) -* Other users that ship applications based on WGPU +* Other users that ship applications based on wgpu It is no coincidence that these groups correspond to the historically most -active and consistent contributors. In general, WGPU's community structure is +active and consistent contributors. In general, wgpu's community structure is meritocratic: social influence is granted proportionate to groups' contribution -to and stake in WGPU's mission. +to and stake in wgpu's mission. These decision-making groups meet together regularly to discuss issues of -importance to the community, with a focus on WGPU's [mission](#Mission). +importance to the community, with a focus on wgpu's [mission](#Mission). --- NOTE: The above is a snapshot of a perpetually changing state of affairs in the -WGPU community. It is not a binding contract between users and decision-makers -of the WGPU project. +wgpu community. It is not a binding contract between users and decision-makers +of the wgpu project. diff --git a/LICENSE.MIT b/LICENSE.MIT index 4699691b8..8d02e4dbd 100644 --- a/LICENSE.MIT +++ b/LICENSE.MIT @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2021 The gfx-rs developers +Copyright (c) 2025 The gfx-rs developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index aaf016183..94d413584 100644 --- a/README.md +++ b/README.md @@ -2,10 +2,10 @@ [![Matrix Space](https://img.shields.io/static/v1?label=Space&message=%23Wgpu&color=blue&logo=matrix)](https://matrix.to/#/#Wgpu:matrix.org) -[![Dev Matrix ](https://img.shields.io/static/v1?label=devs&message=%23wgpu&color=blueviolet&logo=matrix)](https://matrix.to/#/#wgpu:matrix.org) -[![User Matrix ](https://img.shields.io/static/v1?label=users&message=%23wgpu-users&color=blueviolet&logo=matrix)](https://matrix.to/#/#wgpu-users:matrix.org) -[![Build Status](https://github.com/gfx-rs/wgpu/workflows/CI/badge.svg)](https://github.com/gfx-rs/wgpu/actions) -[![codecov.io](https://codecov.io/gh/gfx-rs/wgpu/branch/trunk/graph/badge.svg?token=84qJTesmeS)](https://codecov.io/gh/gfx-rs/wgpu) +[![Dev Matrix](https://img.shields.io/static/v1?label=devs&message=%23wgpu&color=blueviolet&logo=matrix)](https://matrix.to/#/#wgpu:matrix.org) +[![User Matrix](https://img.shields.io/static/v1?label=users&message=%23wgpu-users&color=blueviolet&logo=matrix)](https://matrix.to/#/#wgpu-users:matrix.org) +[![Build Status](https://img.shields.io/github/actions/workflow/status/gfx-rs/wgpu/ci.yml?branch=trunk&logo=github&label=CI)](https://github.com/gfx-rs/wgpu/actions) +[![codecov.io](https://img.shields.io/codecov/c/github/gfx-rs/wgpu?logo=codecov&logoColor=fff&label=codecov&token=84qJTesmeS)](https://codecov.io/gh/gfx-rs/wgpu) `wgpu` is a cross-platform, safe, pure-rust graphics API. It runs natively on Vulkan, Metal, D3D12, and OpenGL; and on top of WebGL2 and WebGPU on wasm. @@ -17,13 +17,13 @@ The API is based on the [WebGPU standard][webgpu]. It serves as the core of the | Docs | Examples | Changelog | |:---------------------:|:-------------------------:|:-----------------------:| -| [v24][rel-docs] | [v24][rel-examples] | [v24][rel-change] | +| [v27][rel-docs] | [v27][rel-examples] | [v27][rel-change] | | [`trunk`][trunk-docs] | [`trunk`][trunk-examples] | [`trunk`][trunk-change] | Contributors are welcome! See [CONTRIBUTING.md][contrib] for more information. [rel-docs]: https://docs.rs/wgpu/ -[rel-examples]: https://github.com/gfx-rs/wgpu/tree/v24/examples#readme +[rel-examples]: https://github.com/gfx-rs/wgpu/tree/v27/examples#readme [rel-change]: https://github.com/gfx-rs/wgpu/releases [trunk-docs]: https://wgpu.rs/doc/wgpu/ [trunk-examples]: https://github.com/gfx-rs/wgpu/tree/trunk/examples#readme @@ -99,6 +99,7 @@ For high-level documentation on how to use these extensions, see the individual 🧪EXPERIMENTAL🧪 APIs are subject to change and may allow undefined behavior if used incorrectly. - 🧪EXPERIMENTAL🧪 [Ray Tracing](./docs/api-specs/ray_tracing.md). +- 🧪EXPERIMENTAL🧪 [Mesh Shading](./docs/api-specs/mesh_shading.md). ## Supported Platforms @@ -148,8 +149,8 @@ On Linux, you can point to them using `LD_LIBRARY_PATH` environment. Due to complex dependants, we have two MSRV policies: -- `naga`, `wgpu-core`, `wgpu-hal`, and `wgpu-types`'s MSRV is **1.76**. -- The rest of the workspace has an MSRV of **1.84**. +- `naga`, `wgpu-core`, `wgpu-hal`, and `wgpu-types`'s MSRV is **1.82**. +- The rest of the workspace has an MSRV of **1.88**. It is enforced on CI (in "/.github/workflows/ci.yml") with the `CORE_MSRV` and `REPO_MSRV` variables. This version can only be upgraded in breaking releases, though we release a breaking version every three months. @@ -168,7 +169,7 @@ All testing and example infrastructure share the same set of environment variabl - `WGPU_ADAPTER_NAME` with a substring of the name of the adapter you want to use (ex. `1080` will match `NVIDIA GeForce 1080ti`). - `WGPU_BACKEND` with a comma-separated list of the backends you want to use (`vulkan`, `metal`, `dx12`, or `gl`). - `WGPU_POWER_PREF` with the power preference to choose when a specific adapter name isn't specified (`high`, `low` or `none`) -- `WGPU_DX12_COMPILER` with the DX12 shader compiler you wish to use (`dxc`, `static-dxc`, or `fxc`). Note that `dxc` requires `dxil.dll` and `dxcompiler.dll` to be in the working directory, and `static-dxc` requires the `static-dxc` crate feature to be enabled. Otherwise, it will fall back to `fxc`. +- `WGPU_DX12_COMPILER` with the DX12 shader compiler you wish to use (`dxc`, `static-dxc`, or `fxc`). Note that `dxc` requires `dxcompiler.dll` (min v1.8.2502) to be in the working directory, and `static-dxc` requires the `static-dxc` crate feature to be enabled. Otherwise, it will fall back to `fxc`. - `WGPU_GLES_MINOR_VERSION` with the minor OpenGL ES 3 version number to request (`0`, `1`, `2` or `automatic`). - `WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER` with a boolean whether non-compliant drivers are enumerated (`0` for false, `1` for true). @@ -212,27 +213,34 @@ If you are a user and want a way to help contribute to wgpu, we always need more ### WebGPU Conformance Test Suite -WebGPU includes a Conformance Test Suite to validate that implementations are working correctly. We can run this CTS against wgpu. +WebGPU includes a Conformance Test Suite to validate that implementations are +working correctly. We run cases from the CTS against wgpu using +[Deno](https://deno.com/). A [default list of enabled +tests](./cts_runner/test.lst) is automatically run on pull requests in CI. -To run the CTS, first, you need to check it out: +To run the default set of CTS tests locally, run: ``` -git clone https://github.com/gpuweb/cts.git -cd cts -# works in bash and powershell -git checkout $(cat ../cts_runner/revision.txt) +cargo xtask cts ``` -To run a given set of tests: +You can also specify a test selector on the command line: ``` -# Must be inside the `cts` folder we just checked out, else this will fail -cargo run --manifest-path ../Cargo.toml -p cts_runner --bin cts_runner -- ./tools/run_deno --verbose "" +cargo xtask cts 'webgpu:api,operation,command_buffer,basic:*' ``` -To find the full list of tests, go to the [online cts viewer](https://gpuweb.github.io/cts/standalone/?runnow=0&worker=0&debug=0&q=webgpu:*). +Or supply your own test list in a file: -The list of currently enabled CTS tests can be found [here](./cts_runner/test.lst). +``` +cargo xtask cts -f your_tests.lst +``` + +To find the full list of tests, go to the +[web version of the CTS](https://gpuweb.github.io/cts/standalone/?runnow=0&worker=0&debug=0&q=webgpu:*). + +The version of the CTS used by `cargo xtask cts` is specified in +[`cts_runner/revision.txt`](./cts_runner/revision.txt). ## Tracking the WebGPU and WGSL draft specifications @@ -247,12 +255,11 @@ as the implementation catches up. Exactly which WGSL features `wgpu` supports depends on how you are using it: -- When running as native code, `wgpu` uses the [Naga][naga] crate +- When running as native code, `wgpu` uses [Naga][naga] to translate WGSL code into the shading language of your platform's native GPU API. - Naga has [a milestone][naga wgsl milestone] - for catching up to the WGSL specification, - but in general, there is no up-to-date summary - of the differences between Naga and the WGSL spec. + Naga is working on catching up to the WGSL specification, + with [bugs][naga bugs] tracking various issues, + but there is no concise summary of differences from the specification. - When running in a web browser (by compilation to WebAssembly) without the `"webgl"` feature enabled, @@ -266,8 +273,8 @@ Exactly which WGSL features `wgpu` supports depends on how you are using it: [webgpu spec]: https://www.w3.org/TR/webgpu/ [wgsl spec]: https://gpuweb.github.io/gpuweb/wgsl/ -[naga]: https://github.com/gfx-rs/naga/ -[naga wgsl milestone]: https://github.com/gfx-rs/naga/milestone/4 +[naga]: https://github.com/gfx-rs/wgpu/tree/trunk/naga/ +[naga bugs]: https://github.com/gfx-rs/wgpu/issues?q=is%3Aissue%20state%3Aopen%20label%3A%22naga%22 ## Coordinate Systems diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000..d6651d1e8 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,84 @@ +# wgpu Security Policy + +This document describes what is considered a security vulnerability in wgpu and +how vulnerabilities should be reported. + + +## Vulnerability Definition + +WebGPU introduces a different threat model than is sometimes applied to +GPU-related software. Unlike typical gaming or high-performance computing +applications, where the software accessing GPU APIs is proprietary or +obtained from a trusted developer, WebGPU makes GPU APIs available to +arbitrary web applications. In the threat model of the web, malicious +content should not be able to use the GPU APIs to access data or interfaces +outside the intended scope for interaction with web content. Therefore, `wgpu` +seeks to prevent undefined behavior and data leaks even when its API is +misused, and failures to do so may be considered vulnerabilities. (This is +also in accordance with the Rust principle of safe vs. unsafe code, since the +`wgpu` library exposes a safe API.) + +The wgpu maintainers have discretion in assigning a severity to individual +vulnerabilities. It is generally considered a high-severity vulnerability in +wgpu if JavaScript or WebAssembly code, running with privileges of ordinary web +content in a browser that is using wgpu to provide the WebGPU API to that +content, is able to: + +- Access data associated with native applications other than the user agent, + or associated with other web origins. +- Escape the applicable sandbox and run arbitrary code or call arbitrary system + APIs on the user agent host. +- Consume system resources to the point that it is difficult to recover + (e.g. by closing the web page). + +The wgpu Rust API offers some functionality, both supported and experimental, +that is not part of the WebGPU standard and is not made available in JavaScript +environments using wgpu. Associated vulnerabilities may be assigned lower +severity than vulnerabilities that apply to a wgpu-based WebGPU implementation +exposed to JavaScript. + + +## Supported Versions + +The wgpu project maintains security support for serious vulnerabilities in the +[most recent major release](https://github.com/gfx-rs/wgpu/releases). Fixes for +security vulnerabilities found shortly after the initial release of a major +version may also be provided for the previous major release. + +Mozilla provides security support for versions of wgpu used in [current +versions of Firefox](https://whattrainisitnow.com/). + +The version of wgpu that is active can be found in the Firefox repositories: + +- [release](https://github.com/mozilla-firefox/firefox/blob/release/gfx/wgpu_bindings/Cargo.toml), +- [beta](https://github.com/mozilla-firefox/firefox/blob/beta/gfx/wgpu_bindings/Cargo.toml), and +- [nightly](https://github.com/mozilla-firefox/firefox/blob/main/gfx/wgpu_bindings/Cargo.toml), + +We welcome reports of security vulnerabilities in any of these released +versions or in the latest code on the `trunk` branch. + + +## Reporting a Vulnerability + +Although not all vulnerabilities in wgpu will affect Firefox, Mozilla accepts +all vulnerability reports for wgpu and directs them appropriately. Additionally, +Mozilla serves as the CVE numbering authority for the wgpu project. + +To report a security problem with wgpu, create a bug in Mozilla's Bugzilla +instance in the +[Core :: Graphics :: WebGPU](https://bugzilla.mozilla.org/enter_bug.cgi?product=Core&component=Graphics%3A+WebGPU&groups=core-security&groups=gfx-core-security) +component. + +**IMPORTANT: For security issues, please make sure that you check the box +labelled "Many users could be harmed by this security problem".** We advise +that you check this option for anything that is potentially +security-relevant, including memory safety, crashes, race conditions, and +handling of confidential information. + +Review Mozilla's [guides on bug +reporting](https://bugzilla.mozilla.org/page.cgi?id=bug-writing.html) before +you open a bug. + +Mozilla operates a [bug bounty +program](https://www.mozilla.org/en-US/security/bug-bounty/). Some +vulnerabilities in this project may be eligible. diff --git a/benches/Cargo.toml b/benches/Cargo.toml index c018aba58..a1d09eea3 100644 --- a/benches/Cargo.toml +++ b/benches/Cargo.toml @@ -9,13 +9,11 @@ repository.workspace = true keywords.workspace = true license.workspace = true rust-version.workspace = true -autobenches = false publish = false [[bench]] name = "wgpu-benchmark" harness = false -path = "benches/root.rs" [features] # Uncomment these features to enable tracy and superluminal profiling. @@ -28,7 +26,7 @@ unexpected_cfgs = { level = "warn", check-cfg = [ ] } [dependencies] -bincode.workspace = true +bincode = { workspace = true, features = ["serde"] } bytemuck.workspace = true criterion.workspace = true naga = { workspace = true, features = [ @@ -43,6 +41,7 @@ naga = { workspace = true, features = [ "glsl-out", "wgsl-out", ] } +naga-test = { workspace = true, features = [] } nanorand.workspace = true pollster.workspace = true profiling.workspace = true diff --git a/benches/benches/bind_groups.rs b/benches/benches/wgpu-benchmark/bind_groups.rs similarity index 98% rename from benches/benches/bind_groups.rs rename to benches/benches/wgpu-benchmark/bind_groups.rs index 6fb23d0a2..cd2ad451a 100644 --- a/benches/benches/bind_groups.rs +++ b/benches/benches/wgpu-benchmark/bind_groups.rs @@ -87,7 +87,7 @@ fn run_bench(ctx: &mut Criterion) { for &count in count_list { group.throughput(Throughput::Elements(count as u64)); group.bench_with_input( - format!("{} Element Bind Group", count), + format!("{count} Element Bind Group"), &count, |b, &count| { b.iter_custom(|iters| { @@ -155,7 +155,7 @@ fn run_bench(ctx: &mut Criterion) { state .device_state .device - .poll(wgpu::PollType::Wait) + .poll(wgpu::PollType::wait_indefinitely()) .unwrap(); } diff --git a/benches/benches/computepass-bindless.wgsl b/benches/benches/wgpu-benchmark/computepass-bindless.wgsl similarity index 100% rename from benches/benches/computepass-bindless.wgsl rename to benches/benches/wgpu-benchmark/computepass-bindless.wgsl diff --git a/benches/benches/computepass.rs b/benches/benches/wgpu-benchmark/computepass.rs similarity index 99% rename from benches/benches/computepass.rs rename to benches/benches/wgpu-benchmark/computepass.rs index 9254547a1..ed8816416 100644 --- a/benches/benches/computepass.rs +++ b/benches/benches/wgpu-benchmark/computepass.rs @@ -489,7 +489,7 @@ fn run_bench(ctx: &mut Criterion) { state .device_state .device - .poll(wgpu::PollType::Wait) + .poll(wgpu::PollType::wait_indefinitely()) .unwrap(); } @@ -538,7 +538,7 @@ fn run_bench(ctx: &mut Criterion) { state .device_state .device - .poll(wgpu::PollType::Wait) + .poll(wgpu::PollType::wait_indefinitely()) .unwrap(); } @@ -584,7 +584,7 @@ fn run_bench(ctx: &mut Criterion) { state .device_state .device - .poll(wgpu::PollType::Wait) + .poll(wgpu::PollType::wait_indefinitely()) .unwrap(); } diff --git a/benches/benches/computepass.wgsl b/benches/benches/wgpu-benchmark/computepass.wgsl similarity index 100% rename from benches/benches/computepass.wgsl rename to benches/benches/wgpu-benchmark/computepass.wgsl diff --git a/benches/benches/root.rs b/benches/benches/wgpu-benchmark/main.rs similarity index 95% rename from benches/benches/root.rs rename to benches/benches/wgpu-benchmark/main.rs index c087f1f84..091ba8d0e 100644 --- a/benches/benches/root.rs +++ b/benches/benches/wgpu-benchmark/main.rs @@ -47,6 +47,7 @@ impl DeviceState { required_features: adapter.features(), required_limits: adapter.limits(), memory_hints: wgpu::MemoryHints::Performance, + experimental_features: unsafe { wgpu::ExperimentalFeatures::enabled() }, label: Some("Compute/RenderPass Device"), trace: wgpu::Trace::Off, })) diff --git a/benches/benches/renderpass-bindless.wgsl b/benches/benches/wgpu-benchmark/renderpass-bindless.wgsl similarity index 100% rename from benches/benches/renderpass-bindless.wgsl rename to benches/benches/wgpu-benchmark/renderpass-bindless.wgsl diff --git a/benches/benches/renderpass.rs b/benches/benches/wgpu-benchmark/renderpass.rs similarity index 98% rename from benches/benches/renderpass.rs rename to benches/benches/wgpu-benchmark/renderpass.rs index 2eb566717..ba387b701 100644 --- a/benches/benches/renderpass.rs +++ b/benches/benches/wgpu-benchmark/renderpass.rs @@ -224,7 +224,7 @@ impl RenderpassState { })], compilation_options: wgpu::PipelineCompilationOptions::default(), }), - multiview: None, + multiview_mask: None, cache: None, }); @@ -322,7 +322,7 @@ impl RenderpassState { })], compilation_options: wgpu::PipelineCompilationOptions::default(), }), - multiview: None, + multiview_mask: None, cache: None, }, )); @@ -360,6 +360,7 @@ impl RenderpassState { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &self.render_target, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), @@ -369,6 +370,7 @@ impl RenderpassState { occlusion_query_set: None, timestamp_writes: None, depth_stencil_attachment: None, + multiview_mask: None, }); let start_idx = pass_number * draws_per_pass; @@ -406,6 +408,7 @@ impl RenderpassState { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &self.render_target, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), @@ -415,6 +418,7 @@ impl RenderpassState { occlusion_query_set: None, timestamp_writes: None, depth_stencil_attachment: None, + multiview_mask: None, }); render_pass.set_pipeline(self.bindless_pipeline.as_ref().unwrap()); @@ -495,7 +499,7 @@ fn run_bench(ctx: &mut Criterion) { state .device_state .device - .poll(wgpu::PollType::Wait) + .poll(wgpu::PollType::wait_indefinitely()) .unwrap(); } @@ -542,7 +546,7 @@ fn run_bench(ctx: &mut Criterion) { state .device_state .device - .poll(wgpu::PollType::Wait) + .poll(wgpu::PollType::wait_indefinitely()) .unwrap(); } @@ -582,7 +586,7 @@ fn run_bench(ctx: &mut Criterion) { state .device_state .device - .poll(wgpu::PollType::Wait) + .poll(wgpu::PollType::wait_indefinitely()) .unwrap(); } diff --git a/benches/benches/renderpass.wgsl b/benches/benches/wgpu-benchmark/renderpass.wgsl similarity index 100% rename from benches/benches/renderpass.wgsl rename to benches/benches/wgpu-benchmark/renderpass.wgsl diff --git a/benches/benches/resource_creation.rs b/benches/benches/wgpu-benchmark/resource_creation.rs similarity index 93% rename from benches/benches/resource_creation.rs rename to benches/benches/wgpu-benchmark/resource_creation.rs index bbbfc3d2e..7f23dd15c 100644 --- a/benches/benches/resource_creation.rs +++ b/benches/benches/wgpu-benchmark/resource_creation.rs @@ -61,7 +61,10 @@ fn run_bench(ctx: &mut Criterion) { drop(buffers); state.queue.submit([]); - state.device.poll(wgpu::PollType::Wait).unwrap(); + state + .device + .poll(wgpu::PollType::wait_indefinitely()) + .unwrap(); } duration diff --git a/benches/benches/shader.rs b/benches/benches/wgpu-benchmark/shader.rs similarity index 55% rename from benches/benches/shader.rs rename to benches/benches/wgpu-benchmark/shader.rs index fee85adbf..7e74df4f5 100644 --- a/benches/benches/shader.rs +++ b/benches/benches/wgpu-benchmark/shader.rs @@ -1,56 +1,56 @@ use criterion::*; -use std::{fs, path::PathBuf, process::Command}; +use std::{fs, process::Command}; -struct Input { - filename: String, - size: u64, +const DIR_IN: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../naga/tests/in"); + +use naga_test::*; + +struct InputWithInfo { + inner: Input, data: Vec, string: Option, + options: Parameters, module: Option, module_info: Option, } +impl From for InputWithInfo { + fn from(value: Input) -> Self { + let mut options = value.read_parameters(DIR_IN); + options.targets = Some(options.targets.unwrap_or(Targets::all())); + Self { + options, + inner: value, + data: Vec::new(), + string: None, + module: None, + module_info: None, + } + } +} +impl InputWithInfo { + fn filename(&self) -> &str { + self.inner.file_name.file_name().unwrap().to_str().unwrap() + } +} struct Inputs { - inner: Vec, + inner: Vec, } impl Inputs { + #[track_caller] fn from_dir(folder: &str, extension: &str) -> Self { - let mut inputs = Vec::new(); - let read_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join(folder) - .read_dir() - .unwrap(); - - for file_entry in read_dir { - match file_entry { - Ok(entry) => match entry.path().extension() { - Some(ostr) if ostr == extension => { - let path = entry.path(); - - inputs.push(Input { - filename: path.to_string_lossy().into_owned(), - size: entry.metadata().unwrap().len(), - string: None, - data: vec![], - module: None, - module_info: None, - }); - } - _ => continue, - }, - Err(e) => { - eprintln!("Skipping file: {e:?}"); - continue; - } - } - } + let inputs: Vec = Input::files_in_dir(folder, &[extension], DIR_IN) + .map(|a| a.into()) + .collect(); Self { inner: inputs } } - fn bytes(&self) -> u64 { - self.inner.iter().map(|input| input.size).sum() + self.inner + .iter() + .map(|input| input.inner.bytes(DIR_IN)) + .sum() } fn load(&mut self) { @@ -59,7 +59,7 @@ impl Inputs { continue; } - input.data = fs::read(&input.filename).unwrap_or_default(); + input.data = fs::read(input.inner.input_path(DIR_IN)).unwrap_or_default(); } } @@ -84,6 +84,8 @@ impl Inputs { continue; } + parser.set_options((&input.options.wgsl_in).into()); + input.module = Some(parser.parse(input.string.as_ref().unwrap()).unwrap()); } } @@ -107,6 +109,10 @@ impl Inputs { self.inner.retain(|input| input.module_info.is_some()); } + + fn is_empty(&self) -> bool { + self.inner.is_empty() + } } fn parse_glsl(stage: naga::ShaderStage, inputs: &Inputs) { @@ -117,20 +123,22 @@ fn parse_glsl(stage: naga::ShaderStage, inputs: &Inputs) { }; for input in &inputs.inner { parser - .parse(&options, input.string.as_deref().unwrap()) + .parse(&options, &input.inner.read_source(DIR_IN, false)) .unwrap(); } } fn get_wgsl_inputs() -> Inputs { - let mut inputs = Inputs::from_dir("../naga/tests/in", "wgsl"); + let mut inputs: Vec = Input::files_in_dir("wgsl", &["wgsl"], DIR_IN) + .map(|a| a.into()) + .collect(); // remove "large-source" tests, they skew the results - inputs - .inner - .retain(|input| !input.filename.contains("large-source")); + inputs.retain(|input| !input.filename().contains("large-source")); - inputs + assert!(!inputs.is_empty()); + + Inputs { inner: inputs } } fn frontends(c: &mut Criterion) { @@ -145,12 +153,22 @@ fn frontends(c: &mut Criterion) { let inputs_bin = inputs_wgsl .inner .iter() - .map(|input| bincode::serialize(&input.module.as_ref().unwrap()).unwrap()) + .map(|input| { + bincode::serde::encode_to_vec( + input.module.as_ref().unwrap(), + bincode::config::standard(), + ) + .unwrap() + }) .collect::>(); b.iter(move || { for input in inputs_bin.iter() { - bincode::deserialize::(input).unwrap(); + bincode::serde::decode_from_slice::( + input, + bincode::config::standard(), + ) + .unwrap(); } }); }); @@ -161,18 +179,20 @@ fn frontends(c: &mut Criterion) { let mut frontend = naga::front::wgsl::Frontend::new(); b.iter(|| { for input in &inputs_wgsl.inner { + frontend.set_options((&input.options.wgsl_in).into()); frontend.parse(input.string.as_ref().unwrap()).unwrap(); } }); }); - let inputs_spirv = Inputs::from_dir("../naga/tests/in/spv", "spvasm"); + let inputs_spirv = Inputs::from_dir("spv", "spvasm"); + assert!(!inputs_spirv.is_empty()); // Assemble all the SPIR-V assembly. let mut assembled_spirv = Vec::>::new(); 'spirv: for input in &inputs_spirv.inner { let output = match Command::new("spirv-as") - .arg(&input.filename) + .arg(input.inner.input_path(DIR_IN)) .arg("-o") .arg("-") .output() @@ -202,19 +222,34 @@ fn frontends(c: &mut Criterion) { let total_bytes = assembled_spirv.iter().map(|spv| spv.len() as u64).sum(); + assert!(assembled_spirv.len() == inputs_spirv.inner.len() || assembled_spirv.is_empty()); + group.throughput(Throughput::Bytes(total_bytes)); group.bench_function("shader: spv-in", |b| { b.iter(|| { - let options = naga::front::spv::Options::default(); - for input in &assembled_spirv { - let parser = naga::front::spv::Frontend::new(input.iter().cloned(), &options); + for (i, input) in assembled_spirv.iter().enumerate() { + let params = &inputs_spirv.inner[i].options; + let SpirvInParameters { + adjust_coordinate_space, + } = params.spv_in; + + let parser = naga::front::spv::Frontend::new( + input.iter().cloned(), + &naga::front::spv::Options { + adjust_coordinate_space, + strict_capabilities: true, + ..Default::default() + }, + ); parser.parse().unwrap(); } }); }); - let mut inputs_vertex = Inputs::from_dir("../naga/tests/in/glsl", "vert"); - let mut inputs_fragment = Inputs::from_dir("../naga/tests/in/glsl", "frag"); + let mut inputs_vertex = Inputs::from_dir("glsl", "vert"); + let mut inputs_fragment = Inputs::from_dir("glsl", "frag"); + assert!(!inputs_vertex.is_empty()); + assert!(!inputs_fragment.is_empty()); // let mut inputs_compute = Inputs::from_dir("../naga/tests/in/glsl", "comp"); group.throughput(Throughput::Bytes( inputs_vertex.bytes() + inputs_fragment.bytes(), // + inputs_compute.bytes() @@ -258,6 +293,26 @@ fn validation(c: &mut Criterion) { group.finish(); } +fn compact(c: &mut Criterion) { + use naga::compact::{compact, KeepUnused}; + + let mut inputs = get_wgsl_inputs(); + + inputs.validate(); + assert!(!inputs.is_empty()); + + let mut group = c.benchmark_group("compact"); + group.throughput(Throughput::Bytes(inputs.bytes())); + group.bench_function("shader: compact", |b| { + b.iter(|| { + for input in &mut inputs.inner { + compact(input.module.as_mut().unwrap(), KeepUnused::No); + } + }); + }); + group.finish(); +} + fn backends(c: &mut Criterion) { let mut inputs = get_wgsl_inputs(); @@ -266,19 +321,22 @@ fn backends(c: &mut Criterion) { // run this to properly know the size of the inputs, as any that fail validation // will be removed. inputs.validate(); + assert!(!inputs.is_empty()); group.throughput(Throughput::Bytes(inputs.bytes())); group.bench_function("shader: wgsl-out", |b| { b.iter(|| { let mut string = String::new(); - let flags = naga::back::wgsl::WriterFlags::empty(); for input in &inputs.inner { - let mut writer = naga::back::wgsl::Writer::new(&mut string, flags); - let _ = writer.write( - input.module.as_ref().unwrap(), - input.module_info.as_ref().unwrap(), - ); - string.clear(); + if input.options.targets.unwrap().contains(Targets::WGSL) { + let mut writer = + naga::back::wgsl::Writer::new(&mut string, (&input.options.wgsl).into()); + let _ = writer.write( + input.module.as_ref().unwrap(), + input.module_info.as_ref().unwrap(), + ); + string.clear(); + } } }); }); @@ -286,17 +344,28 @@ fn backends(c: &mut Criterion) { group.bench_function("shader: spv-out", |b| { b.iter(|| { let mut data = Vec::new(); - let options = naga::back::spv::Options::default(); + let mut writer = naga::back::spv::Writer::new(&Default::default()).unwrap(); for input in &inputs.inner { - let mut writer = naga::back::spv::Writer::new(&options).unwrap(); - let _ = writer.write( - input.module.as_ref().unwrap(), - input.module_info.as_ref().unwrap(), - None, - &None, - &mut data, - ); - data.clear(); + if input.options.targets.unwrap().contains(Targets::SPIRV) { + if input.filename().contains("pointer-function-arg") { + // These fail due to https://github.com/gfx-rs/wgpu/issues/7315 + continue; + } + let opt = input + .options + .spv + .to_options(input.options.bounds_check_policies, None); + if writer.set_options(&opt).is_ok() { + let _ = writer.write( + input.module.as_ref().unwrap(), + input.module_info.as_ref().unwrap(), + None, + &None, + &mut data, + ); + data.clear(); + } + } } }); }); @@ -305,21 +374,27 @@ fn backends(c: &mut Criterion) { let mut data = Vec::new(); let options = naga::back::spv::Options::default(); for input in &inputs.inner { - let mut writer = naga::back::spv::Writer::new(&options).unwrap(); - let module = input.module.as_ref().unwrap(); - for ep in module.entry_points.iter() { - let pipeline_options = naga::back::spv::PipelineOptions { - shader_stage: ep.stage, - entry_point: ep.name.clone(), - }; - let _ = writer.write( - input.module.as_ref().unwrap(), - input.module_info.as_ref().unwrap(), - Some(&pipeline_options), - &None, - &mut data, - ); - data.clear(); + if input.options.targets.unwrap().contains(Targets::SPIRV) { + if input.filename().contains("pointer-function-arg") { + // These fail due to https://github.com/gfx-rs/wgpu/issues/7315 + continue; + } + let mut writer = naga::back::spv::Writer::new(&options).unwrap(); + let module = input.module.as_ref().unwrap(); + for ep in module.entry_points.iter() { + let pipeline_options = naga::back::spv::PipelineOptions { + shader_stage: ep.stage, + entry_point: ep.name.clone(), + }; + let _ = writer.write( + input.module.as_ref().unwrap(), + input.module_info.as_ref().unwrap(), + Some(&pipeline_options), + &None, + &mut data, + ); + data.clear(); + } } } }); @@ -330,15 +405,17 @@ fn backends(c: &mut Criterion) { let mut string = String::new(); let options = naga::back::msl::Options::default(); for input in &inputs.inner { - let pipeline_options = naga::back::msl::PipelineOptions::default(); - let mut writer = naga::back::msl::Writer::new(&mut string); - let _ = writer.write( - input.module.as_ref().unwrap(), - input.module_info.as_ref().unwrap(), - &options, - &pipeline_options, - ); - string.clear(); + if input.options.targets.unwrap().contains(Targets::METAL) { + let pipeline_options = naga::back::msl::PipelineOptions::default(); + let mut writer = naga::back::msl::Writer::new(&mut string); + let _ = writer.write( + input.module.as_ref().unwrap(), + input.module_info.as_ref().unwrap(), + &options, + &pipeline_options, + ); + string.clear(); + } } }); }); @@ -348,13 +425,17 @@ fn backends(c: &mut Criterion) { let options = naga::back::hlsl::Options::default(); let mut string = String::new(); for input in &inputs.inner { - let mut writer = naga::back::hlsl::Writer::new(&mut string, &options); - let _ = writer.write( - input.module.as_ref().unwrap(), - input.module_info.as_ref().unwrap(), - None, - ); // may fail on unimplemented things - string.clear(); + if input.options.targets.unwrap().contains(Targets::HLSL) { + let pipeline_options = Default::default(); + let mut writer = + naga::back::hlsl::Writer::new(&mut string, &options, &pipeline_options); + let _ = writer.write( + input.module.as_ref().unwrap(), + input.module_info.as_ref().unwrap(), + None, + ); // may fail on unimplemented things + string.clear(); + } } }); }); @@ -369,6 +450,9 @@ fn backends(c: &mut Criterion) { zero_initialize_workgroup_memory: true, }; for input in &inputs.inner { + if !input.options.targets.unwrap().contains(Targets::GLSL) { + continue; + } let module = input.module.as_ref().unwrap(); let info = input.module_info.as_ref().unwrap(); for ep in module.entry_points.iter() { @@ -397,4 +481,4 @@ fn backends(c: &mut Criterion) { }); } -criterion_group!(shader, frontends, validation, backends); +criterion_group!(shader, frontends, validation, compact, backends); diff --git a/clippy.toml b/clippy.toml index 35f212da6..1910b9fcb 100644 --- a/clippy.toml +++ b/clippy.toml @@ -3,6 +3,4 @@ disallowed-types = [ { path = "std::collections::HashMap", reason = "use hashbrown::HashMap instead" }, { path = "std::collections::HashSet", reason = "use hashbrown::HashSet instead" }, - { path = "rustc_hash::FxHashMap", reason = "use hashbrown::HashMap instead" }, - { path = "rustc_hash::FxHashSet", reason = "use hashbrown::HashSet instead" }, ] diff --git a/cts_runner/Cargo.toml b/cts_runner/Cargo.toml index 0d651d17a..218a61c80 100644 --- a/cts_runner/Cargo.toml +++ b/cts_runner/Cargo.toml @@ -1,20 +1,27 @@ [package] name = "cts_runner" -version = "0.1.0" +version.workspace = true authors = ["Luca Casonato "] edition.workspace = true description = "CTS runner for wgpu" license.workspace = true publish = false +[dependencies] +env_logger.workspace = true + # We make all dependencies conditional on not being wasm, # so the whole workspace can built as wasm. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] deno_console.workspace = true deno_core.workspace = true +deno_features.workspace = true deno_url.workspace = true deno_web.workspace = true deno_webidl.workspace = true deno_webgpu.workspace = true tokio = { workspace = true, features = ["full"] } termcolor.workspace = true + +[dev-dependencies] +tempfile.workspace = true diff --git a/cts_runner/README.md b/cts_runner/README.md new file mode 100644 index 000000000..2144e49ef --- /dev/null +++ b/cts_runner/README.md @@ -0,0 +1,17 @@ +# cts_runner + +This crate contains infrastructure for running the WebGPU conformance tests on +Deno's `wgpu`-based implementation of WebGPU. + +Instructions for running the tests via the CTS `xtask` are in the +[top-level README](https://github.com/gfx-rs/wgpu/blob/trunk/README.md#webgpu-conformance-test-suite). +The file [revision.txt](./revision.txt) specifies the version of the CTS that +will be used by default. + +`cts_runner` is somewhat misnamed at this point, in that it is useful for +things other than just running the CTS: + +- The [tests](./tests) directory contains a few directed tests for + Deno's bindings to `wgpu`. +- Standalone JavaScript snippets that use WebGPU can be run + with a command like: `cargo run -p cts_runner -- test.js`. diff --git a/cts_runner/examples/hello-compute.js b/cts_runner/examples/hello-compute.js index 9c4023ed5..a6f6ca400 100644 --- a/cts_runner/examples/hello-compute.js +++ b/cts_runner/examples/hello-compute.js @@ -112,8 +112,8 @@ function isTypedArrayEqual(a, b) { const actual = new Uint32Array(data); const expected = new Uint32Array([0, 2, 7, 55]); -console.error("actual", actual); -console.error("expected", expected); +console.log("actual", actual); +console.log("expected", expected); if (!isTypedArrayEqual(actual, expected)) { throw new TypeError("Actual does not equal expected!"); diff --git a/cts_runner/revision.txt b/cts_runner/revision.txt index 4e6b1d36c..3408c477a 100644 --- a/cts_runner/revision.txt +++ b/cts_runner/revision.txt @@ -1 +1 @@ -7ea73ba6f44c9f6fedfffc06f14c73ea9f2eaa11 +964a0b43f1505f75ea62acf88674adf3962a5218 diff --git a/cts_runner/src/bootstrap.js b/cts_runner/src/bootstrap.js index 5d9c6f65d..e4fa7eeca 100644 --- a/cts_runner/src/bootstrap.js +++ b/cts_runner/src/bootstrap.js @@ -29,6 +29,7 @@ import * as performance from "ext:deno_web/15_performance.js"; import { loadWebGPU } from "ext:deno_webgpu/00_init.js"; import * as imageData from "ext:deno_web/16_image_data.js"; const webgpu = loadWebGPU(); +webgpu.initGPU(); // imports needed to pass module evaluation import "ext:deno_url/01_urlpattern.js"; @@ -137,10 +138,6 @@ class Navigator { constructor() { webidl.illegalConstructor(); } - - [Symbol.for("Deno.customInspect")](inspect) { - return `${this.constructor.name} ${inspect({})}`; - } } const NavigatorPrototype = Navigator.prototype; @@ -199,10 +196,13 @@ const windowOrWorkerGlobalScope = { GPUTextureUsage: util.nonEnumerable(webgpu.GPUTextureUsage), GPUTexture: util.nonEnumerable(webgpu.GPUTexture), GPUTextureView: util.nonEnumerable(webgpu.GPUTextureView), + GPUExternalTexture: util.nonEnumerable(webgpu.GPUExternalTexture), GPUSampler: util.nonEnumerable(webgpu.GPUSampler), GPUBindGroupLayout: util.nonEnumerable(webgpu.GPUBindGroupLayout), GPUPipelineLayout: util.nonEnumerable(webgpu.GPUPipelineLayout), GPUBindGroup: util.nonEnumerable(webgpu.GPUBindGroup), + GPUCompilationInfo: util.nonEnumerable(webgpu.GPUCompilationInfo), + GPUCompilationMessage: util.nonEnumerable(webgpu.GPUCompilationMessage), GPUShaderModule: util.nonEnumerable(webgpu.GPUShaderModule), GPUShaderStage: util.nonEnumerable(webgpu.GPUShaderStage), GPUComputePipeline: util.nonEnumerable(webgpu.GPUComputePipeline), @@ -216,12 +216,33 @@ const windowOrWorkerGlobalScope = { GPURenderBundle: util.nonEnumerable(webgpu.GPURenderBundle), GPUQuerySet: util.nonEnumerable(webgpu.GPUQuerySet), GPUError: util.nonEnumerable(webgpu.GPUError), + GPUInternalError: util.nonEnumerable(webgpu.GPUInternalError), GPUValidationError: util.nonEnumerable(webgpu.GPUValidationError), GPUOutOfMemoryError: util.nonEnumerable(webgpu.GPUOutOfMemoryError), + GPUUncapturedErrorEvent: util.nonEnumerable(webgpu.GPUUncapturedErrorEvent), }; windowOrWorkerGlobalScope.console.enumerable = false; +// Print uncaptured WebGPU errors to stderr. This is useful when running +// standalone JavaScript test snippets. It isn't needed for the CTS, because the +// CTS uses error scopes. (The CTS also installs its own error handler with +// `addEventListener`, so having this here may result in printing duplicate +// errors from the CTS in some cases.) Printing uncaptured errors to stderr +// isn't desired as built-in behavior in Deno, because the console is reserved +// for the application. +// +// Note that catching an error here _does not_ result in a non-zero exit status. +const requestDevice = webgpu.GPUAdapter.prototype.requestDevice; +webgpu.GPUAdapter.prototype.requestDevice = function(desc) { + return requestDevice.call(this, desc).then((device) => { + device.onuncapturederror = (event) => { + core.print("cts_runner caught WebGPU error:" + event.error.message, true); + }; + return device; + }) +}; + const mainRuntimeGlobalProperties = { Window: globalInterfaces.windowConstructorDescriptor, window: util.readOnly(globalThis), diff --git a/cts_runner/src/main.rs b/cts_runner/src/main.rs index b8da75af1..cbb88b866 100644 --- a/cts_runner/src/main.rs +++ b/cts_runner/src/main.rs @@ -1,160 +1,148 @@ -#[cfg(not(target_arch = "wasm32"))] -mod native { - use std::sync::Arc; - use std::{ - env, fmt, - io::{Read, Write}, - rc::Rc, +#![cfg_attr(target_arch = "wasm32", no_main)] +#![cfg(not(target_arch = "wasm32"))] + +use std::sync::Arc; +use std::{ + env, fmt, + io::{Read, Write}, + rc::Rc, +}; + +use deno_core::anyhow::anyhow; +use deno_core::error::AnyError; +use deno_core::op2; +use deno_core::resolve_url_or_path; +use deno_core::serde_json::json; +use deno_core::v8; +use deno_core::JsRuntime; +use deno_core::RuntimeOptions; +use deno_web::BlobStore; +use termcolor::Ansi; +use termcolor::Color::Red; +use termcolor::ColorSpec; +use termcolor::WriteColor; + +pub async fn run() -> Result<(), AnyError> { + let mut args_iter = env::args(); + let _ = args_iter.next(); + let url = args_iter + .next() + .ok_or_else(|| anyhow!("missing specifier in first command line argument"))?; + let specifier = resolve_url_or_path(&url, &env::current_dir()?)?; + + let options = RuntimeOptions { + module_loader: Some(Rc::new(deno_core::FsModuleLoader)), + extensions: vec![ + deno_webidl::deno_webidl::init(), + deno_console::deno_console::init(), + deno_url::deno_url::init(), + deno_web::deno_web::init::(Arc::new(BlobStore::default()), None), + deno_webgpu::deno_webgpu::init(), + cts_runner::init(), + ], + ..Default::default() }; + let mut js_runtime = JsRuntime::new(options); + let args = args_iter.collect::>(); + let cfg = json!({"args": args, "cwd": env::current_dir().unwrap().to_string_lossy() }); - use deno_core::anyhow::anyhow; - use deno_core::error::AnyError; - use deno_core::op2; - use deno_core::resolve_url_or_path; - use deno_core::serde_json::json; - use deno_core::v8; - use deno_core::JsRuntime; - use deno_core::RuntimeOptions; - use deno_web::BlobStore; - use termcolor::Ansi; - use termcolor::Color::Red; - use termcolor::ColorSpec; - use termcolor::WriteColor; + { + let context = js_runtime.main_context(); + let scope = &mut js_runtime.handle_scope(); + let context_local = v8::Local::new(scope, context); + let global_obj = context_local.global(scope); + let bootstrap_str = v8::String::new(scope, "bootstrap").unwrap(); + let bootstrap_fn = global_obj.get(scope, bootstrap_str.into()).unwrap(); + let bootstrap_fn = v8::Local::::try_from(bootstrap_fn).unwrap(); - pub async fn run() -> Result<(), AnyError> { - let mut args_iter = env::args(); - let _ = args_iter.next(); - let url = args_iter - .next() - .ok_or_else(|| anyhow!("missing specifier in first command line argument"))?; - let specifier = resolve_url_or_path(&url, &env::current_dir()?)?; + let options_v8 = deno_core::serde_v8::to_v8(scope, cfg).unwrap(); + let undefined = v8::undefined(scope); + bootstrap_fn + .call(scope, undefined.into(), &[options_v8]) + .unwrap(); + } - let mut feature_checker = deno_core::FeatureChecker::default(); + let mod_id = js_runtime.load_main_es_module(&specifier).await?; + let result = js_runtime.mod_evaluate(mod_id); + js_runtime.run_event_loop(Default::default()).await?; + result.await?; + + Ok(()) +} + +deno_core::extension!( + cts_runner, + deps = [deno_webidl, deno_web], + ops = [op_exit, op_read_file_sync, op_write_file_sync], + esm_entry_point = "ext:cts_runner/src/bootstrap.js", + esm = ["src/bootstrap.js"], + state = |state| { + let mut feature_checker = deno_features::FeatureChecker::default(); feature_checker.enable_feature(deno_webgpu::UNSTABLE_FEATURE_NAME); - - let options = RuntimeOptions { - module_loader: Some(Rc::new(deno_core::FsModuleLoader)), - extensions: vec![ - deno_webidl::deno_webidl::init_ops_and_esm(), - deno_console::deno_console::init_ops_and_esm(), - deno_url::deno_url::init_ops_and_esm(), - deno_web::deno_web::init_ops_and_esm::( - Arc::new(BlobStore::default()), - None, - ), - deno_webgpu::deno_webgpu::init_ops_and_esm(), - cts_runner::init_ops_and_esm(), - ], - feature_checker: Some(Arc::new(feature_checker)), - ..Default::default() - }; - let mut js_runtime = JsRuntime::new(options); - let args = args_iter.collect::>(); - let cfg = json!({"args": args, "cwd": env::current_dir().unwrap().to_string_lossy() }); - - { - let context = js_runtime.main_context(); - let scope = &mut js_runtime.handle_scope(); - let context_local = v8::Local::new(scope, context); - let global_obj = context_local.global(scope); - let bootstrap_str = v8::String::new(scope, "bootstrap").unwrap(); - let bootstrap_fn = global_obj.get(scope, bootstrap_str.into()).unwrap(); - let bootstrap_fn = v8::Local::::try_from(bootstrap_fn).unwrap(); - - let options_v8 = deno_core::serde_v8::to_v8(scope, cfg).unwrap(); - let undefined = v8::undefined(scope); - bootstrap_fn - .call(scope, undefined.into(), &[options_v8]) - .unwrap(); - } - - let mod_id = js_runtime.load_main_es_module(&specifier).await?; - let result = js_runtime.mod_evaluate(mod_id); - js_runtime.run_event_loop(Default::default()).await?; - result.await?; - - Ok(()) + state.put(feature_checker); + state.put(Permissions {}); } +); - deno_core::extension!( - cts_runner, - deps = [deno_webidl, deno_web], - ops = [op_exit, op_read_file_sync, op_write_file_sync], - esm_entry_point = "ext:cts_runner/src/bootstrap.js", - esm = ["src/bootstrap.js"], - state = |state| { - state.put(Permissions {}); - } - ); +#[op2(fast)] +fn op_exit(code: i32) { + std::process::exit(code) +} - #[op2(fast)] - fn op_exit(code: i32) { - std::process::exit(code) - } +#[op2] +#[buffer] +fn op_read_file_sync(#[string] path: &str) -> Result, std::io::Error> { + let path = std::path::Path::new(path); + let mut file = std::fs::File::open(path)?; + let mut buf = Vec::new(); + file.read_to_end(&mut buf)?; + Ok(buf) +} - #[op2] - #[buffer] - fn op_read_file_sync(#[string] path: &str) -> Result, std::io::Error> { - let path = std::path::Path::new(path); - let mut file = std::fs::File::open(path)?; - let mut buf = Vec::new(); - file.read_to_end(&mut buf)?; - Ok(buf) - } +#[op2(fast)] +fn op_write_file_sync(#[string] path: &str, #[buffer] buf: &[u8]) -> Result<(), std::io::Error> { + let path = std::path::Path::new(path); + let mut file = std::fs::File::create(path)?; + file.write_all(buf)?; + Ok(()) +} - #[op2(fast)] - fn op_write_file_sync( - #[string] path: &str, - #[buffer] buf: &[u8], - ) -> Result<(), std::io::Error> { - let path = std::path::Path::new(path); - let mut file = std::fs::File::create(path)?; - file.write_all(buf)?; - Ok(()) - } - - pub fn unwrap_or_exit(result: Result) -> T { - match result { - Ok(value) => value, - Err(error) => { - eprintln!("{}: {:?}", red_bold("error"), error); - std::process::exit(1); - } - } - } - - fn style>(s: S, colorspec: ColorSpec) -> impl fmt::Display { - let mut v = Vec::new(); - let mut ansi_writer = Ansi::new(&mut v); - ansi_writer.set_color(&colorspec).unwrap(); - ansi_writer.write_all(s.as_ref().as_bytes()).unwrap(); - ansi_writer.reset().unwrap(); - String::from_utf8_lossy(&v).into_owned() - } - - fn red_bold>(s: S) -> impl fmt::Display { - let mut style_spec = ColorSpec::new(); - style_spec.set_fg(Some(Red)).set_bold(true); - style(s, style_spec) - } - - // NOP permissions - struct Permissions; - - impl deno_web::TimersPermission for Permissions { - fn allow_hrtime(&mut self) -> bool { - false +pub fn unwrap_or_exit(result: Result) -> T { + match result { + Ok(value) => value, + Err(error) => { + eprintln!("{}: {:?}", red_bold("error"), error); + std::process::exit(1); } } } -#[cfg(not(target_arch = "wasm32"))] +fn style>(s: S, colorspec: ColorSpec) -> impl fmt::Display { + let mut v = Vec::new(); + let mut ansi_writer = Ansi::new(&mut v); + ansi_writer.set_color(&colorspec).unwrap(); + ansi_writer.write_all(s.as_ref().as_bytes()).unwrap(); + ansi_writer.reset().unwrap(); + String::from_utf8_lossy(&v).into_owned() +} + +fn red_bold>(s: S) -> impl fmt::Display { + let mut style_spec = ColorSpec::new(); + style_spec.set_fg(Some(Red)).set_bold(true); + style(s, style_spec) +} + +// NOP permissions +struct Permissions; + +impl deno_web::TimersPermission for Permissions { + fn allow_hrtime(&mut self) -> bool { + false + } +} + #[tokio::main(flavor = "current_thread")] async fn main() { - native::unwrap_or_exit(native::run().await) -} - -#[cfg(target_arch = "wasm32")] -fn main() { - panic!("This is a native only module. It can't be run on the web!"); + env_logger::init(); + unwrap_or_exit(run().await) } diff --git a/cts_runner/test.lst b/cts_runner/test.lst index 2a410aa5a..9c8a4f318 100644 --- a/cts_runner/test.lst +++ b/cts_runner/test.lst @@ -1,10 +1,176 @@ +// The following may be useful to generate lists of tests for this file: +// ``` +// cargo xtask cts -- --list +// ``` unittests:* +webgpu:api,operation,buffers,createBindGroup:buffer_binding_resource:* webgpu:api,operation,command_buffer,basic:* -webgpu:api,operation,compute,basic:* +webgpu:api,operation,command_buffer,copyBufferToBuffer:* +fails-if(vulkan) webgpu:api,operation,command_buffer,copyTextureToTexture:copy_depth_stencil:format="depth24plus" +fails-if(vulkan) webgpu:api,operation,command_buffer,copyTextureToTexture:copy_depth_stencil:format="depth24plus-stencil8" +fails-if(vulkan) webgpu:api,operation,command_buffer,copyTextureToTexture:copy_depth_stencil:format="depth16unorm" +fails-if(vulkan) webgpu:api,operation,command_buffer,copyTextureToTexture:copy_depth_stencil:format="depth32float" +fails-if(vulkan) webgpu:api,operation,command_buffer,copyTextureToTexture:copy_depth_stencil:format="depth32float-stencil8" +webgpu:api,operation,command_buffer,copyTextureToTexture:copy_depth_stencil:format="stencil8" +// Fails with OOM in CI. +fails-if(dx12) webgpu:api,operation,command_buffer,image_copy:offsets_and_sizes:* +webgpu:api,operation,command_buffer,image_copy:undefined_params:initMethod="WriteTexture";checkMethod="FullCopyT2B";dimension="1d" +webgpu:api,operation,command_buffer,image_copy:undefined_params:initMethod="WriteTexture";checkMethod="FullCopyT2B";dimension="2d" +webgpu:api,operation,command_buffer,image_copy:undefined_params:initMethod="WriteTexture";checkMethod="FullCopyT2B";dimension="3d" +webgpu:api,operation,command_buffer,image_copy:undefined_params:initMethod="WriteTexture";checkMethod="PartialCopyT2B";dimension="1d" +fails-if(dx12) webgpu:api,operation,command_buffer,image_copy:undefined_params:initMethod="WriteTexture";checkMethod="PartialCopyT2B";dimension="2d" +webgpu:api,operation,command_buffer,image_copy:undefined_params:initMethod="WriteTexture";checkMethod="PartialCopyT2B";dimension="3d" +webgpu:api,operation,command_buffer,image_copy:undefined_params:initMethod="CopyB2T";checkMethod="FullCopyT2B";dimension="1d" +webgpu:api,operation,command_buffer,image_copy:undefined_params:initMethod="CopyB2T";checkMethod="FullCopyT2B";dimension="2d" +fails-if(dx12,vulkan,metal) webgpu:api,operation,command_buffer,image_copy:undefined_params:initMethod="CopyB2T";checkMethod="FullCopyT2B";dimension="3d" +webgpu:api,operation,compute,basic:memcpy:* +//FAIL: webgpu:api,operation,compute,basic:large_dispatch:* +webgpu:api,operation,compute_pipeline,overrides:* +webgpu:api,operation,device,lost:* +webgpu:api,operation,render_pass,storeOp:* +fails-if(vulkan) webgpu:api,operation,vertex_state,correctness:array_stride_zero:* +// Presumably vertex pulling, revisit after https://github.com/gfx-rs/wgpu/issues/7981 is fixed. +fails-if(metal) webgpu:api,operation,vertex_state,correctness:setVertexBuffer_offset_and_attribute_offset:* +fails-if(dx12) webgpu:api,validation,capability_checks,limits,maxBindGroups:setBindGroup,* +webgpu:api,validation,createBindGroup:buffer,effective_buffer_binding_size:* +// Fails because we coerce a size of 0 in `GPUDevice.createBindGroup(…)` to `buffer.size - offset`. +// FAIL webgpu:api,validation,createBindGroup:buffer_offset_and_size_for_bind_groups_match:* +webgpu:api,validation,encoding,beginComputePass:* +webgpu:api,validation,encoding,beginRenderPass:* +webgpu:api,validation,encoding,cmds,clearBuffer:* +webgpu:api,validation,encoding,cmds,compute_pass:set_pipeline:* +webgpu:api,validation,encoding,cmds,compute_pass:dispatch_sizes:* +webgpu:api,validation,encoding,cmds,copyTextureToTexture:copy_with_invalid_or_destroyed_texture:* +webgpu:api,validation,encoding,cmds,copyTextureToTexture:texture,device_mismatch:* +webgpu:api,validation,encoding,cmds,copyTextureToTexture:mipmap_level:* +webgpu:api,validation,encoding,cmds,copyTextureToTexture:texture_usage:* +webgpu:api,validation,encoding,cmds,copyTextureToTexture:sample_count:* +webgpu:api,validation,encoding,cmds,copyTextureToTexture:multisampled_copy_restrictions:* +webgpu:api,validation,encoding,cmds,copyTextureToTexture:texture_format_compatibility:* +webgpu:api,validation,encoding,cmds,copyTextureToTexture:depth_stencil_copy_restrictions:* +// Intermittently fails on dx12, https://github.com/gfx-rs/wgpu/issues/8118 +fails-if(dx12) webgpu:api,validation,encoding,cmds,copyTextureToTexture:copy_ranges:* +webgpu:api,validation,encoding,cmds,copyTextureToTexture:copy_within_same_texture:* +webgpu:api,validation,encoding,cmds,copyTextureToTexture:copy_aspects:* +webgpu:api,validation,encoding,cmds,copyTextureToTexture:copy_ranges_with_compressed_texture_formats:* +webgpu:api,validation,encoding,cmds,debug:debug_group_balanced:encoderType="non-pass" +webgpu:api,validation,encoding,cmds,debug:debug_group_balanced:encoderType="compute%20pass" +webgpu:api,validation,encoding,cmds,debug:debug_group_balanced:encoderType="render%20pass" +//FAIL: webgpu:api,validation,encoding,cmds,debug:debug_group_balanced:encoderType="render%20bundle" +// https://github.com/gfx-rs/wgpu/issues/8039 +webgpu:api,validation,encoding,cmds,debug:debug_group:* +webgpu:api,validation,encoding,cmds,debug:debug_marker:* +webgpu:api,validation,encoding,cmds,index_access:* +//FAIL: webgpu:api,validation,encoding,cmds,render,draw:* +webgpu:api,validation,encoding,cmds,render,draw:index_buffer_OOB:* +webgpu:api,validation,encoding,cmds,render,draw:unused_buffer_bound:* +webgpu:api,validation,encoding,cmds,render,dynamic_state:* +webgpu:api,validation,encoding,cmds,render,setIndexBuffer:* +webgpu:api,validation,encoding,cmds,render,setVertexBuffer:* +webgpu:api,validation,encoding,encoder_state:* +webgpu:api,validation,encoding,encoder_open_state:non_pass_commands:* +webgpu:api,validation,encoding,encoder_open_state:render_pass_commands:* +//FAIL: webgpu:api,validation,encoding,encoder_open_state:render_bundle_commands:* +// https://github.com/gfx-rs/wgpu/issues/7857 +webgpu:api,validation,encoding,encoder_open_state:compute_pass_commands:* +webgpu:api,validation,encoding,programmable,pipeline_bind_group_compat:bgl_binding_mismatch:encoderType="compute%20pass";* +webgpu:api,validation,encoding,programmable,pipeline_bind_group_compat:bgl_binding_mismatch:encoderType="render%20pass";* +webgpu:api,validation,encoding,programmable,pipeline_bind_group_compat:bgl_resource_type_mismatch:encoderType="compute%20pass";* +webgpu:api,validation,encoding,programmable,pipeline_bind_group_compat:bgl_resource_type_mismatch:encoderType="render%20pass";* +webgpu:api,validation,encoding,programmable,pipeline_bind_group_compat:bgl_visibility_mismatch:encoderType="compute%20pass";* +webgpu:api,validation,encoding,programmable,pipeline_bind_group_compat:bgl_visibility_mismatch:encoderType="render%20pass";* +webgpu:api,validation,encoding,programmable,pipeline_bind_group_compat:bind_groups_and_pipeline_layout_mismatch:encoderType="compute%20pass";* +webgpu:api,validation,encoding,programmable,pipeline_bind_group_compat:bind_groups_and_pipeline_layout_mismatch:encoderType="render%20pass";* +webgpu:api,validation,encoding,programmable,pipeline_bind_group_compat:buffer_binding,render_pipeline:* +webgpu:api,validation,encoding,programmable,pipeline_bind_group_compat:sampler_binding,render_pipeline:* +webgpu:api,validation,encoding,queries,general:occlusion_query,query_index:* +webgpu:shader,validation,extension,dual_source_blending:blend_src_syntax_validation:* +webgpu:api,validation,image_copy,buffer_texture_copies:depth_stencil_format,copy_usage_and_aspect:* +webgpu:api,validation,image_copy,buffer_texture_copies:depth_stencil_format,copy_buffer_size:* +// image_copy depth/stencil failures on dx12: https://github.com/gfx-rs/wgpu/issues/8133 +fails-if(dx12) webgpu:api,validation,image_copy,buffer_texture_copies:depth_stencil_format,copy_buffer_offset:format="stencil8";aspect="stencil-only";copyType="CopyB2T" +fails-if(dx12) webgpu:api,validation,image_copy,buffer_texture_copies:depth_stencil_format,copy_buffer_offset:format="stencil8";aspect="stencil-only";copyType="CopyT2B" +fails-if(dx12) webgpu:api,validation,image_copy,buffer_texture_copies:depth_stencil_format,copy_buffer_offset:format="depth32float";aspect="depth-only";copyType="CopyT2B" +fails-if(dx12) webgpu:api,validation,image_copy,buffer_texture_copies:depth_stencil_format,copy_buffer_offset:format="depth24plus-stencil8";aspect="stencil-only";copyType="CopyB2T" +fails-if(dx12) webgpu:api,validation,image_copy,buffer_texture_copies:depth_stencil_format,copy_buffer_offset:format="depth24plus-stencil8";aspect="stencil-only";copyType="CopyT2B" +//mix of PASS and FAIL: other subtests of copy_buffer_offset. Related bugs: +// https://github.com/gfx-rs/wgpu/issues/7946 +webgpu:api,validation,image_copy,buffer_texture_copies:sample_count:* +webgpu:api,validation,image_copy,buffer_texture_copies:texture_buffer_usages:* +webgpu:api,validation,image_copy,buffer_texture_copies:device_mismatch:* +fails-if(dx12) webgpu:api,validation,image_copy,buffer_texture_copies:offset_and_bytesPerRow:format="r8uint";copyType="CopyB2T";dimension="1d" +fails-if(dx12) webgpu:api,validation,image_copy,buffer_texture_copies:offset_and_bytesPerRow:format="r8uint";copyType="CopyT2B";dimension="1d" +fails-if(dx12) webgpu:api,validation,image_copy,buffer_texture_copies:offset_and_bytesPerRow:format="rgba32float";copyType="CopyB2T";dimension="1d" +fails-if(dx12) webgpu:api,validation,image_copy,buffer_texture_copies:offset_and_bytesPerRow:format="rgba32float";copyType="CopyT2B";dimension="1d" +fails-if(dx12) webgpu:api,validation,image_copy,buffer_texture_copies:offset_and_bytesPerRow:format="rgba8unorm";copyType="CopyB2T";dimension="2d" +fails-if(dx12) webgpu:api,validation,image_copy,buffer_texture_copies:offset_and_bytesPerRow:format="rgba8unorm";copyType="CopyT2B";dimension="2d" +fails-if(dx12) webgpu:api,validation,image_copy,buffer_texture_copies:offset_and_bytesPerRow:format="rgba8unorm";copyType="CopyB2T";dimension="3d" +fails-if(dx12) webgpu:api,validation,image_copy,buffer_texture_copies:offset_and_bytesPerRow:format="rgba8unorm";copyType="CopyT2B";dimension="3d" +fails-if(dx12) webgpu:api,validation,image_copy,buffer_texture_copies:offset_and_bytesPerRow:format="bgra8unorm";copyType="CopyB2T";dimension="2d" +fails-if(dx12) webgpu:api,validation,image_copy,buffer_texture_copies:offset_and_bytesPerRow:format="bgra8unorm";copyType="CopyT2B";dimension="2d" +fails-if(dx12) webgpu:api,validation,image_copy,buffer_texture_copies:offset_and_bytesPerRow:format="astc-4x4-unorm";copyType="CopyT2B";dimension="2d" +fails-if(dx12) webgpu:api,validation,image_copy,buffer_texture_copies:offset_and_bytesPerRow:format="astc-4x4-unorm";copyType="CopyB2T";dimension="2d" +fails-if(dx12) webgpu:api,validation,image_copy,buffer_texture_copies:offset_and_bytesPerRow:format="astc-4x4-unorm";copyType="CopyT2B";dimension="3d" +fails-if(dx12) webgpu:api,validation,image_copy,buffer_texture_copies:offset_and_bytesPerRow:format="astc-4x4-unorm";copyType="CopyB2T";dimension="3d" +//mix of PASS and FAIL: other subtests of offset_and_bytesPerRow. Related bugs: +// https://github.com/gfx-rs/wgpu/issues/7946 +webgpu:api,validation,image_copy,layout_related:copy_end_overflows_u64:* +// Fails with OOM in CI. +fails-if(dx12) webgpu:api,validation,image_copy,layout_related:offset_alignment:* +webgpu:api,validation,image_copy,texture_related:format:dimension="1d";* +webgpu:api,validation,queue,submit:command_buffer,* +webgpu:api,validation,render_pass,render_pass_descriptor:attachments,* +webgpu:api,validation,render_pass,render_pass_descriptor:color_attachments,depthSlice,bound_check:* +// Fails due to missing validation. +// FAIL: webgpu:api,validation,render_pass,render_pass_descriptor:color_attachments,depthSlice,overlaps,diff_miplevel:* +webgpu:api,validation,render_pass,render_pass_descriptor:resolveTarget,* +webgpu:api,validation,render_pass,resolve:resolve_attachment:* +webgpu:api,validation,resource_usages,buffer,in_pass_encoder:* +// FAIL: 8 other cases in resource_usages,texture,in_pass_encoder. https://github.com/gfx-rs/wgpu/issues/3126 +webgpu:api,validation,resource_usages,texture,in_pass_encoder:scope,* +webgpu:api,validation,resource_usages,texture,in_pass_encoder:shader_stages_and_visibility,* +webgpu:api,validation,resource_usages,texture,in_pass_encoder:subresources_and_binding_types_combination_for_aspect:* +webgpu:api,validation,resource_usages,texture,in_pass_encoder:subresources_and_binding_types_combination_for_color:compute=false;type0="render-target";type1="render-target" +webgpu:api,validation,resource_usages,texture,in_pass_encoder:unused_bindings_in_pipeline:* +webgpu:api,validation,texture,rg11b10ufloat_renderable:* +webgpu:api,operation,render_pipeline,overrides:* webgpu:api,operation,rendering,basic:clear:* webgpu:api,operation,rendering,basic:fullscreen_quad:* //FAIL: webgpu:api,operation,rendering,basic:large_draw:* -webgpu:api,operation,rendering,blending:* -webgpu:api,operation,rendering,blending:GPUBlendComponent:* +webgpu:api,operation,rendering,color_target_state:blending,GPUBlendComponent:* +webgpu:api,operation,rendering,color_target_state:blending,formats:* +webgpu:api,operation,rendering,color_target_state:blend_constant,setting:* webgpu:api,operation,rendering,depth:* webgpu:api,operation,rendering,draw:* +webgpu:api,operation,shader_module,compilation_info:* +webgpu:api,operation,vertex_state,correctness:non_zero_array_stride_and_attribute_offset:* +// Likely due to https://github.com/gfx-rs/wgpu/issues/7357. +fails-if(metal) webgpu:api,operation,uncapturederror:iff_uncaptured:* +//FAIL: webgpu:shader,execution,expression,call,builtin,select:* +// - Fails with `const`/abstract int cases on all platforms because of . +// - Fails with `vec3` & `f16` cases on macOS because of . +//FAIL: webgpu:api,operation,uncapturederror:onuncapturederror_order_wrt_addEventListener +// There are also two unimplemented SKIPs in uncapturederror not enumerated here. +webgpu:api,validation,encoding,queries,general:occlusion_query,query_type:* +webgpu:shader,execution,expression,call,builtin,atan2:f16:* +webgpu:shader,execution,expression,call,builtin,atan2:f32:* +webgpu:shader,execution,expression,call,builtin,textureSample:sampled_1d_coords:* +webgpu:shader,execution,expression,call,builtin,textureSampleBaseClampToEdge:2d_coords:stage="c";textureType="texture_2d";* +webgpu:shader,execution,flow_control,return:* +// Many other vertex_buffer_access subtests also passing, but there are too many to enumerate. +// Fails on Metal in CI only, not when running locally. +fails-if(metal) webgpu:shader,execution,robust_access_vertex:vertex_buffer_access:indexed=true;indirect=false;drawCallTestParameter="baseVertex";type="float32x4";additionalBuffers=4;partialLastNumber=false;offsetVertexBuffer=true +webgpu:shader,validation,expression,call,builtin,max:values:* +webgpu:shader,validation,statement,statement_behavior:invalid_statements:body="break" +webgpu:shader,validation,statement,statement_behavior:invalid_statements:body="break_if" +webgpu:shader,validation,statement,statement_behavior:invalid_statements:body="continue" +webgpu:shader,validation,statement,statement_behavior:invalid_statements:body="for3" +webgpu:shader,validation,statement,statement_behavior:invalid_statements:body="for4" +webgpu:shader,validation,statement,statement_behavior:invalid_statements:body="for5" +webgpu:shader,validation,statement,statement_behavior:invalid_statements:body="loop4" +webgpu:shader,validation,statement,statement_behavior:invalid_statements:body="loop5" +webgpu:shader,validation,statement,statement_behavior:invalid_statements:body="loop6" +webgpu:shader,validation,statement,statement_behavior:invalid_statements:body="loop8" +webgpu:shader,validation,statement,statement_behavior:invalid_statements:body="switch1" +//FAIL: 9 invalid_statements subtests due to https://github.com/gfx-rs/wgpu/issues/7733 +webgpu:api,validation,render_pipeline,vertex_state:many_attributes_overlapping:* diff --git a/cts_runner/tests/integration.rs b/cts_runner/tests/integration.rs index 30057c3c0..3554b6bc9 100644 --- a/cts_runner/tests/integration.rs +++ b/cts_runner/tests/integration.rs @@ -1,4 +1,16 @@ -use std::path::PathBuf; +// Tests for cts_runner +// +// As of June 2025, these tests are not run in CI. + +use std::{ + ffi::OsStr, + io::Write, + path::PathBuf, + process::{Command, Output}, + str, +}; + +use tempfile::NamedTempFile; pub fn target_dir() -> PathBuf { let current_exe = std::env::current_exe().unwrap(); @@ -15,13 +27,71 @@ pub fn cts_runner_exe_path() -> PathBuf { p } +fn exec_cts_runner(script_file: impl AsRef) -> Output { + Command::new(cts_runner_exe_path()) + .arg(script_file) + .output() + .unwrap() +} + +fn exec_js_file(script_file: impl AsRef) { + let output = exec_cts_runner(script_file); + println!("{}", str::from_utf8(&output.stdout).unwrap()); + eprintln!("{}", str::from_utf8(&output.stderr).unwrap()); + assert!(output.status.success()); +} + +fn check_js_stderr(script: &str, expected: &str) { + let mut tempfile = NamedTempFile::new().unwrap(); + tempfile.write_all(script.as_bytes()).unwrap(); + tempfile.flush().unwrap(); + let output = exec_cts_runner(tempfile.path()); + assert!( + output.stdout.is_empty(), + "unexpected output on stdout: {}", + str::from_utf8(&output.stdout).unwrap(), + ); + assert_eq!(str::from_utf8(&output.stderr).unwrap(), expected); + assert!(output.status.success()); +} + +fn exec_js(script: &str) { + check_js_stderr(script, ""); +} + #[test] fn hello_compute_example() { - let output = std::process::Command::new(cts_runner_exe_path()) - .arg("examples/hello-compute.js") - .spawn() - .unwrap() - .wait_with_output() - .unwrap(); - assert!(output.status.success()) + exec_js_file("examples/hello-compute.js"); +} + +#[test] +fn features() { + exec_js( + r#" + const adapter = await navigator.gpu.requestAdapter(); + + if (adapter.features.has("mappable-primary-buffers")) { + throw new TypeError("Adapter should not report support for wgpu native-only features"); + } + "#, + ); +} + +#[test] +fn uncaptured_error() { + check_js_stderr( + r#" + const code = `const val: u32 = 1.1;`; + + const adapter = await navigator.gpu.requestAdapter(); + const device = await adapter.requestDevice(); + device.createShaderModule({ code }) + "#, + "cts_runner caught WebGPU error: +Shader '' parsing error: the type of `val` is expected to be `u32`, but got `{AbstractFloat}` + ┌─ wgsl:1:7 + │ +1 │ const val: u32 = 1.1; + │ ^^^ definition of `val`\n\n", + ); } diff --git a/deno_webgpu/01_webgpu.js b/deno_webgpu/01_webgpu.js index 903c3b63c..8c5ce5c59 100644 --- a/deno_webgpu/01_webgpu.js +++ b/deno_webgpu/01_webgpu.js @@ -16,6 +16,8 @@ import { GPUBuffer, GPUCommandBuffer, GPUCommandEncoder, + GPUCompilationInfo, + GPUCompilationMessage, GPUComputePassEncoder, GPUComputePipeline, GPUDevice, @@ -33,12 +35,16 @@ import { GPUSupportedLimits, GPUTexture, GPUTextureView, + GPUExternalTexture, op_create_gpu, + op_webgpu_device_start_capture, + op_webgpu_device_stop_capture, } from "ext:core/ops"; const { ObjectDefineProperty, ObjectPrototypeIsPrototypeOf, ObjectSetPrototypeOf, + ReflectGet, Symbol, SymbolFor, } = primordials; @@ -53,9 +59,10 @@ import { import { DOMException } from "ext:deno_web/01_dom_exception.js"; import { createFilteredInspectProxy } from "ext:deno_console/01_console.js"; -const customInspect = SymbolFor("Deno.privateCustomInspect"); +const privateCustomInspect = SymbolFor("Deno.privateCustomInspect"); const _message = Symbol("[[message]]"); const illegalConstructorKey = Symbol("illegalConstructorKey"); + class GPUError { constructor(key = null) { if (key !== illegalConstructorKey) { @@ -69,7 +76,7 @@ class GPUError { return this[_message]; } - [customInspect](inspect, inspectOptions) { + [privateCustomInspect](inspect, inspectOptions) { return inspect( createFilteredInspectProxy({ object: this, @@ -166,14 +173,16 @@ class GPUUncapturedErrorEvent extends Event { } const GPUUncapturedErrorEventPrototype = GPUUncapturedErrorEvent.prototype; -ObjectDefineProperty(GPU, customInspect, { +const GPUPrototype = GPU.prototype; +ObjectDefineProperty(GPUPrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return `${this.constructor.name} ${inspect({}, inspectOptions)}`; }, }); -ObjectDefineProperty(GPUAdapter, customInspect, { +const GPUAdapterPrototype = GPUAdapter.prototype; +ObjectDefineProperty(GPUAdapterPrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return inspect( @@ -184,16 +193,15 @@ ObjectDefineProperty(GPUAdapter, customInspect, { "features", "limits", "info", - "isFallbackAdapter", ], }), inspectOptions, ); }, }); -const GPUAdapterPrototype = GPUAdapter.prototype; -ObjectDefineProperty(GPUAdapterInfo, customInspect, { +const GPUAdapterInfoPrototype = GPUAdapterInfo.prototype; +ObjectDefineProperty(GPUAdapterInfoPrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return inspect( @@ -205,15 +213,19 @@ ObjectDefineProperty(GPUAdapterInfo, customInspect, { "architecture", "device", "description", + "subgroupMinSize", + "subgroupMaxSize", + "isFallbackAdapter", ], }), inspectOptions, ); }, }); -const GPUAdapterInfoPrototype = GPUAdapterInfo.prototype; -ObjectDefineProperty(GPUSupportedFeatures, customInspect, { +const GPUSupportedFeaturesPrototype = GPUSupportedFeatures.prototype; +webidl.setlikeObjectWrap(GPUSupportedFeaturesPrototype, true); +ObjectDefineProperty(GPUSupportedFeaturesPrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { if (ObjectPrototypeIsPrototypeOf(GPUSupportedFeaturesPrototype, this)) { @@ -225,10 +237,61 @@ ObjectDefineProperty(GPUSupportedFeatures, customInspect, { } }, }); -const GPUSupportedFeaturesPrototype = GPUSupportedFeatures.prototype; -webidl.setlikeObjectWrap(GPUSupportedFeaturesPrototype, true); -ObjectDefineProperty(GPUDeviceLostInfo, customInspect, { +const GPUSupportedLimitsPrototype = GPUSupportedLimits.prototype; +ObjectDefineProperty(GPUSupportedLimitsPrototype, privateCustomInspect, { + __proto__: null, + value(inspect, inspectOptions) { + return inspect( + createFilteredInspectProxy({ + object: this, + evaluate: ObjectPrototypeIsPrototypeOf( + GPUSupportedLimitsPrototype, + this, + ), + keys: [ + "maxTextureDimension1D", + "maxTextureDimension2D", + "maxTextureDimension3D", + "maxTextureArrayLayers", + "maxBindGroups", + // TODO(@crowlKats): support max_bind_groups_plus_vertex_buffers + // "maxBindGroupsPlusVertexBuffers", + "maxBindingsPerBindGroup", + "maxDynamicUniformBuffersPerPipelineLayout", + "maxDynamicStorageBuffersPerPipelineLayout", + "maxSampledTexturesPerShaderStage", + "maxSamplersPerShaderStage", + "maxStorageBuffersPerShaderStage", + "maxStorageTexturesPerShaderStage", + "maxUniformBuffersPerShaderStage", + "maxUniformBufferBindingSize", + "maxStorageBufferBindingSize", + "minUniformBufferOffsetAlignment", + "minStorageBufferOffsetAlignment", + "maxVertexBuffers", + "maxBufferSize", + "maxVertexAttributes", + "maxVertexBufferArrayStride", + // TODO(@crowlKats): support max_inter_stage_shader_variables + // "maxInterStageShaderVariables", + "maxColorAttachments", + "maxColorAttachmentBytesPerSample", + "maxComputeWorkgroupStorageSize", + "maxComputeInvocationsPerWorkgroup", + "maxComputeWorkgroupSizeX", + "maxComputeWorkgroupSizeY", + "maxComputeWorkgroupSizeZ", + "maxComputeWorkgroupsPerDimension", + ], + }), + inspectOptions, + ); + }, +}); + +const GPUDeviceLostInfoPrototype = GPUDeviceLostInfo.prototype; +ObjectDefineProperty(GPUDeviceLostInfoPrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return inspect( @@ -247,9 +310,11 @@ ObjectDefineProperty(GPUDeviceLostInfo, customInspect, { ); }, }); -const GPUDeviceLostInfoPrototype = GPUDeviceLostInfo.prototype; -ObjectDefineProperty(GPUDevice, customInspect, { +const GPUDevicePrototype = GPUDevice.prototype; +ObjectSetPrototypeOf(GPUDevicePrototype, EventTargetPrototype); +defineEventHandler(GPUDevicePrototype, "uncapturederror"); +ObjectDefineProperty(GPUDevicePrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return inspect( @@ -270,11 +335,9 @@ ObjectDefineProperty(GPUDevice, customInspect, { ); }, }); -const GPUDevicePrototype = GPUDevice.prototype; -ObjectSetPrototypeOf(GPUDevicePrototype, EventTargetPrototype); -defineEventHandler(GPUDevice.prototype, "uncapturederror"); -ObjectDefineProperty(GPUQueue, customInspect, { +const GPUQueuePrototype = GPUQueue.prototype; +ObjectDefineProperty(GPUQueuePrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return inspect( @@ -289,9 +352,9 @@ ObjectDefineProperty(GPUQueue, customInspect, { ); }, }); -const GPUQueuePrototype = GPUQueue.prototype; -ObjectDefineProperty(GPUBuffer, customInspect, { +const GPUBufferPrototype = GPUBuffer.prototype; +ObjectDefineProperty(GPUBufferPrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return inspect( @@ -309,7 +372,6 @@ ObjectDefineProperty(GPUBuffer, customInspect, { ); }, }); -const GPUBufferPrototype = GPUBuffer.prototype; class GPUBufferUsage { constructor() { @@ -361,7 +423,8 @@ class GPUMapMode { } } -ObjectDefineProperty(GPUTexture, customInspect, { +const GPUTexturePrototype = GPUTexture.prototype; +ObjectDefineProperty(GPUTexturePrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return inspect( @@ -384,7 +447,6 @@ ObjectDefineProperty(GPUTexture, customInspect, { ); }, }); -const GPUTexturePrototype = GPUTexture.prototype; class GPUTextureUsage { constructor() { @@ -408,7 +470,8 @@ class GPUTextureUsage { } } -ObjectDefineProperty(GPUTextureView, customInspect, { +const GPUTextureViewPrototype = GPUTextureView.prototype; +ObjectDefineProperty(GPUTextureViewPrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return inspect( @@ -423,20 +486,29 @@ ObjectDefineProperty(GPUTextureView, customInspect, { ); }, }); -const GPUTextureViewPrototype = GPUTextureView.prototype; -ObjectDefineProperty(GPUSampler, customInspect, { +const GPUSamplerPrototype = GPUSampler.prototype; +ObjectDefineProperty(GPUSamplerPrototype, privateCustomInspect, { __proto__: null, - value(inspect) { - return `${this.constructor.name} ${ - inspect({ - label: this.label, - }) - }`; + value(inspect, inspectOptions) { + return inspect( + createFilteredInspectProxy({ + object: this, + evaluate: ObjectPrototypeIsPrototypeOf( + GPUSamplerPrototype, + this, + ), + keys: [ + "label", + ], + }), + inspectOptions, + ); }, }); -ObjectDefineProperty(GPUBindGroupLayout, customInspect, { +const GPUBindGroupLayoutPrototype = GPUBindGroupLayout.prototype; +ObjectDefineProperty(GPUBindGroupLayout, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return inspect( @@ -454,9 +526,9 @@ ObjectDefineProperty(GPUBindGroupLayout, customInspect, { ); }, }); -const GPUBindGroupLayoutPrototype = GPUBindGroupLayout.prototype; -ObjectDefineProperty(GPUPipelineLayout, customInspect, { +const GPUPipelineLayoutPrototype = GPUPipelineLayout.prototype; +ObjectDefineProperty(GPUPipelineLayoutPrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return inspect( @@ -474,9 +546,9 @@ ObjectDefineProperty(GPUPipelineLayout, customInspect, { ); }, }); -const GPUPipelineLayoutPrototype = GPUPipelineLayout.prototype; -ObjectDefineProperty(GPUBindGroup, customInspect, { +const GPUBindGroupPrototype = GPUBindGroup.prototype; +ObjectDefineProperty(GPUBindGroupPrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return inspect( @@ -491,9 +563,9 @@ ObjectDefineProperty(GPUBindGroup, customInspect, { ); }, }); -const GPUBindGroupPrototype = GPUBindGroup.prototype; -ObjectDefineProperty(GPUShaderModule, customInspect, { +const GPUShaderModulePrototype = GPUShaderModule.prototype; +ObjectDefineProperty(GPUShaderModulePrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return inspect( @@ -508,7 +580,51 @@ ObjectDefineProperty(GPUShaderModule, customInspect, { ); }, }); -const GPUShaderModulePrototype = GPUShaderModule.prototype; + +ObjectDefineProperty(GPUCompilationInfo, privateCustomInspect, { + __proto__: null, + value(inspect, inspectOptions) { + return inspect( + createFilteredInspectProxy({ + object: this, + evaluate: ObjectPrototypeIsPrototypeOf( + GPUCompilationInfoPrototype, + this, + ), + keys: [ + "messages", + ], + }), + inspectOptions, + ); + }, +}); +const GPUCompilationInfoPrototype = GPUCompilationInfo.prototype; + +ObjectDefineProperty(GPUCompilationMessage, privateCustomInspect, { + __proto__: null, + value(inspect, inspectOptions) { + return inspect( + createFilteredInspectProxy({ + object: this, + evaluate: ObjectPrototypeIsPrototypeOf( + GPUCompilationMessagePrototype, + this, + ), + keys: [ + "message", + "type", + "line_num", + "line_pos", + "offset", + "length", + ], + }), + inspectOptions, + ); + }, +}); +const GPUCompilationMessagePrototype = GPUCompilationMessage.prototype; class GPUShaderStage { constructor() { @@ -528,7 +644,8 @@ class GPUShaderStage { } } -ObjectDefineProperty(GPUComputePipeline, customInspect, { +const GPUComputePipelinePrototype = GPUComputePipeline.prototype; +ObjectDefineProperty(GPUComputePipelinePrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return inspect( @@ -546,9 +663,9 @@ ObjectDefineProperty(GPUComputePipeline, customInspect, { ); }, }); -const GPUComputePipelinePrototype = GPUComputePipeline.prototype; -ObjectDefineProperty(GPURenderPipeline, customInspect, { +const GPURenderPipelinePrototype = GPURenderPipeline.prototype; +ObjectDefineProperty(GPURenderPipelinePrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return inspect( @@ -566,7 +683,6 @@ ObjectDefineProperty(GPURenderPipeline, customInspect, { ); }, }); -const GPURenderPipelinePrototype = GPURenderPipeline.prototype; class GPUColorWrite { constructor() { @@ -590,7 +706,8 @@ class GPUColorWrite { } } -ObjectDefineProperty(GPUCommandEncoder, customInspect, { +const GPUCommandEncoderPrototype = GPUCommandEncoder.prototype; +ObjectDefineProperty(GPUCommandEncoderPrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return inspect( @@ -608,9 +725,9 @@ ObjectDefineProperty(GPUCommandEncoder, customInspect, { ); }, }); -const GPUCommandEncoderPrototype = GPUCommandEncoder.prototype; -ObjectDefineProperty(GPURenderPassEncoder, customInspect, { +const GPURenderPassEncoderPrototype = GPURenderPassEncoder.prototype; +ObjectDefineProperty(GPURenderPassEncoderPrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return inspect( @@ -628,9 +745,9 @@ ObjectDefineProperty(GPURenderPassEncoder, customInspect, { ); }, }); -const GPURenderPassEncoderPrototype = GPURenderPassEncoder.prototype; -ObjectDefineProperty(GPUComputePassEncoder, customInspect, { +const GPUComputePassEncoderPrototype = GPUComputePassEncoder.prototype; +ObjectDefineProperty(GPUComputePassEncoderPrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return inspect( @@ -648,9 +765,9 @@ ObjectDefineProperty(GPUComputePassEncoder, customInspect, { ); }, }); -const GPUComputePassEncoderPrototype = GPUComputePassEncoder.prototype; -ObjectDefineProperty(GPUCommandBuffer, customInspect, { +const GPUCommandBufferPrototype = GPUCommandBuffer.prototype; +ObjectDefineProperty(GPUCommandBufferPrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return inspect( @@ -665,9 +782,9 @@ ObjectDefineProperty(GPUCommandBuffer, customInspect, { ); }, }); -const GPUCommandBufferPrototype = GPUCommandBuffer.prototype; -ObjectDefineProperty(GPURenderBundleEncoder, customInspect, { +const GPURenderBundleEncoderPrototype = GPURenderBundleEncoder.prototype; +ObjectDefineProperty(GPURenderBundleEncoderPrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return inspect( @@ -685,9 +802,9 @@ ObjectDefineProperty(GPURenderBundleEncoder, customInspect, { ); }, }); -const GPURenderBundleEncoderPrototype = GPURenderBundleEncoder.prototype; -ObjectDefineProperty(GPURenderBundle, customInspect, { +const GPURenderBundlePrototype = GPURenderBundle.prototype; +ObjectDefineProperty(GPURenderBundlePrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return inspect( @@ -702,9 +819,9 @@ ObjectDefineProperty(GPURenderBundle, customInspect, { ); }, }); -const GPURenderBundlePrototype = GPURenderBundle.prototype; -ObjectDefineProperty(GPUQuerySet, customInspect, { +const GPUQuerySetPrototype = GPUQuerySet.prototype; +ObjectDefineProperty(GPUQuerySetPrototype, privateCustomInspect, { __proto__: null, value(inspect, inspectOptions) { return inspect( @@ -721,7 +838,6 @@ ObjectDefineProperty(GPUQuerySet, customInspect, { ); }, }); -const GPUQuerySetPrototype = GPUQuerySet.prototype; // Converters @@ -756,6 +872,19 @@ webidl.converters["GPUUncapturedErrorEventInit"] = webidl dictMembersGPUUncapturedErrorEventInit, ); +function deviceStartCapture(device) { + op_webgpu_device_start_capture(device); +} + +function deviceStopCapture(device) { + op_webgpu_device_stop_capture(device); +} + +const denoNsWebGPU = { + deviceStartCapture, + deviceStopCapture, +}; + let gpu; function initGPU() { if (!gpu) { @@ -768,6 +897,7 @@ function initGPU() { } export { + denoNsWebGPU, GPU, gpu, GPUAdapter, @@ -779,6 +909,8 @@ export { GPUColorWrite, GPUCommandBuffer, GPUCommandEncoder, + GPUCompilationInfo, + GPUCompilationMessage, GPUComputePassEncoder, GPUComputePipeline, GPUDevice, @@ -802,6 +934,7 @@ export { GPUTexture, GPUTextureUsage, GPUTextureView, + GPUExternalTexture, GPUUncapturedErrorEvent, GPUValidationError, initGPU, diff --git a/deno_webgpu/Cargo.toml b/deno_webgpu/Cargo.toml index 29786bf4c..52df54ec7 100644 --- a/deno_webgpu/Cargo.toml +++ b/deno_webgpu/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno_webgpu" -version = "0.157.0" +version = "0.181.0" authors = ["the Deno authors"] edition.workspace = true license = "MIT" @@ -25,7 +25,7 @@ wgpu-core = { workspace = true, features = [ "wgsl", "gles", ] } -wgpu-types = { workspace = true, features = ["serde"] } +wgpu-types = { workspace = true, features = ["serde", "std"] } deno_core.workspace = true deno_error.workspace = true diff --git a/deno_webgpu/README.md b/deno_webgpu/README.md index c419bfc60..3cedd111c 100644 --- a/deno_webgpu/README.md +++ b/deno_webgpu/README.md @@ -14,13 +14,15 @@ a [wgpu trace](https://github.com/gfx-rs/wgpu/wiki/Debugging-wgpu-Applications#tracing-infrastructure) to the specified directory. -For testing this op crate will make use of the WebGPU conformance tests suite, -running through our WPT runner. This will be used to validate implementation -conformance. +This op crate is tested primarily by running the +[WebGPU conformance test suite](https://github.com/gpuweb/cts) using `wgpu`'s +[`cts_runner`](https://github.com/gfx-rs/wgpu/blob/trunk/README.md#webgpu-conformance-test-suite). +`cts_runner` also has a few +[directed tests](https://github.com/gfx-rs/wgpu/tree/trunk/cts_runner/tests) +to fill in missing coverage. -GitHub CI doesn't run with GPUs, so testing relies on software like DX WARP & -Vulkan lavapipe. Currently, only using DX WARP works, so tests are only run on -Windows. +GPU availability in GitHub CI is limited, so some configurations rely on +software like DX WARP & Vulkan lavapipe. ## Links diff --git a/deno_webgpu/adapter.rs b/deno_webgpu/adapter.rs index 169c9d60c..711a7190c 100644 --- a/deno_webgpu/adapter.rs +++ b/deno_webgpu/adapter.rs @@ -3,17 +3,17 @@ #[allow(clippy::disallowed_types)] use std::collections::HashSet; use std::rc::Rc; -use std::sync::Arc; use deno_core::cppgc::SameObject; use deno_core::op2; use deno_core::v8; use deno_core::GarbageCollected; use deno_core::OpState; +use deno_core::V8TaskSpawner; use deno_core::WebIDL; -use tokio::sync::Mutex; use super::device::GPUDevice; +use crate::error::GPUGenericError; use crate::webidl::features_to_feature_names; use crate::webidl::GPUFeatureName; use crate::Instance; @@ -21,448 +21,469 @@ use crate::Instance; #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPURequestAdapterOptions { - pub power_preference: Option, - #[webidl(default = false)] - pub force_fallback_adapter: bool, + pub power_preference: Option, + #[webidl(default = false)] + pub force_fallback_adapter: bool, } #[derive(WebIDL)] #[webidl(enum)] pub(crate) enum GPUPowerPreference { - LowPower, - HighPerformance, + LowPower, + HighPerformance, } #[derive(WebIDL)] #[webidl(dictionary)] struct GPUDeviceDescriptor { - #[webidl(default = String::new())] - label: String, + #[webidl(default = String::new())] + label: String, - #[webidl(default = vec![])] - required_features: Vec, - #[webidl(default = Default::default())] - #[options(enforce_range = true)] - required_limits: indexmap::IndexMap>, + #[webidl(default = vec![])] + required_features: Vec, + #[webidl(default = Default::default())] + #[options(enforce_range = true)] + required_limits: indexmap::IndexMap>, } pub struct GPUAdapter { - pub instance: Instance, - pub id: wgpu_core::id::AdapterId, + pub instance: Instance, + pub id: wgpu_core::id::AdapterId, - pub features: SameObject, - pub limits: SameObject, - pub info: Rc>, + pub features: SameObject, + pub limits: SameObject, + pub info: Rc>, } impl Drop for GPUAdapter { - fn drop(&mut self) { - self.instance.adapter_drop(self.id); - } + fn drop(&mut self) { + self.instance.adapter_drop(self.id); + } } -impl GarbageCollected for GPUAdapter {} +impl GarbageCollected for GPUAdapter { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUAdapter" + } +} #[op2] impl GPUAdapter { - #[getter] - #[global] - fn info(&self, scope: &mut v8::HandleScope) -> v8::Global { - self.info.get(scope, |_| { - let info = self.instance.adapter_get_info(self.id); - let limits = self.instance.adapter_limits(self.id); + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } - GPUAdapterInfo { - info, - subgroup_min_size: limits.min_subgroup_size, - subgroup_max_size: limits.max_subgroup_size, - } - }) + #[getter] + #[global] + fn info(&self, scope: &mut v8::HandleScope) -> v8::Global { + self.info.get(scope, |_| { + let info = self.instance.adapter_get_info(self.id); + let limits = self.instance.adapter_limits(self.id); + + GPUAdapterInfo { + info, + subgroup_min_size: limits.min_subgroup_size, + subgroup_max_size: limits.max_subgroup_size, + } + }) + } + + #[getter] + #[global] + fn features(&self, scope: &mut v8::HandleScope) -> v8::Global { + self.features.get(scope, |scope| { + let features = self.instance.adapter_features(self.id); + // Only expose WebGPU features, not wgpu native-only features + let features = features & wgpu_types::Features::all_webgpu_mask(); + let features = features_to_feature_names(features); + GPUSupportedFeatures::new(scope, features) + }) + } + + #[getter] + #[global] + fn limits(&self, scope: &mut v8::HandleScope) -> v8::Global { + self.limits.get(scope, |_| { + let adapter_limits = self.instance.adapter_limits(self.id); + GPUSupportedLimits(adapter_limits) + }) + } + + #[async_method(fake)] + #[global] + fn request_device( + &self, + state: &mut OpState, + scope: &mut v8::HandleScope, + #[webidl] descriptor: GPUDeviceDescriptor, + ) -> Result, CreateDeviceError> { + let features = self.instance.adapter_features(self.id); + let supported_features = features_to_feature_names(features); + #[allow(clippy::disallowed_types)] + let required_features = descriptor + .required_features + .iter() + .cloned() + .collect::>(); + + if !required_features.is_subset(&supported_features) { + return Err(CreateDeviceError::RequiredFeaturesNotASubset); } - #[getter] - #[global] - fn features(&self, scope: &mut v8::HandleScope) -> v8::Global { - self.features.get(scope, |scope| { - let features = self.instance.adapter_features(self.id); - let features = features_to_feature_names(features); - GPUSupportedFeatures::new(scope, features) - }) - } - #[getter] - #[global] - fn limits(&self, scope: &mut v8::HandleScope) -> v8::Global { - self.limits.get(scope, |_| { - let adapter_limits = self.instance.adapter_limits(self.id); - GPUSupportedLimits(adapter_limits) - }) - } - #[getter] - fn is_fallback_adapter(&self) -> bool { - // TODO(lucacasonato): report correctly from wgpu - false - } + // When support for compatibility mode is added, this will need to look + // at whether the adapter is "compatibility-defaulting" or + // "core-defaulting", and choose the appropriate set of defaults. + // + // Support for compatibility mode is tracked in + // https://github.com/gfx-rs/wgpu/issues/8124. + let required_limits = serde_json::from_value::( + serde_json::to_value(descriptor.required_limits)?, + )? + .or_better_values_from(&wgpu_types::Limits::default()); - #[async_method(fake)] - #[global] - fn request_device( - &self, - state: &mut OpState, - isolate_ptr: *mut v8::Isolate, - scope: &mut v8::HandleScope, - #[webidl] descriptor: GPUDeviceDescriptor, - ) -> Result, CreateDeviceError> { - let features = self.instance.adapter_features(self.id); - let supported_features = features_to_feature_names(features); - #[allow(clippy::disallowed_types)] - let required_features = descriptor - .required_features - .iter() - .cloned() - .collect::>(); + let trace = std::env::var_os("DENO_WEBGPU_TRACE") + .map(|path| wgpu_types::Trace::Directory(std::path::PathBuf::from(path))) + .unwrap_or_default(); - if !required_features.is_subset(&supported_features) { - return Err(CreateDeviceError::RequiredFeaturesNotASubset); - } + let wgpu_descriptor = wgpu_types::DeviceDescriptor { + label: crate::transform_label(descriptor.label.clone()), + required_features: super::webidl::feature_names_to_features( + descriptor.required_features, + ), + required_limits, + experimental_features: wgpu_types::ExperimentalFeatures::disabled(), + memory_hints: Default::default(), + trace, + }; - let required_limits = - serde_json::from_value(serde_json::to_value(descriptor.required_limits)?)?; + let (device, queue) = self.instance.adapter_request_device( + self.id, + &wgpu_descriptor, + None, + None, + )?; - let webgpu_trace = std::env::var_os("DENO_WEBGPU_TRACE").unwrap(); + let spawner = state.borrow::().clone(); + let lost_resolver = v8::PromiseResolver::new(scope).unwrap(); + let lost_promise = lost_resolver.get_promise(scope); + let device = GPUDevice { + instance: self.instance.clone(), + id: device, + queue, + label: descriptor.label, + queue_obj: SameObject::new(), + adapter_info: self.info.clone(), + error_handler: Rc::new(super::error::DeviceErrorHandler::new( + v8::Global::new(scope, lost_resolver), + spawner, + )), + adapter: self.id, + lost_promise: v8::Global::new(scope, lost_promise), + limits: SameObject::new(), + features: SameObject::new(), + }; + let device = deno_core::cppgc::make_cppgc_object(scope, device); + let weak_device = v8::Weak::new(scope, device); + let event_target_setup = state.borrow::(); + let webidl_brand = v8::Local::new(scope, event_target_setup.brand.clone()); + device.set(scope, webidl_brand, webidl_brand); + let set_event_target_data = + v8::Local::new(scope, event_target_setup.set_event_target_data.clone()) + .cast::(); + let null = v8::null(scope); + set_event_target_data.call(scope, null.into(), &[device.into()]); - let wgpu_descriptor = wgpu_types::DeviceDescriptor { - label: crate::transform_label(descriptor.label.clone()), - required_features: super::webidl::feature_names_to_features( - descriptor.required_features, - ), - required_limits, - memory_hints: Default::default(), - trace: wgpu_types::Trace::Directory(std::path::PathBuf::from(webgpu_trace)), - }; + // Now that the device is fully constructed, give the error handler a + // weak reference to it. + let device = device.cast::(); + deno_core::cppgc::try_unwrap_cppgc_object::(scope, device) + .unwrap() + .error_handler + .set_device(weak_device); - let (device, queue) = - self.instance - .adapter_request_device(self.id, &wgpu_descriptor, None, None)?; - - let (lost_sender, lost_receiver) = tokio::sync::oneshot::channel(); - let (uncaptured_sender, mut uncaptured_receiver) = tokio::sync::mpsc::unbounded_channel(); - let (uncaptured_sender_is_closed_sender, mut uncaptured_sender_is_closed_receiver) = - tokio::sync::oneshot::channel::<()>(); - - let device = GPUDevice { - instance: self.instance.clone(), - id: device, - queue, - label: descriptor.label, - queue_obj: SameObject::new(), - adapter_info: self.info.clone(), - error_handler: Arc::new(super::error::DeviceErrorHandler::new( - lost_sender, - uncaptured_sender, - uncaptured_sender_is_closed_sender, - )), - adapter: self.id, - lost_receiver: Mutex::new(Some(lost_receiver)), - limits: SameObject::new(), - features: SameObject::new(), - }; - let device = deno_core::cppgc::make_cppgc_object(scope, device); - let event_target_setup = state.borrow::(); - let webidl_brand = v8::Local::new(scope, event_target_setup.brand.clone()); - device.set(scope, webidl_brand, webidl_brand); - let set_event_target_data = - v8::Local::new(scope, event_target_setup.set_event_target_data.clone()) - .cast::(); - let null = v8::null(scope); - set_event_target_data.call(scope, null.into(), &[device.into()]); - - let key = v8::String::new(scope, "dispatchEvent").unwrap(); - let val = device.get(scope, key.into()).unwrap(); - let func = v8::Global::new(scope, val.try_cast::().unwrap()); - let device = v8::Global::new(scope, device.cast::()); - let error_event_class = state.borrow::().0.clone(); - - let context = scope.get_current_context(); - let context = v8::Global::new(scope, context); - - let task_device = device.clone(); - deno_unsync::spawn(async move { - loop { - // TODO(@crowlKats): check for uncaptured_receiver.is_closed instead once tokio is upgraded - if !matches!( - uncaptured_sender_is_closed_receiver.try_recv(), - Err(tokio::sync::oneshot::error::TryRecvError::Empty) - ) { - break; - } - let Some(error) = uncaptured_receiver.recv().await else { - break; - }; - - // SAFETY: eh, it's safe - let isolate: &mut v8::Isolate = unsafe { &mut *isolate_ptr }; - let scope = &mut v8::HandleScope::with_context(isolate, &context); - let error = deno_core::error::to_v8_error(scope, &error); - - let error_event_class = v8::Local::new(scope, error_event_class.clone()); - let constructor = v8::Local::::try_from(error_event_class).unwrap(); - let kind = v8::String::new(scope, "uncapturederror").unwrap(); - - let obj = v8::Object::new(scope); - let key = v8::String::new(scope, "error").unwrap(); - obj.set(scope, key.into(), error); - - let event = constructor - .new_instance(scope, &[kind.into(), obj.into()]) - .unwrap(); - - let recv = v8::Local::new(scope, task_device.clone()); - func.open(scope).call(scope, recv, &[event.into()]); - } - }); - - Ok(device) - } + Ok(v8::Global::new(scope, device)) + } } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum CreateDeviceError { - #[class(type)] - #[error("requiredFeatures must be a subset of the adapter features")] - RequiredFeaturesNotASubset, - #[class(inherit)] - #[error(transparent)] - Serde(#[from] serde_json::Error), - #[class(type)] - #[error(transparent)] - Device(#[from] wgpu_core::instance::RequestDeviceError), + #[class(type)] + #[error("requiredFeatures must be a subset of the adapter features")] + RequiredFeaturesNotASubset, + #[class(inherit)] + #[error(transparent)] + Serde(#[from] serde_json::Error), + #[class("DOMExceptionOperationError")] + #[error(transparent)] + Device(#[from] wgpu_core::instance::RequestDeviceError), } pub struct GPUSupportedLimits(pub wgpu_types::Limits); -impl GarbageCollected for GPUSupportedLimits {} +impl GarbageCollected for GPUSupportedLimits { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUSupportedLimits" + } +} #[op2] impl GPUSupportedLimits { - #[getter] - fn maxTextureDimension1D(&self) -> u32 { - self.0.max_texture_dimension_1d - } + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } - #[getter] - fn maxTextureDimension2D(&self) -> u32 { - self.0.max_texture_dimension_2d - } + #[getter] + fn maxTextureDimension1D(&self) -> u32 { + self.0.max_texture_dimension_1d + } - #[getter] - fn maxTextureDimension3D(&self) -> u32 { - self.0.max_texture_dimension_3d - } + #[getter] + fn maxTextureDimension2D(&self) -> u32 { + self.0.max_texture_dimension_2d + } - #[getter] - fn maxTextureArrayLayers(&self) -> u32 { - self.0.max_texture_array_layers - } + #[getter] + fn maxTextureDimension3D(&self) -> u32 { + self.0.max_texture_dimension_3d + } - #[getter] - fn maxBindGroups(&self) -> u32 { - self.0.max_bind_groups - } + #[getter] + fn maxTextureArrayLayers(&self) -> u32 { + self.0.max_texture_array_layers + } - // TODO(@crowlKats): support max_bind_groups_plus_vertex_buffers + #[getter] + fn maxBindGroups(&self) -> u32 { + self.0.max_bind_groups + } - #[getter] - fn maxBindingsPerBindGroup(&self) -> u32 { - self.0.max_bindings_per_bind_group - } + // TODO(@crowlKats): support max_bind_groups_plus_vertex_buffers - #[getter] - fn maxDynamicUniformBuffersPerPipelineLayout(&self) -> u32 { - self.0.max_dynamic_uniform_buffers_per_pipeline_layout - } + #[getter] + fn maxBindingsPerBindGroup(&self) -> u32 { + self.0.max_bindings_per_bind_group + } - #[getter] - fn maxDynamicStorageBuffersPerPipelineLayout(&self) -> u32 { - self.0.max_dynamic_storage_buffers_per_pipeline_layout - } + #[getter] + fn maxDynamicUniformBuffersPerPipelineLayout(&self) -> u32 { + self.0.max_dynamic_uniform_buffers_per_pipeline_layout + } - #[getter] - fn maxSampledTexturesPerShaderStage(&self) -> u32 { - self.0.max_sampled_textures_per_shader_stage - } + #[getter] + fn maxDynamicStorageBuffersPerPipelineLayout(&self) -> u32 { + self.0.max_dynamic_storage_buffers_per_pipeline_layout + } - #[getter] - fn maxSamplersPerShaderStage(&self) -> u32 { - self.0.max_samplers_per_shader_stage - } + #[getter] + fn maxSampledTexturesPerShaderStage(&self) -> u32 { + self.0.max_sampled_textures_per_shader_stage + } - #[getter] - fn maxStorageBuffersPerShaderStage(&self) -> u32 { - self.0.max_storage_buffers_per_shader_stage - } + #[getter] + fn maxSamplersPerShaderStage(&self) -> u32 { + self.0.max_samplers_per_shader_stage + } - #[getter] - fn maxStorageTexturesPerShaderStage(&self) -> u32 { - self.0.max_storage_textures_per_shader_stage - } + #[getter] + fn maxStorageBuffersPerShaderStage(&self) -> u32 { + self.0.max_storage_buffers_per_shader_stage + } - #[getter] - fn maxUniformBuffersPerShaderStage(&self) -> u32 { - self.0.max_uniform_buffers_per_shader_stage - } + #[getter] + fn maxStorageTexturesPerShaderStage(&self) -> u32 { + self.0.max_storage_textures_per_shader_stage + } - #[getter] - fn maxUniformBufferBindingSize(&self) -> u32 { - self.0.max_uniform_buffer_binding_size - } + #[getter] + fn maxUniformBuffersPerShaderStage(&self) -> u32 { + self.0.max_uniform_buffers_per_shader_stage + } - #[getter] - fn maxStorageBufferBindingSize(&self) -> u32 { - self.0.max_storage_buffer_binding_size - } + #[getter] + fn maxUniformBufferBindingSize(&self) -> u32 { + self.0.max_uniform_buffer_binding_size + } - #[getter] - fn minUniformBufferOffsetAlignment(&self) -> u32 { - self.0.min_uniform_buffer_offset_alignment - } + #[getter] + fn maxStorageBufferBindingSize(&self) -> u32 { + self.0.max_storage_buffer_binding_size + } - #[getter] - fn minStorageBufferOffsetAlignment(&self) -> u32 { - self.0.min_storage_buffer_offset_alignment - } + #[getter] + fn minUniformBufferOffsetAlignment(&self) -> u32 { + self.0.min_uniform_buffer_offset_alignment + } - #[getter] - fn maxVertexBuffers(&self) -> u32 { - self.0.max_vertex_buffers - } + #[getter] + fn minStorageBufferOffsetAlignment(&self) -> u32 { + self.0.min_storage_buffer_offset_alignment + } - #[getter] - #[number] - fn maxBufferSize(&self) -> u64 { - self.0.max_buffer_size - } + #[getter] + fn maxVertexBuffers(&self) -> u32 { + self.0.max_vertex_buffers + } - #[getter] - fn maxVertexAttributes(&self) -> u32 { - self.0.max_vertex_attributes - } + #[getter] + #[number] + fn maxBufferSize(&self) -> u64 { + self.0.max_buffer_size + } - #[getter] - fn maxVertexBufferArrayStride(&self) -> u32 { - self.0.max_vertex_buffer_array_stride - } + #[getter] + fn maxVertexAttributes(&self) -> u32 { + self.0.max_vertex_attributes + } - // TODO(@crowlKats): support max_inter_stage_shader_variables + #[getter] + fn maxVertexBufferArrayStride(&self) -> u32 { + self.0.max_vertex_buffer_array_stride + } - #[getter] - fn maxColorAttachments(&self) -> u32 { - self.0.max_color_attachments - } + // TODO(@crowlKats): support max_inter_stage_shader_variables - #[getter] - fn maxColorAttachmentBytesPerSample(&self) -> u32 { - self.0.max_color_attachment_bytes_per_sample - } + #[getter] + fn maxColorAttachments(&self) -> u32 { + self.0.max_color_attachments + } - #[getter] - fn maxComputeWorkgroupStorageSize(&self) -> u32 { - self.0.max_compute_workgroup_storage_size - } + #[getter] + fn maxColorAttachmentBytesPerSample(&self) -> u32 { + self.0.max_color_attachment_bytes_per_sample + } - #[getter] - fn maxComputeInvocationsPerWorkgroup(&self) -> u32 { - self.0.max_compute_invocations_per_workgroup - } + #[getter] + fn maxComputeWorkgroupStorageSize(&self) -> u32 { + self.0.max_compute_workgroup_storage_size + } - #[getter] - fn maxComputeWorkgroupSizeX(&self) -> u32 { - self.0.max_compute_workgroup_size_x - } + #[getter] + fn maxComputeInvocationsPerWorkgroup(&self) -> u32 { + self.0.max_compute_invocations_per_workgroup + } - #[getter] - fn maxComputeWorkgroupSizeY(&self) -> u32 { - self.0.max_compute_workgroup_size_y - } + #[getter] + fn maxComputeWorkgroupSizeX(&self) -> u32 { + self.0.max_compute_workgroup_size_x + } - #[getter] - fn maxComputeWorkgroupSizeZ(&self) -> u32 { - self.0.max_compute_workgroup_size_z - } + #[getter] + fn maxComputeWorkgroupSizeY(&self) -> u32 { + self.0.max_compute_workgroup_size_y + } - #[getter] - fn maxComputeWorkgroupsPerDimension(&self) -> u32 { - self.0.max_compute_workgroups_per_dimension - } + #[getter] + fn maxComputeWorkgroupSizeZ(&self) -> u32 { + self.0.max_compute_workgroup_size_z + } + + #[getter] + fn maxComputeWorkgroupsPerDimension(&self) -> u32 { + self.0.max_compute_workgroups_per_dimension + } } pub struct GPUSupportedFeatures(v8::Global); -impl GarbageCollected for GPUSupportedFeatures {} +impl GarbageCollected for GPUSupportedFeatures { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUSupportedFeatures" + } +} impl GPUSupportedFeatures { - #[allow(clippy::disallowed_types)] - pub fn new(scope: &mut v8::HandleScope, features: HashSet) -> Self { - let set = v8::Set::new(scope); + #[allow(clippy::disallowed_types)] + pub fn new( + scope: &mut v8::HandleScope, + features: HashSet, + ) -> Self { + let set = v8::Set::new(scope); - for feature in features { - let key = v8::String::new(scope, feature.as_str()).unwrap(); - set.add(scope, key.into()); - } - - Self(v8::Global::new(scope, >::from(set))) + for feature in features { + let key = v8::String::new(scope, feature.as_str()).unwrap(); + set.add(scope, key.into()); } + + Self(v8::Global::new(scope, >::from(set))) + } } #[op2] impl GPUSupportedFeatures { - #[global] - #[symbol("setlike_set")] - fn set(&self) -> v8::Global { - self.0.clone() - } + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } + + #[global] + #[symbol("setlike_set")] + fn set(&self) -> v8::Global { + self.0.clone() + } } pub struct GPUAdapterInfo { - pub info: wgpu_types::AdapterInfo, - pub subgroup_min_size: u32, - pub subgroup_max_size: u32, + pub info: wgpu_types::AdapterInfo, + pub subgroup_min_size: u32, + pub subgroup_max_size: u32, } -impl GarbageCollected for GPUAdapterInfo {} +impl GarbageCollected for GPUAdapterInfo { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUAdapterInfo" + } +} #[op2] impl GPUAdapterInfo { - #[getter] - #[string] - fn vendor(&self) -> String { - self.info.vendor.to_string() - } + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } - #[getter] - #[string] - fn architecture(&self) -> &'static str { - "" // TODO: wgpu#2170 - } + #[getter] + #[string] + fn vendor(&self) -> String { + self.info.vendor.to_string() + } - #[getter] - #[string] - fn device(&self) -> String { - self.info.device.to_string() - } + #[getter] + #[string] + fn architecture(&self) -> &'static str { + "" // TODO: wgpu#2170 + } - #[getter] - #[string] - fn description(&self) -> String { - self.info.name.clone() - } + #[getter] + #[string] + fn device(&self) -> String { + self.info.device.to_string() + } - #[getter] - fn subgroup_min_size(&self) -> u32 { - self.subgroup_min_size - } + #[getter] + #[string] + fn description(&self) -> String { + self.info.name.clone() + } - #[getter] - fn subgroup_max_size(&self) -> u32 { - self.subgroup_max_size - } + #[getter] + fn subgroup_min_size(&self) -> u32 { + self.subgroup_min_size + } + + #[getter] + fn subgroup_max_size(&self) -> u32 { + self.subgroup_max_size + } + + #[getter] + fn is_fallback_adapter(&self) -> bool { + // TODO(lucacasonato): report correctly from wgpu + false + } } diff --git a/deno_webgpu/bind_group.rs b/deno_webgpu/bind_group.rs index f147c2178..de329ecf4 100644 --- a/deno_webgpu/bind_group.rs +++ b/deno_webgpu/bind_group.rs @@ -15,102 +15,142 @@ use deno_core::GarbageCollected; use deno_core::WebIDL; use crate::buffer::GPUBuffer; +use crate::error::GPUGenericError; use crate::sampler::GPUSampler; +use crate::texture::GPUTexture; use crate::texture::GPUTextureView; use crate::Instance; pub struct GPUBindGroup { - pub instance: Instance, - pub id: wgpu_core::id::BindGroupId, - pub label: String, + pub instance: Instance, + pub id: wgpu_core::id::BindGroupId, + pub label: String, } impl Drop for GPUBindGroup { - fn drop(&mut self) { - self.instance.bind_group_drop(self.id); - } + fn drop(&mut self) { + self.instance.bind_group_drop(self.id); + } } impl WebIdlInterfaceConverter for GPUBindGroup { - const NAME: &'static str = "GPUBindGroup"; + const NAME: &'static str = "GPUBindGroup"; } -impl GarbageCollected for GPUBindGroup {} +impl GarbageCollected for GPUBindGroup { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUBindGroup" + } +} #[op2] impl GPUBindGroup { - #[getter] - #[string] - fn label(&self) -> String { - self.label.clone() - } - #[setter] - #[string] - fn label(&self, #[webidl] _label: String) { - // TODO(@crowlKats): no-op, needs wpgu to implement changing the label - } + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } + + #[getter] + #[string] + fn label(&self) -> String { + self.label.clone() + } + #[setter] + #[string] + fn label(&self, #[webidl] _label: String) { + // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUBindGroupDescriptor { - #[webidl(default = String::new())] - pub label: String, + #[webidl(default = String::new())] + pub label: String, - pub layout: Ptr, - pub entries: Vec, + pub layout: Ptr, + pub entries: Vec, } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUBindGroupEntry { - #[options(enforce_range = true)] - pub binding: u32, - pub resource: GPUBindingResource, + #[options(enforce_range = true)] + pub binding: u32, + pub resource: GPUBindingResource, } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUBufferBinding { - pub buffer: Ptr, - #[webidl(default = 0)] - #[options(enforce_range = true)] - pub offset: u64, - #[options(enforce_range = true)] - pub size: Option, + pub buffer: Ptr, + #[webidl(default = 0)] + #[options(enforce_range = true)] + pub offset: u64, + #[options(enforce_range = true)] + pub size: Option, } pub(crate) enum GPUBindingResource { - Sampler(Ptr), - TextureView(Ptr), - BufferBinding(GPUBufferBinding), + Sampler(Ptr), + Texture(Ptr), + TextureView(Ptr), + Buffer(Ptr), + BufferBinding(GPUBufferBinding), } impl<'a> WebIdlConverter<'a> for GPUBindingResource { - type Options = (); + type Options = (); - fn convert<'b>( - scope: &mut HandleScope<'a>, - value: Local<'a, Value>, - prefix: Cow<'static, str>, - context: ContextFn<'b>, - options: &Self::Options, - ) -> Result { - >::convert(scope, value, prefix.clone(), context.borrowed(), options) - .map(Self::Sampler) - .or_else(|_| { - >::convert( - scope, - value, - prefix.clone(), - context.borrowed(), - options, - ) - .map(Self::TextureView) - }) - .or_else(|_| { - GPUBufferBinding::convert(scope, value, prefix, context, options) - .map(Self::BufferBinding) - }) - } + fn convert<'b>( + scope: &mut HandleScope<'a>, + value: Local<'a, Value>, + prefix: Cow<'static, str>, + context: ContextFn<'b>, + options: &Self::Options, + ) -> Result { + >::convert( + scope, + value, + prefix.clone(), + context.borrowed(), + options, + ) + .map(Self::Sampler) + .or_else(|_| { + >::convert( + scope, + value, + prefix.clone(), + context.borrowed(), + options, + ) + .map(Self::Texture) + }) + .or_else(|_| { + >::convert( + scope, + value, + prefix.clone(), + context.borrowed(), + options, + ) + .map(Self::TextureView) + }) + .or_else(|_| { + >::convert( + scope, + value, + prefix.clone(), + context.borrowed(), + options, + ) + .map(Self::Buffer) + }) + .or_else(|_| { + GPUBufferBinding::convert(scope, value, prefix, context, options) + .map(Self::BufferBinding) + }) + } } diff --git a/deno_webgpu/bind_group_layout.rs b/deno_webgpu/bind_group_layout.rs index 319f626e7..79b7bbe0b 100644 --- a/deno_webgpu/bind_group_layout.rs +++ b/deno_webgpu/bind_group_layout.rs @@ -4,173 +4,188 @@ use deno_core::op2; use deno_core::GarbageCollected; use deno_core::WebIDL; +use crate::error::GPUGenericError; use crate::texture::GPUTextureViewDimension; use crate::Instance; pub struct GPUBindGroupLayout { - pub instance: Instance, - pub id: wgpu_core::id::BindGroupLayoutId, - pub label: String, + pub instance: Instance, + pub id: wgpu_core::id::BindGroupLayoutId, + pub label: String, } impl Drop for GPUBindGroupLayout { - fn drop(&mut self) { - self.instance.bind_group_layout_drop(self.id); - } + fn drop(&mut self) { + self.instance.bind_group_layout_drop(self.id); + } } impl deno_core::webidl::WebIdlInterfaceConverter for GPUBindGroupLayout { - const NAME: &'static str = "GPUBindGroupLayout"; + const NAME: &'static str = "GPUBindGroupLayout"; } -impl GarbageCollected for GPUBindGroupLayout {} +impl GarbageCollected for GPUBindGroupLayout { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUBindGroupLayout" + } +} #[op2] impl GPUBindGroupLayout { - #[getter] - #[string] - fn label(&self) -> String { - self.label.clone() - } - #[setter] - #[string] - fn label(&self, #[webidl] _label: String) { - // TODO(@crowlKats): no-op, needs wpgu to implement changing the label - } + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } + + #[getter] + #[string] + fn label(&self) -> String { + self.label.clone() + } + #[setter] + #[string] + fn label(&self, #[webidl] _label: String) { + // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUBindGroupLayoutDescriptor { - #[webidl(default = String::new())] - pub label: String, - pub entries: Vec, + #[webidl(default = String::new())] + pub label: String, + pub entries: Vec, } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUBindGroupLayoutEntry { - #[options(enforce_range = true)] - pub binding: u32, - #[options(enforce_range = true)] - pub visibility: u32, - pub buffer: Option, - pub sampler: Option, - pub texture: Option, - pub storage_texture: Option, + #[options(enforce_range = true)] + pub binding: u32, + #[options(enforce_range = true)] + pub visibility: u32, + pub buffer: Option, + pub sampler: Option, + pub texture: Option, + pub storage_texture: Option, } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUBufferBindingLayout { - #[webidl(default = GPUBufferBindingType::Uniform)] - pub r#type: GPUBufferBindingType, - #[webidl(default = false)] - pub has_dynamic_offset: bool, - #[webidl(default = 0)] - pub min_binding_size: u64, + #[webidl(default = GPUBufferBindingType::Uniform)] + pub r#type: GPUBufferBindingType, + #[webidl(default = false)] + pub has_dynamic_offset: bool, + #[webidl(default = 0)] + pub min_binding_size: u64, } #[derive(WebIDL)] #[webidl(enum)] pub(crate) enum GPUBufferBindingType { - Uniform, - Storage, - ReadOnlyStorage, + Uniform, + Storage, + ReadOnlyStorage, } impl From for wgpu_types::BufferBindingType { - fn from(value: GPUBufferBindingType) -> Self { - match value { - GPUBufferBindingType::Uniform => Self::Uniform, - GPUBufferBindingType::Storage => Self::Storage { read_only: false }, - GPUBufferBindingType::ReadOnlyStorage => Self::Storage { read_only: true }, - } + fn from(value: GPUBufferBindingType) -> Self { + match value { + GPUBufferBindingType::Uniform => Self::Uniform, + GPUBufferBindingType::Storage => Self::Storage { read_only: false }, + GPUBufferBindingType::ReadOnlyStorage => { + Self::Storage { read_only: true } + } } + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUSamplerBindingLayout { - #[webidl(default = GPUSamplerBindingType::Filtering)] - pub r#type: GPUSamplerBindingType, + #[webidl(default = GPUSamplerBindingType::Filtering)] + pub r#type: GPUSamplerBindingType, } #[derive(WebIDL)] #[webidl(enum)] pub(crate) enum GPUSamplerBindingType { - Filtering, - NonFiltering, - Comparison, + Filtering, + NonFiltering, + Comparison, } impl From for wgpu_types::SamplerBindingType { - fn from(value: GPUSamplerBindingType) -> Self { - match value { - GPUSamplerBindingType::Filtering => Self::Filtering, - GPUSamplerBindingType::NonFiltering => Self::NonFiltering, - GPUSamplerBindingType::Comparison => Self::Comparison, - } + fn from(value: GPUSamplerBindingType) -> Self { + match value { + GPUSamplerBindingType::Filtering => Self::Filtering, + GPUSamplerBindingType::NonFiltering => Self::NonFiltering, + GPUSamplerBindingType::Comparison => Self::Comparison, } + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUTextureBindingLayout { - #[webidl(default = GPUTextureSampleType::Float)] - pub sample_type: GPUTextureSampleType, - #[webidl(default = GPUTextureViewDimension::D2)] - pub view_dimension: GPUTextureViewDimension, - #[webidl(default = false)] - pub multisampled: bool, + #[webidl(default = GPUTextureSampleType::Float)] + pub sample_type: GPUTextureSampleType, + #[webidl(default = GPUTextureViewDimension::D2)] + pub view_dimension: GPUTextureViewDimension, + #[webidl(default = false)] + pub multisampled: bool, } #[derive(WebIDL)] #[webidl(enum)] pub(crate) enum GPUTextureSampleType { - Float, - UnfilterableFloat, - Depth, - Sint, - Uint, + Float, + UnfilterableFloat, + Depth, + Sint, + Uint, } impl From for wgpu_types::TextureSampleType { - fn from(value: GPUTextureSampleType) -> Self { - match value { - GPUTextureSampleType::Float => Self::Float { filterable: true }, - GPUTextureSampleType::UnfilterableFloat => Self::Float { filterable: false }, - GPUTextureSampleType::Depth => Self::Depth, - GPUTextureSampleType::Sint => Self::Sint, - GPUTextureSampleType::Uint => Self::Uint, - } + fn from(value: GPUTextureSampleType) -> Self { + match value { + GPUTextureSampleType::Float => Self::Float { filterable: true }, + GPUTextureSampleType::UnfilterableFloat => { + Self::Float { filterable: false } + } + GPUTextureSampleType::Depth => Self::Depth, + GPUTextureSampleType::Sint => Self::Sint, + GPUTextureSampleType::Uint => Self::Uint, } + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUStorageTextureBindingLayout { - #[webidl(default = GPUStorageTextureAccess::WriteOnly)] - pub access: GPUStorageTextureAccess, - pub format: super::texture::GPUTextureFormat, - #[webidl(default = GPUTextureViewDimension::D2)] - pub view_dimension: GPUTextureViewDimension, + #[webidl(default = GPUStorageTextureAccess::WriteOnly)] + pub access: GPUStorageTextureAccess, + pub format: super::texture::GPUTextureFormat, + #[webidl(default = GPUTextureViewDimension::D2)] + pub view_dimension: GPUTextureViewDimension, } #[derive(WebIDL)] #[webidl(enum)] pub(crate) enum GPUStorageTextureAccess { - WriteOnly, - ReadOnly, - ReadWrite, + WriteOnly, + ReadOnly, + ReadWrite, } impl From for wgpu_types::StorageTextureAccess { - fn from(value: GPUStorageTextureAccess) -> Self { - match value { - GPUStorageTextureAccess::WriteOnly => Self::WriteOnly, - GPUStorageTextureAccess::ReadOnly => Self::ReadOnly, - GPUStorageTextureAccess::ReadWrite => Self::ReadWrite, - } + fn from(value: GPUStorageTextureAccess) -> Self { + match value { + GPUStorageTextureAccess::WriteOnly => Self::WriteOnly, + GPUStorageTextureAccess::ReadOnly => Self::ReadOnly, + GPUStorageTextureAccess::ReadWrite => Self::ReadWrite, } + } } diff --git a/deno_webgpu/buffer.rs b/deno_webgpu/buffer.rs index da0b1a52d..25b448a0a 100644 --- a/deno_webgpu/buffer.rs +++ b/deno_webgpu/buffer.rs @@ -13,247 +13,266 @@ use deno_core::WebIDL; use deno_error::JsErrorBox; use wgpu_core::device::HostMap as MapMode; +use crate::error::GPUGenericError; use crate::Instance; #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUBufferDescriptor { - #[webidl(default = String::new())] - pub label: String, + #[webidl(default = String::new())] + pub label: String, - pub size: u64, - #[options(enforce_range = true)] - pub usage: u32, - #[webidl(default = false)] - pub mapped_at_creation: bool, + pub size: u64, + #[options(enforce_range = true)] + pub usage: u32, + #[webidl(default = false)] + pub mapped_at_creation: bool, } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum BufferError { - #[class(generic)] - #[error(transparent)] - Canceled(#[from] oneshot::Canceled), - #[class("DOMExceptionOperationError")] - #[error(transparent)] - Access(#[from] wgpu_core::resource::BufferAccessError), - #[class("DOMExceptionOperationError")] - #[error("{0}")] - Operation(&'static str), - #[class(inherit)] - #[error(transparent)] - Other(#[from] JsErrorBox), + #[class(generic)] + #[error(transparent)] + Canceled(#[from] oneshot::Canceled), + #[class("DOMExceptionOperationError")] + #[error(transparent)] + Access(#[from] wgpu_core::resource::BufferAccessError), + #[class("DOMExceptionOperationError")] + #[error("{0}")] + Operation(&'static str), + #[class(inherit)] + #[error(transparent)] + Other(#[from] JsErrorBox), } pub struct GPUBuffer { - pub instance: Instance, - pub error_handler: super::error::ErrorHandler, + pub instance: Instance, + pub error_handler: super::error::ErrorHandler, - pub id: wgpu_core::id::BufferId, - pub device: wgpu_core::id::DeviceId, + pub id: wgpu_core::id::BufferId, + pub device: wgpu_core::id::DeviceId, - pub label: String, + pub label: String, - pub size: u64, - pub usage: u32, + pub size: u64, + pub usage: u32, - pub map_state: RefCell<&'static str>, - pub map_mode: RefCell>, + pub map_state: RefCell<&'static str>, + pub map_mode: RefCell>, - pub mapped_js_buffers: RefCell>>, + pub mapped_js_buffers: RefCell>>, } impl Drop for GPUBuffer { - fn drop(&mut self) { - self.instance.buffer_drop(self.id); - } + fn drop(&mut self) { + self.instance.buffer_drop(self.id); + } } impl WebIdlInterfaceConverter for GPUBuffer { - const NAME: &'static str = "GPUBuffer"; + const NAME: &'static str = "GPUBuffer"; } -impl GarbageCollected for GPUBuffer {} +impl GarbageCollected for GPUBuffer { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUBuffer" + } +} #[op2] impl GPUBuffer { - #[getter] - #[string] - fn label(&self) -> String { - self.label.clone() - } - #[setter] - #[string] - fn label(&self, #[webidl] _label: String) { - // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } + + #[getter] + #[string] + fn label(&self) -> String { + self.label.clone() + } + #[setter] + #[string] + fn label(&self, #[webidl] _label: String) { + // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + } + + #[getter] + #[number] + fn size(&self) -> u64 { + self.size + } + #[getter] + fn usage(&self) -> u32 { + self.usage + } + + #[getter] + #[string] + fn map_state(&self) -> &'static str { + *self.map_state.borrow() + } + + // In the successful case, the promise should resolve to undefined, but + // `#[undefined]` does not seem to work here. + // https://github.com/denoland/deno/issues/29603 + #[async_method] + async fn map_async( + &self, + #[webidl(options(enforce_range = true))] mode: u32, + #[webidl(default = 0)] offset: u64, + #[webidl] size: Option, + ) -> Result<(), BufferError> { + let read_mode = (mode & 0x0001) == 0x0001; + let write_mode = (mode & 0x0002) == 0x0002; + if (read_mode && write_mode) || (!read_mode && !write_mode) { + return Err(BufferError::Operation( + "exactly one of READ or WRITE map mode must be set", + )); } - #[getter] - #[number] - fn size(&self) -> u64 { - self.size - } - #[getter] - fn usage(&self) -> u32 { - self.usage + let mode = if read_mode { + MapMode::Read + } else { + assert!(write_mode); + MapMode::Write + }; + + { + *self.map_state.borrow_mut() = "pending"; } - #[getter] - #[string] - fn map_state(&self) -> &'static str { - *self.map_state.borrow() + let (sender, receiver) = + oneshot::channel::(); + + { + let callback = Box::new(move |status| { + sender.send(status).unwrap(); + }); + + let err = self + .instance + .buffer_map_async( + self.id, + offset, + size, + wgpu_core::resource::BufferMapOperation { + host: mode, + callback: Some(callback), + }, + ) + .err(); + + if err.is_some() { + self.error_handler.push_error(err); + return Err(BufferError::Operation("validation error occurred")); + } } - #[async_method] - async fn map_async( - &self, - #[webidl(options(enforce_range = true))] mode: u32, - #[webidl(default = 0)] offset: u64, - #[webidl] size: Option, - ) -> Result<(), BufferError> { - let read_mode = (mode & 0x0001) == 0x0001; - let write_mode = (mode & 0x0002) == 0x0002; - if (read_mode && write_mode) || (!read_mode && !write_mode) { - return Err(BufferError::Operation( - "exactly one of READ or WRITE map mode must be set", - )); - } - - let mode = if read_mode { - MapMode::Read - } else { - assert!(write_mode); - MapMode::Write - }; - + let done = Rc::new(RefCell::new(false)); + let done_ = done.clone(); + let device_poll_fut = async move { + while !*done.borrow() { { - *self.map_state.borrow_mut() = "pending"; - } - - let (sender, receiver) = oneshot::channel::(); - - { - let callback = Box::new(move |status| { - sender.send(status).unwrap(); - }); - - let err = self - .instance - .buffer_map_async( - self.id, - offset, - size, - wgpu_core::resource::BufferMapOperation { - host: mode, - callback: Some(callback), - }, - ) - .err(); - - if err.is_some() { - self.error_handler.push_error(err); - return Err(BufferError::Operation("validation error occurred")); - } - } - - let done = Rc::new(RefCell::new(false)); - let done_ = done.clone(); - let device_poll_fut = async move { - while !*done.borrow() { - { - self.instance - .device_poll(self.device, wgpu_types::PollType::wait()) - .unwrap(); - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - Ok::<(), BufferError>(()) - }; - - let receiver_fut = async move { - receiver.await??; - let mut done = done_.borrow_mut(); - *done = true; - Ok::<(), BufferError>(()) - }; - - tokio::try_join!(device_poll_fut, receiver_fut)?; - - *self.map_state.borrow_mut() = "mapped"; - *self.map_mode.borrow_mut() = Some(mode); - - Ok(()) - } - - fn get_mapped_range<'s>( - &self, - scope: &mut v8::HandleScope<'s>, - #[webidl(default = 0)] offset: u64, - #[webidl] size: Option, - ) -> Result, BufferError> { - let (slice_pointer, range_size) = self + self .instance - .buffer_get_mapped_range(self.id, offset, size) - .map_err(BufferError::Access)?; - - let mode = self.map_mode.borrow(); - let mode = mode.as_ref().unwrap(); - - let bs = if mode == &MapMode::Write { - unsafe extern "C" fn noop_deleter_callback( - _data: *mut std::ffi::c_void, - _byte_length: usize, - _deleter_data: *mut std::ffi::c_void, - ) { - } - - // SAFETY: creating a backing store from the pointer and length provided by wgpu - unsafe { - v8::ArrayBuffer::new_backing_store_from_ptr( - slice_pointer.as_ptr() as _, - range_size as usize, - noop_deleter_callback, - std::ptr::null_mut(), - ) - } - } else { - // SAFETY: creating a vector from the pointer and length provided by wgpu - let slice = - unsafe { std::slice::from_raw_parts(slice_pointer.as_ptr(), range_size as usize) }; - v8::ArrayBuffer::new_backing_store_from_vec(slice.to_vec()) - }; - - let shared_bs = bs.make_shared(); - let ab = v8::ArrayBuffer::with_backing_store(scope, &shared_bs); - - if mode == &MapMode::Write { - self.mapped_js_buffers - .borrow_mut() - .push(v8::Global::new(scope, ab)); + .device_poll(self.device, wgpu_types::PollType::wait_indefinitely()) + .unwrap(); } + tokio::time::sleep(Duration::from_millis(10)).await; + } + Ok::<(), BufferError>(()) + }; - Ok(ab) + let receiver_fut = async move { + receiver.await??; + let mut done = done_.borrow_mut(); + *done = true; + Ok::<(), BufferError>(()) + }; + + tokio::try_join!(device_poll_fut, receiver_fut)?; + + *self.map_state.borrow_mut() = "mapped"; + *self.map_mode.borrow_mut() = Some(mode); + + Ok(()) + } + + fn get_mapped_range<'s>( + &self, + scope: &mut v8::HandleScope<'s>, + #[webidl(default = 0)] offset: u64, + #[webidl] size: Option, + ) -> Result, BufferError> { + let (slice_pointer, range_size) = self + .instance + .buffer_get_mapped_range(self.id, offset, size) + .map_err(BufferError::Access)?; + + let mode = self.map_mode.borrow(); + let mode = mode.as_ref().unwrap(); + + let bs = if mode == &MapMode::Write { + unsafe extern "C" fn noop_deleter_callback( + _data: *mut std::ffi::c_void, + _byte_length: usize, + _deleter_data: *mut std::ffi::c_void, + ) { + } + + // SAFETY: creating a backing store from the pointer and length provided by wgpu + unsafe { + v8::ArrayBuffer::new_backing_store_from_ptr( + slice_pointer.as_ptr() as _, + range_size as usize, + noop_deleter_callback, + std::ptr::null_mut(), + ) + } + } else { + // SAFETY: creating a vector from the pointer and length provided by wgpu + let slice = unsafe { + std::slice::from_raw_parts(slice_pointer.as_ptr(), range_size as usize) + }; + v8::ArrayBuffer::new_backing_store_from_vec(slice.to_vec()) + }; + + let shared_bs = bs.make_shared(); + let ab = v8::ArrayBuffer::with_backing_store(scope, &shared_bs); + + if mode == &MapMode::Write { + self + .mapped_js_buffers + .borrow_mut() + .push(v8::Global::new(scope, ab)); } - #[nofast] - fn unmap(&self, scope: &mut v8::HandleScope) -> Result<(), BufferError> { - for ab in self.mapped_js_buffers.replace(vec![]) { - let ab = ab.open(scope); - ab.detach(None); - } + Ok(ab) + } - self.instance - .buffer_unmap(self.id) - .map_err(BufferError::Access)?; - - *self.map_state.borrow_mut() = "unmapped"; - - Ok(()) + #[nofast] + #[undefined] + fn unmap(&self, scope: &mut v8::HandleScope) -> Result<(), BufferError> { + for ab in self.mapped_js_buffers.replace(vec![]) { + let ab = ab.open(scope); + ab.detach(None); } - #[fast] - fn destroy(&self) -> Result<(), JsErrorBox> { - self.instance - .buffer_destroy(self.id) - .map_err(|e| JsErrorBox::generic(e.to_string())) - } + self + .instance + .buffer_unmap(self.id) + .map_err(BufferError::Access)?; + + *self.map_state.borrow_mut() = "unmapped"; + + Ok(()) + } + + #[fast] + #[undefined] + fn destroy(&self) { + self.instance.buffer_destroy(self.id); + } } diff --git a/deno_webgpu/byow.rs b/deno_webgpu/byow.rs index bfce74abf..c6e6e7168 100644 --- a/deno_webgpu/byow.rs +++ b/deno_webgpu/byow.rs @@ -3,10 +3,10 @@ use std::cell::RefCell; use std::ffi::c_void; #[cfg(any( - target_os = "linux", - target_os = "macos", - target_os = "freebsd", - target_os = "openbsd" + target_os = "linux", + target_os = "macos", + target_os = "freebsd", + target_os = "openbsd" ))] use std::ptr::NonNull; @@ -24,305 +24,352 @@ use crate::surface::GPUCanvasContext; #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum ByowError { - #[class(type)] - #[error("Cannot create surface outside of WebGPU context. Did you forget to call `navigator.gpu.requestAdapter()`?")] - WebGPUNotInitiated, - #[class(type)] - #[error("Invalid parameters")] - InvalidParameters, - #[class(generic)] - #[error(transparent)] - CreateSurface(wgpu_core::instance::CreateSurfaceError), - #[cfg(target_os = "windows")] - #[class(type)] - #[error("Invalid system on Windows")] - InvalidSystem, - #[cfg(target_os = "macos")] - #[class(type)] - #[error("Invalid system on macOS")] - InvalidSystem, - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] - #[class(type)] - #[error("Invalid system on Linux/BSD")] - InvalidSystem, - #[cfg(any( - target_os = "windows", - target_os = "linux", - target_os = "freebsd", - target_os = "openbsd" - ))] - #[class(type)] - #[error("window is null")] - NullWindow, - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] - #[class(type)] - #[error("display is null")] - NullDisplay, - #[cfg(target_os = "macos")] - #[class(type)] - #[error("ns_view is null")] - NSViewDisplay, -} - -// TODO(@littledivy): This will extend `OffscreenCanvas` when we add it. -pub struct UnsafeWindowSurface { - pub id: wgpu_core::id::SurfaceId, - pub width: RefCell, - pub height: RefCell, - - pub context: SameObject, -} - -impl GarbageCollected for UnsafeWindowSurface {} - -#[op2] -impl UnsafeWindowSurface { - #[constructor] - #[cppgc] - fn new( - state: &mut OpState, - #[from_v8] options: UnsafeWindowSurfaceOptions, - ) -> Result { - let instance = state - .try_borrow::() - .ok_or(ByowError::WebGPUNotInitiated)?; - - // Security note: - // - // The `window_handle` and `display_handle` options are pointers to - // platform-specific window handles. - // - // The code below works under the assumption that: - // - // - handles can only be created by the FFI interface which - // enforces --allow-ffi. - // - // - `*const c_void` deserizalizes null and v8::External. - // - // - Only FFI can export v8::External to user code. - if options.window_handle.is_null() { - return Err(ByowError::InvalidParameters); - } - - let (win_handle, display_handle) = raw_window( - options.system, - options.window_handle, - options.display_handle, - )?; - - // SAFETY: see above comment - let id = unsafe { - instance - .instance_create_surface(display_handle, win_handle, None) - .map_err(ByowError::CreateSurface)? - }; - - Ok(UnsafeWindowSurface { - id, - width: RefCell::new(options.width), - height: RefCell::new(options.height), - context: SameObject::new(), - }) - } - - #[global] - fn get_context( - &self, - #[this] this: v8::Global, - scope: &mut v8::HandleScope, - ) -> v8::Global { - self.context.get(scope, |_| GPUCanvasContext { - surface_id: self.id, - width: self.width.clone(), - height: self.height.clone(), - config: RefCell::new(None), - texture: RefCell::new(None), - canvas: this, - }) - } - - #[nofast] - fn present(&self, scope: &mut v8::HandleScope) -> Result<(), JsErrorBox> { - let Some(context) = self.context.try_unwrap(scope) else { - return Err(JsErrorBox::type_error("getContext was never called")); - }; - - context.present().map_err(JsErrorBox::from_err) - } -} - -struct UnsafeWindowSurfaceOptions { - system: UnsafeWindowSurfaceSystem, - window_handle: *const c_void, - display_handle: *const c_void, - width: u32, - height: u32, -} - -#[derive(Eq, PartialEq)] -enum UnsafeWindowSurfaceSystem { - Cocoa, - Win32, - X11, - Wayland, -} - -impl<'a> FromV8<'a> for UnsafeWindowSurfaceOptions { - type Error = JsErrorBox; - - fn from_v8( - scope: &mut v8::HandleScope<'a>, - value: Local<'a, Value>, - ) -> Result { - let obj = value - .try_cast::() - .map_err(|_| JsErrorBox::type_error("is not an object"))?; - - let key = v8::String::new(scope, "system").unwrap(); - let val = obj - .get(scope, key.into()) - .ok_or_else(|| JsErrorBox::type_error("missing field 'system'"))?; - let s = String::from_v8(scope, val).unwrap(); - let system = match s.as_str() { - "cocoa" => UnsafeWindowSurfaceSystem::Cocoa, - "win32" => UnsafeWindowSurfaceSystem::Win32, - "x11" => UnsafeWindowSurfaceSystem::X11, - "wayland" => UnsafeWindowSurfaceSystem::Wayland, - _ => return Err(JsErrorBox::type_error(format!("Invalid system kind '{s}'"))), - }; - - let key = v8::String::new(scope, "windowHandle").unwrap(); - let val = obj - .get(scope, key.into()) - .ok_or_else(|| JsErrorBox::type_error("missing field 'windowHandle'"))?; - let Some(window_handle) = deno_core::_ops::to_external_option(&val) else { - return Err(JsErrorBox::type_error("expected external")); - }; - - let key = v8::String::new(scope, "displayHandle").unwrap(); - let val = obj - .get(scope, key.into()) - .ok_or_else(|| JsErrorBox::type_error("missing field 'displayHandle'"))?; - let Some(display_handle) = deno_core::_ops::to_external_option(&val) else { - return Err(JsErrorBox::type_error("expected external")); - }; - - let key = v8::String::new(scope, "width").unwrap(); - let val = obj - .get(scope, key.into()) - .ok_or_else(|| JsErrorBox::type_error("missing field 'width'"))?; - let width = deno_core::convert::Number::::from_v8(scope, val)?.0; - - let key = v8::String::new(scope, "height").unwrap(); - let val = obj - .get(scope, key.into()) - .ok_or_else(|| JsErrorBox::type_error("missing field 'height'"))?; - let height = deno_core::convert::Number::::from_v8(scope, val)?.0; - - Ok(Self { - system, - window_handle, - display_handle, - width, - height, - }) - } -} - -type RawHandles = ( - raw_window_handle::RawWindowHandle, - raw_window_handle::RawDisplayHandle, -); - -#[cfg(target_os = "macos")] -fn raw_window( - system: UnsafeWindowSurfaceSystem, - _ns_window: *const c_void, - ns_view: *const c_void, -) -> Result { - if system != UnsafeWindowSurfaceSystem::Cocoa { - return Err(ByowError::InvalidSystem); - } - - let win_handle = - raw_window_handle::RawWindowHandle::AppKit(raw_window_handle::AppKitWindowHandle::new( - NonNull::new(ns_view as *mut c_void).ok_or(ByowError::NSViewDisplay)?, - )); - - let display_handle = - raw_window_handle::RawDisplayHandle::AppKit(raw_window_handle::AppKitDisplayHandle::new()); - Ok((win_handle, display_handle)) -} - -#[cfg(target_os = "windows")] -fn raw_window( - system: UnsafeWindowSurfaceSystem, - window: *const c_void, - hinstance: *const c_void, -) -> Result { - use raw_window_handle::WindowsDisplayHandle; - if system != UnsafeWindowSurfaceSystem::Win32 { - return Err(ByowError::InvalidSystem); - } - - let win_handle = { - let mut handle = raw_window_handle::Win32WindowHandle::new( - std::num::NonZeroIsize::new(window as isize).ok_or(ByowError::NullWindow)?, - ); - handle.hinstance = std::num::NonZeroIsize::new(hinstance as isize); - - raw_window_handle::RawWindowHandle::Win32(handle) - }; - - let display_handle = raw_window_handle::RawDisplayHandle::Windows(WindowsDisplayHandle::new()); - Ok((win_handle, display_handle)) -} - -#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] -fn raw_window( - system: UnsafeWindowSurfaceSystem, - window: *const c_void, - display: *const c_void, -) -> Result { - let (win_handle, display_handle); - if system == UnsafeWindowSurfaceSystem::X11 { - win_handle = raw_window_handle::RawWindowHandle::Xlib( - raw_window_handle::XlibWindowHandle::new(window as *mut c_void as _), - ); - - display_handle = raw_window_handle::RawDisplayHandle::Xlib( - raw_window_handle::XlibDisplayHandle::new(NonNull::new(display as *mut c_void), 0), - ); - } else if system == UnsafeWindowSurfaceSystem::Wayland { - win_handle = raw_window_handle::RawWindowHandle::Wayland( - raw_window_handle::WaylandWindowHandle::new( - NonNull::new(window as *mut c_void).ok_or(ByowError::NullWindow)?, - ), - ); - - display_handle = raw_window_handle::RawDisplayHandle::Wayland( - raw_window_handle::WaylandDisplayHandle::new( - NonNull::new(display as *mut c_void).ok_or(ByowError::NullDisplay)?, - ), - ); - } else { - return Err(ByowError::InvalidSystem); - } - - Ok((win_handle, display_handle)) -} - -#[cfg(not(any( + #[cfg(not(any( target_os = "macos", target_os = "windows", target_os = "linux", target_os = "freebsd", target_os = "openbsd", + )))] + #[class(type)] + #[error("Unsupported platform")] + Unsupported, + #[class(type)] + #[error( + "Cannot create surface outside of WebGPU context. Did you forget to call `navigator.gpu.requestAdapter()`?" + )] + WebGPUNotInitiated, + #[class(type)] + #[error("Invalid parameters")] + InvalidParameters, + #[class(generic)] + #[error(transparent)] + CreateSurface(wgpu_core::instance::CreateSurfaceError), + #[cfg(target_os = "windows")] + #[class(type)] + #[error("Invalid system on Windows")] + InvalidSystem, + #[cfg(target_os = "macos")] + #[class(type)] + #[error("Invalid system on macOS")] + InvalidSystem, + #[cfg(any( + target_os = "linux", + target_os = "freebsd", + target_os = "openbsd" + ))] + #[class(type)] + #[error("Invalid system on Linux/BSD")] + InvalidSystem, + #[cfg(any( + target_os = "windows", + target_os = "linux", + target_os = "freebsd", + target_os = "openbsd" + ))] + #[class(type)] + #[error("window is null")] + NullWindow, + #[cfg(any( + target_os = "linux", + target_os = "freebsd", + target_os = "openbsd" + ))] + #[class(type)] + #[error("display is null")] + NullDisplay, + #[cfg(target_os = "macos")] + #[class(type)] + #[error("ns_view is null")] + NSViewDisplay, +} + +// TODO(@littledivy): This will extend `OffscreenCanvas` when we add it. +pub struct UnsafeWindowSurface { + pub id: wgpu_core::id::SurfaceId, + pub width: RefCell, + pub height: RefCell, + + pub context: SameObject, +} + +impl GarbageCollected for UnsafeWindowSurface { + fn get_name(&self) -> &'static std::ffi::CStr { + c"UnsafeWindowSurface" + } +} + +#[op2] +impl UnsafeWindowSurface { + #[constructor] + #[cppgc] + fn new( + state: &mut OpState, + #[from_v8] options: UnsafeWindowSurfaceOptions, + ) -> Result { + let instance = state + .try_borrow::() + .ok_or(ByowError::WebGPUNotInitiated)?; + + // Security note: + // + // The `window_handle` and `display_handle` options are pointers to + // platform-specific window handles. + // + // The code below works under the assumption that: + // + // - handles can only be created by the FFI interface which + // enforces --allow-ffi. + // + // - `*const c_void` deserizalizes null and v8::External. + // + // - Only FFI can export v8::External to user code. + if options.window_handle.is_null() { + return Err(ByowError::InvalidParameters); + } + + let (win_handle, display_handle) = raw_window( + options.system, + options.window_handle, + options.display_handle, + )?; + + // SAFETY: see above comment + let id = unsafe { + instance + .instance_create_surface(display_handle, win_handle, None) + .map_err(ByowError::CreateSurface)? + }; + + Ok(UnsafeWindowSurface { + id, + width: RefCell::new(options.width), + height: RefCell::new(options.height), + context: SameObject::new(), + }) + } + + #[global] + fn get_context( + &self, + #[this] this: v8::Global, + scope: &mut v8::HandleScope, + ) -> v8::Global { + self.context.get(scope, |_| GPUCanvasContext { + surface_id: self.id, + width: self.width.clone(), + height: self.height.clone(), + config: RefCell::new(None), + texture: RefCell::new(None), + canvas: this, + }) + } + + #[nofast] + fn present(&self, scope: &mut v8::HandleScope) -> Result<(), JsErrorBox> { + let Some(context) = self.context.try_unwrap(scope) else { + return Err(JsErrorBox::type_error("getContext was never called")); + }; + + context.present().map_err(JsErrorBox::from_err) + } + + #[fast] + fn resize(&self, width: u32, height: u32, scope: &mut v8::HandleScope) { + self.width.replace(width); + self.height.replace(height); + + let Some(context) = self.context.try_unwrap(scope) else { + return; + }; + + context.resize_configure(width, height); + } +} + +struct UnsafeWindowSurfaceOptions { + system: UnsafeWindowSurfaceSystem, + window_handle: *const c_void, + display_handle: *const c_void, + width: u32, + height: u32, +} + +#[derive(Eq, PartialEq)] +enum UnsafeWindowSurfaceSystem { + Cocoa, + Win32, + X11, + Wayland, +} + +impl<'a> FromV8<'a> for UnsafeWindowSurfaceOptions { + type Error = JsErrorBox; + + fn from_v8( + scope: &mut v8::HandleScope<'a>, + value: Local<'a, Value>, + ) -> Result { + let obj = value + .try_cast::() + .map_err(|_| JsErrorBox::type_error("is not an object"))?; + + let key = v8::String::new(scope, "system").unwrap(); + let val = obj + .get(scope, key.into()) + .ok_or_else(|| JsErrorBox::type_error("missing field 'system'"))?; + let s = String::from_v8(scope, val).unwrap(); + let system = match s.as_str() { + "cocoa" => UnsafeWindowSurfaceSystem::Cocoa, + "win32" => UnsafeWindowSurfaceSystem::Win32, + "x11" => UnsafeWindowSurfaceSystem::X11, + "wayland" => UnsafeWindowSurfaceSystem::Wayland, + _ => { + return Err(JsErrorBox::type_error(format!( + "Invalid system kind '{s}'" + ))); + } + }; + + let key = v8::String::new(scope, "windowHandle").unwrap(); + let val = obj + .get(scope, key.into()) + .ok_or_else(|| JsErrorBox::type_error("missing field 'windowHandle'"))?; + let Some(window_handle) = deno_core::_ops::to_external_option(&val) else { + return Err(JsErrorBox::type_error("expected external")); + }; + + let key = v8::String::new(scope, "displayHandle").unwrap(); + let val = obj + .get(scope, key.into()) + .ok_or_else(|| JsErrorBox::type_error("missing field 'displayHandle'"))?; + let Some(display_handle) = deno_core::_ops::to_external_option(&val) else { + return Err(JsErrorBox::type_error("expected external")); + }; + + let key = v8::String::new(scope, "width").unwrap(); + let val = obj + .get(scope, key.into()) + .ok_or_else(|| JsErrorBox::type_error("missing field 'width'"))?; + let width = deno_core::convert::Number::::from_v8(scope, val)?.0; + + let key = v8::String::new(scope, "height").unwrap(); + let val = obj + .get(scope, key.into()) + .ok_or_else(|| JsErrorBox::type_error("missing field 'height'"))?; + let height = deno_core::convert::Number::::from_v8(scope, val)?.0; + + Ok(Self { + system, + window_handle, + display_handle, + width, + height, + }) + } +} + +type RawHandles = ( + raw_window_handle::RawWindowHandle, + raw_window_handle::RawDisplayHandle, +); + +#[cfg(target_os = "macos")] +fn raw_window( + system: UnsafeWindowSurfaceSystem, + _ns_window: *const c_void, + ns_view: *const c_void, +) -> Result { + if system != UnsafeWindowSurfaceSystem::Cocoa { + return Err(ByowError::InvalidSystem); + } + + let win_handle = raw_window_handle::RawWindowHandle::AppKit( + raw_window_handle::AppKitWindowHandle::new( + NonNull::new(ns_view as *mut c_void).ok_or(ByowError::NSViewDisplay)?, + ), + ); + + let display_handle = raw_window_handle::RawDisplayHandle::AppKit( + raw_window_handle::AppKitDisplayHandle::new(), + ); + Ok((win_handle, display_handle)) +} + +#[cfg(target_os = "windows")] +fn raw_window( + system: UnsafeWindowSurfaceSystem, + window: *const c_void, + hinstance: *const c_void, +) -> Result { + use raw_window_handle::WindowsDisplayHandle; + if system != UnsafeWindowSurfaceSystem::Win32 { + return Err(ByowError::InvalidSystem); + } + + let win_handle = { + let mut handle = raw_window_handle::Win32WindowHandle::new( + std::num::NonZeroIsize::new(window as isize) + .ok_or(ByowError::NullWindow)?, + ); + handle.hinstance = std::num::NonZeroIsize::new(hinstance as isize); + + raw_window_handle::RawWindowHandle::Win32(handle) + }; + + let display_handle = + raw_window_handle::RawDisplayHandle::Windows(WindowsDisplayHandle::new()); + Ok((win_handle, display_handle)) +} + +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] +fn raw_window( + system: UnsafeWindowSurfaceSystem, + window: *const c_void, + display: *const c_void, +) -> Result { + let (win_handle, display_handle); + if system == UnsafeWindowSurfaceSystem::X11 { + win_handle = raw_window_handle::RawWindowHandle::Xlib( + raw_window_handle::XlibWindowHandle::new(window as *mut c_void as _), + ); + + display_handle = raw_window_handle::RawDisplayHandle::Xlib( + raw_window_handle::XlibDisplayHandle::new( + NonNull::new(display as *mut c_void), + 0, + ), + ); + } else if system == UnsafeWindowSurfaceSystem::Wayland { + win_handle = raw_window_handle::RawWindowHandle::Wayland( + raw_window_handle::WaylandWindowHandle::new( + NonNull::new(window as *mut c_void).ok_or(ByowError::NullWindow)?, + ), + ); + + display_handle = raw_window_handle::RawDisplayHandle::Wayland( + raw_window_handle::WaylandDisplayHandle::new( + NonNull::new(display as *mut c_void).ok_or(ByowError::NullDisplay)?, + ), + ); + } else { + return Err(ByowError::InvalidSystem); + } + + Ok((win_handle, display_handle)) +} + +#[cfg(not(any( + target_os = "macos", + target_os = "windows", + target_os = "linux", + target_os = "freebsd", + target_os = "openbsd", )))] fn raw_window( - _system: UnsafeWindowSurfaceSystem, - _window: *const c_void, - _display: *const c_void, -) -> Result { - Err(deno_error::JsErrorBox::type_error("Unsupported platform")) + _system: UnsafeWindowSurfaceSystem, + _window: *const c_void, + _display: *const c_void, +) -> Result { + Err(ByowError::Unsupported) } diff --git a/deno_webgpu/command_buffer.rs b/deno_webgpu/command_buffer.rs index 6cb9d714c..6ad6dbc09 100644 --- a/deno_webgpu/command_buffer.rs +++ b/deno_webgpu/command_buffer.rs @@ -1,52 +1,57 @@ // Copyright 2018-2025 the Deno authors. MIT license. -use std::cell::OnceCell; - use deno_core::op2; use deno_core::GarbageCollected; use deno_core::WebIDL; +use crate::error::GPUGenericError; use crate::Instance; pub struct GPUCommandBuffer { - pub instance: Instance, - pub id: wgpu_core::id::CommandBufferId, - pub label: String, - - pub consumed: OnceCell<()>, + pub instance: Instance, + pub id: wgpu_core::id::CommandBufferId, + pub label: String, } impl Drop for GPUCommandBuffer { - fn drop(&mut self) { - if self.consumed.get().is_none() { - self.instance.command_buffer_drop(self.id); - } - } + fn drop(&mut self) { + self.instance.command_buffer_drop(self.id); + } } impl deno_core::webidl::WebIdlInterfaceConverter for GPUCommandBuffer { - const NAME: &'static str = "GPUCommandBuffer"; + const NAME: &'static str = "GPUCommandBuffer"; } -impl GarbageCollected for GPUCommandBuffer {} +impl GarbageCollected for GPUCommandBuffer { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUCommandBuffer" + } +} #[op2] impl GPUCommandBuffer { - #[getter] - #[string] - fn label(&self) -> String { - self.label.clone() - } - #[setter] - #[string] - fn label(&self, #[webidl] _label: String) { - // TODO(@crowlKats): no-op, needs wpgu to implement changing the label - } + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } + + #[getter] + #[string] + fn label(&self) -> String { + self.label.clone() + } + #[setter] + #[string] + fn label(&self, #[webidl] _label: String) { + // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUCommandBufferDescriptor { - #[webidl(default = String::new())] - pub label: String, + #[webidl(default = String::new())] + pub label: String, } diff --git a/deno_webgpu/command_encoder.rs b/deno_webgpu/command_encoder.rs index 4715741d6..358d8c352 100644 --- a/deno_webgpu/command_encoder.rs +++ b/deno_webgpu/command_encoder.rs @@ -2,18 +2,22 @@ use std::borrow::Cow; use std::cell::RefCell; +use std::num::NonZero; use deno_core::cppgc::Ptr; use deno_core::op2; +use deno_core::v8; +use deno_core::webidl::{IntOptions, WebIdlConverter, WebIdlError}; use deno_core::GarbageCollected; use deno_core::WebIDL; use deno_error::JsErrorBox; use wgpu_core::command::PassChannel; -use wgpu_types::TexelCopyBufferInfo; +use wgpu_types::{BufferAddress, TexelCopyBufferInfo}; use crate::buffer::GPUBuffer; use crate::command_buffer::GPUCommandBuffer; use crate::compute_pass::GPUComputePassEncoder; +use crate::error::GPUGenericError; use crate::queue::GPUTexelCopyTextureInfo; use crate::render_pass::GPULoadOp; use crate::render_pass::GPURenderPassEncoder; @@ -21,60 +25,73 @@ use crate::webidl::GPUExtent3D; use crate::Instance; pub struct GPUCommandEncoder { - pub instance: Instance, - pub error_handler: super::error::ErrorHandler, + pub instance: Instance, + pub error_handler: super::error::ErrorHandler, - pub id: wgpu_core::id::CommandEncoderId, - pub label: String, + pub id: wgpu_core::id::CommandEncoderId, + pub label: String, } impl Drop for GPUCommandEncoder { - fn drop(&mut self) { - self.instance.command_encoder_drop(self.id); - } + fn drop(&mut self) { + self.instance.command_encoder_drop(self.id); + } } -impl GarbageCollected for GPUCommandEncoder {} +impl GarbageCollected for GPUCommandEncoder { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUCommandEncoder" + } +} #[op2] impl GPUCommandEncoder { - #[getter] - #[string] - fn label(&self) -> String { - self.label.clone() - } - #[setter] - #[string] - fn label(&self, #[webidl] _label: String) { - // TODO(@crowlKats): no-op, needs wpgu to implement changing the label - } + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } - #[required(1)] - #[cppgc] - fn begin_render_pass( - &self, - #[webidl] descriptor: crate::render_pass::GPURenderPassDescriptor, - ) -> Result { - let color_attachments = Cow::Owned( - descriptor - .color_attachments - .into_iter() - .map(|attachment| { - attachment.into_option().map(|attachment| { - wgpu_core::command::RenderPassColorAttachment { - view: attachment.view.id, - resolve_target: attachment.resolve_target.map(|target| target.id), - load_op: attachment - .load_op - .with_default_value(attachment.clear_value.map(Into::into)), - store_op: attachment.store_op.into(), - } - }) - }) - .collect::>(), - ); + #[getter] + #[string] + fn label(&self) -> String { + self.label.clone() + } + #[setter] + #[string] + fn label(&self, #[webidl] _label: String) { + // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + } - let depth_stencil_attachment = descriptor + #[required(1)] + #[cppgc] + fn begin_render_pass( + &self, + #[webidl] descriptor: crate::render_pass::GPURenderPassDescriptor, + ) -> Result { + let color_attachments = Cow::Owned( + descriptor + .color_attachments + .into_iter() + .map(|attachment| { + attachment.into_option().map(|attachment| { + wgpu_core::command::RenderPassColorAttachment { + view: attachment.view.to_view_id(), + depth_slice: attachment.depth_slice, + resolve_target: attachment + .resolve_target + .map(|target| target.to_view_id()), + load_op: attachment + .load_op + .with_default_value(attachment.clear_value.map(Into::into)), + store_op: attachment.store_op.into(), + } + }) + }) + .collect::>(), + ); + + let depth_stencil_attachment = descriptor .depth_stencil_attachment .map(|attachment| { if attachment @@ -89,7 +106,7 @@ impl GPUCommandEncoder { } Ok(wgpu_core::command::RenderPassDepthStencilAttachment { - view: attachment.view.id, + view: attachment.view.to_view_id(), depth: PassChannel { load_op: attachment .depth_load_op @@ -108,295 +125,375 @@ impl GPUCommandEncoder { }) .transpose()?; - let timestamp_writes = descriptor.timestamp_writes.map(|timestamp_writes| { - wgpu_core::command::PassTimestampWrites { - query_set: timestamp_writes.query_set.id, - beginning_of_pass_write_index: timestamp_writes.beginning_of_pass_write_index, - end_of_pass_write_index: timestamp_writes.end_of_pass_write_index, - } - }); - - let wgpu_descriptor = wgpu_core::command::RenderPassDescriptor { - label: crate::transform_label(descriptor.label.clone()), - color_attachments, - depth_stencil_attachment: depth_stencil_attachment.as_ref(), - timestamp_writes: timestamp_writes.as_ref(), - occlusion_query_set: descriptor.occlusion_query_set.map(|query_set| query_set.id), - }; - - let (render_pass, err) = self - .instance - .command_encoder_begin_render_pass(self.id, &wgpu_descriptor); - - self.error_handler.push_error(err); - - Ok(GPURenderPassEncoder { - instance: self.instance.clone(), - error_handler: self.error_handler.clone(), - render_pass: RefCell::new(render_pass), - label: descriptor.label, - }) - } - - #[cppgc] - fn begin_compute_pass( - &self, - #[webidl] descriptor: crate::compute_pass::GPUComputePassDescriptor, - ) -> GPUComputePassEncoder { - let timestamp_writes = descriptor.timestamp_writes.map(|timestamp_writes| { - wgpu_core::command::PassTimestampWrites { - query_set: timestamp_writes.query_set.id, - beginning_of_pass_write_index: timestamp_writes.beginning_of_pass_write_index, - end_of_pass_write_index: timestamp_writes.end_of_pass_write_index, - } - }); - - let wgpu_descriptor = wgpu_core::command::ComputePassDescriptor { - label: crate::transform_label(descriptor.label.clone()), - timestamp_writes, - }; - - let (compute_pass, err) = self - .instance - .command_encoder_begin_compute_pass(self.id, &wgpu_descriptor); - - self.error_handler.push_error(err); - - GPUComputePassEncoder { - instance: self.instance.clone(), - error_handler: self.error_handler.clone(), - compute_pass: RefCell::new(compute_pass), - label: descriptor.label, + let timestamp_writes = + descriptor.timestamp_writes.map(|timestamp_writes| { + wgpu_core::command::PassTimestampWrites { + query_set: timestamp_writes.query_set.id, + beginning_of_pass_write_index: timestamp_writes + .beginning_of_pass_write_index, + end_of_pass_write_index: timestamp_writes.end_of_pass_write_index, } - } + }); - #[required(5)] - fn copy_buffer_to_buffer( - &self, - #[webidl] source: Ptr, - #[webidl(options(enforce_range = true))] source_offset: u64, - #[webidl] destination: Ptr, - #[webidl(options(enforce_range = true))] destination_offset: u64, - #[webidl(options(enforce_range = true))] size: u64, - ) { - let err = self - .instance - .command_encoder_copy_buffer_to_buffer( - self.id, - source.id, - source_offset, - destination.id, - destination_offset, - size, - ) - .err(); + let wgpu_descriptor = wgpu_core::command::RenderPassDescriptor { + label: crate::transform_label(descriptor.label.clone()), + color_attachments, + depth_stencil_attachment: depth_stencil_attachment.as_ref(), + timestamp_writes: timestamp_writes.as_ref(), + occlusion_query_set: descriptor + .occlusion_query_set + .map(|query_set| query_set.id), + multiview_mask: NonZero::new(descriptor.multiview_mask), + }; - self.error_handler.push_error(err); - } + let (render_pass, err) = self + .instance + .command_encoder_begin_render_pass(self.id, &wgpu_descriptor); - #[required(3)] - fn copy_buffer_to_texture( - &self, - #[webidl] source: GPUTexelCopyBufferInfo, - #[webidl] destination: GPUTexelCopyTextureInfo, - #[webidl] copy_size: GPUExtent3D, - ) { - let source = TexelCopyBufferInfo { - buffer: source.buffer.id, - layout: wgpu_types::TexelCopyBufferLayout { - offset: source.offset, - bytes_per_row: source.bytes_per_row, - rows_per_image: source.rows_per_image, - }, - }; - let destination = wgpu_types::TexelCopyTextureInfo { - texture: destination.texture.id, - mip_level: destination.mip_level, - origin: destination.origin.into(), - aspect: destination.aspect.into(), - }; + self.error_handler.push_error(err); - let err = self - .instance - .command_encoder_copy_buffer_to_texture( - self.id, - &source, - &destination, - ©_size.into(), - ) - .err(); + Ok(GPURenderPassEncoder { + instance: self.instance.clone(), + error_handler: self.error_handler.clone(), + render_pass: RefCell::new(render_pass), + label: descriptor.label, + }) + } - self.error_handler.push_error(err); - } - - #[required(3)] - fn copy_texture_to_buffer( - &self, - #[webidl] source: GPUTexelCopyTextureInfo, - #[webidl] destination: GPUTexelCopyBufferInfo, - #[webidl] copy_size: GPUExtent3D, - ) { - let source = wgpu_types::TexelCopyTextureInfo { - texture: source.texture.id, - mip_level: source.mip_level, - origin: source.origin.into(), - aspect: source.aspect.into(), - }; - let destination = TexelCopyBufferInfo { - buffer: destination.buffer.id, - layout: wgpu_types::TexelCopyBufferLayout { - offset: destination.offset, - bytes_per_row: destination.bytes_per_row, - rows_per_image: destination.rows_per_image, - }, - }; - - let err = self - .instance - .command_encoder_copy_texture_to_buffer( - self.id, - &source, - &destination, - ©_size.into(), - ) - .err(); - - self.error_handler.push_error(err); - } - - #[required(3)] - fn copy_texture_to_texture( - &self, - #[webidl] source: GPUTexelCopyTextureInfo, - #[webidl] destination: GPUTexelCopyTextureInfo, - #[webidl] copy_size: GPUExtent3D, - ) { - let source = wgpu_types::TexelCopyTextureInfo { - texture: source.texture.id, - mip_level: source.mip_level, - origin: source.origin.into(), - aspect: source.aspect.into(), - }; - let destination = wgpu_types::TexelCopyTextureInfo { - texture: destination.texture.id, - mip_level: destination.mip_level, - origin: destination.origin.into(), - aspect: destination.aspect.into(), - }; - - let err = self - .instance - .command_encoder_copy_texture_to_texture( - self.id, - &source, - &destination, - ©_size.into(), - ) - .err(); - - self.error_handler.push_error(err); - } - - #[required(1)] - fn clear_buffer( - &self, - #[webidl] buffer: Ptr, - #[webidl(default = 0, options(enforce_range = true))] offset: u64, - #[webidl(options(enforce_range = true))] size: Option, - ) { - let err = self - .instance - .command_encoder_clear_buffer(self.id, buffer.id, offset, size) - .err(); - self.error_handler.push_error(err); - } - - #[required(5)] - fn resolve_query_set( - &self, - #[webidl] query_set: Ptr, - #[webidl(options(enforce_range = true))] first_query: u32, - #[webidl(options(enforce_range = true))] query_count: u32, - #[webidl] destination: Ptr, - #[webidl(options(enforce_range = true))] destination_offset: u64, - ) { - let err = self - .instance - .command_encoder_resolve_query_set( - self.id, - query_set.id, - first_query, - query_count, - destination.id, - destination_offset, - ) - .err(); - - self.error_handler.push_error(err); - } - - #[cppgc] - fn finish( - &self, - #[webidl] descriptor: crate::command_buffer::GPUCommandBufferDescriptor, - ) -> GPUCommandBuffer { - let wgpu_descriptor = wgpu_types::CommandBufferDescriptor { - label: crate::transform_label(descriptor.label.clone()), - }; - - let (id, err) = self - .instance - .command_encoder_finish(self.id, &wgpu_descriptor); - - self.error_handler.push_error(err); - - GPUCommandBuffer { - instance: self.instance.clone(), - id, - label: descriptor.label, - consumed: Default::default(), + #[cppgc] + fn begin_compute_pass( + &self, + #[webidl] descriptor: crate::compute_pass::GPUComputePassDescriptor, + ) -> GPUComputePassEncoder { + let timestamp_writes = + descriptor.timestamp_writes.map(|timestamp_writes| { + wgpu_core::command::PassTimestampWrites { + query_set: timestamp_writes.query_set.id, + beginning_of_pass_write_index: timestamp_writes + .beginning_of_pass_write_index, + end_of_pass_write_index: timestamp_writes.end_of_pass_write_index, } + }); + + let wgpu_descriptor = wgpu_core::command::ComputePassDescriptor { + label: crate::transform_label(descriptor.label.clone()), + timestamp_writes, + }; + + let (compute_pass, err) = self + .instance + .command_encoder_begin_compute_pass(self.id, &wgpu_descriptor); + + self.error_handler.push_error(err); + + GPUComputePassEncoder { + instance: self.instance.clone(), + error_handler: self.error_handler.clone(), + compute_pass: RefCell::new(compute_pass), + label: descriptor.label, + } + } + + #[required(2)] + #[undefined] + fn copy_buffer_to_buffer<'a>( + &self, + scope: &mut v8::HandleScope<'a>, + #[webidl] source: Ptr, + arg2: v8::Local<'a, v8::Value>, + arg3: v8::Local<'a, v8::Value>, + arg4: v8::Local<'a, v8::Value>, + arg5: v8::Local<'a, v8::Value>, + ) -> Result<(), WebIdlError> { + let prefix = "Failed to execute 'GPUCommandEncoder.copyBufferToBuffer'"; + let int_options = IntOptions { + clamp: false, + enforce_range: true, + }; + + let source_offset: BufferAddress; + let destination: Ptr; + let destination_offset: BufferAddress; + let size: Option; + // Note that the last argument to either overload of `copy_buffer_to_buffer` + // is optional, so `arg5.is_undefined()` would not work here. + if arg4.is_undefined() { + // 3-argument overload + source_offset = 0; + destination = Ptr::::convert( + scope, + arg2, + Cow::Borrowed(prefix), + (|| Cow::Borrowed("destination")).into(), + &(), + )?; + destination_offset = 0; + size = >::convert( + scope, + arg3, + Cow::Borrowed(prefix), + (|| Cow::Borrowed("size")).into(), + &int_options, + )?; + } else { + // 5-argument overload + source_offset = u64::convert( + scope, + arg2, + Cow::Borrowed(prefix), + (|| Cow::Borrowed("sourceOffset")).into(), + &int_options, + )?; + destination = Ptr::::convert( + scope, + arg3, + Cow::Borrowed(prefix), + (|| Cow::Borrowed("destination")).into(), + &(), + )?; + destination_offset = u64::convert( + scope, + arg4, + Cow::Borrowed(prefix), + (|| Cow::Borrowed("destinationOffset")).into(), + &int_options, + )?; + size = >::convert( + scope, + arg5, + Cow::Borrowed(prefix), + (|| Cow::Borrowed("size")).into(), + &int_options, + )?; } - fn push_debug_group(&self, #[webidl] group_label: String) { - let err = self - .instance - .command_encoder_push_debug_group(self.id, &group_label) - .err(); - self.error_handler.push_error(err); - } + let err = self + .instance + .command_encoder_copy_buffer_to_buffer( + self.id, + source.id, + source_offset, + destination.id, + destination_offset, + size, + ) + .err(); - #[fast] - fn pop_debug_group(&self) { - let err = self.instance.command_encoder_pop_debug_group(self.id).err(); - self.error_handler.push_error(err); - } + self.error_handler.push_error(err); - fn insert_debug_marker(&self, #[webidl] marker_label: String) { - let err = self - .instance - .command_encoder_insert_debug_marker(self.id, &marker_label) - .err(); - self.error_handler.push_error(err); + Ok(()) + } + + #[required(3)] + #[undefined] + fn copy_buffer_to_texture( + &self, + #[webidl] source: GPUTexelCopyBufferInfo, + #[webidl] destination: GPUTexelCopyTextureInfo, + #[webidl] copy_size: GPUExtent3D, + ) { + let source = TexelCopyBufferInfo { + buffer: source.buffer.id, + layout: wgpu_types::TexelCopyBufferLayout { + offset: source.offset, + bytes_per_row: source.bytes_per_row, + rows_per_image: source.rows_per_image, + }, + }; + let destination = wgpu_types::TexelCopyTextureInfo { + texture: destination.texture.id, + mip_level: destination.mip_level, + origin: destination.origin.into(), + aspect: destination.aspect.into(), + }; + + let err = self + .instance + .command_encoder_copy_buffer_to_texture( + self.id, + &source, + &destination, + ©_size.into(), + ) + .err(); + + self.error_handler.push_error(err); + } + + #[required(3)] + #[undefined] + fn copy_texture_to_buffer( + &self, + #[webidl] source: GPUTexelCopyTextureInfo, + #[webidl] destination: GPUTexelCopyBufferInfo, + #[webidl] copy_size: GPUExtent3D, + ) { + let source = wgpu_types::TexelCopyTextureInfo { + texture: source.texture.id, + mip_level: source.mip_level, + origin: source.origin.into(), + aspect: source.aspect.into(), + }; + let destination = TexelCopyBufferInfo { + buffer: destination.buffer.id, + layout: wgpu_types::TexelCopyBufferLayout { + offset: destination.offset, + bytes_per_row: destination.bytes_per_row, + rows_per_image: destination.rows_per_image, + }, + }; + + let err = self + .instance + .command_encoder_copy_texture_to_buffer( + self.id, + &source, + &destination, + ©_size.into(), + ) + .err(); + + self.error_handler.push_error(err); + } + + #[required(3)] + #[undefined] + fn copy_texture_to_texture( + &self, + #[webidl] source: GPUTexelCopyTextureInfo, + #[webidl] destination: GPUTexelCopyTextureInfo, + #[webidl] copy_size: GPUExtent3D, + ) { + let source = wgpu_types::TexelCopyTextureInfo { + texture: source.texture.id, + mip_level: source.mip_level, + origin: source.origin.into(), + aspect: source.aspect.into(), + }; + let destination = wgpu_types::TexelCopyTextureInfo { + texture: destination.texture.id, + mip_level: destination.mip_level, + origin: destination.origin.into(), + aspect: destination.aspect.into(), + }; + + let err = self + .instance + .command_encoder_copy_texture_to_texture( + self.id, + &source, + &destination, + ©_size.into(), + ) + .err(); + + self.error_handler.push_error(err); + } + + #[required(1)] + #[undefined] + fn clear_buffer( + &self, + #[webidl] buffer: Ptr, + #[webidl(default = 0, options(enforce_range = true))] offset: u64, + #[webidl(options(enforce_range = true))] size: Option, + ) { + let err = self + .instance + .command_encoder_clear_buffer(self.id, buffer.id, offset, size) + .err(); + self.error_handler.push_error(err); + } + + #[required(5)] + #[undefined] + fn resolve_query_set( + &self, + #[webidl] query_set: Ptr, + #[webidl(options(enforce_range = true))] first_query: u32, + #[webidl(options(enforce_range = true))] query_count: u32, + #[webidl] destination: Ptr, + #[webidl(options(enforce_range = true))] destination_offset: u64, + ) { + let err = self + .instance + .command_encoder_resolve_query_set( + self.id, + query_set.id, + first_query, + query_count, + destination.id, + destination_offset, + ) + .err(); + + self.error_handler.push_error(err); + } + + #[cppgc] + fn finish( + &self, + #[webidl] descriptor: crate::command_buffer::GPUCommandBufferDescriptor, + ) -> GPUCommandBuffer { + let wgpu_descriptor = wgpu_types::CommandBufferDescriptor { + label: crate::transform_label(descriptor.label.clone()), + }; + + let (id, opt_label_and_err) = + self + .instance + .command_encoder_finish(self.id, &wgpu_descriptor, None); + + self + .error_handler + .push_error(opt_label_and_err.map(|(_label, err)| err)); + + GPUCommandBuffer { + instance: self.instance.clone(), + id, + label: descriptor.label, } + } + + fn push_debug_group(&self, #[webidl] group_label: String) { + let err = self + .instance + .command_encoder_push_debug_group(self.id, &group_label) + .err(); + self.error_handler.push_error(err); + } + + #[fast] + fn pop_debug_group(&self) { + let err = self.instance.command_encoder_pop_debug_group(self.id).err(); + self.error_handler.push_error(err); + } + + fn insert_debug_marker(&self, #[webidl] marker_label: String) { + let err = self + .instance + .command_encoder_insert_debug_marker(self.id, &marker_label) + .err(); + self.error_handler.push_error(err); + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUCommandEncoderDescriptor { - #[webidl(default = String::new())] - pub label: String, + #[webidl(default = String::new())] + pub label: String, } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUTexelCopyBufferInfo { - pub buffer: Ptr, - #[webidl(default = 0)] - #[options(enforce_range = true)] - offset: u64, - #[options(enforce_range = true)] - bytes_per_row: Option, - #[options(enforce_range = true)] - rows_per_image: Option, + pub buffer: Ptr, + #[webidl(default = 0)] + #[options(enforce_range = true)] + offset: u64, + #[options(enforce_range = true)] + bytes_per_row: Option, + #[options(enforce_range = true)] + rows_per_image: Option, } diff --git a/deno_webgpu/compute_pass.rs b/deno_webgpu/compute_pass.rs index 4cd060818..50dffae29 100644 --- a/deno_webgpu/compute_pass.rs +++ b/deno_webgpu/compute_pass.rs @@ -13,208 +13,240 @@ use deno_core::webidl::WebIdlError; use deno_core::GarbageCollected; use deno_core::WebIDL; +use crate::error::GPUGenericError; use crate::Instance; pub struct GPUComputePassEncoder { - pub instance: Instance, - pub error_handler: super::error::ErrorHandler, + pub instance: Instance, + pub error_handler: super::error::ErrorHandler, - pub compute_pass: RefCell, - pub label: String, + pub compute_pass: RefCell, + pub label: String, } -impl GarbageCollected for GPUComputePassEncoder {} +impl GarbageCollected for GPUComputePassEncoder { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUComputePassEncoder" + } +} #[op2] impl GPUComputePassEncoder { - #[getter] - #[string] - fn label(&self) -> String { - self.label.clone() - } - #[setter] - #[string] - fn label(&self, #[webidl] _label: String) { - // TODO(@crowlKats): no-op, needs wpgu to implement changing the label - } + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } - fn set_pipeline(&self, #[webidl] pipeline: Ptr) { - let err = self - .instance - .compute_pass_set_pipeline(&mut self.compute_pass.borrow_mut(), pipeline.id) - .err(); - self.error_handler.push_error(err); - } + #[getter] + #[string] + fn label(&self) -> String { + self.label.clone() + } + #[setter] + #[string] + fn label(&self, #[webidl] _label: String) { + // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + } - fn dispatch_workgroups( - &self, - #[webidl(options(enforce_range = true))] work_group_count_x: u32, - #[webidl(default = 1, options(enforce_range = true))] work_group_count_y: u32, - #[webidl(default = 1, options(enforce_range = true))] work_group_count_z: u32, - ) { - let err = self - .instance - .compute_pass_dispatch_workgroups( - &mut self.compute_pass.borrow_mut(), - work_group_count_x, - work_group_count_y, - work_group_count_z, - ) - .err(); - self.error_handler.push_error(err); - } + #[undefined] + fn set_pipeline( + &self, + #[webidl] pipeline: Ptr, + ) { + let err = self + .instance + .compute_pass_set_pipeline( + &mut self.compute_pass.borrow_mut(), + pipeline.id, + ) + .err(); + self.error_handler.push_error(err); + } - fn dispatch_workgroups_indirect( - &self, - #[webidl] indirect_buffer: Ptr, - #[webidl(options(enforce_range = true))] indirect_offset: u64, - ) { - let err = self - .instance - .compute_pass_dispatch_workgroups_indirect( - &mut self.compute_pass.borrow_mut(), - indirect_buffer.id, - indirect_offset, - ) - .err(); - self.error_handler.push_error(err); - } + #[undefined] + fn dispatch_workgroups( + &self, + #[webidl(options(enforce_range = true))] work_group_count_x: u32, + #[webidl(default = 1, options(enforce_range = true))] + work_group_count_y: u32, + #[webidl(default = 1, options(enforce_range = true))] + work_group_count_z: u32, + ) { + let err = self + .instance + .compute_pass_dispatch_workgroups( + &mut self.compute_pass.borrow_mut(), + work_group_count_x, + work_group_count_y, + work_group_count_z, + ) + .err(); + self.error_handler.push_error(err); + } - #[fast] - fn end(&self) { - let err = self - .instance - .compute_pass_end(&mut self.compute_pass.borrow_mut()) - .err(); - self.error_handler.push_error(err); - } + #[undefined] + fn dispatch_workgroups_indirect( + &self, + #[webidl] indirect_buffer: Ptr, + #[webidl(options(enforce_range = true))] indirect_offset: u64, + ) { + let err = self + .instance + .compute_pass_dispatch_workgroups_indirect( + &mut self.compute_pass.borrow_mut(), + indirect_buffer.id, + indirect_offset, + ) + .err(); + self.error_handler.push_error(err); + } - fn push_debug_group(&self, #[webidl] group_label: String) { - let err = self - .instance - .compute_pass_push_debug_group( - &mut self.compute_pass.borrow_mut(), - &group_label, - 0, // wgpu#975 - ) - .err(); - self.error_handler.push_error(err); - } + #[fast] + #[undefined] + fn end(&self) { + let err = self + .instance + .compute_pass_end(&mut self.compute_pass.borrow_mut()) + .err(); + self.error_handler.push_error(err); + } - #[fast] - fn pop_debug_group(&self) { - let err = self - .instance - .compute_pass_pop_debug_group(&mut self.compute_pass.borrow_mut()) - .err(); - self.error_handler.push_error(err); - } + #[undefined] + fn push_debug_group(&self, #[webidl] group_label: String) { + let err = self + .instance + .compute_pass_push_debug_group( + &mut self.compute_pass.borrow_mut(), + &group_label, + 0, // wgpu#975 + ) + .err(); + self.error_handler.push_error(err); + } - fn insert_debug_marker(&self, #[webidl] marker_label: String) { - let err = self - .instance - .compute_pass_insert_debug_marker( - &mut self.compute_pass.borrow_mut(), - &marker_label, - 0, // wgpu#975 - ) - .err(); - self.error_handler.push_error(err); - } + #[fast] + #[undefined] + fn pop_debug_group(&self) { + let err = self + .instance + .compute_pass_pop_debug_group(&mut self.compute_pass.borrow_mut()) + .err(); + self.error_handler.push_error(err); + } - fn set_bind_group<'a>( - &self, - scope: &mut v8::HandleScope<'a>, - #[webidl(options(enforce_range = true))] index: u32, - #[webidl] bind_group: Nullable>, - dynamic_offsets: v8::Local<'a, v8::Value>, - dynamic_offsets_data_start: v8::Local<'a, v8::Value>, - dynamic_offsets_data_length: v8::Local<'a, v8::Value>, - ) -> Result<(), WebIdlError> { - const PREFIX: &str = "Failed to execute 'setBindGroup' on 'GPUComputePassEncoder'"; - let err = if let Ok(uint_32) = dynamic_offsets.try_cast::() { - let start = u64::convert( - scope, - dynamic_offsets_data_start, - Cow::Borrowed(PREFIX), - (|| Cow::Borrowed("Argument 4")).into(), - &IntOptions { - clamp: false, - enforce_range: true, - }, - )? as usize; - let len = u32::convert( - scope, - dynamic_offsets_data_length, - Cow::Borrowed(PREFIX), - (|| Cow::Borrowed("Argument 5")).into(), - &IntOptions { - clamp: false, - enforce_range: true, - }, - )? as usize; + #[undefined] + fn insert_debug_marker(&self, #[webidl] marker_label: String) { + let err = self + .instance + .compute_pass_insert_debug_marker( + &mut self.compute_pass.borrow_mut(), + &marker_label, + 0, // wgpu#975 + ) + .err(); + self.error_handler.push_error(err); + } - let ab = uint_32.buffer(scope).unwrap(); - let ptr = ab.data().unwrap(); - let ab_len = ab.byte_length() / 4; + #[undefined] + fn set_bind_group<'a>( + &self, + scope: &mut v8::HandleScope<'a>, + #[webidl(options(enforce_range = true))] index: u32, + #[webidl] bind_group: Nullable>, + dynamic_offsets: v8::Local<'a, v8::Value>, + dynamic_offsets_data_start: v8::Local<'a, v8::Value>, + dynamic_offsets_data_length: v8::Local<'a, v8::Value>, + ) -> Result<(), WebIdlError> { + const PREFIX: &str = + "Failed to execute 'setBindGroup' on 'GPUComputePassEncoder'"; + let err = if let Ok(uint_32) = dynamic_offsets.try_cast::() + { + let start = u64::convert( + scope, + dynamic_offsets_data_start, + Cow::Borrowed(PREFIX), + (|| Cow::Borrowed("Argument 4")).into(), + &IntOptions { + clamp: false, + enforce_range: true, + }, + )? as usize; + let len = u32::convert( + scope, + dynamic_offsets_data_length, + Cow::Borrowed(PREFIX), + (|| Cow::Borrowed("Argument 5")).into(), + &IntOptions { + clamp: false, + enforce_range: true, + }, + )? as usize; - // SAFETY: compute_pass_set_bind_group internally calls extend_from_slice with this slice - let data = unsafe { std::slice::from_raw_parts(ptr.as_ptr() as _, ab_len) }; + let ab = uint_32.buffer(scope).unwrap(); + let ptr = ab.data().unwrap(); + let ab_len = ab.byte_length() / 4; - let offsets = &data[start..(start + len)]; + // SAFETY: compute_pass_set_bind_group internally calls extend_from_slice with this slice + let data = + unsafe { std::slice::from_raw_parts(ptr.as_ptr() as _, ab_len) }; - self.instance - .compute_pass_set_bind_group( - &mut self.compute_pass.borrow_mut(), - index, - bind_group.into_option().map(|bind_group| bind_group.id), - offsets, - ) - .err() - } else { - let offsets = >>::convert( - scope, - dynamic_offsets, - Cow::Borrowed(PREFIX), - (|| Cow::Borrowed("Argument 3")).into(), - &IntOptions { - clamp: false, - enforce_range: true, - }, - )? - .unwrap_or_default(); + let offsets = &data[start..(start + len)]; - self.instance - .compute_pass_set_bind_group( - &mut self.compute_pass.borrow_mut(), - index, - bind_group.into_option().map(|bind_group| bind_group.id), - &offsets, - ) - .err() - }; + self + .instance + .compute_pass_set_bind_group( + &mut self.compute_pass.borrow_mut(), + index, + bind_group.into_option().map(|bind_group| bind_group.id), + offsets, + ) + .err() + } else { + let offsets = >>::convert( + scope, + dynamic_offsets, + Cow::Borrowed(PREFIX), + (|| Cow::Borrowed("Argument 3")).into(), + &IntOptions { + clamp: false, + enforce_range: true, + }, + )? + .unwrap_or_default(); - self.error_handler.push_error(err); + self + .instance + .compute_pass_set_bind_group( + &mut self.compute_pass.borrow_mut(), + index, + bind_group.into_option().map(|bind_group| bind_group.id), + &offsets, + ) + .err() + }; - Ok(()) - } + self.error_handler.push_error(err); + + Ok(()) + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUComputePassDescriptor { - #[webidl(default = String::new())] - pub label: String, + #[webidl(default = String::new())] + pub label: String, - pub timestamp_writes: Option, + pub timestamp_writes: Option, } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUComputePassTimestampWrites { - pub query_set: Ptr, - #[options(enforce_range = true)] - pub beginning_of_pass_write_index: Option, - #[options(enforce_range = true)] - pub end_of_pass_write_index: Option, + pub query_set: Ptr, + #[options(enforce_range = true)] + pub beginning_of_pass_write_index: Option, + #[options(enforce_range = true)] + pub end_of_pass_write_index: Option, } diff --git a/deno_webgpu/compute_pipeline.rs b/deno_webgpu/compute_pipeline.rs index eb29686bc..bd7a96959 100644 --- a/deno_webgpu/compute_pipeline.rs +++ b/deno_webgpu/compute_pipeline.rs @@ -8,75 +8,86 @@ use deno_core::WebIDL; use indexmap::IndexMap; use crate::bind_group_layout::GPUBindGroupLayout; +use crate::error::GPUGenericError; use crate::shader::GPUShaderModule; use crate::webidl::GPUPipelineLayoutOrGPUAutoLayoutMode; use crate::Instance; pub struct GPUComputePipeline { - pub instance: Instance, - pub error_handler: super::error::ErrorHandler, + pub instance: Instance, + pub error_handler: super::error::ErrorHandler, - pub id: wgpu_core::id::ComputePipelineId, - pub label: String, + pub id: wgpu_core::id::ComputePipelineId, + pub label: String, } impl Drop for GPUComputePipeline { - fn drop(&mut self) { - self.instance.compute_pipeline_drop(self.id); - } + fn drop(&mut self) { + self.instance.compute_pipeline_drop(self.id); + } } impl WebIdlInterfaceConverter for GPUComputePipeline { - const NAME: &'static str = "GPUComputePipeline"; + const NAME: &'static str = "GPUComputePipeline"; } -impl GarbageCollected for GPUComputePipeline {} +impl GarbageCollected for GPUComputePipeline { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUComputePipeline" + } +} #[op2] impl GPUComputePipeline { - #[getter] - #[string] - fn label(&self) -> String { - self.label.clone() - } - #[setter] - #[string] - fn label(&self, #[webidl] _label: String) { - // TODO(@crowlKats): no-op, needs wpgu to implement changing the label - } + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } - #[cppgc] - fn get_bind_group_layout(&self, #[webidl] index: u32) -> GPUBindGroupLayout { - let (id, err) = self - .instance - .compute_pipeline_get_bind_group_layout(self.id, index, None); + #[getter] + #[string] + fn label(&self) -> String { + self.label.clone() + } + #[setter] + #[string] + fn label(&self, #[webidl] _label: String) { + // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + } - self.error_handler.push_error(err); + #[cppgc] + fn get_bind_group_layout(&self, #[webidl] index: u32) -> GPUBindGroupLayout { + let (id, err) = self + .instance + .compute_pipeline_get_bind_group_layout(self.id, index, None); - // TODO(wgpu): needs to support retrieving the label - GPUBindGroupLayout { - instance: self.instance.clone(), - id, - label: "".to_string(), - } + self.error_handler.push_error(err); + + // TODO(wgpu): needs to support retrieving the label + GPUBindGroupLayout { + instance: self.instance.clone(), + id, + label: "".to_string(), } + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUComputePipelineDescriptor { - #[webidl(default = String::new())] - pub label: String, + #[webidl(default = String::new())] + pub label: String, - pub compute: GPUProgrammableStage, - pub layout: GPUPipelineLayoutOrGPUAutoLayoutMode, + pub compute: GPUProgrammableStage, + pub layout: GPUPipelineLayoutOrGPUAutoLayoutMode, } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUProgrammableStage { - pub module: Ptr, - pub entry_point: Option, - #[webidl(default = Default::default())] - pub constants: IndexMap, + pub module: Ptr, + pub entry_point: Option, + #[webidl(default = Default::default())] + pub constants: IndexMap, } diff --git a/deno_webgpu/device.rs b/deno_webgpu/device.rs index 77f5966c5..5289ad207 100644 --- a/deno_webgpu/device.rs +++ b/deno_webgpu/device.rs @@ -5,6 +5,7 @@ use std::cell::RefCell; use std::num::NonZeroU64; use std::rc::Rc; +use deno_core::cppgc::make_cppgc_object; use deno_core::cppgc::SameObject; use deno_core::op2; use deno_core::v8; @@ -29,815 +30,938 @@ use crate::adapter::GPUAdapterInfo; use crate::adapter::GPUSupportedFeatures; use crate::adapter::GPUSupportedLimits; use crate::command_encoder::GPUCommandEncoder; +use crate::error::{GPUError, GPUGenericError}; use crate::query_set::GPUQuerySet; use crate::render_bundle::GPURenderBundleEncoder; use crate::render_pipeline::GPURenderPipeline; +use crate::shader::GPUCompilationInfo; use crate::webidl::features_to_feature_names; use crate::Instance; pub struct GPUDevice { - pub instance: Instance, - pub id: wgpu_core::id::DeviceId, - pub adapter: wgpu_core::id::AdapterId, - pub queue: wgpu_core::id::QueueId, + pub instance: Instance, + pub id: wgpu_core::id::DeviceId, + pub adapter: wgpu_core::id::AdapterId, + pub queue: wgpu_core::id::QueueId, - pub label: String, + pub label: String, - pub features: SameObject, - pub limits: SameObject, - pub adapter_info: Rc>, + pub features: SameObject, + pub limits: SameObject, + pub adapter_info: Rc>, - pub queue_obj: SameObject, + pub queue_obj: SameObject, - pub error_handler: super::error::ErrorHandler, - pub lost_receiver: tokio::sync::Mutex>>, + pub error_handler: super::error::ErrorHandler, + pub lost_promise: v8::Global, } impl Drop for GPUDevice { - fn drop(&mut self) { - self.instance.device_drop(self.id); - } + fn drop(&mut self) { + self.instance.device_drop(self.id); + } } impl WebIdlInterfaceConverter for GPUDevice { - const NAME: &'static str = "GPUDevice"; + const NAME: &'static str = "GPUDevice"; } -impl GarbageCollected for GPUDevice {} +impl GarbageCollected for GPUDevice { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUDevice" + } +} // EventTarget is extended in JS #[op2] impl GPUDevice { - #[getter] - #[string] - fn label(&self) -> String { - self.label.clone() - } - #[setter] - #[string] - fn label(&self, #[webidl] _label: String) { - // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } + + #[getter] + #[string] + fn label(&self) -> String { + self.label.clone() + } + #[setter] + #[string] + fn label(&self, #[webidl] _label: String) { + // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + } + + #[getter] + #[global] + fn features(&self, scope: &mut v8::HandleScope) -> v8::Global { + self.features.get(scope, |scope| { + let features = self.instance.device_features(self.id); + let features = features_to_feature_names(features); + GPUSupportedFeatures::new(scope, features) + }) + } + + #[getter] + #[global] + fn limits(&self, scope: &mut v8::HandleScope) -> v8::Global { + self.limits.get(scope, |_| { + let limits = self.instance.device_limits(self.id); + GPUSupportedLimits(limits) + }) + } + + #[getter] + #[global] + fn adapter_info( + &self, + scope: &mut v8::HandleScope, + ) -> v8::Global { + self.adapter_info.get(scope, |_| { + let info = self.instance.adapter_get_info(self.adapter); + let limits = self.instance.adapter_limits(self.adapter); + + GPUAdapterInfo { + info, + subgroup_min_size: limits.min_subgroup_size, + subgroup_max_size: limits.max_subgroup_size, + } + }) + } + + #[getter] + #[global] + fn queue(&self, scope: &mut v8::HandleScope) -> v8::Global { + self.queue_obj.get(scope, |_| GPUQueue { + id: self.queue, + device: self.id, + error_handler: self.error_handler.clone(), + instance: self.instance.clone(), + label: self.label.clone(), + }) + } + + #[fast] + #[undefined] + fn destroy(&self) { + self.instance.device_destroy(self.id); + self + .error_handler + .push_error(Some(GPUError::Lost(GPUDeviceLostReason::Destroyed))); + } + + #[required(1)] + #[cppgc] + fn create_buffer( + &self, + #[webidl] descriptor: super::buffer::GPUBufferDescriptor, + ) -> GPUBuffer { + // Validation of the usage needs to happen on the device timeline, so + // don't raise an error immediately if it isn't valid. wgpu will + // reject `BufferUsages::empty()`. + let usage = wgpu_types::BufferUsages::from_bits(descriptor.usage) + .unwrap_or(wgpu_types::BufferUsages::empty()); + + let wgpu_descriptor = wgpu_core::resource::BufferDescriptor { + label: crate::transform_label(descriptor.label.clone()), + size: descriptor.size, + usage, + mapped_at_creation: descriptor.mapped_at_creation, + }; + + let (id, err) = + self + .instance + .device_create_buffer(self.id, &wgpu_descriptor, None); + + self.error_handler.push_error(err); + + GPUBuffer { + instance: self.instance.clone(), + error_handler: self.error_handler.clone(), + id, + device: self.id, + label: descriptor.label, + size: descriptor.size, + usage: descriptor.usage, + map_state: RefCell::new(if descriptor.mapped_at_creation { + "mapped" + } else { + "unmapped" + }), + map_mode: RefCell::new(if descriptor.mapped_at_creation { + Some(wgpu_core::device::HostMap::Write) + } else { + None + }), + mapped_js_buffers: RefCell::new(vec![]), } + } - #[getter] - #[global] - fn features(&self, scope: &mut v8::HandleScope) -> v8::Global { - self.features.get(scope, |scope| { - let features = self.instance.device_features(self.id); - let features = features_to_feature_names(features); - GPUSupportedFeatures::new(scope, features) - }) - } + #[required(1)] + #[cppgc] + fn create_texture( + &self, + #[webidl] descriptor: super::texture::GPUTextureDescriptor, + ) -> Result { + let wgpu_descriptor = wgpu_core::resource::TextureDescriptor { + label: crate::transform_label(descriptor.label.clone()), + size: descriptor.size.into(), + mip_level_count: descriptor.mip_level_count, + sample_count: descriptor.sample_count, + dimension: descriptor.dimension.clone().into(), + format: descriptor.format.clone().into(), + usage: wgpu_types::TextureUsages::from_bits(descriptor.usage) + .ok_or_else(|| JsErrorBox::type_error("usage is not valid"))?, + view_formats: descriptor + .view_formats + .into_iter() + .map(Into::into) + .collect(), + }; - #[getter] - #[global] - fn limits(&self, scope: &mut v8::HandleScope) -> v8::Global { - self.limits.get(scope, |_| { - let limits = self.instance.device_limits(self.id); - GPUSupportedLimits(limits) - }) - } + let (id, err) = + self + .instance + .device_create_texture(self.id, &wgpu_descriptor, None); - #[getter] - #[global] - fn adapter_info(&self, scope: &mut v8::HandleScope) -> v8::Global { - self.adapter_info.get(scope, |_| { - let info = self.instance.adapter_get_info(self.adapter); - let limits = self.instance.adapter_limits(self.adapter); + self.error_handler.push_error(err); - GPUAdapterInfo { - info, - subgroup_min_size: limits.min_subgroup_size, - subgroup_max_size: limits.max_subgroup_size, - } - }) - } + Ok(GPUTexture { + instance: self.instance.clone(), + error_handler: self.error_handler.clone(), + id, + default_view_id: Default::default(), + label: descriptor.label, + size: wgpu_descriptor.size, + mip_level_count: wgpu_descriptor.mip_level_count, + sample_count: wgpu_descriptor.sample_count, + dimension: descriptor.dimension, + format: descriptor.format, + usage: descriptor.usage, + }) + } - #[getter] - #[global] - fn queue(&self, scope: &mut v8::HandleScope) -> v8::Global { - self.queue_obj.get(scope, |_| GPUQueue { - id: self.queue, - error_handler: self.error_handler.clone(), - instance: self.instance.clone(), - label: self.label.clone(), - }) - } + #[cppgc] + fn create_sampler( + &self, + #[webidl] descriptor: super::sampler::GPUSamplerDescriptor, + ) -> Result { + let wgpu_descriptor = wgpu_core::resource::SamplerDescriptor { + label: crate::transform_label(descriptor.label.clone()), + address_modes: [ + descriptor.address_mode_u.into(), + descriptor.address_mode_v.into(), + descriptor.address_mode_w.into(), + ], + mag_filter: descriptor.mag_filter.into(), + min_filter: descriptor.min_filter.into(), + mipmap_filter: descriptor.mipmap_filter.into(), + lod_min_clamp: descriptor.lod_min_clamp, + lod_max_clamp: descriptor.lod_max_clamp, + compare: descriptor.compare.map(Into::into), + anisotropy_clamp: descriptor.max_anisotropy, + border_color: None, + }; - #[fast] - fn destroy(&self) { - self.instance.device_destroy(self.id); - } + let (id, err) = + self + .instance + .device_create_sampler(self.id, &wgpu_descriptor, None); - #[required(1)] - #[cppgc] - fn create_buffer( - &self, - #[webidl] descriptor: super::buffer::GPUBufferDescriptor, - ) -> Result { - let wgpu_descriptor = wgpu_core::resource::BufferDescriptor { - label: crate::transform_label(descriptor.label.clone()), - size: descriptor.size, - usage: wgpu_types::BufferUsages::from_bits(descriptor.usage) - .ok_or_else(|| JsErrorBox::type_error("usage is not valid"))?, - mapped_at_creation: descriptor.mapped_at_creation, - }; + self.error_handler.push_error(err); - let (id, err) = self - .instance - .device_create_buffer(self.id, &wgpu_descriptor, None); + Ok(GPUSampler { + instance: self.instance.clone(), + id, + label: descriptor.label, + }) + } - self.error_handler.push_error(err); + #[required(1)] + #[cppgc] + fn create_bind_group_layout( + &self, + #[webidl] + descriptor: super::bind_group_layout::GPUBindGroupLayoutDescriptor, + ) -> Result { + let mut entries = Vec::with_capacity(descriptor.entries.len()); - Ok(GPUBuffer { - instance: self.instance.clone(), - error_handler: self.error_handler.clone(), - id, - device: self.id, - label: descriptor.label, - size: descriptor.size, - usage: descriptor.usage, - map_state: RefCell::new(if descriptor.mapped_at_creation { - "mapped" - } else { - "unmapped" - }), - map_mode: RefCell::new(if descriptor.mapped_at_creation { - Some(wgpu_core::device::HostMap::Write) - } else { - None - }), - mapped_js_buffers: RefCell::new(vec![]), - }) - } + for entry in descriptor.entries { + let n_entries = [ + entry.buffer.is_some(), + entry.sampler.is_some(), + entry.texture.is_some(), + entry.storage_texture.is_some(), + ] + .into_iter() + .filter(|t| *t) + .count(); - #[required(1)] - #[cppgc] - fn create_texture( - &self, - #[webidl] descriptor: super::texture::GPUTextureDescriptor, - ) -> Result { - let wgpu_descriptor = wgpu_core::resource::TextureDescriptor { - label: crate::transform_label(descriptor.label.clone()), - size: descriptor.size.into(), - mip_level_count: descriptor.mip_level_count, - sample_count: descriptor.sample_count, - dimension: descriptor.dimension.clone().into(), - format: descriptor.format.clone().into(), - usage: wgpu_types::TextureUsages::from_bits(descriptor.usage) - .ok_or_else(|| JsErrorBox::type_error("usage is not valid"))?, - view_formats: descriptor - .view_formats - .into_iter() - .map(Into::into) - .collect(), - }; + if n_entries != 1 { + return Err(JsErrorBox::type_error( + "Only one of 'buffer', 'sampler', 'texture' and 'storageTexture' may be specified", + )); + } - let (id, err) = self - .instance - .device_create_texture(self.id, &wgpu_descriptor, None); - - self.error_handler.push_error(err); - - Ok(GPUTexture { - instance: self.instance.clone(), - error_handler: self.error_handler.clone(), - id, - label: descriptor.label, - size: wgpu_descriptor.size, - mip_level_count: wgpu_descriptor.mip_level_count, - sample_count: wgpu_descriptor.sample_count, - dimension: descriptor.dimension, - format: descriptor.format, - usage: descriptor.usage, - }) - } - - #[cppgc] - fn create_sampler( - &self, - #[webidl] descriptor: super::sampler::GPUSamplerDescriptor, - ) -> Result { - let wgpu_descriptor = wgpu_core::resource::SamplerDescriptor { - label: crate::transform_label(descriptor.label.clone()), - address_modes: [ - descriptor.address_mode_u.into(), - descriptor.address_mode_v.into(), - descriptor.address_mode_w.into(), - ], - mag_filter: descriptor.mag_filter.into(), - min_filter: descriptor.min_filter.into(), - mipmap_filter: descriptor.mipmap_filter.into(), - lod_min_clamp: descriptor.lod_min_clamp, - lod_max_clamp: descriptor.lod_max_clamp, - compare: descriptor.compare.map(Into::into), - anisotropy_clamp: descriptor.max_anisotropy, - border_color: None, - }; - - let (id, err) = self - .instance - .device_create_sampler(self.id, &wgpu_descriptor, None); - - self.error_handler.push_error(err); - - Ok(GPUSampler { - instance: self.instance.clone(), - id, - label: descriptor.label, - }) - } - - #[required(1)] - #[cppgc] - fn create_bind_group_layout( - &self, - #[webidl] descriptor: super::bind_group_layout::GPUBindGroupLayoutDescriptor, - ) -> Result { - let mut entries = Vec::with_capacity(descriptor.entries.len()); - - for entry in descriptor.entries { - let n_entries = [ - entry.buffer.is_some(), - entry.sampler.is_some(), - entry.texture.is_some(), - entry.storage_texture.is_some(), - ] - .into_iter() - .filter(|t| *t) - .count(); - - if n_entries != 1 { - return Err(JsErrorBox::type_error("Only one of 'buffer', 'sampler', 'texture' and 'storageTexture' may be specified")); - } - - let ty = if let Some(buffer) = entry.buffer { - BindingType::Buffer { - ty: buffer.r#type.into(), - has_dynamic_offset: buffer.has_dynamic_offset, - min_binding_size: NonZeroU64::new(buffer.min_binding_size), - } - } else if let Some(sampler) = entry.sampler { - BindingType::Sampler(sampler.r#type.into()) - } else if let Some(texture) = entry.texture { - BindingType::Texture { - sample_type: texture.sample_type.into(), - view_dimension: texture.view_dimension.into(), - multisampled: texture.multisampled, - } - } else if let Some(storage_texture) = entry.storage_texture { - BindingType::StorageTexture { - access: storage_texture.access.into(), - format: storage_texture.format.into(), - view_dimension: storage_texture.view_dimension.into(), - } - } else { - unreachable!() - }; - - entries.push(wgpu_types::BindGroupLayoutEntry { - binding: entry.binding, - visibility: wgpu_types::ShaderStages::from_bits(entry.visibility) - .ok_or_else(|| JsErrorBox::type_error("usage is not valid"))?, - ty, - count: None, // native-only - }); + let ty = if let Some(buffer) = entry.buffer { + BindingType::Buffer { + ty: buffer.r#type.into(), + has_dynamic_offset: buffer.has_dynamic_offset, + min_binding_size: NonZeroU64::new(buffer.min_binding_size), } - - let wgpu_descriptor = wgpu_core::binding_model::BindGroupLayoutDescriptor { - label: crate::transform_label(descriptor.label.clone()), - entries: Cow::Owned(entries), - }; - - let (id, err) = - self.instance - .device_create_bind_group_layout(self.id, &wgpu_descriptor, None); - - self.error_handler.push_error(err); - - Ok(GPUBindGroupLayout { - instance: self.instance.clone(), - id, - label: descriptor.label, - }) - } - - #[required(1)] - #[cppgc] - fn create_pipeline_layout( - &self, - #[webidl] descriptor: super::pipeline_layout::GPUPipelineLayoutDescriptor, - ) -> GPUPipelineLayout { - let bind_group_layouts = descriptor - .bind_group_layouts - .into_iter() - .map(|bind_group_layout| bind_group_layout.id) - .collect(); - - let wgpu_descriptor = wgpu_core::binding_model::PipelineLayoutDescriptor { - label: crate::transform_label(descriptor.label.clone()), - bind_group_layouts: Cow::Owned(bind_group_layouts), - push_constant_ranges: Default::default(), - }; - - let (id, err) = - self.instance - .device_create_pipeline_layout(self.id, &wgpu_descriptor, None); - - self.error_handler.push_error(err); - - GPUPipelineLayout { - instance: self.instance.clone(), - id, - label: descriptor.label, + } else if let Some(sampler) = entry.sampler { + BindingType::Sampler(sampler.r#type.into()) + } else if let Some(texture) = entry.texture { + BindingType::Texture { + sample_type: texture.sample_type.into(), + view_dimension: texture.view_dimension.into(), + multisampled: texture.multisampled, } + } else if let Some(storage_texture) = entry.storage_texture { + BindingType::StorageTexture { + access: storage_texture.access.into(), + format: storage_texture.format.into(), + view_dimension: storage_texture.view_dimension.into(), + } + } else { + unreachable!() + }; + + entries.push(wgpu_types::BindGroupLayoutEntry { + binding: entry.binding, + visibility: wgpu_types::ShaderStages::from_bits(entry.visibility) + .ok_or_else(|| JsErrorBox::type_error("usage is not valid"))?, + ty, + count: None, // native-only + }); } - #[required(1)] - #[cppgc] - fn create_bind_group( - &self, - #[webidl] descriptor: super::bind_group::GPUBindGroupDescriptor, - ) -> GPUBindGroup { - let entries = descriptor - .entries - .into_iter() - .map(|entry| wgpu_core::binding_model::BindGroupEntry { - binding: entry.binding, - resource: match entry.resource { - GPUBindingResource::Sampler(sampler) => BindingResource::Sampler(sampler.id), - GPUBindingResource::TextureView(texture_view) => { - BindingResource::TextureView(texture_view.id) - } - GPUBindingResource::BufferBinding(buffer_binding) => { - BindingResource::Buffer(wgpu_core::binding_model::BufferBinding { - buffer: buffer_binding.buffer.id, - offset: buffer_binding.offset, - size: buffer_binding.size.and_then(NonZeroU64::new), - }) - } - }, + let wgpu_descriptor = wgpu_core::binding_model::BindGroupLayoutDescriptor { + label: crate::transform_label(descriptor.label.clone()), + entries: Cow::Owned(entries), + }; + + let (id, err) = self.instance.device_create_bind_group_layout( + self.id, + &wgpu_descriptor, + None, + ); + + self.error_handler.push_error(err); + + Ok(GPUBindGroupLayout { + instance: self.instance.clone(), + id, + label: descriptor.label, + }) + } + + #[required(1)] + #[cppgc] + fn create_pipeline_layout( + &self, + #[webidl] descriptor: super::pipeline_layout::GPUPipelineLayoutDescriptor, + ) -> GPUPipelineLayout { + let bind_group_layouts = descriptor + .bind_group_layouts + .into_iter() + .map(|bind_group_layout| bind_group_layout.id) + .collect(); + + let wgpu_descriptor = wgpu_core::binding_model::PipelineLayoutDescriptor { + label: crate::transform_label(descriptor.label.clone()), + bind_group_layouts: Cow::Owned(bind_group_layouts), + push_constant_ranges: Default::default(), + }; + + let (id, err) = self.instance.device_create_pipeline_layout( + self.id, + &wgpu_descriptor, + None, + ); + + self.error_handler.push_error(err); + + GPUPipelineLayout { + instance: self.instance.clone(), + id, + label: descriptor.label, + } + } + + #[required(1)] + #[cppgc] + fn create_bind_group( + &self, + #[webidl] descriptor: super::bind_group::GPUBindGroupDescriptor, + ) -> GPUBindGroup { + let entries = descriptor + .entries + .into_iter() + .map(|entry| wgpu_core::binding_model::BindGroupEntry { + binding: entry.binding, + resource: match entry.resource { + GPUBindingResource::Sampler(sampler) => { + BindingResource::Sampler(sampler.id) + } + GPUBindingResource::Texture(texture) => { + BindingResource::TextureView(texture.default_view_id()) + } + GPUBindingResource::TextureView(texture_view) => { + BindingResource::TextureView(texture_view.id) + } + GPUBindingResource::Buffer(buffer) => { + BindingResource::Buffer(wgpu_core::binding_model::BufferBinding { + buffer: buffer.id, + offset: 0, + size: NonZeroU64::new(buffer.size), }) - .collect::>(); + } + GPUBindingResource::BufferBinding(buffer_binding) => { + BindingResource::Buffer(wgpu_core::binding_model::BufferBinding { + buffer: buffer_binding.buffer.id, + offset: buffer_binding.offset, + size: buffer_binding.size.and_then(NonZeroU64::new), + }) + } + }, + }) + .collect::>(); - let wgpu_descriptor = wgpu_core::binding_model::BindGroupDescriptor { - label: crate::transform_label(descriptor.label.clone()), - layout: descriptor.layout.id, - entries: Cow::Owned(entries), - }; + let wgpu_descriptor = wgpu_core::binding_model::BindGroupDescriptor { + label: crate::transform_label(descriptor.label.clone()), + layout: descriptor.layout.id, + entries: Cow::Owned(entries), + }; - let (id, err) = self - .instance - .device_create_bind_group(self.id, &wgpu_descriptor, None); + let (id, err) = + self + .instance + .device_create_bind_group(self.id, &wgpu_descriptor, None); - self.error_handler.push_error(err); + self.error_handler.push_error(err); - GPUBindGroup { - instance: self.instance.clone(), - id, - label: descriptor.label, + GPUBindGroup { + instance: self.instance.clone(), + id, + label: descriptor.label, + } + } + + #[required(1)] + #[cppgc] + fn create_shader_module( + &self, + scope: &mut v8::HandleScope<'_>, + #[webidl] descriptor: super::shader::GPUShaderModuleDescriptor, + ) -> GPUShaderModule { + let wgpu_descriptor = wgpu_core::pipeline::ShaderModuleDescriptor { + label: crate::transform_label(descriptor.label.clone()), + runtime_checks: wgpu_types::ShaderRuntimeChecks::default(), + }; + + let (id, err) = self.instance.device_create_shader_module( + self.id, + &wgpu_descriptor, + wgpu_core::pipeline::ShaderModuleSource::Wgsl(Cow::Borrowed( + &descriptor.code, + )), + None, + ); + + let compilation_info = + GPUCompilationInfo::new(scope, err.iter(), &descriptor.code); + let compilation_info = make_cppgc_object(scope, compilation_info); + let compilation_info = v8::Global::new(scope, compilation_info); + self.error_handler.push_error(err); + + GPUShaderModule { + instance: self.instance.clone(), + id, + label: descriptor.label, + compilation_info, + } + } + + #[required(1)] + #[cppgc] + fn create_compute_pipeline( + &self, + #[webidl] descriptor: super::compute_pipeline::GPUComputePipelineDescriptor, + ) -> GPUComputePipeline { + self.new_compute_pipeline(descriptor) + } + + #[required(1)] + #[cppgc] + fn create_render_pipeline( + &self, + #[webidl] descriptor: super::render_pipeline::GPURenderPipelineDescriptor, + ) -> Result { + self.new_render_pipeline(descriptor) + } + + #[async_method] + #[required(1)] + #[cppgc] + async fn create_compute_pipeline_async( + &self, + #[webidl] descriptor: super::compute_pipeline::GPUComputePipelineDescriptor, + ) -> GPUComputePipeline { + self.new_compute_pipeline(descriptor) + } + + #[async_method] + #[required(1)] + #[cppgc] + async fn create_render_pipeline_async( + &self, + #[webidl] descriptor: super::render_pipeline::GPURenderPipelineDescriptor, + ) -> Result { + self.new_render_pipeline(descriptor) + } + + #[cppgc] + fn create_command_encoder( + &self, + #[webidl] descriptor: Option< + super::command_encoder::GPUCommandEncoderDescriptor, + >, + ) -> GPUCommandEncoder { + let label = descriptor.map(|d| d.label).unwrap_or_default(); + let wgpu_descriptor = wgpu_types::CommandEncoderDescriptor { + label: Some(Cow::Owned(label.clone())), + }; + + let (id, err) = self.instance.device_create_command_encoder( + self.id, + &wgpu_descriptor, + None, + ); + + self.error_handler.push_error(err); + + GPUCommandEncoder { + instance: self.instance.clone(), + error_handler: self.error_handler.clone(), + id, + label, + } + } + + #[required(1)] + #[cppgc] + fn create_render_bundle_encoder( + &self, + #[webidl] + descriptor: super::render_bundle::GPURenderBundleEncoderDescriptor, + ) -> GPURenderBundleEncoder { + let wgpu_descriptor = wgpu_core::command::RenderBundleEncoderDescriptor { + label: crate::transform_label(descriptor.label.clone()), + color_formats: Cow::Owned( + descriptor + .color_formats + .into_iter() + .map(|format| format.into_option().map(Into::into)) + .collect::>(), + ), + depth_stencil: descriptor.depth_stencil_format.map(|format| { + wgpu_types::RenderBundleDepthStencil { + format: format.into(), + depth_read_only: descriptor.depth_read_only, + stencil_read_only: descriptor.stencil_read_only, } + }), + sample_count: descriptor.sample_count, + multiview: None, + }; + + let res = + wgpu_core::command::RenderBundleEncoder::new(&wgpu_descriptor, self.id); + let (encoder, err) = match res { + Ok(encoder) => (encoder, None), + Err(e) => ( + wgpu_core::command::RenderBundleEncoder::dummy(self.id), + Some(e), + ), + }; + + self.error_handler.push_error(err); + + GPURenderBundleEncoder { + instance: self.instance.clone(), + error_handler: self.error_handler.clone(), + encoder: RefCell::new(Some(encoder)), + label: descriptor.label, + } + } + + #[required(1)] + #[cppgc] + fn create_query_set( + &self, + #[webidl] descriptor: crate::query_set::GPUQuerySetDescriptor, + ) -> GPUQuerySet { + let wgpu_descriptor = wgpu_core::resource::QuerySetDescriptor { + label: crate::transform_label(descriptor.label.clone()), + ty: descriptor.r#type.clone().into(), + count: descriptor.count, + }; + + let (id, err) = + self + .instance + .device_create_query_set(self.id, &wgpu_descriptor, None); + + self.error_handler.push_error(err); + + GPUQuerySet { + instance: self.instance.clone(), + id, + r#type: descriptor.r#type, + count: descriptor.count, + label: descriptor.label, + } + } + + #[getter] + #[global] + fn lost(&self) -> v8::Global { + self.lost_promise.clone() + } + + #[required(1)] + #[undefined] + fn push_error_scope(&self, #[webidl] filter: super::error::GPUErrorFilter) { + self + .error_handler + .scopes + .lock() + .unwrap() + .push((filter, vec![])); + } + + #[async_method(fake)] + #[global] + fn pop_error_scope( + &self, + scope: &mut v8::HandleScope, + ) -> Result, JsErrorBox> { + if self.error_handler.is_lost.get().is_some() { + let val = v8::null(scope).cast::(); + return Ok(v8::Global::new(scope, val)); } - #[required(1)] - #[cppgc] - fn create_shader_module( - &self, - #[webidl] descriptor: super::shader::GPUShaderModuleDescriptor, - ) -> GPUShaderModule { - let wgpu_descriptor = wgpu_core::pipeline::ShaderModuleDescriptor { - label: crate::transform_label(descriptor.label.clone()), - runtime_checks: wgpu_types::ShaderRuntimeChecks::default(), - }; + let Some((_, errors)) = self.error_handler.scopes.lock().unwrap().pop() + else { + return Err(JsErrorBox::new( + "DOMExceptionOperationError", + "There are no error scopes on the error scope stack", + )); + }; - let (id, err) = self.instance.device_create_shader_module( - self.id, - &wgpu_descriptor, - wgpu_core::pipeline::ShaderModuleSource::Wgsl(Cow::Owned(descriptor.code)), - None, - ); + let val = if let Some(err) = errors.into_iter().next() { + deno_core::error::to_v8_error(scope, &err) + } else { + v8::null(scope).into() + }; - self.error_handler.push_error(err); + Ok(v8::Global::new(scope, val)) + } - GPUShaderModule { - instance: self.instance.clone(), - id, - label: descriptor.label, - } - } - - #[required(1)] - #[cppgc] - fn create_compute_pipeline( - &self, - #[webidl] descriptor: super::compute_pipeline::GPUComputePipelineDescriptor, - ) -> GPUComputePipeline { - self.new_compute_pipeline(descriptor) - } - - #[required(1)] - #[cppgc] - fn create_render_pipeline( - &self, - #[webidl] descriptor: super::render_pipeline::GPURenderPipelineDescriptor, - ) -> Result { - self.new_render_pipeline(descriptor) - } - - #[async_method] - #[required(1)] - #[cppgc] - async fn create_compute_pipeline_async( - &self, - #[webidl] descriptor: super::compute_pipeline::GPUComputePipelineDescriptor, - ) -> GPUComputePipeline { - self.new_compute_pipeline(descriptor) - } - - #[async_method] - #[required(1)] - #[cppgc] - async fn create_render_pipeline_async( - &self, - #[webidl] descriptor: super::render_pipeline::GPURenderPipelineDescriptor, - ) -> Result { - self.new_render_pipeline(descriptor) - } - - #[cppgc] - fn create_command_encoder( - &self, - #[webidl] descriptor: Option, - ) -> GPUCommandEncoder { - let label = descriptor.map(|d| d.label).unwrap_or_default(); - let wgpu_descriptor = wgpu_types::CommandEncoderDescriptor { - label: Some(Cow::Owned(label.clone())), - }; - - let (id, err) = - self.instance - .device_create_command_encoder(self.id, &wgpu_descriptor, None); - - self.error_handler.push_error(err); - - GPUCommandEncoder { - instance: self.instance.clone(), - error_handler: self.error_handler.clone(), - id, - label, - } - } - - #[required(1)] - #[cppgc] - fn create_render_bundle_encoder( - &self, - #[webidl] descriptor: super::render_bundle::GPURenderBundleEncoderDescriptor, - ) -> GPURenderBundleEncoder { - let wgpu_descriptor = wgpu_core::command::RenderBundleEncoderDescriptor { - label: crate::transform_label(descriptor.label.clone()), - color_formats: Cow::Owned( - descriptor - .color_formats - .into_iter() - .map(|format| format.into_option().map(Into::into)) - .collect::>(), - ), - depth_stencil: descriptor.depth_stencil_format.map(|format| { - wgpu_types::RenderBundleDepthStencil { - format: format.into(), - depth_read_only: descriptor.depth_read_only, - stencil_read_only: descriptor.stencil_read_only, - } - }), - sample_count: descriptor.sample_count, - multiview: None, - }; - - let res = wgpu_core::command::RenderBundleEncoder::new(&wgpu_descriptor, self.id, None); - let (encoder, err) = match res { - Ok(encoder) => (encoder, None), - Err(e) => ( - wgpu_core::command::RenderBundleEncoder::dummy(self.id), - Some(e), - ), - }; - - self.error_handler.push_error(err); - - GPURenderBundleEncoder { - instance: self.instance.clone(), - error_handler: self.error_handler.clone(), - encoder: RefCell::new(Some(encoder)), - label: descriptor.label, - } - } - - #[required(1)] - #[cppgc] - fn create_query_set( - &self, - #[webidl] descriptor: crate::query_set::GPUQuerySetDescriptor, - ) -> GPUQuerySet { - let wgpu_descriptor = wgpu_core::resource::QuerySetDescriptor { - label: crate::transform_label(descriptor.label.clone()), - ty: descriptor.r#type.clone().into(), - count: descriptor.count, - }; - - let (id, err) = self - .instance - .device_create_query_set(self.id, &wgpu_descriptor, None); - - self.error_handler.push_error(err); - - GPUQuerySet { - instance: self.instance.clone(), - id, - r#type: descriptor.r#type, - count: descriptor.count, - label: descriptor.label, - } - } - - // TODO(@crowlKats): support returning same promise - #[async_method] - #[getter] - #[cppgc] - async fn lost(&self) -> GPUDeviceLostInfo { - if let Some(lost_receiver) = self.lost_receiver.lock().await.take() { - let _ = lost_receiver.await; - } - - GPUDeviceLostInfo - } - - #[required(1)] - fn push_error_scope(&self, #[webidl] filter: super::error::GPUErrorFilter) { - self.error_handler - .scopes - .lock() - .unwrap() - .push((filter, vec![])); - } - - #[async_method(fake)] - #[global] - fn pop_error_scope( - &self, - scope: &mut v8::HandleScope, - ) -> Result, JsErrorBox> { - if self.error_handler.is_lost.get().is_some() { - let val = v8::null(scope).cast::(); - return Ok(v8::Global::new(scope, val)); - } - - let Some((_, errors)) = self.error_handler.scopes.lock().unwrap().pop() else { - return Err(JsErrorBox::new( - "DOMExceptionOperationError", - "There are no error scopes on the error scope stack", - )); - }; - - let val = if let Some(err) = errors.into_iter().next() { - deno_core::error::to_v8_error(scope, &err) - } else { - v8::null(scope).into() - }; - - Ok(v8::Global::new(scope, val)) - } - - #[fast] - fn start_capture(&self) { - self.instance.device_start_capture(self.id); - } - #[fast] - fn stop_capture(&self) { - self.instance - .device_poll(self.id, wgpu_types::PollType::wait()) - .unwrap(); - self.instance.device_stop_capture(self.id); - } + #[fast] + fn start_capture(&self) { + unsafe { + self + .instance + .device_start_graphics_debugger_capture(self.id) + }; + } + #[fast] + fn stop_capture(&self) { + self + .instance + .device_poll(self.id, wgpu_types::PollType::wait_indefinitely()) + .unwrap(); + unsafe { self.instance.device_stop_graphics_debugger_capture(self.id) }; + } } impl GPUDevice { - fn new_compute_pipeline( - &self, - descriptor: super::compute_pipeline::GPUComputePipelineDescriptor, - ) -> GPUComputePipeline { - let wgpu_descriptor = wgpu_core::pipeline::ComputePipelineDescriptor { - label: crate::transform_label(descriptor.label.clone()), - layout: descriptor.layout.into(), - stage: ProgrammableStageDescriptor { - module: descriptor.compute.module.id, - entry_point: descriptor.compute.entry_point.map(Into::into), - constants: descriptor.compute.constants.into_iter().collect(), - zero_initialize_workgroup_memory: true, - }, - cache: None, - }; + fn new_compute_pipeline( + &self, + descriptor: super::compute_pipeline::GPUComputePipelineDescriptor, + ) -> GPUComputePipeline { + let wgpu_descriptor = wgpu_core::pipeline::ComputePipelineDescriptor { + label: crate::transform_label(descriptor.label.clone()), + layout: descriptor.layout.into(), + stage: ProgrammableStageDescriptor { + module: descriptor.compute.module.id, + entry_point: descriptor.compute.entry_point.map(Into::into), + constants: descriptor.compute.constants.into_iter().collect(), + zero_initialize_workgroup_memory: true, + }, + cache: None, + }; - let (id, err) = - self.instance - .device_create_compute_pipeline(self.id, &wgpu_descriptor, None, None); + let (id, err) = self.instance.device_create_compute_pipeline( + self.id, + &wgpu_descriptor, + None, + ); - self.error_handler.push_error(err); + self.error_handler.push_error(err); - GPUComputePipeline { - instance: self.instance.clone(), - error_handler: self.error_handler.clone(), - id, - label: descriptor.label.clone(), - } + GPUComputePipeline { + instance: self.instance.clone(), + error_handler: self.error_handler.clone(), + id, + label: descriptor.label.clone(), } + } - fn new_render_pipeline( - &self, - descriptor: super::render_pipeline::GPURenderPipelineDescriptor, - ) -> Result { - let vertex = wgpu_core::pipeline::VertexState { - stage: ProgrammableStageDescriptor { - module: descriptor.vertex.module.id, - entry_point: descriptor.vertex.entry_point.map(Into::into), - constants: descriptor.vertex.constants.into_iter().collect(), - zero_initialize_workgroup_memory: true, - }, - buffers: Cow::Owned( - descriptor - .vertex - .buffers + fn new_render_pipeline( + &self, + descriptor: super::render_pipeline::GPURenderPipelineDescriptor, + ) -> Result { + let vertex = wgpu_core::pipeline::VertexState { + stage: ProgrammableStageDescriptor { + module: descriptor.vertex.module.id, + entry_point: descriptor.vertex.entry_point.map(Into::into), + constants: descriptor.vertex.constants.into_iter().collect(), + zero_initialize_workgroup_memory: true, + }, + buffers: Cow::Owned( + descriptor + .vertex + .buffers + .into_iter() + .map(|b| { + b.into_option().map_or_else( + wgpu_core::pipeline::VertexBufferLayout::default, + |layout| wgpu_core::pipeline::VertexBufferLayout { + array_stride: layout.array_stride, + step_mode: layout.step_mode.into(), + attributes: Cow::Owned( + layout + .attributes .into_iter() - .map(|b| { - let layout = b.into_option().ok_or_else(|| { - JsErrorBox::type_error( - "Nullable GPUVertexBufferLayouts are currently not supported", - ) - })?; - - Ok(wgpu_core::pipeline::VertexBufferLayout { - array_stride: layout.array_stride, - step_mode: layout.step_mode.into(), - attributes: Cow::Owned( - layout - .attributes - .into_iter() - .map(|attr| wgpu_types::VertexAttribute { - format: attr.format.into(), - offset: attr.offset, - shader_location: attr.shader_location, - }) - .collect(), - ), - }) + .map(|attr| wgpu_types::VertexAttribute { + format: attr.format.into(), + offset: attr.offset, + shader_location: attr.shader_location, }) - .collect::>()?, - ), - }; + .collect(), + ), + }, + ) + }) + .collect(), + ), + }; - let primitive = wgpu_types::PrimitiveState { - topology: descriptor.primitive.topology.into(), - strip_index_format: descriptor.primitive.strip_index_format.map(Into::into), - front_face: descriptor.primitive.front_face.into(), - cull_mode: descriptor.primitive.cull_mode.into(), - unclipped_depth: descriptor.primitive.unclipped_depth, - polygon_mode: Default::default(), - conservative: false, - }; + let primitive = wgpu_types::PrimitiveState { + topology: descriptor.primitive.topology.into(), + strip_index_format: descriptor + .primitive + .strip_index_format + .map(Into::into), + front_face: descriptor.primitive.front_face.into(), + cull_mode: descriptor.primitive.cull_mode.into(), + unclipped_depth: descriptor.primitive.unclipped_depth, + polygon_mode: Default::default(), + conservative: false, + }; - let depth_stencil = descriptor.depth_stencil.map(|depth_stencil| { - let front = wgpu_types::StencilFaceState { - compare: depth_stencil.stencil_front.compare.into(), - fail_op: depth_stencil.stencil_front.fail_op.into(), - depth_fail_op: depth_stencil.stencil_front.depth_fail_op.into(), - pass_op: depth_stencil.stencil_front.pass_op.into(), - }; - let back = wgpu_types::StencilFaceState { - compare: depth_stencil.stencil_back.compare.into(), - fail_op: depth_stencil.stencil_back.fail_op.into(), - depth_fail_op: depth_stencil.stencil_back.depth_fail_op.into(), - pass_op: depth_stencil.stencil_back.pass_op.into(), - }; + let depth_stencil = descriptor.depth_stencil.map(|depth_stencil| { + let front = wgpu_types::StencilFaceState { + compare: depth_stencil.stencil_front.compare.into(), + fail_op: depth_stencil.stencil_front.fail_op.into(), + depth_fail_op: depth_stencil.stencil_front.depth_fail_op.into(), + pass_op: depth_stencil.stencil_front.pass_op.into(), + }; + let back = wgpu_types::StencilFaceState { + compare: depth_stencil.stencil_back.compare.into(), + fail_op: depth_stencil.stencil_back.fail_op.into(), + depth_fail_op: depth_stencil.stencil_back.depth_fail_op.into(), + pass_op: depth_stencil.stencil_back.pass_op.into(), + }; - wgpu_types::DepthStencilState { - format: depth_stencil.format.into(), - depth_write_enabled: depth_stencil.depth_write_enabled.unwrap_or_default(), - depth_compare: depth_stencil - .depth_compare - .map(Into::into) - .unwrap_or(wgpu_types::CompareFunction::Never), // TODO(wgpu): should be optional here - stencil: wgpu_types::StencilState { - front, - back, - read_mask: depth_stencil.stencil_read_mask, - write_mask: depth_stencil.stencil_write_mask, - }, - bias: wgpu_types::DepthBiasState { - constant: depth_stencil.depth_bias, - slope_scale: depth_stencil.depth_bias_slope_scale, - clamp: depth_stencil.depth_bias_clamp, - }, - } - }); + wgpu_types::DepthStencilState { + format: depth_stencil.format.into(), + depth_write_enabled: depth_stencil + .depth_write_enabled + .unwrap_or_default(), + depth_compare: depth_stencil + .depth_compare + .map(Into::into) + .unwrap_or(wgpu_types::CompareFunction::Never), // TODO(wgpu): should be optional here + stencil: wgpu_types::StencilState { + front, + back, + read_mask: depth_stencil.stencil_read_mask, + write_mask: depth_stencil.stencil_write_mask, + }, + bias: wgpu_types::DepthBiasState { + constant: depth_stencil.depth_bias, + slope_scale: depth_stencil.depth_bias_slope_scale, + clamp: depth_stencil.depth_bias_clamp, + }, + } + }); - let multisample = wgpu_types::MultisampleState { - count: descriptor.multisample.count, - mask: descriptor.multisample.mask as u64, - alpha_to_coverage_enabled: descriptor.multisample.alpha_to_coverage_enabled, - }; + let multisample = wgpu_types::MultisampleState { + count: descriptor.multisample.count, + mask: descriptor.multisample.mask as u64, + alpha_to_coverage_enabled: descriptor + .multisample + .alpha_to_coverage_enabled, + }; - let fragment = descriptor - .fragment - .map(|fragment| { - Ok::<_, JsErrorBox>(wgpu_core::pipeline::FragmentState { - stage: ProgrammableStageDescriptor { - module: fragment.module.id, - entry_point: fragment.entry_point.map(Into::into), - constants: fragment.constants.into_iter().collect(), - zero_initialize_workgroup_memory: true, - }, - targets: Cow::Owned( - fragment - .targets - .into_iter() - .map(|target| { - target - .into_option() - .map(|target| { - Ok(wgpu_types::ColorTargetState { - format: target.format.into(), - blend: target.blend.map(|blend| { - wgpu_types::BlendState { - color: wgpu_types::BlendComponent { - src_factor: blend.color.src_factor.into(), - dst_factor: blend.color.dst_factor.into(), - operation: blend.color.operation.into(), - }, - alpha: wgpu_types::BlendComponent { - src_factor: blend.alpha.src_factor.into(), - dst_factor: blend.alpha.dst_factor.into(), - operation: blend.alpha.operation.into(), - }, - } - }), - write_mask: wgpu_types::ColorWrites::from_bits( - target.write_mask, - ) - .ok_or_else(|| { - JsErrorBox::type_error("usage is not valid") - })?, - }) - }) - .transpose() - }) - .collect::>()?, - ), - }) - }) - .transpose()?; - - let wgpu_descriptor = wgpu_core::pipeline::RenderPipelineDescriptor { - label: crate::transform_label(descriptor.label.clone()), - layout: descriptor.layout.into(), - vertex, - primitive, - depth_stencil, - multisample, - fragment, - cache: None, - multiview: None, - }; - - let (id, err) = - self.instance - .device_create_render_pipeline(self.id, &wgpu_descriptor, None, None); - - self.error_handler.push_error(err); - - Ok(GPURenderPipeline { - instance: self.instance.clone(), - error_handler: self.error_handler.clone(), - id, - label: descriptor.label, + let fragment = descriptor + .fragment + .map(|fragment| { + Ok::<_, JsErrorBox>(wgpu_core::pipeline::FragmentState { + stage: ProgrammableStageDescriptor { + module: fragment.module.id, + entry_point: fragment.entry_point.map(Into::into), + constants: fragment.constants.into_iter().collect(), + zero_initialize_workgroup_memory: true, + }, + targets: Cow::Owned( + fragment + .targets + .into_iter() + .map(|target| { + target + .into_option() + .map(|target| { + Ok(wgpu_types::ColorTargetState { + format: target.format.into(), + blend: target.blend.map(|blend| wgpu_types::BlendState { + color: wgpu_types::BlendComponent { + src_factor: blend.color.src_factor.into(), + dst_factor: blend.color.dst_factor.into(), + operation: blend.color.operation.into(), + }, + alpha: wgpu_types::BlendComponent { + src_factor: blend.alpha.src_factor.into(), + dst_factor: blend.alpha.dst_factor.into(), + operation: blend.alpha.operation.into(), + }, + }), + write_mask: wgpu_types::ColorWrites::from_bits( + target.write_mask, + ) + .ok_or_else(|| { + JsErrorBox::type_error("usage is not valid") + })?, + }) + }) + .transpose() + }) + .collect::>()?, + ), }) - } + }) + .transpose()?; + + let wgpu_descriptor = wgpu_core::pipeline::RenderPipelineDescriptor { + label: crate::transform_label(descriptor.label.clone()), + layout: descriptor.layout.into(), + vertex, + primitive, + depth_stencil, + multisample, + fragment, + cache: None, + multiview_mask: None, + }; + + let (id, err) = self.instance.device_create_render_pipeline( + self.id, + &wgpu_descriptor, + None, + ); + + self.error_handler.push_error(err); + + Ok(GPURenderPipeline { + instance: self.instance.clone(), + error_handler: self.error_handler.clone(), + id, + label: descriptor.label, + }) + } } -pub struct GPUDeviceLostInfo; +#[derive(Clone, Debug, Default, Hash, Eq, PartialEq)] +pub enum GPUDeviceLostReason { + #[default] + Unknown, + Destroyed, +} -impl GarbageCollected for GPUDeviceLostInfo {} +impl From for GPUDeviceLostReason { + fn from(value: wgpu_types::DeviceLostReason) -> Self { + match value { + wgpu_types::DeviceLostReason::Unknown => Self::Unknown, + wgpu_types::DeviceLostReason::Destroyed => Self::Destroyed, + } + } +} + +#[derive(Default)] +pub struct GPUDeviceLostInfo { + pub reason: GPUDeviceLostReason, +} + +impl GarbageCollected for GPUDeviceLostInfo { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUDeviceLostInfo" + } +} #[op2] impl GPUDeviceLostInfo { - #[getter] - #[string] - fn reason(&self) -> &'static str { - "unknown" - } + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } - #[getter] - #[string] - fn message(&self) -> &'static str { - "device was lost" + #[getter] + #[string] + fn reason(&self) -> &'static str { + use GPUDeviceLostReason::*; + match self.reason { + Unknown => "unknown", + Destroyed => "destroyed", } + } + + #[getter] + #[string] + fn message(&self) -> &'static str { + "device was lost" + } +} + +#[op2(fast)] +pub fn op_webgpu_device_start_capture(#[cppgc] device: &GPUDevice) { + unsafe { + device + .instance + .device_start_graphics_debugger_capture(device.id); + } +} + +#[op2(fast)] +pub fn op_webgpu_device_stop_capture(#[cppgc] device: &GPUDevice) { + unsafe { + device + .instance + .device_stop_graphics_debugger_capture(device.id); + } } diff --git a/deno_webgpu/error.rs b/deno_webgpu/error.rs index 377ae9af6..57bfd1445 100644 --- a/deno_webgpu/error.rs +++ b/deno_webgpu/error.rs @@ -5,6 +5,11 @@ use std::fmt::Formatter; use std::sync::Mutex; use std::sync::OnceLock; +use deno_core::cppgc::make_cppgc_object; +use deno_core::v8; + +use deno_core::JsRuntime; +use deno_core::V8TaskSpawner; use wgpu_core::binding_model::CreateBindGroupError; use wgpu_core::binding_model::CreateBindGroupLayoutError; use wgpu_core::binding_model::CreatePipelineLayoutError; @@ -12,8 +17,9 @@ use wgpu_core::binding_model::GetBindGroupLayoutError; use wgpu_core::command::ClearError; use wgpu_core::command::CommandEncoderError; use wgpu_core::command::ComputePassError; -use wgpu_core::command::CopyError; use wgpu_core::command::CreateRenderBundleError; +use wgpu_core::command::EncoderStateError; +use wgpu_core::command::PassStateError; use wgpu_core::command::QueryError; use wgpu_core::command::RenderBundleError; use wgpu_core::command::RenderPassError; @@ -30,323 +36,346 @@ use wgpu_core::resource::CreateQuerySetError; use wgpu_core::resource::CreateSamplerError; use wgpu_core::resource::CreateTextureError; use wgpu_core::resource::CreateTextureViewError; +use wgpu_types::error::{ErrorType, WebGpuError}; -pub type ErrorHandler = std::sync::Arc; +use crate::device::GPUDeviceLostInfo; +use crate::device::GPUDeviceLostReason; + +pub type ErrorHandler = std::rc::Rc; pub struct DeviceErrorHandler { - pub is_lost: OnceLock<()>, - lost_sender: Mutex>>, - uncaptured_sender_is_closed: Mutex>>, + pub is_lost: OnceLock<()>, + pub scopes: Mutex)>>, + lost_resolver: Mutex>>, + spawner: V8TaskSpawner, - pub uncaptured_sender: tokio::sync::mpsc::UnboundedSender, - - pub scopes: Mutex)>>, -} - -impl Drop for DeviceErrorHandler { - fn drop(&mut self) { - if let Some(sender) = self.uncaptured_sender_is_closed.lock().unwrap().take() { - let _ = sender.send(()); - } - } + // The error handler is constructed before the device. A weak + // reference to the device is placed here with `set_device` + // after the device is constructed. + device: OnceLock>, } impl DeviceErrorHandler { - pub fn new( - lost_sender: tokio::sync::oneshot::Sender<()>, - uncaptured_sender: tokio::sync::mpsc::UnboundedSender, - uncaptured_sender_is_closed: tokio::sync::oneshot::Sender<()>, - ) -> Self { - Self { - is_lost: Default::default(), - lost_sender: Mutex::new(Some(lost_sender)), - uncaptured_sender, - uncaptured_sender_is_closed: Mutex::new(Some(uncaptured_sender_is_closed)), - scopes: Mutex::new(vec![]), - } + pub fn new( + lost_resolver: v8::Global, + spawner: V8TaskSpawner, + ) -> Self { + Self { + is_lost: Default::default(), + scopes: Mutex::new(vec![]), + lost_resolver: Mutex::new(Some(lost_resolver)), + device: OnceLock::new(), + spawner, + } + } + + pub fn set_device(&self, device: v8::Weak) { + self.device.set(device).unwrap() + } + + pub fn push_error>(&self, err: Option) { + let Some(err) = err else { + return; + }; + + if self.is_lost.get().is_some() { + return; } - pub fn push_error>(&self, err: Option) { - let Some(err) = err else { - return; - }; + let err = err.into(); - if self.is_lost.get().is_some() { - return; - } + if let GPUError::Lost(reason) = err { + let _ = self.is_lost.set(()); + if let Some(resolver) = self.lost_resolver.lock().unwrap().take() { + self.spawner.spawn(move |scope| { + let resolver = v8::Local::new(scope, resolver); + let info = make_cppgc_object(scope, GPUDeviceLostInfo { reason }); + let info = v8::Local::new(scope, info); + resolver.resolve(scope, info.into()); + }); + } - let err = err.into(); - - if matches!(err, GPUError::Lost) { - let _ = self.is_lost.set(()); - - if let Some(sender) = self.lost_sender.lock().unwrap().take() { - let _ = sender.send(()); - } - return; - } - - let error_filter = match err { - GPUError::Lost => unreachable!(), - GPUError::Validation(_) => GPUErrorFilter::Validation, - GPUError::OutOfMemory => GPUErrorFilter::OutOfMemory, - GPUError::Internal => GPUErrorFilter::Internal, - }; - - let mut scopes = self.scopes.lock().unwrap(); - let scope = scopes - .iter_mut() - .rfind(|(filter, _)| filter == &error_filter); - - if let Some(scope) = scope { - scope.1.push(err); - } else { - self.uncaptured_sender.send(err).unwrap(); - } + return; } + + let error_filter = match err { + GPUError::Lost(_) => unreachable!(), + GPUError::Validation(_) => GPUErrorFilter::Validation, + GPUError::OutOfMemory => GPUErrorFilter::OutOfMemory, + GPUError::Internal => GPUErrorFilter::Internal, + }; + + let mut scopes = self.scopes.lock().unwrap(); + let scope = scopes + .iter_mut() + .rfind(|(filter, _)| filter == &error_filter); + + if let Some(scope) = scope { + scope.1.push(err); + } else { + let device = self + .device + .get() + .expect("set_device was not called") + .clone(); + self.spawner.spawn(move |scope| { + let state = JsRuntime::op_state_from(&*scope); + let Some(device) = device.to_local(scope) else { + // The device has already gone away, so we don't have + // anywhere to report the error. + return; + }; + let key = v8::String::new(scope, "dispatchEvent").unwrap(); + let val = device.get(scope, key.into()).unwrap(); + let func = + v8::Global::new(scope, val.try_cast::().unwrap()); + let device = v8::Global::new(scope, device.cast::()); + let error_event_class = + state.borrow().borrow::().0.clone(); + + let error = deno_core::error::to_v8_error(scope, &err); + + let error_event_class = + v8::Local::new(scope, error_event_class.clone()); + let constructor = + v8::Local::::try_from(error_event_class).unwrap(); + let kind = v8::String::new(scope, "uncapturederror").unwrap(); + + let obj = v8::Object::new(scope); + let key = v8::String::new(scope, "error").unwrap(); + obj.set(scope, key.into(), error); + + let event = constructor + .new_instance(scope, &[kind.into(), obj.into()]) + .unwrap(); + + let recv = v8::Local::new(scope, device); + func.open(scope).call(scope, recv, &[event.into()]); + }); + } + } } #[derive(deno_core::WebIDL, Eq, PartialEq)] #[webidl(enum)] pub enum GPUErrorFilter { - Validation, - OutOfMemory, - Internal, + Validation, + OutOfMemory, + Internal, } #[derive(Debug, deno_error::JsError)] pub enum GPUError { - // TODO(@crowlKats): consider adding an unreachable value that uses unreachable!() - #[class("UNREACHABLE")] - Lost, - #[class("GPUValidationError")] - Validation(String), - #[class("GPUOutOfMemoryError")] - OutOfMemory, - #[allow(dead_code)] - #[class("GPUInternalError")] - Internal, + // TODO(@crowlKats): consider adding an unreachable value that uses unreachable!() + #[class("UNREACHABLE")] + Lost(GPUDeviceLostReason), + #[class("GPUValidationError")] + Validation(String), + #[class("GPUOutOfMemoryError")] + OutOfMemory, + #[class("GPUInternalError")] + Internal, } impl Display for GPUError { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - match self { - GPUError::Lost => Ok(()), - GPUError::Validation(s) => f.write_str(s), - GPUError::OutOfMemory => f.write_str("not enough memory left"), - GPUError::Internal => Ok(()), - } + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + match self { + GPUError::Lost(_) => Ok(()), + GPUError::Validation(s) => f.write_str(s), + GPUError::OutOfMemory => f.write_str("not enough memory left"), + GPUError::Internal => Ok(()), } + } } impl std::error::Error for GPUError {} +impl GPUError { + fn from_webgpu(e: impl WebGpuError) -> Self { + match e.webgpu_error_type() { + ErrorType::Internal => GPUError::Internal, + ErrorType::DeviceLost => GPUError::Lost(GPUDeviceLostReason::Unknown), // TODO: this variant should be ignored, register the lost callback instead. + ErrorType::OutOfMemory => GPUError::OutOfMemory, + ErrorType::Validation => GPUError::Validation(fmt_err(&e)), + } + } +} + fn fmt_err(err: &(dyn std::error::Error + 'static)) -> String { - let mut output = err.to_string(); + let mut output = err.to_string(); - let mut e = err.source(); - while let Some(source) = e { - output.push_str(&format!(": {source}")); - e = source.source(); - } + let mut e = err.source(); + while let Some(source) = e { + output.push_str(&format!(": {source}")); + e = source.source(); + } - if output.is_empty() { - output.push_str("validation error"); - } + if output.is_empty() { + output.push_str("validation error"); + } - output + output +} + +impl From for GPUError { + fn from(err: EncoderStateError) -> Self { + GPUError::from_webgpu(err) + } +} + +impl From for GPUError { + fn from(err: PassStateError) -> Self { + GPUError::Validation(fmt_err(&err)) + } } impl From for GPUError { - fn from(err: CreateBufferError) -> Self { - match err { - CreateBufferError::Device(err) => err.into(), - CreateBufferError::AccessError(err) => err.into(), - err => GPUError::Validation(fmt_err(&err)), - } - } + fn from(err: CreateBufferError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: DeviceError) -> Self { - match err { - DeviceError::Lost => GPUError::Lost, - DeviceError::OutOfMemory => GPUError::OutOfMemory, - _ => GPUError::Validation(fmt_err(&err)), - } - } + fn from(err: DeviceError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: BufferAccessError) -> Self { - match err { - BufferAccessError::Device(err) => err.into(), - err => GPUError::Validation(fmt_err(&err)), - } - } + fn from(err: BufferAccessError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: CreateBindGroupLayoutError) -> Self { - match err { - CreateBindGroupLayoutError::Device(err) => err.into(), - err => GPUError::Validation(fmt_err(&err)), - } - } + fn from(err: CreateBindGroupLayoutError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: CreatePipelineLayoutError) -> Self { - match err { - CreatePipelineLayoutError::Device(err) => err.into(), - err => GPUError::Validation(fmt_err(&err)), - } - } + fn from(err: CreatePipelineLayoutError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: CreateBindGroupError) -> Self { - match err { - CreateBindGroupError::Device(err) => err.into(), - err => GPUError::Validation(fmt_err(&err)), - } - } + fn from(err: CreateBindGroupError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: RenderBundleError) -> Self { - GPUError::Validation(fmt_err(&err)) - } + fn from(err: RenderBundleError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: CreateRenderBundleError) -> Self { - GPUError::Validation(fmt_err(&err)) - } -} - -impl From for GPUError { - fn from(err: CopyError) -> Self { - GPUError::Validation(fmt_err(&err)) - } + fn from(err: CreateRenderBundleError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: CommandEncoderError) -> Self { - GPUError::Validation(fmt_err(&err)) - } + fn from(err: CommandEncoderError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: QueryError) -> Self { - GPUError::Validation(fmt_err(&err)) - } + fn from(err: QueryError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: ComputePassError) -> Self { - GPUError::Validation(fmt_err(&err)) - } + fn from(err: ComputePassError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: CreateComputePipelineError) -> Self { - match err { - CreateComputePipelineError::Device(err) => err.into(), - err => GPUError::Validation(fmt_err(&err)), - } - } + fn from(err: CreateComputePipelineError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: GetBindGroupLayoutError) -> Self { - GPUError::Validation(fmt_err(&err)) - } + fn from(err: GetBindGroupLayoutError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: CreateRenderPipelineError) -> Self { - match err { - CreateRenderPipelineError::Device(err) => err.into(), - err => GPUError::Validation(fmt_err(&err)), - } - } + fn from(err: CreateRenderPipelineError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: RenderPassError) -> Self { - GPUError::Validation(fmt_err(&err)) - } + fn from(err: RenderPassError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: CreateSamplerError) -> Self { - match err { - CreateSamplerError::Device(err) => err.into(), - err => GPUError::Validation(fmt_err(&err)), - } - } + fn from(err: CreateSamplerError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: CreateShaderModuleError) -> Self { - match err { - CreateShaderModuleError::Device(err) => err.into(), - err => GPUError::Validation(fmt_err(&err)), - } - } + fn from(err: CreateShaderModuleError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: CreateTextureError) -> Self { - match err { - CreateTextureError::Device(err) => err.into(), - err => GPUError::Validation(fmt_err(&err)), - } - } + fn from(err: CreateTextureError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: CreateTextureViewError) -> Self { - GPUError::Validation(fmt_err(&err)) - } + fn from(err: CreateTextureViewError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: CreateQuerySetError) -> Self { - match err { - CreateQuerySetError::Device(err) => err.into(), - err => GPUError::Validation(fmt_err(&err)), - } - } + fn from(err: CreateQuerySetError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: QueueSubmitError) -> Self { - match err { - QueueSubmitError::Queue(err) => err.into(), - err => GPUError::Validation(fmt_err(&err)), - } - } + fn from(err: QueueSubmitError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: QueueWriteError) -> Self { - match err { - QueueWriteError::Queue(err) => err.into(), - err => GPUError::Validation(fmt_err(&err)), - } - } + fn from(err: QueueWriteError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: ClearError) -> Self { - GPUError::Validation(fmt_err(&err)) - } + fn from(err: ClearError) -> Self { + GPUError::from_webgpu(err) + } } impl From for GPUError { - fn from(err: ConfigureSurfaceError) -> Self { - GPUError::Validation(fmt_err(&err)) - } + fn from(err: ConfigureSurfaceError) -> Self { + GPUError::from_webgpu(err) + } +} + +#[derive(Debug, thiserror::Error, deno_error::JsError)] +pub enum GPUGenericError { + #[class(type)] + #[error("Illegal constructor")] + InvalidConstructor, } diff --git a/deno_webgpu/lib.rs b/deno_webgpu/lib.rs index 44ed02ff0..2b6dfcfee 100644 --- a/deno_webgpu/lib.rs +++ b/deno_webgpu/lib.rs @@ -15,6 +15,8 @@ pub use wgpu_core; pub use wgpu_types; use wgpu_types::PowerPreference; +use crate::error::GPUGenericError; + mod adapter; mod bind_group; mod bind_group_layout; @@ -42,163 +44,185 @@ pub const UNSTABLE_FEATURE_NAME: &str = "webgpu"; #[allow(clippy::print_stdout)] pub fn print_linker_flags(name: &str) { - if cfg!(windows) { - // these dls load slowly, so delay loading them - let dlls = [ - // webgpu - "d3dcompiler_47", - "OPENGL32", - // network related functions - "iphlpapi", - ]; - for dll in dlls { - println!("cargo:rustc-link-arg-bin={name}=/delayload:{dll}.dll"); - } - // enable delay loading - println!("cargo:rustc-link-arg-bin={name}=delayimp.lib"); + if cfg!(windows) { + // these dls load slowly, so delay loading them + let dlls = [ + // webgpu + "d3dcompiler_47", + "OPENGL32", + // network related functions + "iphlpapi", + ]; + for dll in dlls { + println!("cargo:rustc-link-arg-bin={name}=/delayload:{dll}.dll"); } + // enable delay loading + println!("cargo:rustc-link-arg-bin={name}=delayimp.lib"); + } } pub type Instance = Arc; deno_core::extension!( - deno_webgpu, - deps = [deno_webidl, deno_web], - ops = [op_create_gpu], - objects = [ - GPU, - adapter::GPUAdapter, - adapter::GPUAdapterInfo, - bind_group::GPUBindGroup, - bind_group_layout::GPUBindGroupLayout, - buffer::GPUBuffer, - command_buffer::GPUCommandBuffer, - command_encoder::GPUCommandEncoder, - compute_pass::GPUComputePassEncoder, - compute_pipeline::GPUComputePipeline, - device::GPUDevice, - device::GPUDeviceLostInfo, - pipeline_layout::GPUPipelineLayout, - query_set::GPUQuerySet, - queue::GPUQueue, - render_bundle::GPURenderBundle, - render_bundle::GPURenderBundleEncoder, - render_pass::GPURenderPassEncoder, - render_pipeline::GPURenderPipeline, - sampler::GPUSampler, - shader::GPUShaderModule, - adapter::GPUSupportedFeatures, - adapter::GPUSupportedLimits, - texture::GPUTexture, - texture::GPUTextureView, - byow::UnsafeWindowSurface, - surface::GPUCanvasContext, - ], - esm = ["00_init.js", "02_surface.js"], - lazy_loaded_esm = ["01_webgpu.js"], + deno_webgpu, + deps = [deno_webidl, deno_web], + ops = [ + op_create_gpu, + device::op_webgpu_device_start_capture, + device::op_webgpu_device_stop_capture, + ], + objects = [ + GPU, + adapter::GPUAdapter, + adapter::GPUAdapterInfo, + bind_group::GPUBindGroup, + bind_group_layout::GPUBindGroupLayout, + buffer::GPUBuffer, + command_buffer::GPUCommandBuffer, + command_encoder::GPUCommandEncoder, + compute_pass::GPUComputePassEncoder, + compute_pipeline::GPUComputePipeline, + device::GPUDevice, + device::GPUDeviceLostInfo, + pipeline_layout::GPUPipelineLayout, + query_set::GPUQuerySet, + queue::GPUQueue, + render_bundle::GPURenderBundle, + render_bundle::GPURenderBundleEncoder, + render_pass::GPURenderPassEncoder, + render_pipeline::GPURenderPipeline, + sampler::GPUSampler, + shader::GPUCompilationInfo, + shader::GPUCompilationMessage, + shader::GPUShaderModule, + adapter::GPUSupportedFeatures, + adapter::GPUSupportedLimits, + texture::GPUTexture, + texture::GPUTextureView, + texture::GPUExternalTexture, + byow::UnsafeWindowSurface, + surface::GPUCanvasContext, + ], + esm = ["00_init.js", "02_surface.js"], + lazy_loaded_esm = ["01_webgpu.js"], ); #[op2] #[cppgc] pub fn op_create_gpu( - state: &mut OpState, - scope: &mut v8::HandleScope, - webidl_brand: v8::Local, - set_event_target_data: v8::Local, - error_event_class: v8::Local, + state: &mut OpState, + scope: &mut v8::HandleScope, + webidl_brand: v8::Local, + set_event_target_data: v8::Local, + error_event_class: v8::Local, ) -> GPU { - state.put(EventTargetSetup { - brand: v8::Global::new(scope, webidl_brand), - set_event_target_data: v8::Global::new(scope, set_event_target_data), - }); - state.put(ErrorEventClass(v8::Global::new(scope, error_event_class))); - GPU + state.put(EventTargetSetup { + brand: v8::Global::new(scope, webidl_brand), + set_event_target_data: v8::Global::new(scope, set_event_target_data), + }); + state.put(ErrorEventClass(v8::Global::new(scope, error_event_class))); + GPU } struct EventTargetSetup { - brand: v8::Global, - set_event_target_data: v8::Global, + brand: v8::Global, + set_event_target_data: v8::Global, } struct ErrorEventClass(v8::Global); pub struct GPU; -impl GarbageCollected for GPU {} +impl GarbageCollected for GPU { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPU" + } +} #[op2] impl GPU { - #[async_method] - #[cppgc] - async fn request_adapter( - &self, - state: Rc>, - #[webidl] options: adapter::GPURequestAdapterOptions, - ) -> Option { - let mut state = state.borrow_mut(); + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } - let backends = std::env::var("DENO_WEBGPU_BACKEND").map_or_else( - |_| wgpu_types::Backends::all(), - |s| wgpu_types::Backends::from_comma_list(&s), - ); - let instance = if let Some(instance) = state.try_borrow::() { - instance - } else { - state.put(Arc::new(wgpu_core::global::Global::new( - "webgpu", - &wgpu_types::InstanceDescriptor { - backends, - flags: wgpu_types::InstanceFlags::from_build_config(), - backend_options: wgpu_types::BackendOptions { - dx12: wgpu_types::Dx12BackendOptions { - shader_compiler: wgpu_types::Dx12Compiler::Fxc, - }, - gl: wgpu_types::GlBackendOptions::default(), - noop: wgpu_types::NoopBackendOptions::default(), - }, - }, - ))); - state.borrow::() - }; + #[async_method] + #[cppgc] + async fn request_adapter( + &self, + state: Rc>, + #[webidl] options: adapter::GPURequestAdapterOptions, + ) -> Option { + let mut state = state.borrow_mut(); - let descriptor = wgpu_core::instance::RequestAdapterOptions { - power_preference: options - .power_preference - .map(|pp| match pp { - adapter::GPUPowerPreference::LowPower => PowerPreference::LowPower, - adapter::GPUPowerPreference::HighPerformance => { - PowerPreference::HighPerformance - } - }) - .unwrap_or_default(), - force_fallback_adapter: options.force_fallback_adapter, - compatible_surface: None, // windowless - }; - let id = instance.request_adapter(&descriptor, backends, None).ok()?; + let backends = std::env::var("DENO_WEBGPU_BACKEND").map_or_else( + |_| wgpu_types::Backends::all(), + |s| wgpu_types::Backends::from_comma_list(&s), + ); + let instance = if let Some(instance) = state.try_borrow::() { + instance + } else { + state.put(Arc::new(wgpu_core::global::Global::new( + "webgpu", + &wgpu_types::InstanceDescriptor { + backends, + flags: wgpu_types::InstanceFlags::from_build_config(), + memory_budget_thresholds: wgpu_types::MemoryBudgetThresholds { + for_resource_creation: Some(97), + for_device_loss: Some(99), + }, + backend_options: wgpu_types::BackendOptions { + dx12: wgpu_types::Dx12BackendOptions { + shader_compiler: wgpu_types::Dx12Compiler::Fxc, + ..Default::default() + }, + gl: wgpu_types::GlBackendOptions::default(), + noop: wgpu_types::NoopBackendOptions::default(), + }, + }, + ))); + state.borrow::() + }; - Some(adapter::GPUAdapter { - instance: instance.clone(), - features: SameObject::new(), - limits: SameObject::new(), - info: Rc::new(SameObject::new()), - id, + let descriptor = wgpu_core::instance::RequestAdapterOptions { + power_preference: options + .power_preference + .map(|pp| match pp { + adapter::GPUPowerPreference::LowPower => PowerPreference::LowPower, + adapter::GPUPowerPreference::HighPerformance => { + PowerPreference::HighPerformance + } }) - } + .unwrap_or_default(), + force_fallback_adapter: options.force_fallback_adapter, + compatible_surface: None, // windowless + }; + let id = instance.request_adapter(&descriptor, backends, None).ok()?; - #[string] - fn getPreferredCanvasFormat(&self) -> &'static str { - // https://github.com/mozilla/gecko-dev/blob/b75080bb8b11844d18cb5f9ac6e68a866ef8e243/dom/webgpu/Instance.h#L42-L47 - if cfg!(target_os = "android") { - texture::GPUTextureFormat::Rgba8unorm.as_str() - } else { - texture::GPUTextureFormat::Bgra8unorm.as_str() - } + Some(adapter::GPUAdapter { + instance: instance.clone(), + features: SameObject::new(), + limits: SameObject::new(), + info: Rc::new(SameObject::new()), + id, + }) + } + + #[string] + fn getPreferredCanvasFormat(&self) -> &'static str { + // https://github.com/mozilla/gecko-dev/blob/b75080bb8b11844d18cb5f9ac6e68a866ef8e243/dom/webgpu/Instance.h#L42-L47 + if cfg!(target_os = "android") { + texture::GPUTextureFormat::Rgba8unorm.as_str() + } else { + texture::GPUTextureFormat::Bgra8unorm.as_str() } + } } fn transform_label<'a>(label: String) -> Option> { - if label.is_empty() { - None - } else { - Some(std::borrow::Cow::Owned(label)) - } + if label.is_empty() { + None + } else { + Some(std::borrow::Cow::Owned(label)) + } } diff --git a/deno_webgpu/pipeline_layout.rs b/deno_webgpu/pipeline_layout.rs index c785eea73..1d71a9902 100644 --- a/deno_webgpu/pipeline_layout.rs +++ b/deno_webgpu/pipeline_layout.rs @@ -6,45 +6,57 @@ use deno_core::webidl::WebIdlInterfaceConverter; use deno_core::GarbageCollected; use deno_core::WebIDL; +use crate::error::GPUGenericError; use crate::Instance; pub struct GPUPipelineLayout { - pub instance: Instance, - pub id: wgpu_core::id::PipelineLayoutId, - pub label: String, + pub instance: Instance, + pub id: wgpu_core::id::PipelineLayoutId, + pub label: String, } impl Drop for GPUPipelineLayout { - fn drop(&mut self) { - self.instance.pipeline_layout_drop(self.id); - } + fn drop(&mut self) { + self.instance.pipeline_layout_drop(self.id); + } } impl WebIdlInterfaceConverter for GPUPipelineLayout { - const NAME: &'static str = "GPUPipelineLayout"; + const NAME: &'static str = "GPUPipelineLayout"; } -impl GarbageCollected for GPUPipelineLayout {} +impl GarbageCollected for GPUPipelineLayout { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUPipelineLayout" + } +} #[op2] impl GPUPipelineLayout { - #[getter] - #[string] - fn label(&self) -> String { - self.label.clone() - } - #[setter] - #[string] - fn label(&self, #[webidl] _label: String) { - // TODO(@crowlKats): no-op, needs wpgu to implement changing the label - } + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } + + #[getter] + #[string] + fn label(&self) -> String { + self.label.clone() + } + #[setter] + #[string] + fn label(&self, #[webidl] _label: String) { + // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUPipelineLayoutDescriptor { - #[webidl(default = String::new())] - pub label: String, + #[webidl(default = String::new())] + pub label: String, - pub bind_group_layouts: Vec>, + pub bind_group_layouts: + Vec>, } diff --git a/deno_webgpu/query_set.rs b/deno_webgpu/query_set.rs index cf10d6427..5b5e7dd8f 100644 --- a/deno_webgpu/query_set.rs +++ b/deno_webgpu/query_set.rs @@ -6,82 +6,96 @@ use deno_core::GarbageCollected; use deno_core::WebIDL; use deno_error::JsErrorBox; +use crate::error::GPUGenericError; use crate::Instance; pub struct GPUQuerySet { - pub instance: Instance, - pub id: wgpu_core::id::QuerySetId, - pub r#type: GPUQueryType, - pub count: u32, - pub label: String, + pub instance: Instance, + pub id: wgpu_core::id::QuerySetId, + pub r#type: GPUQueryType, + pub count: u32, + pub label: String, } impl Drop for GPUQuerySet { - fn drop(&mut self) { - self.instance.query_set_drop(self.id); - } + fn drop(&mut self) { + self.instance.query_set_drop(self.id); + } } impl WebIdlInterfaceConverter for GPUQuerySet { - const NAME: &'static str = "GPUQuerySet"; + const NAME: &'static str = "GPUQuerySet"; } -impl GarbageCollected for GPUQuerySet {} +impl GarbageCollected for GPUQuerySet { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUQuerySet" + } +} #[op2] impl GPUQuerySet { - #[getter] - #[string] - fn label(&self) -> String { - self.label.clone() - } - #[setter] - #[string] - fn label(&self, #[webidl] _label: String) { - // TODO(@crowlKats): no-op, needs wpgu to implement changing the label - } + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } - #[fast] - fn destroy(&self) -> Result<(), JsErrorBox> { - Err(JsErrorBox::generic( - "This operation is currently not supported", - )) - } + #[getter] + #[string] + fn label(&self) -> String { + self.label.clone() + } + #[setter] + #[string] + fn label(&self, #[webidl] _label: String) { + // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + } - #[getter] - #[string] - fn r#type(&self) -> &'static str { - self.r#type.as_str() - } + #[fast] + #[undefined] + fn destroy(&self) -> Result<(), JsErrorBox> { + // TODO(https://github.com/gfx-rs/wgpu/issues/6495): Destroy the query + // set. Until that is supported, it is okay to do nothing here, the + // query set will be garbage collected and dropped eventually. + Ok(()) + } - #[getter] - fn count(&self) -> u32 { - self.count - } + #[getter] + #[string] + #[rename("type")] + fn r#type(&self) -> &'static str { + self.r#type.as_str() + } + + #[getter] + fn count(&self) -> u32 { + self.count + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUQuerySetDescriptor { - #[webidl(default = String::new())] - pub label: String, + #[webidl(default = String::new())] + pub label: String, - pub r#type: GPUQueryType, - #[options(enforce_range = true)] - pub count: u32, + pub r#type: GPUQueryType, + #[options(enforce_range = true)] + pub count: u32, } #[derive(WebIDL, Clone)] #[webidl(enum)] pub(crate) enum GPUQueryType { - Occlusion, - Timestamp, + Occlusion, + Timestamp, } impl From for wgpu_types::QueryType { - fn from(value: GPUQueryType) -> Self { - match value { - GPUQueryType::Occlusion => Self::Occlusion, - GPUQueryType::Timestamp => Self::Timestamp, - } + fn from(value: GPUQueryType) -> Self { + match value { + GPUQueryType::Occlusion => Self::Occlusion, + GPUQueryType::Timestamp => Self::Timestamp, } + } } diff --git a/deno_webgpu/queue.rs b/deno_webgpu/queue.rs index 920640f9d..dee47927f 100644 --- a/deno_webgpu/queue.rs +++ b/deno_webgpu/queue.rs @@ -1,6 +1,11 @@ // Copyright 2018-2025 the Deno authors. MIT license. +use std::cell::RefCell; +use std::rc::Rc; +use std::time::Duration; + use deno_core::cppgc::Ptr; +use deno_core::futures::channel::oneshot; use deno_core::op2; use deno_core::GarbageCollected; use deno_core::WebIDL; @@ -8,6 +13,7 @@ use deno_error::JsErrorBox; use crate::buffer::GPUBuffer; use crate::command_buffer::GPUCommandBuffer; +use crate::error::GPUGenericError; use crate::texture::GPUTexture; use crate::texture::GPUTextureAspect; use crate::webidl::GPUExtent3D; @@ -15,143 +21,193 @@ use crate::webidl::GPUOrigin3D; use crate::Instance; pub struct GPUQueue { - pub instance: Instance, - pub error_handler: super::error::ErrorHandler, + pub instance: Instance, + pub error_handler: super::error::ErrorHandler, - pub label: String, + pub label: String, - pub id: wgpu_core::id::QueueId, + pub id: wgpu_core::id::QueueId, + pub device: wgpu_core::id::DeviceId, } impl Drop for GPUQueue { - fn drop(&mut self) { - self.instance.queue_drop(self.id); - } + fn drop(&mut self) { + self.instance.queue_drop(self.id); + } } -impl GarbageCollected for GPUQueue {} +impl GarbageCollected for GPUQueue { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUQueue" + } +} #[op2] impl GPUQueue { - #[getter] - #[string] - fn label(&self) -> String { - self.label.clone() - } - #[setter] - #[string] - fn label(&self, #[webidl] _label: String) { - // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } + + #[getter] + #[string] + fn label(&self) -> String { + self.label.clone() + } + #[setter] + #[string] + fn label(&self, #[webidl] _label: String) { + // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + } + + #[required(1)] + #[undefined] + fn submit( + &self, + #[webidl] command_buffers: Vec>, + ) -> Result<(), JsErrorBox> { + let ids = command_buffers + .into_iter() + .map(|cb| cb.id) + .collect::>(); + + let err = self.instance.queue_submit(self.id, &ids).err(); + + if let Some((_, err)) = err { + self.error_handler.push_error(Some(err)); } - #[required(1)] - fn submit( - &self, - #[webidl] command_buffers: Vec>, - ) -> Result<(), JsErrorBox> { - let ids = command_buffers - .into_iter() - .enumerate() - .map(|(i, cb)| { - if cb.consumed.set(()).is_err() { - Err(JsErrorBox::type_error(format!( - "The command buffer at position {i} has already been submitted." - ))) - } else { - Ok(cb.id) - } - }) - .collect::, _>>()?; + Ok(()) + } - let err = self.instance.queue_submit(self.id, &ids).err(); + // In the successful case, the promise should resolve to undefined, but + // `#[undefined]` does not seem to work here. + // https://github.com/denoland/deno/issues/29603 + #[async_method] + async fn on_submitted_work_done(&self) -> Result<(), JsErrorBox> { + let (sender, receiver) = oneshot::channel::<()>(); - if let Some((_, err)) = err { - self.error_handler.push_error(Some(err)); + let callback = Box::new(move || { + sender.send(()).unwrap(); + }); + + self + .instance + .queue_on_submitted_work_done(self.id, callback); + + let done = Rc::new(RefCell::new(false)); + let done_ = done.clone(); + let device_poll_fut = async move { + while !*done.borrow() { + { + self + .instance + .device_poll(self.device, wgpu_types::PollType::wait_indefinitely()) + .unwrap(); } + tokio::time::sleep(Duration::from_millis(10)).await; + } + Ok::<(), JsErrorBox>(()) + }; - Ok(()) - } + let receiver_fut = async move { + receiver + .await + .map_err(|e| JsErrorBox::generic(e.to_string()))?; + let mut done = done_.borrow_mut(); + *done = true; + Ok::<(), JsErrorBox>(()) + }; - #[async_method] - async fn on_submitted_work_done(&self) -> Result<(), JsErrorBox> { - Err(JsErrorBox::generic( - "This operation is currently not supported", - )) - } + tokio::try_join!(device_poll_fut, receiver_fut)?; - #[required(3)] - fn write_buffer( - &self, - #[webidl] buffer: Ptr, - #[webidl(options(enforce_range = true))] buffer_offset: u64, - #[anybuffer] buf: &[u8], - #[webidl(default = 0, options(enforce_range = true))] data_offset: u64, - #[webidl(options(enforce_range = true))] size: Option, - ) { - let data = match size { - Some(size) => &buf[(data_offset as usize)..((data_offset + size) as usize)], - None => &buf[(data_offset as usize)..], - }; + Ok(()) + } - let err = self - .instance - .queue_write_buffer(self.id, buffer.id, buffer_offset, data) - .err(); + #[required(3)] + #[undefined] + fn write_buffer( + &self, + #[webidl] buffer: Ptr, + #[webidl(options(enforce_range = true))] buffer_offset: u64, + #[anybuffer] buf: &[u8], + #[webidl(default = 0, options(enforce_range = true))] data_offset: u64, + #[webidl(options(enforce_range = true))] size: Option, + ) { + let data = match size { + Some(size) => { + &buf[(data_offset as usize)..((data_offset + size) as usize)] + } + None => &buf[(data_offset as usize)..], + }; - self.error_handler.push_error(err); - } + let err = self + .instance + .queue_write_buffer(self.id, buffer.id, buffer_offset, data) + .err(); - #[required(4)] - fn write_texture( - &self, - #[webidl] destination: GPUTexelCopyTextureInfo, - #[anybuffer] buf: &[u8], - #[webidl] data_layout: GPUTexelCopyBufferLayout, - #[webidl] size: GPUExtent3D, - ) { - let destination = wgpu_core::command::TexelCopyTextureInfo { - texture: destination.texture.id, - mip_level: destination.mip_level, - origin: destination.origin.into(), - aspect: destination.aspect.into(), - }; + self.error_handler.push_error(err); + } - let data_layout = wgpu_types::TexelCopyBufferLayout { - offset: data_layout.offset, - bytes_per_row: data_layout.bytes_per_row, - rows_per_image: data_layout.rows_per_image, - }; + #[required(4)] + #[undefined] + fn write_texture( + &self, + #[webidl] destination: GPUTexelCopyTextureInfo, + #[anybuffer] buf: &[u8], + #[webidl] data_layout: GPUTexelCopyBufferLayout, + #[webidl] size: GPUExtent3D, + ) { + let destination = wgpu_types::TexelCopyTextureInfo { + texture: destination.texture.id, + mip_level: destination.mip_level, + origin: destination.origin.into(), + aspect: destination.aspect.into(), + }; - let err = self - .instance - .queue_write_texture(self.id, &destination, buf, &data_layout, &size.into()) - .err(); + let data_layout = wgpu_types::TexelCopyBufferLayout { + offset: data_layout.offset, + bytes_per_row: data_layout.bytes_per_row, + rows_per_image: data_layout.rows_per_image, + }; - self.error_handler.push_error(err); - } + let err = self + .instance + .queue_write_texture( + self.id, + &destination, + buf, + &data_layout, + &size.into(), + ) + .err(); + + self.error_handler.push_error(err); + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUTexelCopyTextureInfo { - pub texture: Ptr, - #[webidl(default = 0)] - #[options(enforce_range = true)] - pub mip_level: u32, - #[webidl(default = Default::default())] - pub origin: GPUOrigin3D, - #[webidl(default = GPUTextureAspect::All)] - pub aspect: GPUTextureAspect, + pub texture: Ptr, + #[webidl(default = 0)] + #[options(enforce_range = true)] + pub mip_level: u32, + #[webidl(default = Default::default())] + pub origin: GPUOrigin3D, + #[webidl(default = GPUTextureAspect::All)] + pub aspect: GPUTextureAspect, } #[derive(WebIDL)] #[webidl(dictionary)] struct GPUTexelCopyBufferLayout { - #[webidl(default = 0)] - #[options(enforce_range = true)] - offset: u64, - #[options(enforce_range = true)] - bytes_per_row: Option, - #[options(enforce_range = true)] - rows_per_image: Option, + #[webidl(default = 0)] + #[options(enforce_range = true)] + offset: u64, + #[options(enforce_range = true)] + bytes_per_row: Option, + #[options(enforce_range = true)] + rows_per_image: Option, } diff --git a/deno_webgpu/render_bundle.rs b/deno_webgpu/render_bundle.rs index de6dec878..964d72413 100644 --- a/deno_webgpu/render_bundle.rs +++ b/deno_webgpu/render_bundle.rs @@ -17,393 +17,447 @@ use deno_core::WebIDL; use deno_error::JsErrorBox; use crate::buffer::GPUBuffer; +use crate::error::GPUGenericError; use crate::texture::GPUTextureFormat; use crate::Instance; -pub struct GPURenderBundleEncoder { - pub instance: Instance, - pub error_handler: super::error::ErrorHandler, - - pub encoder: RefCell>, - pub label: String, +fn c_string_truncated_at_first_nul>>( + src: T, +) -> std::ffi::CString { + std::ffi::CString::new(src).unwrap_or_else(|err| { + let nul_pos = err.nul_position(); + std::ffi::CString::new(err.into_vec().split_at(nul_pos).0).unwrap() + }) } -impl GarbageCollected for GPURenderBundleEncoder {} +pub struct GPURenderBundleEncoder { + pub instance: Instance, + pub error_handler: super::error::ErrorHandler, + + pub encoder: RefCell>, + pub label: String, +} + +impl GarbageCollected for GPURenderBundleEncoder { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPURenderBundleEncoder" + } +} #[op2] impl GPURenderBundleEncoder { - #[getter] - #[string] - fn label(&self) -> String { - self.label.clone() + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } + + #[getter] + #[string] + fn label(&self) -> String { + self.label.clone() + } + #[setter] + #[string] + fn label(&self, #[webidl] _label: String) { + // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + } + + #[cppgc] + fn finish( + &self, + #[webidl] descriptor: GPURenderBundleDescriptor, + ) -> GPURenderBundle { + let wgpu_descriptor = wgpu_core::command::RenderBundleDescriptor { + label: crate::transform_label(descriptor.label.clone()), + }; + + let (id, err) = self.instance.render_bundle_encoder_finish( + self.encoder.borrow_mut().take().unwrap(), + &wgpu_descriptor, + None, + ); + + self.error_handler.push_error(err); + + GPURenderBundle { + instance: self.instance.clone(), + id, + label: descriptor.label.clone(), } - #[setter] - #[string] - fn label(&self, #[webidl] _label: String) { - // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + } + + #[undefined] + fn push_debug_group( + &self, + #[webidl] group_label: String, + ) -> Result<(), JsErrorBox> { + let mut encoder = self.encoder.borrow_mut(); + let encoder = encoder.as_mut().ok_or_else(|| { + JsErrorBox::generic("Encoder has already been finished") + })?; + + let label = c_string_truncated_at_first_nul(group_label); + // SAFETY: the string the raw pointer points to lives longer than the below + // function invocation. + unsafe { + wgpu_core::command::bundle_ffi::wgpu_render_bundle_push_debug_group( + encoder, + label.as_ptr(), + ); } - #[cppgc] - fn finish(&self, #[webidl] descriptor: GPURenderBundleDescriptor) -> GPURenderBundle { - let wgpu_descriptor = wgpu_core::command::RenderBundleDescriptor { - label: crate::transform_label(descriptor.label.clone()), - }; + Ok(()) + } - let (id, err) = self.instance.render_bundle_encoder_finish( - self.encoder.borrow_mut().take().unwrap(), - &wgpu_descriptor, - None, + #[fast] + #[undefined] + fn pop_debug_group(&self) -> Result<(), JsErrorBox> { + let mut encoder = self.encoder.borrow_mut(); + let encoder = encoder.as_mut().ok_or_else(|| { + JsErrorBox::generic("Encoder has already been finished") + })?; + wgpu_core::command::bundle_ffi::wgpu_render_bundle_pop_debug_group(encoder); + Ok(()) + } + + #[undefined] + fn insert_debug_marker( + &self, + #[webidl] marker_label: String, + ) -> Result<(), JsErrorBox> { + let mut encoder = self.encoder.borrow_mut(); + let encoder = encoder.as_mut().ok_or_else(|| { + JsErrorBox::generic("Encoder has already been finished") + })?; + + let label = c_string_truncated_at_first_nul(marker_label); + // SAFETY: the string the raw pointer points to lives longer than the below + // function invocation. + unsafe { + wgpu_core::command::bundle_ffi::wgpu_render_bundle_insert_debug_marker( + encoder, + label.as_ptr(), + ); + } + Ok(()) + } + + #[undefined] + fn set_bind_group<'a>( + &self, + scope: &mut v8::HandleScope<'a>, + #[webidl(options(enforce_range = true))] index: u32, + #[webidl] bind_group: Nullable>, + dynamic_offsets: v8::Local<'a, v8::Value>, + dynamic_offsets_data_start: v8::Local<'a, v8::Value>, + dynamic_offsets_data_length: v8::Local<'a, v8::Value>, + ) -> Result<(), SetBindGroupError> { + let mut encoder = self.encoder.borrow_mut(); + let encoder = encoder.as_mut().ok_or_else(|| { + JsErrorBox::generic("Encoder has already been finished") + })?; + + const PREFIX: &str = + "Failed to execute 'setBindGroup' on 'GPUComputePassEncoder'"; + if let Ok(uint_32) = dynamic_offsets.try_cast::() { + let start = u64::convert( + scope, + dynamic_offsets_data_start, + Cow::Borrowed(PREFIX), + (|| Cow::Borrowed("Argument 4")).into(), + &IntOptions { + clamp: false, + enforce_range: true, + }, + )? as usize; + let len = u32::convert( + scope, + dynamic_offsets_data_length, + Cow::Borrowed(PREFIX), + (|| Cow::Borrowed("Argument 5")).into(), + &IntOptions { + clamp: false, + enforce_range: true, + }, + )? as usize; + + let ab = uint_32.buffer(scope).unwrap(); + let ptr = ab.data().unwrap(); + let ab_len = ab.byte_length() / 4; + + // SAFETY: created from an array buffer, slice is dropped at end of function call + let data = + unsafe { std::slice::from_raw_parts(ptr.as_ptr() as _, ab_len) }; + + let offsets = &data[start..(start + len)]; + + // SAFETY: wgpu FFI call + unsafe { + wgpu_core::command::bundle_ffi::wgpu_render_bundle_set_bind_group( + encoder, + index, + bind_group.into_option().map(|bind_group| bind_group.id), + offsets.as_ptr(), + offsets.len(), ); + } + } else { + let offsets = >>::convert( + scope, + dynamic_offsets, + Cow::Borrowed(PREFIX), + (|| Cow::Borrowed("Argument 3")).into(), + &IntOptions { + clamp: false, + enforce_range: true, + }, + )? + .unwrap_or_default(); - self.error_handler.push_error(err); - - GPURenderBundle { - instance: self.instance.clone(), - id, - label: descriptor.label.clone(), - } - } - - fn push_debug_group(&self, #[webidl] group_label: String) -> Result<(), JsErrorBox> { - let mut encoder = self.encoder.borrow_mut(); - let encoder = encoder - .as_mut() - .ok_or_else(|| JsErrorBox::generic("Encoder has already been finished"))?; - - let label = std::ffi::CString::new(group_label).unwrap(); - // SAFETY: the string the raw pointer points to lives longer than the below - // function invocation. - unsafe { - wgpu_core::command::bundle_ffi::wgpu_render_bundle_push_debug_group( - encoder, - label.as_ptr(), - ); - } - - Ok(()) - } - - #[fast] - fn pop_debug_group(&self) -> Result<(), JsErrorBox> { - let mut encoder = self.encoder.borrow_mut(); - let encoder = encoder - .as_mut() - .ok_or_else(|| JsErrorBox::generic("Encoder has already been finished"))?; - wgpu_core::command::bundle_ffi::wgpu_render_bundle_pop_debug_group(encoder); - Ok(()) - } - - fn insert_debug_marker(&self, #[webidl] marker_label: String) -> Result<(), JsErrorBox> { - let mut encoder = self.encoder.borrow_mut(); - let encoder = encoder - .as_mut() - .ok_or_else(|| JsErrorBox::generic("Encoder has already been finished"))?; - - let label = std::ffi::CString::new(marker_label).unwrap(); - - // SAFETY: the string the raw pointer points to lives longer than the below - // function invocation. - unsafe { - wgpu_core::command::bundle_ffi::wgpu_render_bundle_insert_debug_marker( - encoder, - label.as_ptr(), - ); - } - Ok(()) - } - - fn set_bind_group<'a>( - &self, - scope: &mut v8::HandleScope<'a>, - #[webidl(options(enforce_range = true))] index: u32, - #[webidl] bind_group: Nullable>, - dynamic_offsets: v8::Local<'a, v8::Value>, - dynamic_offsets_data_start: v8::Local<'a, v8::Value>, - dynamic_offsets_data_length: v8::Local<'a, v8::Value>, - ) -> Result<(), SetBindGroupError> { - let mut encoder = self.encoder.borrow_mut(); - let encoder = encoder - .as_mut() - .ok_or_else(|| JsErrorBox::generic("Encoder has already been finished"))?; - - const PREFIX: &str = "Failed to execute 'setBindGroup' on 'GPUComputePassEncoder'"; - if let Ok(uint_32) = dynamic_offsets.try_cast::() { - let start = u64::convert( - scope, - dynamic_offsets_data_start, - Cow::Borrowed(PREFIX), - (|| Cow::Borrowed("Argument 4")).into(), - &IntOptions { - clamp: false, - enforce_range: true, - }, - )? as usize; - let len = u32::convert( - scope, - dynamic_offsets_data_length, - Cow::Borrowed(PREFIX), - (|| Cow::Borrowed("Argument 5")).into(), - &IntOptions { - clamp: false, - enforce_range: true, - }, - )? as usize; - - let ab = uint_32.buffer(scope).unwrap(); - let ptr = ab.data().unwrap(); - let ab_len = ab.byte_length() / 4; - - // SAFETY: created from an array buffer, slice is dropped at end of function call - let data = unsafe { std::slice::from_raw_parts(ptr.as_ptr() as _, ab_len) }; - - let offsets = &data[start..(start + len)]; - - // SAFETY: wgpu FFI call - unsafe { - wgpu_core::command::bundle_ffi::wgpu_render_bundle_set_bind_group( - encoder, - index, - bind_group.into_option().map(|bind_group| bind_group.id), - offsets.as_ptr(), - offsets.len(), - ); - } - } else { - let offsets = >>::convert( - scope, - dynamic_offsets, - Cow::Borrowed(PREFIX), - (|| Cow::Borrowed("Argument 3")).into(), - &IntOptions { - clamp: false, - enforce_range: true, - }, - )? - .unwrap_or_default(); - - // SAFETY: wgpu FFI call - unsafe { - wgpu_core::command::bundle_ffi::wgpu_render_bundle_set_bind_group( - encoder, - index, - bind_group.into_option().map(|bind_group| bind_group.id), - offsets.as_ptr(), - offsets.len(), - ); - } - } - - Ok(()) - } - - fn set_pipeline( - &self, - #[webidl] pipeline: Ptr, - ) -> Result<(), JsErrorBox> { - let mut encoder = self.encoder.borrow_mut(); - let encoder = encoder - .as_mut() - .ok_or_else(|| JsErrorBox::generic("Encoder has already been finished"))?; - - wgpu_core::command::bundle_ffi::wgpu_render_bundle_set_pipeline(encoder, pipeline.id); - Ok(()) - } - - #[required(2)] - fn set_index_buffer( - &self, - #[webidl] buffer: Ptr, - #[webidl] index_format: crate::render_pipeline::GPUIndexFormat, - #[webidl(default = 0, options(enforce_range = true))] offset: u64, - #[webidl(options(enforce_range = true))] size: Option, - ) -> Result<(), JsErrorBox> { - let mut encoder = self.encoder.borrow_mut(); - let encoder = encoder - .as_mut() - .ok_or_else(|| JsErrorBox::generic("Encoder has already been finished"))?; - - encoder.set_index_buffer( - buffer.id, - index_format.into(), - offset, - size.and_then(NonZeroU64::new), + // SAFETY: wgpu FFI call + unsafe { + wgpu_core::command::bundle_ffi::wgpu_render_bundle_set_bind_group( + encoder, + index, + bind_group.into_option().map(|bind_group| bind_group.id), + offsets.as_ptr(), + offsets.len(), ); - Ok(()) + } } - #[required(2)] - fn set_vertex_buffer( - &self, - #[webidl(options(enforce_range = true))] slot: u32, - #[webidl] buffer: Ptr, // TODO(wgpu): support nullable buffer - #[webidl(default = 0, options(enforce_range = true))] offset: u64, - #[webidl(options(enforce_range = true))] size: Option, - ) -> Result<(), JsErrorBox> { - let mut encoder = self.encoder.borrow_mut(); - let encoder = encoder - .as_mut() - .ok_or_else(|| JsErrorBox::generic("Encoder has already been finished"))?; + Ok(()) + } - wgpu_core::command::bundle_ffi::wgpu_render_bundle_set_vertex_buffer( - encoder, - slot, - buffer.id, - offset, - size.and_then(NonZeroU64::new), - ); - Ok(()) - } + #[undefined] + fn set_pipeline( + &self, + #[webidl] pipeline: Ptr, + ) -> Result<(), JsErrorBox> { + let mut encoder = self.encoder.borrow_mut(); + let encoder = encoder.as_mut().ok_or_else(|| { + JsErrorBox::generic("Encoder has already been finished") + })?; - #[required(1)] - fn draw( - &self, - #[webidl(options(enforce_range = true))] vertex_count: u32, - #[webidl(default = 1, options(enforce_range = true))] instance_count: u32, - #[webidl(default = 0, options(enforce_range = true))] first_vertex: u32, - #[webidl(default = 0, options(enforce_range = true))] first_instance: u32, - ) -> Result<(), JsErrorBox> { - let mut encoder = self.encoder.borrow_mut(); - let encoder = encoder - .as_mut() - .ok_or_else(|| JsErrorBox::generic("Encoder has already been finished"))?; + wgpu_core::command::bundle_ffi::wgpu_render_bundle_set_pipeline( + encoder, + pipeline.id, + ); + Ok(()) + } - wgpu_core::command::bundle_ffi::wgpu_render_bundle_draw( - encoder, - vertex_count, - instance_count, - first_vertex, - first_instance, - ); - Ok(()) - } + #[required(2)] + #[undefined] + fn set_index_buffer( + &self, + #[webidl] buffer: Ptr, + #[webidl] index_format: crate::render_pipeline::GPUIndexFormat, + #[webidl(default = 0, options(enforce_range = true))] offset: u64, + #[webidl(options(enforce_range = true))] size: Option, + ) -> Result<(), JsErrorBox> { + let mut encoder = self.encoder.borrow_mut(); + let encoder = encoder.as_mut().ok_or_else(|| { + JsErrorBox::generic("Encoder has already been finished") + })?; - #[required(1)] - fn draw_indexed( - &self, - #[webidl(options(enforce_range = true))] index_count: u32, - #[webidl(default = 1, options(enforce_range = true))] instance_count: u32, - #[webidl(default = 0, options(enforce_range = true))] first_index: u32, - #[webidl(default = 0, options(enforce_range = true))] base_vertex: i32, - #[webidl(default = 0, options(enforce_range = true))] first_instance: u32, - ) -> Result<(), JsErrorBox> { - let mut encoder = self.encoder.borrow_mut(); - let encoder = encoder - .as_mut() - .ok_or_else(|| JsErrorBox::generic("Encoder has already been finished"))?; + encoder.set_index_buffer( + buffer.id, + index_format.into(), + offset, + size.and_then(NonZeroU64::new), + ); + Ok(()) + } - wgpu_core::command::bundle_ffi::wgpu_render_bundle_draw_indexed( - encoder, - index_count, - instance_count, - first_index, - base_vertex, - first_instance, - ); - Ok(()) - } + #[required(2)] + #[undefined] + fn set_vertex_buffer( + &self, + #[webidl(options(enforce_range = true))] slot: u32, + #[webidl] buffer: Ptr, // TODO(wgpu): support nullable buffer + #[webidl(default = 0, options(enforce_range = true))] offset: u64, + #[webidl(options(enforce_range = true))] size: Option, + ) -> Result<(), JsErrorBox> { + let mut encoder = self.encoder.borrow_mut(); + let encoder = encoder.as_mut().ok_or_else(|| { + JsErrorBox::generic("Encoder has already been finished") + })?; - #[required(2)] - fn draw_indirect( - &self, - #[webidl] indirect_buffer: Ptr, - #[webidl(options(enforce_range = true))] indirect_offset: u64, - ) -> Result<(), JsErrorBox> { - let mut encoder = self.encoder.borrow_mut(); - let encoder = encoder - .as_mut() - .ok_or_else(|| JsErrorBox::generic("Encoder has already been finished"))?; + wgpu_core::command::bundle_ffi::wgpu_render_bundle_set_vertex_buffer( + encoder, + slot, + buffer.id, + offset, + size.and_then(NonZeroU64::new), + ); + Ok(()) + } - wgpu_core::command::bundle_ffi::wgpu_render_bundle_draw_indirect( - encoder, - indirect_buffer.id, - indirect_offset, - ); - Ok(()) - } + #[required(1)] + #[undefined] + fn draw( + &self, + #[webidl(options(enforce_range = true))] vertex_count: u32, + #[webidl(default = 1, options(enforce_range = true))] instance_count: u32, + #[webidl(default = 0, options(enforce_range = true))] first_vertex: u32, + #[webidl(default = 0, options(enforce_range = true))] first_instance: u32, + ) -> Result<(), JsErrorBox> { + let mut encoder = self.encoder.borrow_mut(); + let encoder = encoder.as_mut().ok_or_else(|| { + JsErrorBox::generic("Encoder has already been finished") + })?; - #[required(2)] - fn draw_indexed_indirect( - &self, - #[webidl] indirect_buffer: Ptr, - #[webidl(options(enforce_range = true))] indirect_offset: u64, - ) -> Result<(), JsErrorBox> { - let mut encoder = self.encoder.borrow_mut(); - let encoder = encoder - .as_mut() - .ok_or_else(|| JsErrorBox::generic("Encoder has already been finished"))?; + wgpu_core::command::bundle_ffi::wgpu_render_bundle_draw( + encoder, + vertex_count, + instance_count, + first_vertex, + first_instance, + ); + Ok(()) + } - wgpu_core::command::bundle_ffi::wgpu_render_bundle_draw_indexed_indirect( - encoder, - indirect_buffer.id, - indirect_offset, - ); - Ok(()) - } + #[required(1)] + #[undefined] + fn draw_indexed( + &self, + #[webidl(options(enforce_range = true))] index_count: u32, + #[webidl(default = 1, options(enforce_range = true))] instance_count: u32, + #[webidl(default = 0, options(enforce_range = true))] first_index: u32, + #[webidl(default = 0, options(enforce_range = true))] base_vertex: i32, + #[webidl(default = 0, options(enforce_range = true))] first_instance: u32, + ) -> Result<(), JsErrorBox> { + let mut encoder = self.encoder.borrow_mut(); + let encoder = encoder.as_mut().ok_or_else(|| { + JsErrorBox::generic("Encoder has already been finished") + })?; + + wgpu_core::command::bundle_ffi::wgpu_render_bundle_draw_indexed( + encoder, + index_count, + instance_count, + first_index, + base_vertex, + first_instance, + ); + Ok(()) + } + + #[required(2)] + #[undefined] + fn draw_indirect( + &self, + #[webidl] indirect_buffer: Ptr, + #[webidl(options(enforce_range = true))] indirect_offset: u64, + ) -> Result<(), JsErrorBox> { + let mut encoder = self.encoder.borrow_mut(); + let encoder = encoder.as_mut().ok_or_else(|| { + JsErrorBox::generic("Encoder has already been finished") + })?; + + wgpu_core::command::bundle_ffi::wgpu_render_bundle_draw_indirect( + encoder, + indirect_buffer.id, + indirect_offset, + ); + Ok(()) + } + + #[required(2)] + #[undefined] + fn draw_indexed_indirect( + &self, + #[webidl] indirect_buffer: Ptr, + #[webidl(options(enforce_range = true))] indirect_offset: u64, + ) -> Result<(), JsErrorBox> { + let mut encoder = self.encoder.borrow_mut(); + let encoder = encoder.as_mut().ok_or_else(|| { + JsErrorBox::generic("Encoder has already been finished") + })?; + + wgpu_core::command::bundle_ffi::wgpu_render_bundle_draw_indexed_indirect( + encoder, + indirect_buffer.id, + indirect_offset, + ); + Ok(()) + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPURenderBundleEncoderDescriptor { - #[webidl(default = String::new())] - pub label: String, + #[webidl(default = String::new())] + pub label: String, - pub color_formats: Vec>, - pub depth_stencil_format: Option, - #[webidl(default = 1)] - #[options(enforce_range = true)] - pub sample_count: u32, + pub color_formats: Vec>, + pub depth_stencil_format: Option, + #[webidl(default = 1)] + #[options(enforce_range = true)] + pub sample_count: u32, - #[webidl(default = false)] - pub depth_read_only: bool, - #[webidl(default = false)] - pub stencil_read_only: bool, + #[webidl(default = false)] + pub depth_read_only: bool, + #[webidl(default = false)] + pub stencil_read_only: bool, } #[derive(Debug, thiserror::Error, deno_error::JsError)] enum SetBindGroupError { - #[class(inherit)] - #[error(transparent)] - WebIDL(#[from] WebIdlError), - #[class(inherit)] - #[error(transparent)] - Other(#[from] JsErrorBox), + #[class(inherit)] + #[error(transparent)] + WebIDL(#[from] WebIdlError), + #[class(inherit)] + #[error(transparent)] + Other(#[from] JsErrorBox), } pub struct GPURenderBundle { - pub instance: Instance, - pub id: wgpu_core::id::RenderBundleId, - pub label: String, + pub instance: Instance, + pub id: wgpu_core::id::RenderBundleId, + pub label: String, } impl Drop for GPURenderBundle { - fn drop(&mut self) { - self.instance.render_bundle_drop(self.id); - } + fn drop(&mut self) { + self.instance.render_bundle_drop(self.id); + } } impl WebIdlInterfaceConverter for GPURenderBundle { - const NAME: &'static str = "GPURenderBundle"; + const NAME: &'static str = "GPURenderBundle"; } -impl GarbageCollected for GPURenderBundle {} +impl GarbageCollected for GPURenderBundle { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPURenderBundle" + } +} #[op2] impl GPURenderBundle { - #[getter] - #[string] - fn label(&self) -> String { - self.label.clone() - } - #[setter] - #[string] - fn label(&self, #[webidl] _label: String) { - // TODO(@crowlKats): no-op, needs wpgu to implement changing the label - } + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } + + #[getter] + #[string] + fn label(&self) -> String { + self.label.clone() + } + #[setter] + #[string] + fn label(&self, #[webidl] _label: String) { + // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPURenderBundleDescriptor { - #[webidl(default = String::new())] - pub label: String, + #[webidl(default = String::new())] + pub label: String, } diff --git a/deno_webgpu/render_pass.rs b/deno_webgpu/render_pass.rs index cdb8bd8f6..31e75e589 100644 --- a/deno_webgpu/render_pass.rs +++ b/deno_webgpu/render_pass.rs @@ -7,6 +7,10 @@ use std::num::NonZeroU64; use deno_core::cppgc::Ptr; use deno_core::op2; use deno_core::v8; +use deno_core::v8::HandleScope; +use deno_core::v8::Local; +use deno_core::v8::Value; +use deno_core::webidl::ContextFn; use deno_core::webidl::IntOptions; use deno_core::webidl::Nullable; use deno_core::webidl::WebIdlConverter; @@ -15,462 +19,575 @@ use deno_core::GarbageCollected; use deno_core::WebIDL; use crate::buffer::GPUBuffer; +use crate::error::GPUGenericError; use crate::render_bundle::GPURenderBundle; +use crate::texture::GPUTexture; use crate::texture::GPUTextureView; use crate::webidl::GPUColor; use crate::Instance; pub struct GPURenderPassEncoder { - pub instance: Instance, - pub error_handler: super::error::ErrorHandler, + pub instance: Instance, + pub error_handler: super::error::ErrorHandler, - pub render_pass: RefCell, - pub label: String, + pub render_pass: RefCell, + pub label: String, } -impl GarbageCollected for GPURenderPassEncoder {} +impl GarbageCollected for GPURenderPassEncoder { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPURenderPassEncoder" + } +} #[op2] impl GPURenderPassEncoder { - #[getter] - #[string] - fn label(&self) -> String { - self.label.clone() - } - #[setter] - #[string] - fn label(&self, #[webidl] _label: String) { - // TODO(@crowlKats): no-op, needs wpgu to implement changing the label - } + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } - #[required(6)] - fn set_viewport( - &self, - #[webidl] x: f32, - #[webidl] y: f32, - #[webidl] width: f32, - #[webidl] height: f32, - #[webidl] min_depth: f32, - #[webidl] max_depth: f32, - ) { - let err = self - .instance - .render_pass_set_viewport( - &mut self.render_pass.borrow_mut(), - x, - y, - width, - height, - min_depth, - max_depth, - ) - .err(); - self.error_handler.push_error(err); - } + #[getter] + #[string] + fn label(&self) -> String { + self.label.clone() + } + #[setter] + #[string] + fn label(&self, #[webidl] _label: String) { + // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + } - #[required(4)] - fn set_scissor_rect( - &self, - #[webidl(options(enforce_range = true))] x: u32, - #[webidl(options(enforce_range = true))] y: u32, - #[webidl(options(enforce_range = true))] width: u32, - #[webidl(options(enforce_range = true))] height: u32, - ) { - let err = self - .instance - .render_pass_set_scissor_rect(&mut self.render_pass.borrow_mut(), x, y, width, height) - .err(); - self.error_handler.push_error(err); - } + #[required(6)] + #[undefined] + fn set_viewport( + &self, + #[webidl] x: f32, + #[webidl] y: f32, + #[webidl] width: f32, + #[webidl] height: f32, + #[webidl] min_depth: f32, + #[webidl] max_depth: f32, + ) { + let err = self + .instance + .render_pass_set_viewport( + &mut self.render_pass.borrow_mut(), + x, + y, + width, + height, + min_depth, + max_depth, + ) + .err(); + self.error_handler.push_error(err); + } - #[required(1)] - fn set_blend_constant(&self, #[webidl] color: GPUColor) { - let err = self - .instance - .render_pass_set_blend_constant(&mut self.render_pass.borrow_mut(), color.into()) - .err(); - self.error_handler.push_error(err); - } + #[required(4)] + #[undefined] + fn set_scissor_rect( + &self, + #[webidl(options(enforce_range = true))] x: u32, + #[webidl(options(enforce_range = true))] y: u32, + #[webidl(options(enforce_range = true))] width: u32, + #[webidl(options(enforce_range = true))] height: u32, + ) { + let err = self + .instance + .render_pass_set_scissor_rect( + &mut self.render_pass.borrow_mut(), + x, + y, + width, + height, + ) + .err(); + self.error_handler.push_error(err); + } - #[required(1)] - fn set_stencil_reference(&self, #[webidl(options(enforce_range = true))] reference: u32) { - let err = self - .instance - .render_pass_set_stencil_reference(&mut self.render_pass.borrow_mut(), reference) - .err(); - self.error_handler.push_error(err); - } + #[required(1)] + #[undefined] + fn set_blend_constant(&self, #[webidl] color: GPUColor) { + let err = self + .instance + .render_pass_set_blend_constant( + &mut self.render_pass.borrow_mut(), + color.into(), + ) + .err(); + self.error_handler.push_error(err); + } - #[required(1)] - fn begin_occlusion_query(&self, #[webidl(options(enforce_range = true))] query_index: u32) { - let err = self - .instance - .render_pass_begin_occlusion_query(&mut self.render_pass.borrow_mut(), query_index) - .err(); - self.error_handler.push_error(err); - } + #[required(1)] + #[undefined] + fn set_stencil_reference( + &self, + #[webidl(options(enforce_range = true))] reference: u32, + ) { + let err = self + .instance + .render_pass_set_stencil_reference( + &mut self.render_pass.borrow_mut(), + reference, + ) + .err(); + self.error_handler.push_error(err); + } - #[fast] - fn end_occlusion_query(&self) { - let err = self - .instance - .render_pass_end_occlusion_query(&mut self.render_pass.borrow_mut()) - .err(); - self.error_handler.push_error(err); - } + #[required(1)] + #[undefined] + fn begin_occlusion_query( + &self, + #[webidl(options(enforce_range = true))] query_index: u32, + ) { + let err = self + .instance + .render_pass_begin_occlusion_query( + &mut self.render_pass.borrow_mut(), + query_index, + ) + .err(); + self.error_handler.push_error(err); + } - #[required(1)] - fn execute_bundles(&self, #[webidl] bundles: Vec>) { - let err = self - .instance - .render_pass_execute_bundles( - &mut self.render_pass.borrow_mut(), - &bundles - .into_iter() - .map(|bundle| bundle.id) - .collect::>(), - ) - .err(); - self.error_handler.push_error(err); - } + #[fast] + #[undefined] + fn end_occlusion_query(&self) { + let err = self + .instance + .render_pass_end_occlusion_query(&mut self.render_pass.borrow_mut()) + .err(); + self.error_handler.push_error(err); + } - #[fast] - fn end(&self) { - let err = self - .instance - .render_pass_end(&mut self.render_pass.borrow_mut()) - .err(); - self.error_handler.push_error(err); - } + #[required(1)] + #[undefined] + fn execute_bundles(&self, #[webidl] bundles: Vec>) { + let err = self + .instance + .render_pass_execute_bundles( + &mut self.render_pass.borrow_mut(), + &bundles + .into_iter() + .map(|bundle| bundle.id) + .collect::>(), + ) + .err(); + self.error_handler.push_error(err); + } - fn push_debug_group(&self, #[webidl] group_label: String) { - let err = self - .instance - .render_pass_push_debug_group( - &mut self.render_pass.borrow_mut(), - &group_label, - 0, // wgpu#975 - ) - .err(); - self.error_handler.push_error(err); - } + #[fast] + #[undefined] + fn end(&self) { + let err = self + .instance + .render_pass_end(&mut self.render_pass.borrow_mut()) + .err(); + self.error_handler.push_error(err); + } - #[fast] - fn pop_debug_group(&self) { - let err = self - .instance - .render_pass_pop_debug_group(&mut self.render_pass.borrow_mut()) - .err(); - self.error_handler.push_error(err); - } + #[undefined] + fn push_debug_group(&self, #[webidl] group_label: String) { + let err = self + .instance + .render_pass_push_debug_group( + &mut self.render_pass.borrow_mut(), + &group_label, + 0, // wgpu#975 + ) + .err(); + self.error_handler.push_error(err); + } - fn insert_debug_marker(&self, #[webidl] marker_label: String) { - let err = self - .instance - .render_pass_insert_debug_marker( - &mut self.render_pass.borrow_mut(), - &marker_label, - 0, // wgpu#975 - ) - .err(); - self.error_handler.push_error(err); - } + #[fast] + #[undefined] + fn pop_debug_group(&self) { + let err = self + .instance + .render_pass_pop_debug_group(&mut self.render_pass.borrow_mut()) + .err(); + self.error_handler.push_error(err); + } - fn set_bind_group<'a>( - &self, - scope: &mut v8::HandleScope<'a>, - #[webidl(options(enforce_range = true))] index: u32, - #[webidl] bind_group: Nullable>, - dynamic_offsets: v8::Local<'a, v8::Value>, - dynamic_offsets_data_start: v8::Local<'a, v8::Value>, - dynamic_offsets_data_length: v8::Local<'a, v8::Value>, - ) -> Result<(), WebIdlError> { - const PREFIX: &str = "Failed to execute 'setBindGroup' on 'GPUComputePassEncoder'"; + #[undefined] + fn insert_debug_marker(&self, #[webidl] marker_label: String) { + let err = self + .instance + .render_pass_insert_debug_marker( + &mut self.render_pass.borrow_mut(), + &marker_label, + 0, // wgpu#975 + ) + .err(); + self.error_handler.push_error(err); + } - let err = if let Ok(uint_32) = dynamic_offsets.try_cast::() { - let start = u64::convert( - scope, - dynamic_offsets_data_start, - Cow::Borrowed(PREFIX), - (|| Cow::Borrowed("Argument 4")).into(), - &IntOptions { - clamp: false, - enforce_range: true, - }, - )? as usize; - let len = u32::convert( - scope, - dynamic_offsets_data_length, - Cow::Borrowed(PREFIX), - (|| Cow::Borrowed("Argument 5")).into(), - &IntOptions { - clamp: false, - enforce_range: true, - }, - )? as usize; + #[undefined] + fn set_bind_group<'a>( + &self, + scope: &mut v8::HandleScope<'a>, + #[webidl(options(enforce_range = true))] index: u32, + #[webidl] bind_group: Nullable>, + dynamic_offsets: v8::Local<'a, v8::Value>, + dynamic_offsets_data_start: v8::Local<'a, v8::Value>, + dynamic_offsets_data_length: v8::Local<'a, v8::Value>, + ) -> Result<(), WebIdlError> { + const PREFIX: &str = + "Failed to execute 'setBindGroup' on 'GPUComputePassEncoder'"; - let ab = uint_32.buffer(scope).unwrap(); - let ptr = ab.data().unwrap(); - let ab_len = ab.byte_length() / 4; + let err = if let Ok(uint_32) = dynamic_offsets.try_cast::() + { + let start = u64::convert( + scope, + dynamic_offsets_data_start, + Cow::Borrowed(PREFIX), + (|| Cow::Borrowed("Argument 4")).into(), + &IntOptions { + clamp: false, + enforce_range: true, + }, + )? as usize; + let len = u32::convert( + scope, + dynamic_offsets_data_length, + Cow::Borrowed(PREFIX), + (|| Cow::Borrowed("Argument 5")).into(), + &IntOptions { + clamp: false, + enforce_range: true, + }, + )? as usize; - // SAFETY: created from an array buffer, slice is dropped at end of function call - let data = unsafe { std::slice::from_raw_parts(ptr.as_ptr() as _, ab_len) }; + let ab = uint_32.buffer(scope).unwrap(); + let ptr = ab.data().unwrap(); + let ab_len = ab.byte_length() / 4; - let offsets = &data[start..(start + len)]; + // SAFETY: created from an array buffer, slice is dropped at end of function call + let data = + unsafe { std::slice::from_raw_parts(ptr.as_ptr() as _, ab_len) }; - self.instance - .render_pass_set_bind_group( - &mut self.render_pass.borrow_mut(), - index, - bind_group.into_option().map(|bind_group| bind_group.id), - offsets, - ) - .err() - } else { - let offsets = >>::convert( - scope, - dynamic_offsets, - Cow::Borrowed(PREFIX), - (|| Cow::Borrowed("Argument 3")).into(), - &IntOptions { - clamp: false, - enforce_range: true, - }, - )? - .unwrap_or_default(); + let offsets = &data[start..(start + len)]; - self.instance - .render_pass_set_bind_group( - &mut self.render_pass.borrow_mut(), - index, - bind_group.into_option().map(|bind_group| bind_group.id), - &offsets, - ) - .err() - }; + self + .instance + .render_pass_set_bind_group( + &mut self.render_pass.borrow_mut(), + index, + bind_group.into_option().map(|bind_group| bind_group.id), + offsets, + ) + .err() + } else { + let offsets = >>::convert( + scope, + dynamic_offsets, + Cow::Borrowed(PREFIX), + (|| Cow::Borrowed("Argument 3")).into(), + &IntOptions { + clamp: false, + enforce_range: true, + }, + )? + .unwrap_or_default(); - self.error_handler.push_error(err); + self + .instance + .render_pass_set_bind_group( + &mut self.render_pass.borrow_mut(), + index, + bind_group.into_option().map(|bind_group| bind_group.id), + &offsets, + ) + .err() + }; - Ok(()) - } + self.error_handler.push_error(err); - fn set_pipeline(&self, #[webidl] pipeline: Ptr) { - let err = self - .instance - .render_pass_set_pipeline(&mut self.render_pass.borrow_mut(), pipeline.id) - .err(); - self.error_handler.push_error(err); - } + Ok(()) + } - #[required(2)] - fn set_index_buffer( - &self, - #[webidl] buffer: Ptr, - #[webidl] index_format: crate::render_pipeline::GPUIndexFormat, - #[webidl(default = 0, options(enforce_range = true))] offset: u64, - #[webidl(options(enforce_range = true))] size: Option, - ) { - let err = self - .instance - .render_pass_set_index_buffer( - &mut self.render_pass.borrow_mut(), - buffer.id, - index_format.into(), - offset, - size.and_then(NonZeroU64::new), - ) - .err(); - self.error_handler.push_error(err); - } + #[undefined] + fn set_pipeline( + &self, + #[webidl] pipeline: Ptr, + ) { + let err = self + .instance + .render_pass_set_pipeline(&mut self.render_pass.borrow_mut(), pipeline.id) + .err(); + self.error_handler.push_error(err); + } - #[required(2)] - fn set_vertex_buffer( - &self, - #[webidl(options(enforce_range = true))] slot: u32, - #[webidl] buffer: Ptr, // TODO(wgpu): support nullable buffer - #[webidl(default = 0, options(enforce_range = true))] offset: u64, - #[webidl(options(enforce_range = true))] size: Option, - ) { - let err = self - .instance - .render_pass_set_vertex_buffer( - &mut self.render_pass.borrow_mut(), - slot, - buffer.id, - offset, - size.and_then(NonZeroU64::new), - ) - .err(); - self.error_handler.push_error(err); - } + #[required(2)] + #[undefined] + fn set_index_buffer( + &self, + #[webidl] buffer: Ptr, + #[webidl] index_format: crate::render_pipeline::GPUIndexFormat, + #[webidl(default = 0, options(enforce_range = true))] offset: u64, + #[webidl(options(enforce_range = true))] size: Option, + ) { + let err = self + .instance + .render_pass_set_index_buffer( + &mut self.render_pass.borrow_mut(), + buffer.id, + index_format.into(), + offset, + size.and_then(NonZeroU64::new), + ) + .err(); + self.error_handler.push_error(err); + } - #[required(1)] - fn draw( - &self, - #[webidl(options(enforce_range = true))] vertex_count: u32, - #[webidl(default = 1, options(enforce_range = true))] instance_count: u32, - #[webidl(default = 0, options(enforce_range = true))] first_vertex: u32, - #[webidl(default = 0, options(enforce_range = true))] first_instance: u32, - ) { - let err = self - .instance - .render_pass_draw( - &mut self.render_pass.borrow_mut(), - vertex_count, - instance_count, - first_vertex, - first_instance, - ) - .err(); - self.error_handler.push_error(err); - } + #[required(2)] + #[undefined] + fn set_vertex_buffer( + &self, + #[webidl(options(enforce_range = true))] slot: u32, + #[webidl] buffer: Ptr, // TODO(wgpu): support nullable buffer + #[webidl(default = 0, options(enforce_range = true))] offset: u64, + #[webidl(options(enforce_range = true))] size: Option, + ) { + let err = self + .instance + .render_pass_set_vertex_buffer( + &mut self.render_pass.borrow_mut(), + slot, + buffer.id, + offset, + size.and_then(NonZeroU64::new), + ) + .err(); + self.error_handler.push_error(err); + } - #[required(1)] - fn draw_indexed( - &self, - #[webidl(options(enforce_range = true))] index_count: u32, - #[webidl(default = 1, options(enforce_range = true))] instance_count: u32, - #[webidl(default = 0, options(enforce_range = true))] first_index: u32, - #[webidl(default = 0, options(enforce_range = true))] base_vertex: i32, - #[webidl(default = 0, options(enforce_range = true))] first_instance: u32, - ) { - let err = self - .instance - .render_pass_draw_indexed( - &mut self.render_pass.borrow_mut(), - index_count, - instance_count, - first_index, - base_vertex, - first_instance, - ) - .err(); - self.error_handler.push_error(err); - } + #[required(1)] + #[undefined] + fn draw( + &self, + #[webidl(options(enforce_range = true))] vertex_count: u32, + #[webidl(default = 1, options(enforce_range = true))] instance_count: u32, + #[webidl(default = 0, options(enforce_range = true))] first_vertex: u32, + #[webidl(default = 0, options(enforce_range = true))] first_instance: u32, + ) { + let err = self + .instance + .render_pass_draw( + &mut self.render_pass.borrow_mut(), + vertex_count, + instance_count, + first_vertex, + first_instance, + ) + .err(); + self.error_handler.push_error(err); + } - #[required(2)] - fn draw_indirect( - &self, - #[webidl] indirect_buffer: Ptr, - #[webidl(options(enforce_range = true))] indirect_offset: u64, - ) { - let err = self - .instance - .render_pass_draw_indirect( - &mut self.render_pass.borrow_mut(), - indirect_buffer.id, - indirect_offset, - ) - .err(); - self.error_handler.push_error(err); - } + #[required(1)] + #[undefined] + fn draw_indexed( + &self, + #[webidl(options(enforce_range = true))] index_count: u32, + #[webidl(default = 1, options(enforce_range = true))] instance_count: u32, + #[webidl(default = 0, options(enforce_range = true))] first_index: u32, + #[webidl(default = 0, options(enforce_range = true))] base_vertex: i32, + #[webidl(default = 0, options(enforce_range = true))] first_instance: u32, + ) { + let err = self + .instance + .render_pass_draw_indexed( + &mut self.render_pass.borrow_mut(), + index_count, + instance_count, + first_index, + base_vertex, + first_instance, + ) + .err(); + self.error_handler.push_error(err); + } - #[required(2)] - fn draw_indexed_indirect( - &self, - #[webidl] indirect_buffer: Ptr, - #[webidl(options(enforce_range = true))] indirect_offset: u64, - ) { - let err = self - .instance - .render_pass_draw_indexed_indirect( - &mut self.render_pass.borrow_mut(), - indirect_buffer.id, - indirect_offset, - ) - .err(); - self.error_handler.push_error(err); - } + #[required(2)] + #[undefined] + fn draw_indirect( + &self, + #[webidl] indirect_buffer: Ptr, + #[webidl(options(enforce_range = true))] indirect_offset: u64, + ) { + let err = self + .instance + .render_pass_draw_indirect( + &mut self.render_pass.borrow_mut(), + indirect_buffer.id, + indirect_offset, + ) + .err(); + self.error_handler.push_error(err); + } + + #[required(2)] + #[undefined] + fn draw_indexed_indirect( + &self, + #[webidl] indirect_buffer: Ptr, + #[webidl(options(enforce_range = true))] indirect_offset: u64, + ) { + let err = self + .instance + .render_pass_draw_indexed_indirect( + &mut self.render_pass.borrow_mut(), + indirect_buffer.id, + indirect_offset, + ) + .err(); + self.error_handler.push_error(err); + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPURenderPassDescriptor { - #[webidl(default = String::new())] - pub label: String, + #[webidl(default = String::new())] + pub label: String, - pub color_attachments: Vec>, - pub depth_stencil_attachment: Option, - pub occlusion_query_set: Option>, - pub timestamp_writes: Option, - /*#[webidl(default = 50000000)] - #[options(enforce_range = true)] - pub max_draw_count: u64,*/ + pub color_attachments: Vec>, + pub depth_stencil_attachment: Option, + pub occlusion_query_set: Option>, + pub timestamp_writes: Option, + /*#[webidl(default = 50000000)] + #[options(enforce_range = true)] + pub max_draw_count: u64,*/ + #[webidl(default = 0)] + #[options(enforce_range = true)] + pub multiview_mask: u32, } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPURenderPassColorAttachment { - pub view: Ptr, - /*#[options(enforce_range = true)] - pub depth_slice: Option,*/ - pub resolve_target: Option>, - pub clear_value: Option, - pub load_op: GPULoadOp, - pub store_op: GPUStoreOp, + pub view: GPUTextureOrView, + #[options(enforce_range = true)] + pub depth_slice: Option, + pub resolve_target: Option, + pub clear_value: Option, + pub load_op: GPULoadOp, + pub store_op: GPUStoreOp, } #[derive(WebIDL)] #[webidl(enum)] pub(crate) enum GPULoadOp { - Load, - Clear, + Load, + Clear, } impl GPULoadOp { - pub fn with_default_value(self, val: Option) -> wgpu_core::command::LoadOp { - match self { - GPULoadOp::Load => wgpu_core::command::LoadOp::Load, - GPULoadOp::Clear => wgpu_core::command::LoadOp::Clear(val.unwrap_or_default()), - } + pub fn with_default_value( + self, + val: Option, + ) -> wgpu_core::command::LoadOp { + match self { + GPULoadOp::Load => wgpu_core::command::LoadOp::Load, + GPULoadOp::Clear => { + wgpu_core::command::LoadOp::Clear(val.unwrap_or_default()) + } } + } - pub fn with_value(self, val: V) -> wgpu_core::command::LoadOp { - match self { - GPULoadOp::Load => wgpu_core::command::LoadOp::Load, - GPULoadOp::Clear => wgpu_core::command::LoadOp::Clear(val), - } + pub fn with_value(self, val: V) -> wgpu_core::command::LoadOp { + match self { + GPULoadOp::Load => wgpu_core::command::LoadOp::Load, + GPULoadOp::Clear => wgpu_core::command::LoadOp::Clear(val), } + } } #[derive(WebIDL)] #[webidl(enum)] pub(crate) enum GPUStoreOp { - Store, - Discard, + Store, + Discard, } impl From for wgpu_core::command::StoreOp { - fn from(value: GPUStoreOp) -> Self { - match value { - GPUStoreOp::Store => Self::Store, - GPUStoreOp::Discard => Self::Discard, - } + fn from(value: GPUStoreOp) -> Self { + match value { + GPUStoreOp::Store => Self::Store, + GPUStoreOp::Discard => Self::Discard, } + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPURenderPassDepthStencilAttachment { - pub view: Ptr, - pub depth_clear_value: Option, - pub depth_load_op: Option, - pub depth_store_op: Option, - #[webidl(default = false)] - pub depth_read_only: bool, - #[webidl(default = 0)] - #[options(enforce_range = true)] - pub stencil_clear_value: u32, - pub stencil_load_op: Option, - pub stencil_store_op: Option, - #[webidl(default = false)] - pub stencil_read_only: bool, + pub view: GPUTextureOrView, + pub depth_clear_value: Option, + pub depth_load_op: Option, + pub depth_store_op: Option, + #[webidl(default = false)] + pub depth_read_only: bool, + #[webidl(default = 0)] + #[options(enforce_range = true)] + pub stencil_clear_value: u32, + pub stencil_load_op: Option, + pub stencil_store_op: Option, + #[webidl(default = false)] + pub stencil_read_only: bool, } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPURenderPassTimestampWrites { - pub query_set: Ptr, - #[options(enforce_range = true)] - pub beginning_of_pass_write_index: Option, - #[options(enforce_range = true)] - pub end_of_pass_write_index: Option, + pub query_set: Ptr, + #[options(enforce_range = true)] + pub beginning_of_pass_write_index: Option, + #[options(enforce_range = true)] + pub end_of_pass_write_index: Option, +} + +pub(crate) enum GPUTextureOrView { + Texture(Ptr), + TextureView(Ptr), +} + +impl GPUTextureOrView { + pub(crate) fn to_view_id(&self) -> wgpu_core::id::TextureViewId { + match self { + Self::Texture(texture) => texture.default_view_id(), + Self::TextureView(texture_view) => texture_view.id, + } + } +} + +impl<'a> WebIdlConverter<'a> for GPUTextureOrView { + type Options = (); + + fn convert<'b>( + scope: &mut HandleScope<'a>, + value: Local<'a, Value>, + prefix: Cow<'static, str>, + context: ContextFn<'b>, + options: &Self::Options, + ) -> Result { + >::convert( + scope, + value, + prefix.clone(), + context.borrowed(), + options, + ) + .map(Self::Texture) + .or_else(|_| { + >::convert( + scope, + value, + prefix.clone(), + context.borrowed(), + options, + ) + .map(Self::TextureView) + }) + } } diff --git a/deno_webgpu/render_pipeline.rs b/deno_webgpu/render_pipeline.rs index fcd9d786d..1a0fc2210 100644 --- a/deno_webgpu/render_pipeline.rs +++ b/deno_webgpu/render_pipeline.rs @@ -9,6 +9,7 @@ use deno_core::WebIDL; use indexmap::IndexMap; use crate::bind_group_layout::GPUBindGroupLayout; +use crate::error::GPUGenericError; use crate::sampler::GPUCompareFunction; use crate::shader::GPUShaderModule; use crate::texture::GPUTextureFormat; @@ -16,535 +17,545 @@ use crate::webidl::GPUPipelineLayoutOrGPUAutoLayoutMode; use crate::Instance; pub struct GPURenderPipeline { - pub instance: Instance, - pub error_handler: super::error::ErrorHandler, + pub instance: Instance, + pub error_handler: super::error::ErrorHandler, - pub id: wgpu_core::id::RenderPipelineId, - pub label: String, + pub id: wgpu_core::id::RenderPipelineId, + pub label: String, } impl Drop for GPURenderPipeline { - fn drop(&mut self) { - self.instance.render_pipeline_drop(self.id); - } + fn drop(&mut self) { + self.instance.render_pipeline_drop(self.id); + } } impl WebIdlInterfaceConverter for GPURenderPipeline { - const NAME: &'static str = "GPURenderPipeline"; + const NAME: &'static str = "GPURenderPipeline"; } -impl GarbageCollected for GPURenderPipeline {} +impl GarbageCollected for GPURenderPipeline { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPURenderPipeline" + } +} #[op2] impl GPURenderPipeline { - #[getter] - #[string] - fn label(&self) -> String { - self.label.clone() - } - #[setter] - #[string] - fn label(&self, #[webidl] _label: String) { - // TODO(@crowlKats): no-op, needs wpgu to implement changing the label - } + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } - #[cppgc] - fn get_bind_group_layout(&self, #[webidl] index: u32) -> GPUBindGroupLayout { - let (id, err) = self - .instance - .render_pipeline_get_bind_group_layout(self.id, index, None); + #[getter] + #[string] + fn label(&self) -> String { + self.label.clone() + } + #[setter] + #[string] + fn label(&self, #[webidl] _label: String) { + // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + } - self.error_handler.push_error(err); + #[cppgc] + fn get_bind_group_layout(&self, #[webidl] index: u32) -> GPUBindGroupLayout { + let (id, err) = self + .instance + .render_pipeline_get_bind_group_layout(self.id, index, None); - // TODO(wgpu): needs to add a way to retrieve the label - GPUBindGroupLayout { - instance: self.instance.clone(), - id, - label: "".to_string(), - } + self.error_handler.push_error(err); + + // TODO(wgpu): needs to add a way to retrieve the label + GPUBindGroupLayout { + instance: self.instance.clone(), + id, + label: "".to_string(), } + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPURenderPipelineDescriptor { - #[webidl(default = String::new())] - pub label: String, + #[webidl(default = String::new())] + pub label: String, - pub layout: GPUPipelineLayoutOrGPUAutoLayoutMode, - pub vertex: GPUVertexState, - pub primitive: GPUPrimitiveState, - pub depth_stencil: Option, - pub multisample: GPUMultisampleState, - pub fragment: Option, + pub layout: GPUPipelineLayoutOrGPUAutoLayoutMode, + pub vertex: GPUVertexState, + pub primitive: GPUPrimitiveState, + pub depth_stencil: Option, + pub multisample: GPUMultisampleState, + pub fragment: Option, } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUMultisampleState { - #[webidl(default = 1)] - #[options(enforce_range = true)] - pub count: u32, - #[webidl(default = 0xFFFFFFFF)] - #[options(enforce_range = true)] - pub mask: u32, - #[webidl(default = false)] - pub alpha_to_coverage_enabled: bool, + #[webidl(default = 1)] + #[options(enforce_range = true)] + pub count: u32, + #[webidl(default = 0xFFFFFFFF)] + #[options(enforce_range = true)] + pub mask: u32, + #[webidl(default = false)] + pub alpha_to_coverage_enabled: bool, } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUDepthStencilState { - pub format: GPUTextureFormat, - pub depth_write_enabled: Option, - pub depth_compare: Option, - pub stencil_front: GPUStencilFaceState, - pub stencil_back: GPUStencilFaceState, - #[webidl(default = 0xFFFFFFFF)] - #[options(enforce_range = true)] - pub stencil_read_mask: u32, - #[webidl(default = 0xFFFFFFFF)] - #[options(enforce_range = true)] - pub stencil_write_mask: u32, - #[webidl(default = 0)] - #[options(enforce_range = true)] - pub depth_bias: i32, - #[webidl(default = 0.0)] - pub depth_bias_slope_scale: f32, - #[webidl(default = 0.0)] - pub depth_bias_clamp: f32, + pub format: GPUTextureFormat, + pub depth_write_enabled: Option, + pub depth_compare: Option, + pub stencil_front: GPUStencilFaceState, + pub stencil_back: GPUStencilFaceState, + #[webidl(default = 0xFFFFFFFF)] + #[options(enforce_range = true)] + pub stencil_read_mask: u32, + #[webidl(default = 0xFFFFFFFF)] + #[options(enforce_range = true)] + pub stencil_write_mask: u32, + #[webidl(default = 0)] + #[options(enforce_range = true)] + pub depth_bias: i32, + #[webidl(default = 0.0)] + pub depth_bias_slope_scale: f32, + #[webidl(default = 0.0)] + pub depth_bias_clamp: f32, } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUStencilFaceState { - #[webidl(default = GPUCompareFunction::Always)] - pub compare: GPUCompareFunction, - #[webidl(default = GPUStencilOperation::Keep)] - pub fail_op: GPUStencilOperation, - #[webidl(default = GPUStencilOperation::Keep)] - pub depth_fail_op: GPUStencilOperation, - #[webidl(default = GPUStencilOperation::Keep)] - pub pass_op: GPUStencilOperation, + #[webidl(default = GPUCompareFunction::Always)] + pub compare: GPUCompareFunction, + #[webidl(default = GPUStencilOperation::Keep)] + pub fail_op: GPUStencilOperation, + #[webidl(default = GPUStencilOperation::Keep)] + pub depth_fail_op: GPUStencilOperation, + #[webidl(default = GPUStencilOperation::Keep)] + pub pass_op: GPUStencilOperation, } #[derive(WebIDL)] #[webidl(enum)] pub(crate) enum GPUStencilOperation { - Keep, - Zero, - Replace, - Invert, - IncrementClamp, - DecrementClamp, - IncrementWrap, - DecrementWrap, + Keep, + Zero, + Replace, + Invert, + IncrementClamp, + DecrementClamp, + IncrementWrap, + DecrementWrap, } impl From for wgpu_types::StencilOperation { - fn from(value: GPUStencilOperation) -> Self { - match value { - GPUStencilOperation::Keep => Self::Keep, - GPUStencilOperation::Zero => Self::Zero, - GPUStencilOperation::Replace => Self::Replace, - GPUStencilOperation::Invert => Self::Invert, - GPUStencilOperation::IncrementClamp => Self::IncrementClamp, - GPUStencilOperation::DecrementClamp => Self::DecrementClamp, - GPUStencilOperation::IncrementWrap => Self::IncrementWrap, - GPUStencilOperation::DecrementWrap => Self::DecrementWrap, - } + fn from(value: GPUStencilOperation) -> Self { + match value { + GPUStencilOperation::Keep => Self::Keep, + GPUStencilOperation::Zero => Self::Zero, + GPUStencilOperation::Replace => Self::Replace, + GPUStencilOperation::Invert => Self::Invert, + GPUStencilOperation::IncrementClamp => Self::IncrementClamp, + GPUStencilOperation::DecrementClamp => Self::DecrementClamp, + GPUStencilOperation::IncrementWrap => Self::IncrementWrap, + GPUStencilOperation::DecrementWrap => Self::DecrementWrap, } + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUVertexState { - pub module: Ptr, - pub entry_point: Option, - #[webidl(default = Default::default())] - pub constants: IndexMap, - #[webidl(default = vec![])] - pub buffers: Vec>, + pub module: Ptr, + pub entry_point: Option, + #[webidl(default = Default::default())] + pub constants: IndexMap, + #[webidl(default = vec![])] + pub buffers: Vec>, } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUFragmentState { - pub module: Ptr, - pub entry_point: Option, - #[webidl(default = Default::default())] - pub constants: IndexMap, - pub targets: Vec>, + pub module: Ptr, + pub entry_point: Option, + #[webidl(default = Default::default())] + pub constants: IndexMap, + pub targets: Vec>, } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUColorTargetState { - pub format: GPUTextureFormat, - pub blend: Option, - #[webidl(default = 0xF)] - #[options(enforce_range = true)] - pub write_mask: u32, + pub format: GPUTextureFormat, + pub blend: Option, + #[webidl(default = 0xF)] + #[options(enforce_range = true)] + pub write_mask: u32, } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUBlendState { - pub color: GPUBlendComponent, - pub alpha: GPUBlendComponent, + pub color: GPUBlendComponent, + pub alpha: GPUBlendComponent, } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUBlendComponent { - #[webidl(default = GPUBlendOperation::Add)] - pub operation: GPUBlendOperation, - #[webidl(default = GPUBlendFactor::One)] - pub src_factor: GPUBlendFactor, - #[webidl(default = GPUBlendFactor::Zero)] - pub dst_factor: GPUBlendFactor, + #[webidl(default = GPUBlendOperation::Add)] + pub operation: GPUBlendOperation, + #[webidl(default = GPUBlendFactor::One)] + pub src_factor: GPUBlendFactor, + #[webidl(default = GPUBlendFactor::Zero)] + pub dst_factor: GPUBlendFactor, } #[derive(WebIDL)] #[webidl(enum)] pub(crate) enum GPUBlendOperation { - Add, - Subtract, - ReverseSubtract, - Min, - Max, + Add, + Subtract, + ReverseSubtract, + Min, + Max, } impl From for wgpu_types::BlendOperation { - fn from(value: GPUBlendOperation) -> Self { - match value { - GPUBlendOperation::Add => Self::Add, - GPUBlendOperation::Subtract => Self::Subtract, - GPUBlendOperation::ReverseSubtract => Self::ReverseSubtract, - GPUBlendOperation::Min => Self::Min, - GPUBlendOperation::Max => Self::Max, - } + fn from(value: GPUBlendOperation) -> Self { + match value { + GPUBlendOperation::Add => Self::Add, + GPUBlendOperation::Subtract => Self::Subtract, + GPUBlendOperation::ReverseSubtract => Self::ReverseSubtract, + GPUBlendOperation::Min => Self::Min, + GPUBlendOperation::Max => Self::Max, } + } } #[derive(WebIDL)] #[webidl(enum)] pub(crate) enum GPUBlendFactor { - #[webidl(rename = "zero")] - Zero, - #[webidl(rename = "one")] - One, - #[webidl(rename = "src")] - Src, - #[webidl(rename = "one-minus-src")] - OneMinusSrc, - #[webidl(rename = "src-alpha")] - SrcAlpha, - #[webidl(rename = "one-minus-src-alpha")] - OneMinusSrcAlpha, - #[webidl(rename = "dst")] - Dst, - #[webidl(rename = "one-minus-dst")] - OneMinusDst, - #[webidl(rename = "dst-alpha")] - DstAlpha, - #[webidl(rename = "one-minus-dst-alpha")] - OneMinusDstAlpha, - #[webidl(rename = "src-alpha-saturated")] - SrcAlphaSaturated, - #[webidl(rename = "constant")] - Constant, - #[webidl(rename = "one-minus-constant")] - OneMinusConstant, - #[webidl(rename = "src1")] - Src1, - #[webidl(rename = "one-minus-src1")] - OneMinusSrc1, - #[webidl(rename = "src1-alpha")] - Src1Alpha, - #[webidl(rename = "one-minus-src1-alpha")] - OneMinusSrc1Alpha, + #[webidl(rename = "zero")] + Zero, + #[webidl(rename = "one")] + One, + #[webidl(rename = "src")] + Src, + #[webidl(rename = "one-minus-src")] + OneMinusSrc, + #[webidl(rename = "src-alpha")] + SrcAlpha, + #[webidl(rename = "one-minus-src-alpha")] + OneMinusSrcAlpha, + #[webidl(rename = "dst")] + Dst, + #[webidl(rename = "one-minus-dst")] + OneMinusDst, + #[webidl(rename = "dst-alpha")] + DstAlpha, + #[webidl(rename = "one-minus-dst-alpha")] + OneMinusDstAlpha, + #[webidl(rename = "src-alpha-saturated")] + SrcAlphaSaturated, + #[webidl(rename = "constant")] + Constant, + #[webidl(rename = "one-minus-constant")] + OneMinusConstant, + #[webidl(rename = "src1")] + Src1, + #[webidl(rename = "one-minus-src1")] + OneMinusSrc1, + #[webidl(rename = "src1-alpha")] + Src1Alpha, + #[webidl(rename = "one-minus-src1-alpha")] + OneMinusSrc1Alpha, } impl From for wgpu_types::BlendFactor { - fn from(value: GPUBlendFactor) -> Self { - match value { - GPUBlendFactor::Zero => Self::Zero, - GPUBlendFactor::One => Self::One, - GPUBlendFactor::Src => Self::Src, - GPUBlendFactor::OneMinusSrc => Self::OneMinusSrc, - GPUBlendFactor::SrcAlpha => Self::SrcAlpha, - GPUBlendFactor::OneMinusSrcAlpha => Self::OneMinusSrcAlpha, - GPUBlendFactor::Dst => Self::Dst, - GPUBlendFactor::OneMinusDst => Self::OneMinusDst, - GPUBlendFactor::DstAlpha => Self::DstAlpha, - GPUBlendFactor::OneMinusDstAlpha => Self::OneMinusDstAlpha, - GPUBlendFactor::SrcAlphaSaturated => Self::SrcAlphaSaturated, - GPUBlendFactor::Constant => Self::Constant, - GPUBlendFactor::OneMinusConstant => Self::OneMinusConstant, - GPUBlendFactor::Src1 => Self::Src1, - GPUBlendFactor::OneMinusSrc1 => Self::OneMinusSrc1, - GPUBlendFactor::Src1Alpha => Self::Src1Alpha, - GPUBlendFactor::OneMinusSrc1Alpha => Self::OneMinusSrc1Alpha, - } + fn from(value: GPUBlendFactor) -> Self { + match value { + GPUBlendFactor::Zero => Self::Zero, + GPUBlendFactor::One => Self::One, + GPUBlendFactor::Src => Self::Src, + GPUBlendFactor::OneMinusSrc => Self::OneMinusSrc, + GPUBlendFactor::SrcAlpha => Self::SrcAlpha, + GPUBlendFactor::OneMinusSrcAlpha => Self::OneMinusSrcAlpha, + GPUBlendFactor::Dst => Self::Dst, + GPUBlendFactor::OneMinusDst => Self::OneMinusDst, + GPUBlendFactor::DstAlpha => Self::DstAlpha, + GPUBlendFactor::OneMinusDstAlpha => Self::OneMinusDstAlpha, + GPUBlendFactor::SrcAlphaSaturated => Self::SrcAlphaSaturated, + GPUBlendFactor::Constant => Self::Constant, + GPUBlendFactor::OneMinusConstant => Self::OneMinusConstant, + GPUBlendFactor::Src1 => Self::Src1, + GPUBlendFactor::OneMinusSrc1 => Self::OneMinusSrc1, + GPUBlendFactor::Src1Alpha => Self::Src1Alpha, + GPUBlendFactor::OneMinusSrc1Alpha => Self::OneMinusSrc1Alpha, } + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUPrimitiveState { - #[webidl(default = GPUPrimitiveTopology::TriangleList)] - pub topology: GPUPrimitiveTopology, - pub strip_index_format: Option, - #[webidl(default = GPUFrontFace::Ccw)] - pub front_face: GPUFrontFace, - #[webidl(default = GPUCullMode::None)] - pub cull_mode: GPUCullMode, - #[webidl(default = false)] - pub unclipped_depth: bool, + #[webidl(default = GPUPrimitiveTopology::TriangleList)] + pub topology: GPUPrimitiveTopology, + pub strip_index_format: Option, + #[webidl(default = GPUFrontFace::Ccw)] + pub front_face: GPUFrontFace, + #[webidl(default = GPUCullMode::None)] + pub cull_mode: GPUCullMode, + #[webidl(default = false)] + pub unclipped_depth: bool, } #[derive(WebIDL)] #[webidl(enum)] pub(crate) enum GPUPrimitiveTopology { - PointList, - LineList, - LineStrip, - TriangleList, - TriangleStrip, + PointList, + LineList, + LineStrip, + TriangleList, + TriangleStrip, } impl From for wgpu_types::PrimitiveTopology { - fn from(value: GPUPrimitiveTopology) -> Self { - match value { - GPUPrimitiveTopology::PointList => Self::PointList, - GPUPrimitiveTopology::LineList => Self::LineList, - GPUPrimitiveTopology::LineStrip => Self::LineStrip, - GPUPrimitiveTopology::TriangleList => Self::TriangleList, - GPUPrimitiveTopology::TriangleStrip => Self::TriangleStrip, - } + fn from(value: GPUPrimitiveTopology) -> Self { + match value { + GPUPrimitiveTopology::PointList => Self::PointList, + GPUPrimitiveTopology::LineList => Self::LineList, + GPUPrimitiveTopology::LineStrip => Self::LineStrip, + GPUPrimitiveTopology::TriangleList => Self::TriangleList, + GPUPrimitiveTopology::TriangleStrip => Self::TriangleStrip, } + } } #[derive(WebIDL)] #[webidl(enum)] pub(crate) enum GPUIndexFormat { - #[webidl(rename = "uint16")] - Uint16, - #[webidl(rename = "uint32")] - Uint32, + #[webidl(rename = "uint16")] + Uint16, + #[webidl(rename = "uint32")] + Uint32, } impl From for wgpu_types::IndexFormat { - fn from(value: GPUIndexFormat) -> Self { - match value { - GPUIndexFormat::Uint16 => Self::Uint16, - GPUIndexFormat::Uint32 => Self::Uint32, - } + fn from(value: GPUIndexFormat) -> Self { + match value { + GPUIndexFormat::Uint16 => Self::Uint16, + GPUIndexFormat::Uint32 => Self::Uint32, } + } } #[derive(WebIDL)] #[webidl(enum)] pub(crate) enum GPUFrontFace { - Ccw, - Cw, + Ccw, + Cw, } impl From for wgpu_types::FrontFace { - fn from(value: GPUFrontFace) -> Self { - match value { - GPUFrontFace::Ccw => Self::Ccw, - GPUFrontFace::Cw => Self::Cw, - } + fn from(value: GPUFrontFace) -> Self { + match value { + GPUFrontFace::Ccw => Self::Ccw, + GPUFrontFace::Cw => Self::Cw, } + } } #[derive(WebIDL)] #[webidl(enum)] pub(crate) enum GPUCullMode { - None, - Front, - Back, + None, + Front, + Back, } impl From for Option { - fn from(value: GPUCullMode) -> Self { - match value { - GPUCullMode::None => None, - GPUCullMode::Front => Some(wgpu_types::Face::Front), - GPUCullMode::Back => Some(wgpu_types::Face::Back), - } + fn from(value: GPUCullMode) -> Self { + match value { + GPUCullMode::None => None, + GPUCullMode::Front => Some(wgpu_types::Face::Front), + GPUCullMode::Back => Some(wgpu_types::Face::Back), } + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUVertexBufferLayout { - #[options(enforce_range = true)] - pub array_stride: u64, - #[webidl(default = GPUVertexStepMode::Vertex)] - pub step_mode: GPUVertexStepMode, - pub attributes: Vec, + #[options(enforce_range = true)] + pub array_stride: u64, + #[webidl(default = GPUVertexStepMode::Vertex)] + pub step_mode: GPUVertexStepMode, + pub attributes: Vec, } #[derive(WebIDL)] #[webidl(enum)] pub(crate) enum GPUVertexStepMode { - Vertex, - Instance, + Vertex, + Instance, } impl From for wgpu_types::VertexStepMode { - fn from(value: GPUVertexStepMode) -> Self { - match value { - GPUVertexStepMode::Vertex => Self::Vertex, - GPUVertexStepMode::Instance => Self::Instance, - } + fn from(value: GPUVertexStepMode) -> Self { + match value { + GPUVertexStepMode::Vertex => Self::Vertex, + GPUVertexStepMode::Instance => Self::Instance, } + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUVertexAttribute { - pub format: GPUVertexFormat, - #[options(enforce_range = true)] - pub offset: u64, - #[options(enforce_range = true)] - pub shader_location: u32, + pub format: GPUVertexFormat, + #[options(enforce_range = true)] + pub offset: u64, + #[options(enforce_range = true)] + pub shader_location: u32, } #[derive(WebIDL)] #[webidl(enum)] pub(crate) enum GPUVertexFormat { - // #[webidl(rename = "uint8")] - // Uint8, - #[webidl(rename = "uint8x2")] - Uint8x2, - #[webidl(rename = "uint8x4")] - Uint8x4, - // #[webidl(rename = "sint8")] - // Sint8, - #[webidl(rename = "sint8x2")] - Sint8x2, - #[webidl(rename = "sint8x4")] - Sint8x4, - // #[webidl(rename = "unorm8")] - // Unorm8, - #[webidl(rename = "unorm8x2")] - Unorm8x2, - #[webidl(rename = "unorm8x4")] - Unorm8x4, - // #[webidl(rename = "snorm8")] - // Snorm8, - #[webidl(rename = "snorm8x2")] - Snorm8x2, - #[webidl(rename = "snorm8x4")] - Snorm8x4, - // #[webidl(rename = "uint16")] - // Uint16, - #[webidl(rename = "uint16x2")] - Uint16x2, - #[webidl(rename = "uint16x4")] - Uint16x4, - // #[webidl(rename = "sint16")] - // Sint16, - #[webidl(rename = "sint16x2")] - Sint16x2, - #[webidl(rename = "sint16x4")] - Sint16x4, - // #[webidl(rename = "unorm16")] - // Unorm16, - #[webidl(rename = "unorm16x2")] - Unorm16x2, - #[webidl(rename = "unorm16x4")] - Unorm16x4, - // #[webidl(rename = "snorm16")] - // Snorm16, - #[webidl(rename = "snorm16x2")] - Snorm16x2, - #[webidl(rename = "snorm16x4")] - Snorm16x4, - // #[webidl(rename = "float16")] - // Float16, - #[webidl(rename = "float16x2")] - Float16x2, - #[webidl(rename = "float16x4")] - Float16x4, - #[webidl(rename = "float32")] - Float32, - #[webidl(rename = "float32x2")] - Float32x2, - #[webidl(rename = "float32x3")] - Float32x3, - #[webidl(rename = "float32x4")] - Float32x4, - #[webidl(rename = "uint32")] - Uint32, - #[webidl(rename = "uint32x2")] - Uint32x2, - #[webidl(rename = "uint32x3")] - Uint32x3, - #[webidl(rename = "uint32x4")] - Uint32x4, - #[webidl(rename = "sint32")] - Sint32, - #[webidl(rename = "sint32x2")] - Sint32x2, - #[webidl(rename = "sint32x3")] - Sint32x3, - #[webidl(rename = "sint32x4")] - Sint32x4, - #[webidl(rename = "unorm10-10-10-2")] - Unorm1010102, - // #[webidl(rename = "unorm8x4-bgra")] - // Unorm8x4Bgra, + #[webidl(rename = "uint8")] + Uint8, + #[webidl(rename = "uint8x2")] + Uint8x2, + #[webidl(rename = "uint8x4")] + Uint8x4, + #[webidl(rename = "sint8")] + Sint8, + #[webidl(rename = "sint8x2")] + Sint8x2, + #[webidl(rename = "sint8x4")] + Sint8x4, + #[webidl(rename = "unorm8")] + Unorm8, + #[webidl(rename = "unorm8x2")] + Unorm8x2, + #[webidl(rename = "unorm8x4")] + Unorm8x4, + #[webidl(rename = "snorm8")] + Snorm8, + #[webidl(rename = "snorm8x2")] + Snorm8x2, + #[webidl(rename = "snorm8x4")] + Snorm8x4, + #[webidl(rename = "uint16")] + Uint16, + #[webidl(rename = "uint16x2")] + Uint16x2, + #[webidl(rename = "uint16x4")] + Uint16x4, + #[webidl(rename = "sint16")] + Sint16, + #[webidl(rename = "sint16x2")] + Sint16x2, + #[webidl(rename = "sint16x4")] + Sint16x4, + #[webidl(rename = "unorm16")] + Unorm16, + #[webidl(rename = "unorm16x2")] + Unorm16x2, + #[webidl(rename = "unorm16x4")] + Unorm16x4, + #[webidl(rename = "snorm16")] + Snorm16, + #[webidl(rename = "snorm16x2")] + Snorm16x2, + #[webidl(rename = "snorm16x4")] + Snorm16x4, + #[webidl(rename = "float16")] + Float16, + #[webidl(rename = "float16x2")] + Float16x2, + #[webidl(rename = "float16x4")] + Float16x4, + #[webidl(rename = "float32")] + Float32, + #[webidl(rename = "float32x2")] + Float32x2, + #[webidl(rename = "float32x3")] + Float32x3, + #[webidl(rename = "float32x4")] + Float32x4, + #[webidl(rename = "uint32")] + Uint32, + #[webidl(rename = "uint32x2")] + Uint32x2, + #[webidl(rename = "uint32x3")] + Uint32x3, + #[webidl(rename = "uint32x4")] + Uint32x4, + #[webidl(rename = "sint32")] + Sint32, + #[webidl(rename = "sint32x2")] + Sint32x2, + #[webidl(rename = "sint32x3")] + Sint32x3, + #[webidl(rename = "sint32x4")] + Sint32x4, + #[webidl(rename = "unorm10-10-10-2")] + Unorm1010102, + #[webidl(rename = "unorm8x4-bgra")] + Unorm8x4Bgra, } impl From for wgpu_types::VertexFormat { - fn from(value: GPUVertexFormat) -> Self { - match value { - //GPUVertexFormat::Uint8 => Self::Uint8, - GPUVertexFormat::Uint8x2 => Self::Uint8x2, - GPUVertexFormat::Uint8x4 => Self::Uint8x4, - //GPUVertexFormat::Sint8 => Self::Sint8, - GPUVertexFormat::Sint8x2 => Self::Sint8x2, - GPUVertexFormat::Sint8x4 => Self::Sint8x4, - //GPUVertexFormat::Unorm8 => Self::Unorm8, - GPUVertexFormat::Unorm8x2 => Self::Unorm8x2, - GPUVertexFormat::Unorm8x4 => Self::Unorm8x4, - //GPUVertexFormat::Snorm8 => Self::Snorm8, - GPUVertexFormat::Snorm8x2 => Self::Snorm8x2, - GPUVertexFormat::Snorm8x4 => Self::Snorm8x4, - //GPUVertexFormat::Uint16 => Self::Uint16, - GPUVertexFormat::Uint16x2 => Self::Uint16x2, - GPUVertexFormat::Uint16x4 => Self::Uint16x4, - //GPUVertexFormat::Sint16 => Self::Sint16, - GPUVertexFormat::Sint16x2 => Self::Sint16x2, - GPUVertexFormat::Sint16x4 => Self::Sint16x4, - //GPUVertexFormat::Unorm16 => Self::Unorm16, - GPUVertexFormat::Unorm16x2 => Self::Unorm16x2, - GPUVertexFormat::Unorm16x4 => Self::Unorm16x4, - //GPUVertexFormat::Snorm16 => Self::Snorm16, - GPUVertexFormat::Snorm16x2 => Self::Snorm16x2, - GPUVertexFormat::Snorm16x4 => Self::Snorm16x4, - //GPUVertexFormat::Float16 => Self::Float16, - GPUVertexFormat::Float16x2 => Self::Float16x2, - GPUVertexFormat::Float16x4 => Self::Float16x4, - GPUVertexFormat::Float32 => Self::Float32, - GPUVertexFormat::Float32x2 => Self::Float32x2, - GPUVertexFormat::Float32x3 => Self::Float32x3, - GPUVertexFormat::Float32x4 => Self::Float32x4, - GPUVertexFormat::Uint32 => Self::Uint32, - GPUVertexFormat::Uint32x2 => Self::Uint32x2, - GPUVertexFormat::Uint32x3 => Self::Uint32x3, - GPUVertexFormat::Uint32x4 => Self::Uint32x4, - GPUVertexFormat::Sint32 => Self::Sint32, - GPUVertexFormat::Sint32x2 => Self::Sint32x2, - GPUVertexFormat::Sint32x3 => Self::Sint32x3, - GPUVertexFormat::Sint32x4 => Self::Sint32x4, - GPUVertexFormat::Unorm1010102 => Self::Unorm10_10_10_2, - //GPUVertexFormat::Unorm8x4Bgra => Self::Unorm8x4Bgra, - } + fn from(value: GPUVertexFormat) -> Self { + match value { + GPUVertexFormat::Uint8 => Self::Uint8, + GPUVertexFormat::Uint8x2 => Self::Uint8x2, + GPUVertexFormat::Uint8x4 => Self::Uint8x4, + GPUVertexFormat::Sint8 => Self::Sint8, + GPUVertexFormat::Sint8x2 => Self::Sint8x2, + GPUVertexFormat::Sint8x4 => Self::Sint8x4, + GPUVertexFormat::Unorm8 => Self::Unorm8, + GPUVertexFormat::Unorm8x2 => Self::Unorm8x2, + GPUVertexFormat::Unorm8x4 => Self::Unorm8x4, + GPUVertexFormat::Snorm8 => Self::Snorm8, + GPUVertexFormat::Snorm8x2 => Self::Snorm8x2, + GPUVertexFormat::Snorm8x4 => Self::Snorm8x4, + GPUVertexFormat::Uint16 => Self::Uint16, + GPUVertexFormat::Uint16x2 => Self::Uint16x2, + GPUVertexFormat::Uint16x4 => Self::Uint16x4, + GPUVertexFormat::Sint16 => Self::Sint16, + GPUVertexFormat::Sint16x2 => Self::Sint16x2, + GPUVertexFormat::Sint16x4 => Self::Sint16x4, + GPUVertexFormat::Unorm16 => Self::Unorm16, + GPUVertexFormat::Unorm16x2 => Self::Unorm16x2, + GPUVertexFormat::Unorm16x4 => Self::Unorm16x4, + GPUVertexFormat::Snorm16 => Self::Snorm16, + GPUVertexFormat::Snorm16x2 => Self::Snorm16x2, + GPUVertexFormat::Snorm16x4 => Self::Snorm16x4, + GPUVertexFormat::Float16 => Self::Float16, + GPUVertexFormat::Float16x2 => Self::Float16x2, + GPUVertexFormat::Float16x4 => Self::Float16x4, + GPUVertexFormat::Float32 => Self::Float32, + GPUVertexFormat::Float32x2 => Self::Float32x2, + GPUVertexFormat::Float32x3 => Self::Float32x3, + GPUVertexFormat::Float32x4 => Self::Float32x4, + GPUVertexFormat::Uint32 => Self::Uint32, + GPUVertexFormat::Uint32x2 => Self::Uint32x2, + GPUVertexFormat::Uint32x3 => Self::Uint32x3, + GPUVertexFormat::Uint32x4 => Self::Uint32x4, + GPUVertexFormat::Sint32 => Self::Sint32, + GPUVertexFormat::Sint32x2 => Self::Sint32x2, + GPUVertexFormat::Sint32x3 => Self::Sint32x3, + GPUVertexFormat::Sint32x4 => Self::Sint32x4, + GPUVertexFormat::Unorm1010102 => Self::Unorm10_10_10_2, + GPUVertexFormat::Unorm8x4Bgra => Self::Unorm8x4Bgra, } + } } diff --git a/deno_webgpu/rustfmt.toml b/deno_webgpu/rustfmt.toml new file mode 100644 index 000000000..9bb8d9d45 --- /dev/null +++ b/deno_webgpu/rustfmt.toml @@ -0,0 +1,3 @@ +max_width = 80 +tab_spaces = 2 +edition = "2021" diff --git a/deno_webgpu/sampler.rs b/deno_webgpu/sampler.rs index 46c08bc74..c1b5f483f 100644 --- a/deno_webgpu/sampler.rs +++ b/deno_webgpu/sampler.rs @@ -5,130 +5,156 @@ use deno_core::webidl::WebIdlInterfaceConverter; use deno_core::GarbageCollected; use deno_core::WebIDL; +use crate::error::GPUGenericError; use crate::Instance; pub struct GPUSampler { - pub instance: Instance, - pub id: wgpu_core::id::SamplerId, - pub label: String, + pub instance: Instance, + pub id: wgpu_core::id::SamplerId, + pub label: String, } impl Drop for GPUSampler { - fn drop(&mut self) { - self.instance.sampler_drop(self.id); - } + fn drop(&mut self) { + self.instance.sampler_drop(self.id); + } } impl WebIdlInterfaceConverter for GPUSampler { - const NAME: &'static str = "GPUSampler"; + const NAME: &'static str = "GPUSampler"; } -impl GarbageCollected for GPUSampler {} +impl GarbageCollected for GPUSampler { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUSampler" + } +} #[op2] impl GPUSampler { - #[getter] - #[string] - fn label(&self) -> String { - self.label.clone() - } - #[setter] - #[string] - fn label(&self, #[webidl] _label: String) { - // TODO(@crowlKats): no-op, needs wpgu to implement changing the label - } + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } + + #[getter] + #[string] + fn label(&self) -> String { + self.label.clone() + } + #[setter] + #[string] + fn label(&self, #[webidl] _label: String) { + // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(super) struct GPUSamplerDescriptor { - #[webidl(default = String::new())] - pub label: String, + #[webidl(default = String::new())] + pub label: String, - #[webidl(default = GPUAddressMode::ClampToEdge)] - pub address_mode_u: GPUAddressMode, - #[webidl(default = GPUAddressMode::ClampToEdge)] - pub address_mode_v: GPUAddressMode, - #[webidl(default = GPUAddressMode::ClampToEdge)] - pub address_mode_w: GPUAddressMode, - #[webidl(default = GPUFilterMode::Nearest)] - pub mag_filter: GPUFilterMode, - #[webidl(default = GPUFilterMode::Nearest)] - pub min_filter: GPUFilterMode, - #[webidl(default = GPUFilterMode::Nearest)] - pub mipmap_filter: GPUFilterMode, + #[webidl(default = GPUAddressMode::ClampToEdge)] + pub address_mode_u: GPUAddressMode, + #[webidl(default = GPUAddressMode::ClampToEdge)] + pub address_mode_v: GPUAddressMode, + #[webidl(default = GPUAddressMode::ClampToEdge)] + pub address_mode_w: GPUAddressMode, + #[webidl(default = GPUFilterMode::Nearest)] + pub mag_filter: GPUFilterMode, + #[webidl(default = GPUFilterMode::Nearest)] + pub min_filter: GPUFilterMode, + #[webidl(default = GPUMipmapFilterMode::Nearest)] + pub mipmap_filter: GPUMipmapFilterMode, - #[webidl(default = 0.0)] - pub lod_min_clamp: f32, - #[webidl(default = 32.0)] - pub lod_max_clamp: f32, + #[webidl(default = 0.0)] + pub lod_min_clamp: f32, + #[webidl(default = 32.0)] + pub lod_max_clamp: f32, - pub compare: Option, + pub compare: Option, - #[webidl(default = 1)] - #[options(clamp = true)] - pub max_anisotropy: u16, + #[webidl(default = 1)] + #[options(clamp = true)] + pub max_anisotropy: u16, } #[derive(WebIDL)] #[webidl(enum)] pub(crate) enum GPUAddressMode { - ClampToEdge, - Repeat, - MirrorRepeat, + ClampToEdge, + Repeat, + MirrorRepeat, } impl From for wgpu_types::AddressMode { - fn from(value: GPUAddressMode) -> Self { - match value { - GPUAddressMode::ClampToEdge => Self::ClampToEdge, - GPUAddressMode::Repeat => Self::Repeat, - GPUAddressMode::MirrorRepeat => Self::MirrorRepeat, - } + fn from(value: GPUAddressMode) -> Self { + match value { + GPUAddressMode::ClampToEdge => Self::ClampToEdge, + GPUAddressMode::Repeat => Self::Repeat, + GPUAddressMode::MirrorRepeat => Self::MirrorRepeat, } + } } -// Same as GPUMipmapFilterMode #[derive(WebIDL)] #[webidl(enum)] pub(crate) enum GPUFilterMode { - Nearest, - Linear, + Nearest, + Linear, } impl From for wgpu_types::FilterMode { - fn from(value: GPUFilterMode) -> Self { - match value { - GPUFilterMode::Nearest => Self::Nearest, - GPUFilterMode::Linear => Self::Linear, - } + fn from(value: GPUFilterMode) -> Self { + match value { + GPUFilterMode::Nearest => Self::Nearest, + GPUFilterMode::Linear => Self::Linear, } + } +} + +#[derive(WebIDL)] +#[webidl(enum)] +pub(crate) enum GPUMipmapFilterMode { + Nearest, + Linear, +} + +impl From for wgpu_types::MipmapFilterMode { + fn from(value: GPUMipmapFilterMode) -> Self { + match value { + GPUMipmapFilterMode::Nearest => Self::Nearest, + GPUMipmapFilterMode::Linear => Self::Linear, + } + } } #[derive(WebIDL)] #[webidl(enum)] pub(crate) enum GPUCompareFunction { - Never, - Less, - Equal, - LessEqual, - Greater, - NotEqual, - GreaterEqual, - Always, + Never, + Less, + Equal, + LessEqual, + Greater, + NotEqual, + GreaterEqual, + Always, } impl From for wgpu_types::CompareFunction { - fn from(value: GPUCompareFunction) -> Self { - match value { - GPUCompareFunction::Never => Self::Never, - GPUCompareFunction::Less => Self::Less, - GPUCompareFunction::Equal => Self::Equal, - GPUCompareFunction::LessEqual => Self::LessEqual, - GPUCompareFunction::Greater => Self::Greater, - GPUCompareFunction::NotEqual => Self::NotEqual, - GPUCompareFunction::GreaterEqual => Self::GreaterEqual, - GPUCompareFunction::Always => Self::Always, - } + fn from(value: GPUCompareFunction) -> Self { + match value { + GPUCompareFunction::Never => Self::Never, + GPUCompareFunction::Less => Self::Less, + GPUCompareFunction::Equal => Self::Equal, + GPUCompareFunction::LessEqual => Self::LessEqual, + GPUCompareFunction::Greater => Self::Greater, + GPUCompareFunction::NotEqual => Self::NotEqual, + GPUCompareFunction::GreaterEqual => Self::GreaterEqual, + GPUCompareFunction::Always => Self::Always, } + } } diff --git a/deno_webgpu/shader.rs b/deno_webgpu/shader.rs index 6b91bebb0..49a81a83c 100644 --- a/deno_webgpu/shader.rs +++ b/deno_webgpu/shader.rs @@ -1,49 +1,226 @@ // Copyright 2018-2025 the Deno authors. MIT license. +use deno_core::cppgc::make_cppgc_object; use deno_core::op2; +use deno_core::v8; use deno_core::webidl::WebIdlInterfaceConverter; use deno_core::GarbageCollected; use deno_core::WebIDL; +use wgpu_core::pipeline; +use crate::error::GPUGenericError; use crate::Instance; pub struct GPUShaderModule { - pub instance: Instance, - pub id: wgpu_core::id::ShaderModuleId, - pub label: String, + pub instance: Instance, + pub id: wgpu_core::id::ShaderModuleId, + pub label: String, + pub compilation_info: v8::Global, } impl Drop for GPUShaderModule { - fn drop(&mut self) { - self.instance.shader_module_drop(self.id); - } + fn drop(&mut self) { + self.instance.shader_module_drop(self.id); + } } impl WebIdlInterfaceConverter for GPUShaderModule { - const NAME: &'static str = "GPUShaderModule"; + const NAME: &'static str = "GPUShaderModule"; } -impl GarbageCollected for GPUShaderModule {} +impl GarbageCollected for GPUShaderModule { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUShaderModule" + } +} #[op2] impl GPUShaderModule { - #[getter] - #[string] - fn label(&self) -> String { - self.label.clone() - } - #[setter] - #[string] - fn label(&self, #[webidl] _label: String) { - // TODO(@crowlKats): no-op, needs wpgu to implement changing the label - } + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } + + #[getter] + #[string] + fn label(&self) -> String { + self.label.clone() + } + #[setter] + #[string] + fn label(&self, #[webidl] _label: String) { + // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + } + + fn get_compilation_info<'a>( + &self, + scope: &mut v8::HandleScope<'a>, + ) -> v8::Local<'a, v8::Promise> { + let resolver = v8::PromiseResolver::new(scope).unwrap(); + let info = v8::Local::new(scope, self.compilation_info.clone()); + resolver.resolve(scope, info.into()).unwrap(); + resolver.get_promise(scope) + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUShaderModuleDescriptor { - #[webidl(default = String::new())] - pub label: String, + #[webidl(default = String::new())] + pub label: String, - pub code: String, + pub code: String, +} + +pub struct GPUCompilationMessage { + message: String, + r#type: GPUCompilationMessageType, + line_num: u64, + line_pos: u64, + offset: u64, + length: u64, +} + +impl GarbageCollected for GPUCompilationMessage { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUCompilationMessage" + } +} + +#[op2] +impl GPUCompilationMessage { + #[getter] + #[string] + fn message(&self) -> String { + self.message.clone() + } + + #[getter] + #[string] + #[rename("type")] + fn r#type(&self) -> &'static str { + self.r#type.as_str() + } + + #[getter] + #[number] + fn line_num(&self) -> u64 { + self.line_num + } + + #[getter] + #[number] + fn line_pos(&self) -> u64 { + self.line_pos + } + + #[getter] + #[number] + fn offset(&self) -> u64 { + self.offset + } + + #[getter] + #[number] + fn length(&self) -> u64 { + self.length + } +} + +impl GPUCompilationMessage { + fn new(error: &pipeline::CreateShaderModuleError, source: &str) -> Self { + let message = error.to_string(); + + let loc = match error { + pipeline::CreateShaderModuleError::Parsing(e) => e.inner.location(source), + pipeline::CreateShaderModuleError::Validation(e) => { + e.inner.location(source) + } + _ => None, + }; + + match loc { + Some(loc) => { + let len_utf16 = |s: &str| s.chars().map(|c| c.len_utf16() as u64).sum(); + + let start = loc.offset as usize; + + // Naga reports a `line_pos` using UTF-8 bytes, so we cannot use it. + let line_start = + source[0..start].rfind('\n').map(|pos| pos + 1).unwrap_or(0); + let line_pos = len_utf16(&source[line_start..start]) + 1; + + Self { + message, + r#type: GPUCompilationMessageType::Error, + line_num: loc.line_number.into(), + line_pos, + offset: len_utf16(&source[0..start]), + length: len_utf16(&source[start..start + loc.length as usize]), + } + } + _ => Self { + message, + r#type: GPUCompilationMessageType::Error, + line_num: 0, + line_pos: 0, + offset: 0, + length: 0, + }, + } + } +} + +pub struct GPUCompilationInfo { + messages: v8::Global, +} + +impl GarbageCollected for GPUCompilationInfo { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUCompilationInfo" + } +} + +#[op2] +impl GPUCompilationInfo { + #[getter] + #[global] + fn messages(&self) -> v8::Global { + self.messages.clone() + } +} + +impl GPUCompilationInfo { + pub fn new<'args, 'scope>( + scope: &mut v8::HandleScope<'scope>, + messages: impl ExactSizeIterator< + Item = &'args pipeline::CreateShaderModuleError, + >, + source: &'args str, + ) -> Self { + let array = v8::Array::new(scope, messages.len().try_into().unwrap()); + for (i, message) in messages.enumerate() { + let message_object = + make_cppgc_object(scope, GPUCompilationMessage::new(message, source)); + array.set_index(scope, i.try_into().unwrap(), message_object.into()); + } + + let object: v8::Local = array.into(); + object + .set_integrity_level(scope, v8::IntegrityLevel::Frozen) + .unwrap(); + + Self { + messages: v8::Global::new(scope, object), + } + } +} + +#[derive(WebIDL, Clone)] +#[webidl(enum)] +pub(crate) enum GPUCompilationMessageType { + Error, + Warning, + Info, } diff --git a/deno_webgpu/surface.rs b/deno_webgpu/surface.rs index 8c8445a9a..60df27ce0 100644 --- a/deno_webgpu/surface.rs +++ b/deno_webgpu/surface.rs @@ -2,228 +2,273 @@ use std::cell::RefCell; -use deno_core::op2; -use deno_core::v8; use deno_core::GarbageCollected; use deno_core::WebIDL; use deno_core::_ops::make_cppgc_object; use deno_core::cppgc::Ptr; +use deno_core::op2; +use deno_core::v8; use deno_error::JsErrorBox; use wgpu_types::SurfaceStatus; use crate::device::GPUDevice; +use crate::error::GPUGenericError; use crate::texture::GPUTexture; use crate::texture::GPUTextureFormat; #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum SurfaceError { - #[class("DOMExceptionInvalidStateError")] - #[error("Context is not configured")] - UnconfiguredContext, - #[class(generic)] - #[error("Invalid Surface Status")] - InvalidStatus, - #[class(generic)] - #[error(transparent)] - Surface(#[from] wgpu_core::present::SurfaceError), + #[class("DOMExceptionInvalidStateError")] + #[error("Context is not configured")] + UnconfiguredContext, + #[class(generic)] + #[error("Invalid Surface Status")] + InvalidStatus, + #[class(generic)] + #[error(transparent)] + Surface(#[from] wgpu_core::present::SurfaceError), } pub struct Configuration { - pub device: Ptr, - pub usage: u32, - pub format: GPUTextureFormat, + pub device: Ptr, + pub usage: u32, + pub format: GPUTextureFormat, + pub surface_config: + wgpu_types::SurfaceConfiguration>, } pub struct GPUCanvasContext { - pub surface_id: wgpu_core::id::SurfaceId, - pub width: RefCell, - pub height: RefCell, + pub surface_id: wgpu_core::id::SurfaceId, + pub width: RefCell, + pub height: RefCell, - pub config: RefCell>, - pub texture: RefCell>>, + pub config: RefCell>, + pub texture: RefCell>>, - pub canvas: v8::Global, + pub canvas: v8::Global, } -impl GarbageCollected for GPUCanvasContext {} +impl GarbageCollected for GPUCanvasContext { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUCanvasContext" + } +} #[op2] impl GPUCanvasContext { - #[getter] - #[global] - fn canvas(&self) -> v8::Global { - self.canvas.clone() + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } + + #[getter] + #[global] + fn canvas(&self) -> v8::Global { + self.canvas.clone() + } + + #[undefined] + fn configure( + &self, + #[webidl] configuration: GPUCanvasConfiguration, + ) -> Result<(), JsErrorBox> { + let usage = wgpu_types::TextureUsages::from_bits(configuration.usage) + .ok_or_else(|| JsErrorBox::type_error("usage is not valid"))?; + let format = configuration.format.clone().into(); + let conf = wgpu_types::SurfaceConfiguration { + usage, + format, + width: *self.width.borrow(), + height: *self.height.borrow(), + present_mode: configuration + .present_mode + .map(Into::into) + .unwrap_or_default(), + alpha_mode: configuration.alpha_mode.into(), + view_formats: configuration + .view_formats + .into_iter() + .map(Into::into) + .collect(), + desired_maximum_frame_latency: 2, + }; + + let device = configuration.device; + + let err = + device + .instance + .surface_configure(self.surface_id, device.id, &conf); + + device.error_handler.push_error(err); + + self.config.borrow_mut().replace(Configuration { + device, + usage: configuration.usage, + format: configuration.format, + surface_config: conf, + }); + + Ok(()) + } + + #[fast] + #[undefined] + fn unconfigure(&self) { + *self.config.borrow_mut() = None; + } + + #[global] + fn get_current_texture( + &self, + scope: &mut v8::HandleScope, + ) -> Result, SurfaceError> { + let config = self.config.borrow(); + let Some(config) = config.as_ref() else { + return Err(SurfaceError::UnconfiguredContext); + }; + + { + if let Some(obj) = self.texture.borrow().as_ref() { + return Ok(obj.clone()); + } } - fn configure(&self, #[webidl] configuration: GPUCanvasConfiguration) -> Result<(), JsErrorBox> { - let usage = wgpu_types::TextureUsages::from_bits(configuration.usage) - .ok_or_else(|| JsErrorBox::type_error("usage is not valid"))?; - let format = configuration.format.clone().into(); - let conf = wgpu_types::SurfaceConfiguration { - usage, - format, + let output = config + .device + .instance + .surface_get_current_texture(self.surface_id, None)?; + + match output.status { + SurfaceStatus::Good | SurfaceStatus::Suboptimal => { + let id = output.texture.unwrap(); + + let texture = GPUTexture { + instance: config.device.instance.clone(), + error_handler: config.device.error_handler.clone(), + id, + default_view_id: Default::default(), + label: "".to_string(), + size: wgpu_types::Extent3d { width: *self.width.borrow(), height: *self.height.borrow(), - present_mode: configuration - .present_mode - .map(Into::into) - .unwrap_or_default(), - alpha_mode: configuration.alpha_mode.into(), - view_formats: configuration - .view_formats - .into_iter() - .map(Into::into) - .collect(), - desired_maximum_frame_latency: 2, + depth_or_array_layers: 1, + }, + mip_level_count: 0, + sample_count: 0, + dimension: crate::texture::GPUTextureDimension::D2, + format: config.format.clone(), + usage: config.usage, }; + let obj = make_cppgc_object(scope, texture); + let obj = v8::Global::new(scope, obj); + *self.texture.borrow_mut() = Some(obj.clone()); - let device = configuration.device; - - let err = device - .instance - .surface_configure(self.surface_id, device.id, &conf); - - device.error_handler.push_error(err); - - self.config.borrow_mut().replace(Configuration { - device, - usage: configuration.usage, - format: configuration.format, - }); - - Ok(()) - } - - #[fast] - fn unconfigure(&self) { - *self.config.borrow_mut() = None; - } - - #[global] - fn get_current_texture( - &self, - scope: &mut v8::HandleScope, - ) -> Result, SurfaceError> { - let config = self.config.borrow(); - let Some(config) = config.as_ref() else { - return Err(SurfaceError::UnconfiguredContext); - }; - - { - if let Some(obj) = self.texture.borrow().as_ref() { - return Ok(obj.clone()); - } - } - - let output = config - .device - .instance - .surface_get_current_texture(self.surface_id, None)?; - - match output.status { - SurfaceStatus::Good | SurfaceStatus::Suboptimal => { - let id = output.texture.unwrap(); - - let texture = GPUTexture { - instance: config.device.instance.clone(), - error_handler: config.device.error_handler.clone(), - id, - label: "".to_string(), - size: wgpu_types::Extent3d { - width: *self.width.borrow(), - height: *self.height.borrow(), - depth_or_array_layers: 1, - }, - mip_level_count: 0, - sample_count: 0, - dimension: crate::texture::GPUTextureDimension::D2, - format: config.format.clone(), - usage: config.usage, - }; - let obj = make_cppgc_object(scope, texture); - let obj = v8::Global::new(scope, obj); - *self.texture.borrow_mut() = Some(obj.clone()); - - Ok(obj) - } - _ => Err(SurfaceError::InvalidStatus), - } + Ok(obj) + } + _ => Err(SurfaceError::InvalidStatus), } + } } impl GPUCanvasContext { - pub fn present(&self) -> Result<(), SurfaceError> { - let config = self.config.borrow(); - let Some(config) = config.as_ref() else { - return Err(SurfaceError::UnconfiguredContext); - }; + pub fn present(&self) -> Result<(), SurfaceError> { + let config = self.config.borrow(); + let Some(config) = config.as_ref() else { + return Err(SurfaceError::UnconfiguredContext); + }; - config.device.instance.surface_present(self.surface_id)?; + config.device.instance.surface_present(self.surface_id)?; - Ok(()) - } + // next `get_current_texture` call would get a new texture + *self.texture.borrow_mut() = None; + + Ok(()) + } + + pub fn resize_configure(&self, width: u32, height: u32) { + self.width.replace(width); + self.height.replace(height); + + let mut config = self.config.borrow_mut(); + let Some(config) = &mut *config else { + return; + }; + + config.surface_config.width = width; + config.surface_config.height = height; + + let err = config.device.instance.surface_configure( + self.surface_id, + config.device.id, + &config.surface_config, + ); + + config.device.error_handler.push_error(err); + } } #[derive(WebIDL)] #[webidl(dictionary)] struct GPUCanvasConfiguration { - device: Ptr, - format: GPUTextureFormat, - #[webidl(default = wgpu_types::TextureUsages::RENDER_ATTACHMENT.bits())] - #[options(enforce_range = true)] - usage: u32, - #[webidl(default = GPUCanvasAlphaMode::Opaque)] - alpha_mode: GPUCanvasAlphaMode, + device: Ptr, + format: GPUTextureFormat, + #[webidl(default = wgpu_types::TextureUsages::RENDER_ATTACHMENT.bits())] + #[options(enforce_range = true)] + usage: u32, + #[webidl(default = GPUCanvasAlphaMode::Opaque)] + alpha_mode: GPUCanvasAlphaMode, - // Extended from spec - present_mode: Option, - #[webidl(default = vec![])] - view_formats: Vec, + // Extended from spec + present_mode: Option, + #[webidl(default = vec![])] + view_formats: Vec, } #[derive(WebIDL)] #[webidl(enum)] enum GPUCanvasAlphaMode { - Opaque, - Premultiplied, + Opaque, + Premultiplied, } impl From for wgpu_types::CompositeAlphaMode { - fn from(value: GPUCanvasAlphaMode) -> Self { - match value { - GPUCanvasAlphaMode::Opaque => Self::Opaque, - GPUCanvasAlphaMode::Premultiplied => Self::PreMultiplied, - } + fn from(value: GPUCanvasAlphaMode) -> Self { + match value { + GPUCanvasAlphaMode::Opaque => Self::Opaque, + GPUCanvasAlphaMode::Premultiplied => Self::PreMultiplied, } + } } // Extended from spec #[derive(WebIDL)] #[webidl(enum)] enum GPUPresentMode { - #[webidl(rename = "autoVsync")] - AutoVsync, - #[webidl(rename = "autoNoVsync")] - AutoNoVsync, - #[webidl(rename = "fifo")] - Fifo, - #[webidl(rename = "fifoRelaxed")] - FifoRelaxed, - #[webidl(rename = "immediate")] - Immediate, - #[webidl(rename = "mailbox")] - Mailbox, + #[webidl(rename = "autoVsync")] + AutoVsync, + #[webidl(rename = "autoNoVsync")] + AutoNoVsync, + #[webidl(rename = "fifo")] + Fifo, + #[webidl(rename = "fifoRelaxed")] + FifoRelaxed, + #[webidl(rename = "immediate")] + Immediate, + #[webidl(rename = "mailbox")] + Mailbox, } impl From for wgpu_types::PresentMode { - fn from(value: GPUPresentMode) -> Self { - match value { - GPUPresentMode::AutoVsync => Self::AutoVsync, - GPUPresentMode::AutoNoVsync => Self::AutoNoVsync, - GPUPresentMode::Fifo => Self::Fifo, - GPUPresentMode::FifoRelaxed => Self::FifoRelaxed, - GPUPresentMode::Immediate => Self::Immediate, - GPUPresentMode::Mailbox => Self::Mailbox, - } + fn from(value: GPUPresentMode) -> Self { + match value { + GPUPresentMode::AutoVsync => Self::AutoVsync, + GPUPresentMode::AutoNoVsync => Self::AutoNoVsync, + GPUPresentMode::Fifo => Self::Fifo, + GPUPresentMode::FifoRelaxed => Self::FifoRelaxed, + GPUPresentMode::Immediate => Self::Immediate, + GPUPresentMode::Mailbox => Self::Mailbox, } + } } diff --git a/deno_webgpu/texture.rs b/deno_webgpu/texture.rs index 4ecaa3220..8d92d7f30 100644 --- a/deno_webgpu/texture.rs +++ b/deno_webgpu/texture.rs @@ -1,5 +1,7 @@ // Copyright 2018-2025 the Deno authors. MIT license. +use std::sync::OnceLock; + use deno_core::op2; use deno_core::webidl::WebIdlInterfaceConverter; use deno_core::GarbageCollected; @@ -13,652 +15,716 @@ use wgpu_types::TextureDimension; use wgpu_types::TextureFormat; use wgpu_types::TextureViewDimension; +use crate::error::GPUGenericError; use crate::Instance; #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUTextureDescriptor { - #[webidl(default = String::new())] - pub label: String, + #[webidl(default = String::new())] + pub label: String, - pub size: super::webidl::GPUExtent3D, - #[webidl(default = 1)] - #[options(enforce_range = true)] - pub mip_level_count: u32, - #[webidl(default = 1)] - #[options(enforce_range = true)] - pub sample_count: u32, - #[webidl(default = GPUTextureDimension::D2)] - pub dimension: GPUTextureDimension, - pub format: GPUTextureFormat, - #[options(enforce_range = true)] - pub usage: u32, - #[webidl(default = vec![])] - pub view_formats: Vec, + pub size: super::webidl::GPUExtent3D, + #[webidl(default = 1)] + #[options(enforce_range = true)] + pub mip_level_count: u32, + #[webidl(default = 1)] + #[options(enforce_range = true)] + pub sample_count: u32, + #[webidl(default = GPUTextureDimension::D2)] + pub dimension: GPUTextureDimension, + pub format: GPUTextureFormat, + #[options(enforce_range = true)] + pub usage: u32, + #[webidl(default = vec![])] + pub view_formats: Vec, } pub struct GPUTexture { - pub instance: Instance, - pub error_handler: super::error::ErrorHandler, + pub instance: Instance, + pub error_handler: super::error::ErrorHandler, - pub id: wgpu_core::id::TextureId, + pub id: wgpu_core::id::TextureId, + pub default_view_id: OnceLock, - pub label: String, + pub label: String, - pub size: Extent3d, - pub mip_level_count: u32, - pub sample_count: u32, - pub dimension: GPUTextureDimension, - pub format: GPUTextureFormat, - pub usage: u32, + pub size: Extent3d, + pub mip_level_count: u32, + pub sample_count: u32, + pub dimension: GPUTextureDimension, + pub format: GPUTextureFormat, + pub usage: u32, +} + +impl GPUTexture { + pub(crate) fn default_view_id(&self) -> wgpu_core::id::TextureViewId { + *self.default_view_id.get_or_init(|| { + let (id, err) = + self + .instance + .texture_create_view(self.id, &Default::default(), None); + if let Some(err) = err { + use wgpu_types::error::WebGpuError; + assert_ne!( + err.webgpu_error_type(), + wgpu_types::error::ErrorType::Validation, + concat!( + "getting default view for a texture ", + "caused a validation error (!?)" + ) + ); + self.error_handler.push_error(Some(err)); + } + id + }) + } } impl Drop for GPUTexture { - fn drop(&mut self) { - self.instance.texture_drop(self.id); + fn drop(&mut self) { + if let Some(id) = self.default_view_id.take() { + self.instance.texture_view_drop(id).unwrap(); } + self.instance.texture_drop(self.id); + } } impl WebIdlInterfaceConverter for GPUTexture { - const NAME: &'static str = "GPUTexture"; + const NAME: &'static str = "GPUTexture"; } -impl GarbageCollected for GPUTexture {} +impl GarbageCollected for GPUTexture { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUTexture" + } +} #[op2] impl GPUTexture { - #[getter] - #[string] - fn label(&self) -> String { - self.label.clone() - } - #[setter] - #[string] - fn label(&self, #[webidl] _label: String) { - // TODO(@crowlKats): no-op, needs wpgu to implement changing the label - } + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } - #[getter] - fn width(&self) -> u32 { - self.size.width - } - #[getter] - fn height(&self) -> u32 { - self.size.height - } - #[getter] - fn depth_or_array_layers(&self) -> u32 { - self.size.depth_or_array_layers - } - #[getter] - fn mip_level_count(&self) -> u32 { - self.mip_level_count - } - #[getter] - fn sample_count(&self) -> u32 { - self.sample_count - } - #[getter] - #[string] - fn dimension(&self) -> &'static str { - self.dimension.as_str() - } - #[getter] - #[string] - fn format(&self) -> &'static str { - self.format.as_str() - } - #[getter] - fn usage(&self) -> u32 { - self.usage - } - #[fast] - fn destroy(&self) -> Result<(), JsErrorBox> { - self.instance - .texture_destroy(self.id) - .map_err(|e| JsErrorBox::generic(e.to_string())) - } + #[getter] + #[string] + fn label(&self) -> String { + self.label.clone() + } + #[setter] + #[string] + fn label(&self, #[webidl] _label: String) { + // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + } - #[cppgc] - fn create_view( - &self, - #[webidl] descriptor: GPUTextureViewDescriptor, - ) -> Result { - let wgpu_descriptor = wgpu_core::resource::TextureViewDescriptor { - label: crate::transform_label(descriptor.label.clone()), - format: descriptor.format.map(Into::into), - dimension: descriptor.dimension.map(Into::into), - usage: Some( - wgpu_types::TextureUsages::from_bits(descriptor.usage) - .ok_or_else(|| JsErrorBox::type_error("usage is not valid"))?, - ), - range: wgpu_types::ImageSubresourceRange { - aspect: descriptor.aspect.into(), - base_mip_level: descriptor.base_mip_level, - mip_level_count: descriptor.mip_level_count, - base_array_layer: descriptor.base_array_layer, - array_layer_count: descriptor.array_layer_count, - }, - }; + #[getter] + fn width(&self) -> u32 { + self.size.width + } + #[getter] + fn height(&self) -> u32 { + self.size.height + } + #[getter] + fn depth_or_array_layers(&self) -> u32 { + self.size.depth_or_array_layers + } + #[getter] + fn mip_level_count(&self) -> u32 { + self.mip_level_count + } + #[getter] + fn sample_count(&self) -> u32 { + self.sample_count + } + #[getter] + #[string] + fn dimension(&self) -> &'static str { + self.dimension.as_str() + } + #[getter] + #[string] + fn format(&self) -> &'static str { + self.format.as_str() + } + #[getter] + fn usage(&self) -> u32 { + self.usage + } + #[fast] + #[undefined] + fn destroy(&self) { + self.instance.texture_destroy(self.id); + } - let (id, err) = self - .instance - .texture_create_view(self.id, &wgpu_descriptor, None); + #[cppgc] + fn create_view( + &self, + #[webidl] descriptor: GPUTextureViewDescriptor, + ) -> Result { + let wgpu_descriptor = wgpu_core::resource::TextureViewDescriptor { + label: crate::transform_label(descriptor.label.clone()), + format: descriptor.format.map(Into::into), + dimension: descriptor.dimension.map(Into::into), + usage: Some( + wgpu_types::TextureUsages::from_bits(descriptor.usage) + .ok_or_else(|| JsErrorBox::type_error("usage is not valid"))?, + ), + range: wgpu_types::ImageSubresourceRange { + aspect: descriptor.aspect.into(), + base_mip_level: descriptor.base_mip_level, + mip_level_count: descriptor.mip_level_count, + base_array_layer: descriptor.base_array_layer, + array_layer_count: descriptor.array_layer_count, + }, + }; - self.error_handler.push_error(err); + let (id, err) = + self + .instance + .texture_create_view(self.id, &wgpu_descriptor, None); - Ok(GPUTextureView { - instance: self.instance.clone(), - id, - label: descriptor.label, - }) - } + self.error_handler.push_error(err); + + Ok(GPUTextureView { + instance: self.instance.clone(), + id, + label: descriptor.label, + }) + } } #[derive(WebIDL)] #[webidl(dictionary)] struct GPUTextureViewDescriptor { - #[webidl(default = String::new())] - label: String, + #[webidl(default = String::new())] + label: String, - format: Option, - dimension: Option, - #[webidl(default = 0)] - #[options(enforce_range = true)] - usage: u32, - #[webidl(default = GPUTextureAspect::All)] - aspect: GPUTextureAspect, - #[webidl(default = 0)] - #[options(enforce_range = true)] - base_mip_level: u32, - #[options(enforce_range = true)] - mip_level_count: Option, - #[webidl(default = 0)] - #[options(enforce_range = true)] - base_array_layer: u32, - #[options(enforce_range = true)] - array_layer_count: Option, + format: Option, + dimension: Option, + #[webidl(default = 0)] + #[options(enforce_range = true)] + usage: u32, + #[webidl(default = GPUTextureAspect::All)] + aspect: GPUTextureAspect, + #[webidl(default = 0)] + #[options(enforce_range = true)] + base_mip_level: u32, + #[options(enforce_range = true)] + mip_level_count: Option, + #[webidl(default = 0)] + #[options(enforce_range = true)] + base_array_layer: u32, + #[options(enforce_range = true)] + array_layer_count: Option, } #[derive(WebIDL)] #[webidl(enum)] pub(crate) enum GPUTextureViewDimension { - #[webidl(rename = "1d")] - D1, - #[webidl(rename = "2d")] - D2, - #[webidl(rename = "2d-array")] - D2Array, - #[webidl(rename = "cube")] - Cube, - #[webidl(rename = "cube-array")] - CubeArray, - #[webidl(rename = "3d")] - D3, + #[webidl(rename = "1d")] + D1, + #[webidl(rename = "2d")] + D2, + #[webidl(rename = "2d-array")] + D2Array, + #[webidl(rename = "cube")] + Cube, + #[webidl(rename = "cube-array")] + CubeArray, + #[webidl(rename = "3d")] + D3, } impl From for TextureViewDimension { - fn from(value: GPUTextureViewDimension) -> Self { - match value { - GPUTextureViewDimension::D1 => Self::D1, - GPUTextureViewDimension::D2 => Self::D2, - GPUTextureViewDimension::D3 => Self::D3, - GPUTextureViewDimension::D2Array => Self::D2Array, - GPUTextureViewDimension::Cube => Self::Cube, - GPUTextureViewDimension::CubeArray => Self::CubeArray, - } + fn from(value: GPUTextureViewDimension) -> Self { + match value { + GPUTextureViewDimension::D1 => Self::D1, + GPUTextureViewDimension::D2 => Self::D2, + GPUTextureViewDimension::D3 => Self::D3, + GPUTextureViewDimension::D2Array => Self::D2Array, + GPUTextureViewDimension::Cube => Self::Cube, + GPUTextureViewDimension::CubeArray => Self::CubeArray, } + } } #[derive(WebIDL)] #[webidl(enum)] pub enum GPUTextureAspect { - All, - StencilOnly, - DepthOnly, + All, + StencilOnly, + DepthOnly, } impl From for TextureAspect { - fn from(value: GPUTextureAspect) -> Self { - match value { - GPUTextureAspect::All => Self::All, - GPUTextureAspect::StencilOnly => Self::StencilOnly, - GPUTextureAspect::DepthOnly => Self::DepthOnly, - } + fn from(value: GPUTextureAspect) -> Self { + match value { + GPUTextureAspect::All => Self::All, + GPUTextureAspect::StencilOnly => Self::StencilOnly, + GPUTextureAspect::DepthOnly => Self::DepthOnly, } + } } pub struct GPUTextureView { - pub instance: Instance, - pub id: wgpu_core::id::TextureViewId, - pub label: String, + pub instance: Instance, + pub id: wgpu_core::id::TextureViewId, + pub label: String, } impl Drop for GPUTextureView { - fn drop(&mut self) { - let _ = self.instance.texture_view_drop(self.id); - } + fn drop(&mut self) { + let _ = self.instance.texture_view_drop(self.id); + } } impl WebIdlInterfaceConverter for GPUTextureView { - const NAME: &'static str = "GPUTextureView"; + const NAME: &'static str = "GPUTextureView"; } -impl GarbageCollected for GPUTextureView {} +impl GarbageCollected for GPUTextureView { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUTextureView" + } +} // TODO(@crowlKats): weakref in texture for view #[op2] impl GPUTextureView { - #[getter] - #[string] - fn label(&self) -> String { - self.label.clone() - } - #[setter] - #[string] - fn label(&self, #[webidl] _label: String) { - // TODO(@crowlKats): no-op, needs wpgu to implement changing the label - } + #[constructor] + #[cppgc] + fn constructor(_: bool) -> Result { + Err(GPUGenericError::InvalidConstructor) + } + + #[getter] + #[string] + fn label(&self) -> String { + self.label.clone() + } + #[setter] + #[string] + fn label(&self, #[webidl] _label: String) { + // TODO(@crowlKats): no-op, needs wpgu to implement changing the label + } } #[derive(WebIDL, Clone)] #[webidl(enum)] pub enum GPUTextureDimension { - #[webidl(rename = "1d")] - D1, - #[webidl(rename = "2d")] - D2, - #[webidl(rename = "3d")] - D3, + #[webidl(rename = "1d")] + D1, + #[webidl(rename = "2d")] + D2, + #[webidl(rename = "3d")] + D3, } impl From for TextureDimension { - fn from(value: GPUTextureDimension) -> Self { - match value { - GPUTextureDimension::D1 => Self::D1, - GPUTextureDimension::D2 => Self::D2, - GPUTextureDimension::D3 => Self::D3, - } + fn from(value: GPUTextureDimension) -> Self { + match value { + GPUTextureDimension::D1 => Self::D1, + GPUTextureDimension::D2 => Self::D2, + GPUTextureDimension::D3 => Self::D3, } + } } #[derive(WebIDL, Clone)] #[webidl(enum)] pub(crate) enum GPUTextureFormat { - #[webidl(rename = "r8unorm")] - R8unorm, - #[webidl(rename = "r8snorm")] - R8snorm, - #[webidl(rename = "r8uint")] - R8uint, - #[webidl(rename = "r8sint")] - R8sint, - #[webidl(rename = "r16uint")] - R16uint, - #[webidl(rename = "r16sint")] - R16sint, - #[webidl(rename = "r16float")] - R16float, - #[webidl(rename = "rg8unorm")] - Rg8unorm, - #[webidl(rename = "rg8snorm")] - Rg8snorm, - #[webidl(rename = "rg8uint")] - Rg8uint, - #[webidl(rename = "rg8sint")] - Rg8sint, - #[webidl(rename = "r32uint")] - R32uint, - #[webidl(rename = "r32sint")] - R32sint, - #[webidl(rename = "r32float")] - R32float, - #[webidl(rename = "rg16uint")] - Rg16uint, - #[webidl(rename = "rg16sint")] - Rg16sint, - #[webidl(rename = "rg16float")] - Rg16float, - #[webidl(rename = "rgba8unorm")] - Rgba8unorm, - #[webidl(rename = "rgba8unorm-srgb")] - Rgba8unormSrgb, - #[webidl(rename = "rgba8snorm")] - Rgba8snorm, - #[webidl(rename = "rgba8uint")] - Rgba8uint, - #[webidl(rename = "rgba8sint")] - Rgba8sint, - #[webidl(rename = "bgra8unorm")] - Bgra8unorm, - #[webidl(rename = "bgra8unorm-srgb")] - Bgra8unormSrgb, - #[webidl(rename = "rgb9e5ufloat")] - Rgb9e5ufloat, - #[webidl(rename = "rgb10a2uint")] - Rgb10a2uint, - #[webidl(rename = "rgb10a2unorm")] - Rgb10a2unorm, - #[webidl(rename = "rg11b10ufloat")] - Rg11b10ufloat, - #[webidl(rename = "rg32uint")] - Rg32uint, - #[webidl(rename = "rg32sint")] - Rg32sint, - #[webidl(rename = "rg32float")] - Rg32float, - #[webidl(rename = "rgba16uint")] - Rgba16uint, - #[webidl(rename = "rgba16sint")] - Rgba16sint, - #[webidl(rename = "rgba16float")] - Rgba16float, - #[webidl(rename = "rgba32uint")] - Rgba32uint, - #[webidl(rename = "rgba32sint")] - Rgba32sint, - #[webidl(rename = "rgba32float")] - Rgba32float, - #[webidl(rename = "stencil8")] - Stencil8, - #[webidl(rename = "depth16unorm")] - Depth16unorm, - #[webidl(rename = "depth24plus")] - Depth24plus, - #[webidl(rename = "depth24plus-stencil8")] - Depth24plusStencil8, - #[webidl(rename = "depth32float")] - Depth32float, - #[webidl(rename = "depth32float-stencil8")] - Depth32floatStencil8, - #[webidl(rename = "bc1-rgba-unorm")] - Bc1RgbaUnorm, - #[webidl(rename = "bc1-rgba-unorm-srgb")] - Bc1RgbaUnormSrgb, - #[webidl(rename = "bc2-rgba-unorm")] - Bc2RgbaUnorm, - #[webidl(rename = "bc2-rgba-unorm-srgb")] - Bc2RgbaUnormSrgb, - #[webidl(rename = "bc3-rgba-unorm")] - Bc3RgbaUnorm, - #[webidl(rename = "bc3-rgba-unorm-srgb")] - Bc3RgbaUnormSrgb, - #[webidl(rename = "bc4-r-unorm")] - Bc4RUnorm, - #[webidl(rename = "bc4-r-snorm")] - Bc4RSnorm, - #[webidl(rename = "bc5-rg-unorm")] - Bc5RgUnorm, - #[webidl(rename = "bc5-rg-snorm")] - Bc5RgSnorm, - #[webidl(rename = "bc6h-rgb-ufloat")] - Bc6hRgbUfloat, - #[webidl(rename = "bc6h-rgb-float")] - Bc6hRgbFloat, - #[webidl(rename = "bc7-rgba-unorm")] - Bc7RgbaUnorm, - #[webidl(rename = "bc7-rgba-unorm-srgb")] - Bc7RgbaUnormSrgb, - #[webidl(rename = "etc2-rgb8unorm")] - Etc2Rgb8unorm, - #[webidl(rename = "etc2-rgb8unorm-srgb")] - Etc2Rgb8unormSrgb, - #[webidl(rename = "etc2-rgb8a1unorm")] - Etc2Rgb8a1unorm, - #[webidl(rename = "etc2-rgb8a1unorm-srgb")] - Etc2Rgb8a1unormSrgb, - #[webidl(rename = "etc2-rgba8unorm")] - Etc2Rgba8unorm, - #[webidl(rename = "etc2-rgba8unorm-srgb")] - Etc2Rgba8unormSrgb, - #[webidl(rename = "eac-r11unorm")] - EacR11unorm, - #[webidl(rename = "eac-r11snorm")] - EacR11snorm, - #[webidl(rename = "eac-rg11unorm")] - EacRg11unorm, - #[webidl(rename = "eac-rg11snorm")] - EacRg11snorm, - #[webidl(rename = "astc-4x4-unorm")] - Astc4x4Unorm, - #[webidl(rename = "astc-4x4-unorm-srgb")] - Astc4x4UnormSrgb, - #[webidl(rename = "astc-5x4-unorm")] - Astc5x4Unorm, - #[webidl(rename = "astc-5x4-unorm-srgb")] - Astc5x4UnormSrgb, - #[webidl(rename = "astc-5x5-unorm")] - Astc5x5Unorm, - #[webidl(rename = "astc-5x5-unorm-srgb")] - Astc5x5UnormSrgb, - #[webidl(rename = "astc-6x5-unorm")] - Astc6x5Unorm, - #[webidl(rename = "astc-6x5-unorm-srgb")] - Astc6x5UnormSrgb, - #[webidl(rename = "astc-6x6-unorm")] - Astc6x6Unorm, - #[webidl(rename = "astc-6x6-unorm-srgb")] - Astc6x6UnormSrgb, - #[webidl(rename = "astc-8x5-unorm")] - Astc8x5Unorm, - #[webidl(rename = "astc-8x5-unorm-srgb")] - Astc8x5UnormSrgb, - #[webidl(rename = "astc-8x6-unorm")] - Astc8x6Unorm, - #[webidl(rename = "astc-8x6-unorm-srgb")] - Astc8x6UnormSrgb, - #[webidl(rename = "astc-8x8-unorm")] - Astc8x8Unorm, - #[webidl(rename = "astc-8x8-unorm-srgb")] - Astc8x8UnormSrgb, - #[webidl(rename = "astc-10x5-unorm")] - Astc10x5Unorm, - #[webidl(rename = "astc-10x5-unorm-srgb")] - Astc10x5UnormSrgb, - #[webidl(rename = "astc-10x6-unorm")] - Astc10x6Unorm, - #[webidl(rename = "astc-10x6-unorm-srgb")] - Astc10x6UnormSrgb, - #[webidl(rename = "astc-10x8-unorm")] - Astc10x8Unorm, - #[webidl(rename = "astc-10x8-unorm-srgb")] - Astc10x8UnormSrgb, - #[webidl(rename = "astc-10x10-unorm")] - Astc10x10Unorm, - #[webidl(rename = "astc-10x10-unorm-srgb")] - Astc10x10UnormSrgb, - #[webidl(rename = "astc-12x10-unorm")] - Astc12x10Unorm, - #[webidl(rename = "astc-12x10-unorm-srgb")] - Astc12x10UnormSrgb, - #[webidl(rename = "astc-12x12-unorm")] - Astc12x12Unorm, - #[webidl(rename = "astc-12x12-unorm-srgb")] - Astc12x12UnormSrgb, + #[webidl(rename = "r8unorm")] + R8unorm, + #[webidl(rename = "r8snorm")] + R8snorm, + #[webidl(rename = "r8uint")] + R8uint, + #[webidl(rename = "r8sint")] + R8sint, + #[webidl(rename = "r16uint")] + R16uint, + #[webidl(rename = "r16sint")] + R16sint, + #[webidl(rename = "r16float")] + R16float, + #[webidl(rename = "rg8unorm")] + Rg8unorm, + #[webidl(rename = "rg8snorm")] + Rg8snorm, + #[webidl(rename = "rg8uint")] + Rg8uint, + #[webidl(rename = "rg8sint")] + Rg8sint, + #[webidl(rename = "r32uint")] + R32uint, + #[webidl(rename = "r32sint")] + R32sint, + #[webidl(rename = "r32float")] + R32float, + #[webidl(rename = "rg16uint")] + Rg16uint, + #[webidl(rename = "rg16sint")] + Rg16sint, + #[webidl(rename = "rg16float")] + Rg16float, + #[webidl(rename = "rgba8unorm")] + Rgba8unorm, + #[webidl(rename = "rgba8unorm-srgb")] + Rgba8unormSrgb, + #[webidl(rename = "rgba8snorm")] + Rgba8snorm, + #[webidl(rename = "rgba8uint")] + Rgba8uint, + #[webidl(rename = "rgba8sint")] + Rgba8sint, + #[webidl(rename = "bgra8unorm")] + Bgra8unorm, + #[webidl(rename = "bgra8unorm-srgb")] + Bgra8unormSrgb, + #[webidl(rename = "rgb9e5ufloat")] + Rgb9e5ufloat, + #[webidl(rename = "rgb10a2uint")] + Rgb10a2uint, + #[webidl(rename = "rgb10a2unorm")] + Rgb10a2unorm, + #[webidl(rename = "rg11b10ufloat")] + Rg11b10ufloat, + #[webidl(rename = "rg32uint")] + Rg32uint, + #[webidl(rename = "rg32sint")] + Rg32sint, + #[webidl(rename = "rg32float")] + Rg32float, + #[webidl(rename = "rgba16uint")] + Rgba16uint, + #[webidl(rename = "rgba16sint")] + Rgba16sint, + #[webidl(rename = "rgba16float")] + Rgba16float, + #[webidl(rename = "rgba32uint")] + Rgba32uint, + #[webidl(rename = "rgba32sint")] + Rgba32sint, + #[webidl(rename = "rgba32float")] + Rgba32float, + #[webidl(rename = "stencil8")] + Stencil8, + #[webidl(rename = "depth16unorm")] + Depth16unorm, + #[webidl(rename = "depth24plus")] + Depth24plus, + #[webidl(rename = "depth24plus-stencil8")] + Depth24plusStencil8, + #[webidl(rename = "depth32float")] + Depth32float, + #[webidl(rename = "depth32float-stencil8")] + Depth32floatStencil8, + #[webidl(rename = "bc1-rgba-unorm")] + Bc1RgbaUnorm, + #[webidl(rename = "bc1-rgba-unorm-srgb")] + Bc1RgbaUnormSrgb, + #[webidl(rename = "bc2-rgba-unorm")] + Bc2RgbaUnorm, + #[webidl(rename = "bc2-rgba-unorm-srgb")] + Bc2RgbaUnormSrgb, + #[webidl(rename = "bc3-rgba-unorm")] + Bc3RgbaUnorm, + #[webidl(rename = "bc3-rgba-unorm-srgb")] + Bc3RgbaUnormSrgb, + #[webidl(rename = "bc4-r-unorm")] + Bc4RUnorm, + #[webidl(rename = "bc4-r-snorm")] + Bc4RSnorm, + #[webidl(rename = "bc5-rg-unorm")] + Bc5RgUnorm, + #[webidl(rename = "bc5-rg-snorm")] + Bc5RgSnorm, + #[webidl(rename = "bc6h-rgb-ufloat")] + Bc6hRgbUfloat, + #[webidl(rename = "bc6h-rgb-float")] + Bc6hRgbFloat, + #[webidl(rename = "bc7-rgba-unorm")] + Bc7RgbaUnorm, + #[webidl(rename = "bc7-rgba-unorm-srgb")] + Bc7RgbaUnormSrgb, + #[webidl(rename = "etc2-rgb8unorm")] + Etc2Rgb8unorm, + #[webidl(rename = "etc2-rgb8unorm-srgb")] + Etc2Rgb8unormSrgb, + #[webidl(rename = "etc2-rgb8a1unorm")] + Etc2Rgb8a1unorm, + #[webidl(rename = "etc2-rgb8a1unorm-srgb")] + Etc2Rgb8a1unormSrgb, + #[webidl(rename = "etc2-rgba8unorm")] + Etc2Rgba8unorm, + #[webidl(rename = "etc2-rgba8unorm-srgb")] + Etc2Rgba8unormSrgb, + #[webidl(rename = "eac-r11unorm")] + EacR11unorm, + #[webidl(rename = "eac-r11snorm")] + EacR11snorm, + #[webidl(rename = "eac-rg11unorm")] + EacRg11unorm, + #[webidl(rename = "eac-rg11snorm")] + EacRg11snorm, + #[webidl(rename = "astc-4x4-unorm")] + Astc4x4Unorm, + #[webidl(rename = "astc-4x4-unorm-srgb")] + Astc4x4UnormSrgb, + #[webidl(rename = "astc-5x4-unorm")] + Astc5x4Unorm, + #[webidl(rename = "astc-5x4-unorm-srgb")] + Astc5x4UnormSrgb, + #[webidl(rename = "astc-5x5-unorm")] + Astc5x5Unorm, + #[webidl(rename = "astc-5x5-unorm-srgb")] + Astc5x5UnormSrgb, + #[webidl(rename = "astc-6x5-unorm")] + Astc6x5Unorm, + #[webidl(rename = "astc-6x5-unorm-srgb")] + Astc6x5UnormSrgb, + #[webidl(rename = "astc-6x6-unorm")] + Astc6x6Unorm, + #[webidl(rename = "astc-6x6-unorm-srgb")] + Astc6x6UnormSrgb, + #[webidl(rename = "astc-8x5-unorm")] + Astc8x5Unorm, + #[webidl(rename = "astc-8x5-unorm-srgb")] + Astc8x5UnormSrgb, + #[webidl(rename = "astc-8x6-unorm")] + Astc8x6Unorm, + #[webidl(rename = "astc-8x6-unorm-srgb")] + Astc8x6UnormSrgb, + #[webidl(rename = "astc-8x8-unorm")] + Astc8x8Unorm, + #[webidl(rename = "astc-8x8-unorm-srgb")] + Astc8x8UnormSrgb, + #[webidl(rename = "astc-10x5-unorm")] + Astc10x5Unorm, + #[webidl(rename = "astc-10x5-unorm-srgb")] + Astc10x5UnormSrgb, + #[webidl(rename = "astc-10x6-unorm")] + Astc10x6Unorm, + #[webidl(rename = "astc-10x6-unorm-srgb")] + Astc10x6UnormSrgb, + #[webidl(rename = "astc-10x8-unorm")] + Astc10x8Unorm, + #[webidl(rename = "astc-10x8-unorm-srgb")] + Astc10x8UnormSrgb, + #[webidl(rename = "astc-10x10-unorm")] + Astc10x10Unorm, + #[webidl(rename = "astc-10x10-unorm-srgb")] + Astc10x10UnormSrgb, + #[webidl(rename = "astc-12x10-unorm")] + Astc12x10Unorm, + #[webidl(rename = "astc-12x10-unorm-srgb")] + Astc12x10UnormSrgb, + #[webidl(rename = "astc-12x12-unorm")] + Astc12x12Unorm, + #[webidl(rename = "astc-12x12-unorm-srgb")] + Astc12x12UnormSrgb, } impl From for TextureFormat { - fn from(value: GPUTextureFormat) -> Self { - match value { - GPUTextureFormat::R8unorm => Self::R8Unorm, - GPUTextureFormat::R8snorm => Self::R8Snorm, - GPUTextureFormat::R8uint => Self::R8Uint, - GPUTextureFormat::R8sint => Self::R8Sint, - GPUTextureFormat::R16uint => Self::R16Uint, - GPUTextureFormat::R16sint => Self::R16Sint, - GPUTextureFormat::R16float => Self::R16Float, - GPUTextureFormat::Rg8unorm => Self::Rg8Unorm, - GPUTextureFormat::Rg8snorm => Self::Rg8Snorm, - GPUTextureFormat::Rg8uint => Self::Rg8Uint, - GPUTextureFormat::Rg8sint => Self::Rg8Sint, - GPUTextureFormat::R32uint => Self::R32Uint, - GPUTextureFormat::R32sint => Self::R32Sint, - GPUTextureFormat::R32float => Self::R32Float, - GPUTextureFormat::Rg16uint => Self::Rg16Uint, - GPUTextureFormat::Rg16sint => Self::Rg16Sint, - GPUTextureFormat::Rg16float => Self::Rg16Float, - GPUTextureFormat::Rgba8unorm => Self::Rgba8Unorm, - GPUTextureFormat::Rgba8unormSrgb => Self::Rgba8UnormSrgb, - GPUTextureFormat::Rgba8snorm => Self::Rgba8Snorm, - GPUTextureFormat::Rgba8uint => Self::Rgba8Uint, - GPUTextureFormat::Rgba8sint => Self::Rgba8Sint, - GPUTextureFormat::Bgra8unorm => Self::Bgra8Unorm, - GPUTextureFormat::Bgra8unormSrgb => Self::Bgra8UnormSrgb, - GPUTextureFormat::Rgb9e5ufloat => Self::Rgb9e5Ufloat, - GPUTextureFormat::Rgb10a2uint => Self::Rgb10a2Uint, - GPUTextureFormat::Rgb10a2unorm => Self::Rgb10a2Unorm, - GPUTextureFormat::Rg11b10ufloat => Self::Rg11b10Ufloat, - GPUTextureFormat::Rg32uint => Self::Rg32Uint, - GPUTextureFormat::Rg32sint => Self::Rg32Sint, - GPUTextureFormat::Rg32float => Self::Rg32Float, - GPUTextureFormat::Rgba16uint => Self::Rgba16Uint, - GPUTextureFormat::Rgba16sint => Self::Rgba16Sint, - GPUTextureFormat::Rgba16float => Self::Rgba16Float, - GPUTextureFormat::Rgba32uint => Self::Rgba32Uint, - GPUTextureFormat::Rgba32sint => Self::Rgba32Sint, - GPUTextureFormat::Rgba32float => Self::Rgba32Float, - GPUTextureFormat::Stencil8 => Self::Stencil8, - GPUTextureFormat::Depth16unorm => Self::Depth16Unorm, - GPUTextureFormat::Depth24plus => Self::Depth24Plus, - GPUTextureFormat::Depth24plusStencil8 => Self::Depth24PlusStencil8, - GPUTextureFormat::Depth32float => Self::Depth32Float, - GPUTextureFormat::Depth32floatStencil8 => Self::Depth32FloatStencil8, - GPUTextureFormat::Bc1RgbaUnorm => Self::Bc1RgbaUnorm, - GPUTextureFormat::Bc1RgbaUnormSrgb => Self::Bc1RgbaUnormSrgb, - GPUTextureFormat::Bc2RgbaUnorm => Self::Bc2RgbaUnorm, - GPUTextureFormat::Bc2RgbaUnormSrgb => Self::Bc2RgbaUnormSrgb, - GPUTextureFormat::Bc3RgbaUnorm => Self::Bc3RgbaUnorm, - GPUTextureFormat::Bc3RgbaUnormSrgb => Self::Bc3RgbaUnormSrgb, - GPUTextureFormat::Bc4RUnorm => Self::Bc4RUnorm, - GPUTextureFormat::Bc4RSnorm => Self::Bc4RSnorm, - GPUTextureFormat::Bc5RgUnorm => Self::Bc5RgUnorm, - GPUTextureFormat::Bc5RgSnorm => Self::Bc5RgSnorm, - GPUTextureFormat::Bc6hRgbUfloat => Self::Bc6hRgbUfloat, - GPUTextureFormat::Bc6hRgbFloat => Self::Bc6hRgbFloat, - GPUTextureFormat::Bc7RgbaUnorm => Self::Bc7RgbaUnorm, - GPUTextureFormat::Bc7RgbaUnormSrgb => Self::Bc7RgbaUnormSrgb, - GPUTextureFormat::Etc2Rgb8unorm => Self::Etc2Rgb8Unorm, - GPUTextureFormat::Etc2Rgb8unormSrgb => Self::Etc2Rgb8UnormSrgb, - GPUTextureFormat::Etc2Rgb8a1unorm => Self::Etc2Rgb8A1Unorm, - GPUTextureFormat::Etc2Rgb8a1unormSrgb => Self::Etc2Rgb8A1UnormSrgb, - GPUTextureFormat::Etc2Rgba8unorm => Self::Etc2Rgba8Unorm, - GPUTextureFormat::Etc2Rgba8unormSrgb => Self::Etc2Rgba8UnormSrgb, - GPUTextureFormat::EacR11unorm => Self::EacR11Unorm, - GPUTextureFormat::EacR11snorm => Self::EacR11Snorm, - GPUTextureFormat::EacRg11unorm => Self::EacRg11Unorm, - GPUTextureFormat::EacRg11snorm => Self::EacRg11Snorm, - GPUTextureFormat::Astc4x4Unorm => Self::Astc { - block: AstcBlock::B4x4, - channel: AstcChannel::Unorm, - }, - GPUTextureFormat::Astc4x4UnormSrgb => Self::Astc { - block: AstcBlock::B5x4, - channel: AstcChannel::UnormSrgb, - }, - GPUTextureFormat::Astc5x4Unorm => Self::Astc { - block: AstcBlock::B5x4, - channel: AstcChannel::Unorm, - }, - GPUTextureFormat::Astc5x4UnormSrgb => Self::Astc { - block: AstcBlock::B5x4, - channel: AstcChannel::UnormSrgb, - }, - GPUTextureFormat::Astc5x5Unorm => Self::Astc { - block: AstcBlock::B5x5, - channel: AstcChannel::Unorm, - }, - GPUTextureFormat::Astc5x5UnormSrgb => Self::Astc { - block: AstcBlock::B5x5, - channel: AstcChannel::UnormSrgb, - }, - GPUTextureFormat::Astc6x5Unorm => Self::Astc { - block: AstcBlock::B6x5, - channel: AstcChannel::Unorm, - }, - GPUTextureFormat::Astc6x5UnormSrgb => Self::Astc { - block: AstcBlock::B6x5, - channel: AstcChannel::UnormSrgb, - }, - GPUTextureFormat::Astc6x6Unorm => Self::Astc { - block: AstcBlock::B6x6, - channel: AstcChannel::Unorm, - }, - GPUTextureFormat::Astc6x6UnormSrgb => Self::Astc { - block: AstcBlock::B6x6, - channel: AstcChannel::UnormSrgb, - }, - GPUTextureFormat::Astc8x5Unorm => Self::Astc { - block: AstcBlock::B8x5, - channel: AstcChannel::Unorm, - }, - GPUTextureFormat::Astc8x5UnormSrgb => Self::Astc { - block: AstcBlock::B8x5, - channel: AstcChannel::UnormSrgb, - }, - GPUTextureFormat::Astc8x6Unorm => Self::Astc { - block: AstcBlock::B8x6, - channel: AstcChannel::Unorm, - }, - GPUTextureFormat::Astc8x6UnormSrgb => Self::Astc { - block: AstcBlock::B8x6, - channel: AstcChannel::UnormSrgb, - }, - GPUTextureFormat::Astc8x8Unorm => Self::Astc { - block: AstcBlock::B8x8, - channel: AstcChannel::Unorm, - }, - GPUTextureFormat::Astc8x8UnormSrgb => Self::Astc { - block: AstcBlock::B8x8, - channel: AstcChannel::UnormSrgb, - }, - GPUTextureFormat::Astc10x5Unorm => Self::Astc { - block: AstcBlock::B10x5, - channel: AstcChannel::Unorm, - }, - GPUTextureFormat::Astc10x5UnormSrgb => Self::Astc { - block: AstcBlock::B10x5, - channel: AstcChannel::UnormSrgb, - }, - GPUTextureFormat::Astc10x6Unorm => Self::Astc { - block: AstcBlock::B10x6, - channel: AstcChannel::Unorm, - }, - GPUTextureFormat::Astc10x6UnormSrgb => Self::Astc { - block: AstcBlock::B10x6, - channel: AstcChannel::UnormSrgb, - }, - GPUTextureFormat::Astc10x8Unorm => Self::Astc { - block: AstcBlock::B10x8, - channel: AstcChannel::Unorm, - }, - GPUTextureFormat::Astc10x8UnormSrgb => Self::Astc { - block: AstcBlock::B10x8, - channel: AstcChannel::UnormSrgb, - }, - GPUTextureFormat::Astc10x10Unorm => Self::Astc { - block: AstcBlock::B10x10, - channel: AstcChannel::Unorm, - }, - GPUTextureFormat::Astc10x10UnormSrgb => Self::Astc { - block: AstcBlock::B10x10, - channel: AstcChannel::UnormSrgb, - }, - GPUTextureFormat::Astc12x10Unorm => Self::Astc { - block: AstcBlock::B12x10, - channel: AstcChannel::Unorm, - }, - GPUTextureFormat::Astc12x10UnormSrgb => Self::Astc { - block: AstcBlock::B12x10, - channel: AstcChannel::UnormSrgb, - }, - GPUTextureFormat::Astc12x12Unorm => Self::Astc { - block: AstcBlock::B12x12, - channel: AstcChannel::Unorm, - }, - GPUTextureFormat::Astc12x12UnormSrgb => Self::Astc { - block: AstcBlock::B12x12, - channel: AstcChannel::UnormSrgb, - }, - } + fn from(value: GPUTextureFormat) -> Self { + match value { + GPUTextureFormat::R8unorm => Self::R8Unorm, + GPUTextureFormat::R8snorm => Self::R8Snorm, + GPUTextureFormat::R8uint => Self::R8Uint, + GPUTextureFormat::R8sint => Self::R8Sint, + GPUTextureFormat::R16uint => Self::R16Uint, + GPUTextureFormat::R16sint => Self::R16Sint, + GPUTextureFormat::R16float => Self::R16Float, + GPUTextureFormat::Rg8unorm => Self::Rg8Unorm, + GPUTextureFormat::Rg8snorm => Self::Rg8Snorm, + GPUTextureFormat::Rg8uint => Self::Rg8Uint, + GPUTextureFormat::Rg8sint => Self::Rg8Sint, + GPUTextureFormat::R32uint => Self::R32Uint, + GPUTextureFormat::R32sint => Self::R32Sint, + GPUTextureFormat::R32float => Self::R32Float, + GPUTextureFormat::Rg16uint => Self::Rg16Uint, + GPUTextureFormat::Rg16sint => Self::Rg16Sint, + GPUTextureFormat::Rg16float => Self::Rg16Float, + GPUTextureFormat::Rgba8unorm => Self::Rgba8Unorm, + GPUTextureFormat::Rgba8unormSrgb => Self::Rgba8UnormSrgb, + GPUTextureFormat::Rgba8snorm => Self::Rgba8Snorm, + GPUTextureFormat::Rgba8uint => Self::Rgba8Uint, + GPUTextureFormat::Rgba8sint => Self::Rgba8Sint, + GPUTextureFormat::Bgra8unorm => Self::Bgra8Unorm, + GPUTextureFormat::Bgra8unormSrgb => Self::Bgra8UnormSrgb, + GPUTextureFormat::Rgb9e5ufloat => Self::Rgb9e5Ufloat, + GPUTextureFormat::Rgb10a2uint => Self::Rgb10a2Uint, + GPUTextureFormat::Rgb10a2unorm => Self::Rgb10a2Unorm, + GPUTextureFormat::Rg11b10ufloat => Self::Rg11b10Ufloat, + GPUTextureFormat::Rg32uint => Self::Rg32Uint, + GPUTextureFormat::Rg32sint => Self::Rg32Sint, + GPUTextureFormat::Rg32float => Self::Rg32Float, + GPUTextureFormat::Rgba16uint => Self::Rgba16Uint, + GPUTextureFormat::Rgba16sint => Self::Rgba16Sint, + GPUTextureFormat::Rgba16float => Self::Rgba16Float, + GPUTextureFormat::Rgba32uint => Self::Rgba32Uint, + GPUTextureFormat::Rgba32sint => Self::Rgba32Sint, + GPUTextureFormat::Rgba32float => Self::Rgba32Float, + GPUTextureFormat::Stencil8 => Self::Stencil8, + GPUTextureFormat::Depth16unorm => Self::Depth16Unorm, + GPUTextureFormat::Depth24plus => Self::Depth24Plus, + GPUTextureFormat::Depth24plusStencil8 => Self::Depth24PlusStencil8, + GPUTextureFormat::Depth32float => Self::Depth32Float, + GPUTextureFormat::Depth32floatStencil8 => Self::Depth32FloatStencil8, + GPUTextureFormat::Bc1RgbaUnorm => Self::Bc1RgbaUnorm, + GPUTextureFormat::Bc1RgbaUnormSrgb => Self::Bc1RgbaUnormSrgb, + GPUTextureFormat::Bc2RgbaUnorm => Self::Bc2RgbaUnorm, + GPUTextureFormat::Bc2RgbaUnormSrgb => Self::Bc2RgbaUnormSrgb, + GPUTextureFormat::Bc3RgbaUnorm => Self::Bc3RgbaUnorm, + GPUTextureFormat::Bc3RgbaUnormSrgb => Self::Bc3RgbaUnormSrgb, + GPUTextureFormat::Bc4RUnorm => Self::Bc4RUnorm, + GPUTextureFormat::Bc4RSnorm => Self::Bc4RSnorm, + GPUTextureFormat::Bc5RgUnorm => Self::Bc5RgUnorm, + GPUTextureFormat::Bc5RgSnorm => Self::Bc5RgSnorm, + GPUTextureFormat::Bc6hRgbUfloat => Self::Bc6hRgbUfloat, + GPUTextureFormat::Bc6hRgbFloat => Self::Bc6hRgbFloat, + GPUTextureFormat::Bc7RgbaUnorm => Self::Bc7RgbaUnorm, + GPUTextureFormat::Bc7RgbaUnormSrgb => Self::Bc7RgbaUnormSrgb, + GPUTextureFormat::Etc2Rgb8unorm => Self::Etc2Rgb8Unorm, + GPUTextureFormat::Etc2Rgb8unormSrgb => Self::Etc2Rgb8UnormSrgb, + GPUTextureFormat::Etc2Rgb8a1unorm => Self::Etc2Rgb8A1Unorm, + GPUTextureFormat::Etc2Rgb8a1unormSrgb => Self::Etc2Rgb8A1UnormSrgb, + GPUTextureFormat::Etc2Rgba8unorm => Self::Etc2Rgba8Unorm, + GPUTextureFormat::Etc2Rgba8unormSrgb => Self::Etc2Rgba8UnormSrgb, + GPUTextureFormat::EacR11unorm => Self::EacR11Unorm, + GPUTextureFormat::EacR11snorm => Self::EacR11Snorm, + GPUTextureFormat::EacRg11unorm => Self::EacRg11Unorm, + GPUTextureFormat::EacRg11snorm => Self::EacRg11Snorm, + GPUTextureFormat::Astc4x4Unorm => Self::Astc { + block: AstcBlock::B4x4, + channel: AstcChannel::Unorm, + }, + GPUTextureFormat::Astc4x4UnormSrgb => Self::Astc { + block: AstcBlock::B4x4, + channel: AstcChannel::UnormSrgb, + }, + GPUTextureFormat::Astc5x4Unorm => Self::Astc { + block: AstcBlock::B5x4, + channel: AstcChannel::Unorm, + }, + GPUTextureFormat::Astc5x4UnormSrgb => Self::Astc { + block: AstcBlock::B5x4, + channel: AstcChannel::UnormSrgb, + }, + GPUTextureFormat::Astc5x5Unorm => Self::Astc { + block: AstcBlock::B5x5, + channel: AstcChannel::Unorm, + }, + GPUTextureFormat::Astc5x5UnormSrgb => Self::Astc { + block: AstcBlock::B5x5, + channel: AstcChannel::UnormSrgb, + }, + GPUTextureFormat::Astc6x5Unorm => Self::Astc { + block: AstcBlock::B6x5, + channel: AstcChannel::Unorm, + }, + GPUTextureFormat::Astc6x5UnormSrgb => Self::Astc { + block: AstcBlock::B6x5, + channel: AstcChannel::UnormSrgb, + }, + GPUTextureFormat::Astc6x6Unorm => Self::Astc { + block: AstcBlock::B6x6, + channel: AstcChannel::Unorm, + }, + GPUTextureFormat::Astc6x6UnormSrgb => Self::Astc { + block: AstcBlock::B6x6, + channel: AstcChannel::UnormSrgb, + }, + GPUTextureFormat::Astc8x5Unorm => Self::Astc { + block: AstcBlock::B8x5, + channel: AstcChannel::Unorm, + }, + GPUTextureFormat::Astc8x5UnormSrgb => Self::Astc { + block: AstcBlock::B8x5, + channel: AstcChannel::UnormSrgb, + }, + GPUTextureFormat::Astc8x6Unorm => Self::Astc { + block: AstcBlock::B8x6, + channel: AstcChannel::Unorm, + }, + GPUTextureFormat::Astc8x6UnormSrgb => Self::Astc { + block: AstcBlock::B8x6, + channel: AstcChannel::UnormSrgb, + }, + GPUTextureFormat::Astc8x8Unorm => Self::Astc { + block: AstcBlock::B8x8, + channel: AstcChannel::Unorm, + }, + GPUTextureFormat::Astc8x8UnormSrgb => Self::Astc { + block: AstcBlock::B8x8, + channel: AstcChannel::UnormSrgb, + }, + GPUTextureFormat::Astc10x5Unorm => Self::Astc { + block: AstcBlock::B10x5, + channel: AstcChannel::Unorm, + }, + GPUTextureFormat::Astc10x5UnormSrgb => Self::Astc { + block: AstcBlock::B10x5, + channel: AstcChannel::UnormSrgb, + }, + GPUTextureFormat::Astc10x6Unorm => Self::Astc { + block: AstcBlock::B10x6, + channel: AstcChannel::Unorm, + }, + GPUTextureFormat::Astc10x6UnormSrgb => Self::Astc { + block: AstcBlock::B10x6, + channel: AstcChannel::UnormSrgb, + }, + GPUTextureFormat::Astc10x8Unorm => Self::Astc { + block: AstcBlock::B10x8, + channel: AstcChannel::Unorm, + }, + GPUTextureFormat::Astc10x8UnormSrgb => Self::Astc { + block: AstcBlock::B10x8, + channel: AstcChannel::UnormSrgb, + }, + GPUTextureFormat::Astc10x10Unorm => Self::Astc { + block: AstcBlock::B10x10, + channel: AstcChannel::Unorm, + }, + GPUTextureFormat::Astc10x10UnormSrgb => Self::Astc { + block: AstcBlock::B10x10, + channel: AstcChannel::UnormSrgb, + }, + GPUTextureFormat::Astc12x10Unorm => Self::Astc { + block: AstcBlock::B12x10, + channel: AstcChannel::Unorm, + }, + GPUTextureFormat::Astc12x10UnormSrgb => Self::Astc { + block: AstcBlock::B12x10, + channel: AstcChannel::UnormSrgb, + }, + GPUTextureFormat::Astc12x12Unorm => Self::Astc { + block: AstcBlock::B12x12, + channel: AstcChannel::Unorm, + }, + GPUTextureFormat::Astc12x12UnormSrgb => Self::Astc { + block: AstcBlock::B12x12, + channel: AstcChannel::UnormSrgb, + }, } + } } + +pub struct GPUExternalTexture {} + +impl WebIdlInterfaceConverter for GPUExternalTexture { + const NAME: &'static str = "GPUExternalTexture"; +} + +impl GarbageCollected for GPUExternalTexture { + fn get_name(&self) -> &'static std::ffi::CStr { + c"GPUExternalTexture" + } +} + +#[op2] +impl GPUExternalTexture {} diff --git a/deno_webgpu/webgpu.idl b/deno_webgpu/webgpu.idl deleted file mode 100644 index df2aef498..000000000 --- a/deno_webgpu/webgpu.idl +++ /dev/null @@ -1,1243 +0,0 @@ -interface mixin GPUObjectBase { - attribute USVString label; -}; - -dictionary GPUObjectDescriptorBase { - USVString label = ""; -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUSupportedLimits { - readonly attribute unsigned long maxTextureDimension1D; - readonly attribute unsigned long maxTextureDimension2D; - readonly attribute unsigned long maxTextureDimension3D; - readonly attribute unsigned long maxTextureArrayLayers; - readonly attribute unsigned long maxBindGroups; - readonly attribute unsigned long maxBindingsPerBindGroup; - readonly attribute unsigned long maxDynamicUniformBuffersPerPipelineLayout; - readonly attribute unsigned long maxDynamicStorageBuffersPerPipelineLayout; - readonly attribute unsigned long maxSampledTexturesPerShaderStage; - readonly attribute unsigned long maxSamplersPerShaderStage; - readonly attribute unsigned long maxStorageBuffersPerShaderStage; - readonly attribute unsigned long maxStorageTexturesPerShaderStage; - readonly attribute unsigned long maxUniformBuffersPerShaderStage; - readonly attribute unsigned long long maxUniformBufferBindingSize; - readonly attribute unsigned long long maxStorageBufferBindingSize; - readonly attribute unsigned long minUniformBufferOffsetAlignment; - readonly attribute unsigned long minStorageBufferOffsetAlignment; - readonly attribute unsigned long maxVertexBuffers; - readonly attribute unsigned long long maxBufferSize; - readonly attribute unsigned long maxVertexAttributes; - readonly attribute unsigned long maxVertexBufferArrayStride; - readonly attribute unsigned long maxColorAttachments; - readonly attribute unsigned long maxColorAttachmentBytesPerSample; - readonly attribute unsigned long maxComputeWorkgroupStorageSize; - readonly attribute unsigned long maxComputeInvocationsPerWorkgroup; - readonly attribute unsigned long maxComputeWorkgroupSizeX; - readonly attribute unsigned long maxComputeWorkgroupSizeY; - readonly attribute unsigned long maxComputeWorkgroupSizeZ; - readonly attribute unsigned long maxComputeWorkgroupsPerDimension; -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUSupportedFeatures { - readonly setlike; -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUAdapterInfo { - readonly attribute DOMString vendor; - readonly attribute DOMString architecture; - readonly attribute DOMString device; - readonly attribute DOMString description; - readonly attribute unsigned long subgroupMinSize; - readonly attribute unsigned long subgroupMaxSize; -}; - -interface mixin NavigatorGPU { - [SameObject, SecureContext] readonly attribute GPU gpu; -}; -Navigator includes NavigatorGPU; -WorkerNavigator includes NavigatorGPU; - -[Exposed=(Window, Worker), SecureContext] -interface GPU { - Promise requestAdapter(optional GPURequestAdapterOptions options = {}); - GPUTextureFormat getPreferredCanvasFormat(); -}; - -dictionary GPURequestAdapterOptions { - GPUPowerPreference powerPreference; - boolean forceFallbackAdapter = false; -}; - -enum GPUPowerPreference { - "low-power", - "high-performance", -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUAdapter { - [SameObject] readonly attribute GPUSupportedFeatures features; - [SameObject] readonly attribute GPUSupportedLimits limits; - [SameObject] readonly attribute GPUAdapterInfo info; - readonly attribute boolean isFallbackAdapter; - - Promise requestDevice(optional GPUDeviceDescriptor descriptor = {}); -}; - -dictionary GPUDeviceDescriptor - : GPUObjectDescriptorBase { - sequence requiredFeatures = []; - record requiredLimits = {}; -}; - -enum GPUFeatureName { - "depth-clip-control", - "depth32float-stencil8", - "texture-compression-bc", - "texture-compression-bc-sliced-3d", - "texture-compression-etc2", - "texture-compression-astc", - "timestamp-query", - "indirect-first-instance", - "shader-f16", - "rg11b10ufloat-renderable", - "bgra8unorm-storage", - "float32-filterable", - "subgroups", -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUDevice : EventTarget { - [SameObject] readonly attribute GPUSupportedFeatures features; - [SameObject] readonly attribute GPUSupportedLimits limits; - [SameObject] readonly attribute GPUAdapterInfo adapterInfo; - - [SameObject] readonly attribute GPUQueue queue; - - undefined destroy(); - - GPUBuffer createBuffer(GPUBufferDescriptor descriptor); - GPUTexture createTexture(GPUTextureDescriptor descriptor); - GPUSampler createSampler(optional GPUSamplerDescriptor descriptor = {}); - - GPUBindGroupLayout createBindGroupLayout(GPUBindGroupLayoutDescriptor descriptor); - GPUPipelineLayout createPipelineLayout(GPUPipelineLayoutDescriptor descriptor); - GPUBindGroup createBindGroup(GPUBindGroupDescriptor descriptor); - - GPUShaderModule createShaderModule(GPUShaderModuleDescriptor descriptor); - GPUComputePipeline createComputePipeline(GPUComputePipelineDescriptor descriptor); - GPURenderPipeline createRenderPipeline(GPURenderPipelineDescriptor descriptor); - Promise createComputePipelineAsync(GPUComputePipelineDescriptor descriptor); - Promise createRenderPipelineAsync(GPURenderPipelineDescriptor descriptor); - - GPUCommandEncoder createCommandEncoder(optional GPUCommandEncoderDescriptor descriptor = {}); - GPURenderBundleEncoder createRenderBundleEncoder(GPURenderBundleEncoderDescriptor descriptor); - - GPUQuerySet createQuerySet(GPUQuerySetDescriptor descriptor); -}; -GPUDevice includes GPUObjectBase; - -[Exposed=(Window, Worker), SecureContext] -interface GPUBuffer { - readonly attribute GPUSize64Out size; - readonly attribute GPUFlagsConstant usage; - - readonly attribute GPUBufferMapState mapState; - - Promise mapAsync(GPUMapModeFlags mode, optional GPUSize64 offset = 0, optional GPUSize64 size); - ArrayBuffer getMappedRange(optional GPUSize64 offset = 0, optional GPUSize64 size); - undefined unmap(); - - undefined destroy(); -}; -GPUBuffer includes GPUObjectBase; - -enum GPUBufferMapState { - "unmapped", - "pending", - "mapped", -}; - -dictionary GPUBufferDescriptor - : GPUObjectDescriptorBase { - required GPUSize64 size; - required GPUBufferUsageFlags usage; - boolean mappedAtCreation = false; -}; - -typedef [EnforceRange] unsigned long GPUBufferUsageFlags; -[Exposed=(Window, Worker), SecureContext] -namespace GPUBufferUsage { - const GPUFlagsConstant MAP_READ = 0x0001; - const GPUFlagsConstant MAP_WRITE = 0x0002; - const GPUFlagsConstant COPY_SRC = 0x0004; - const GPUFlagsConstant COPY_DST = 0x0008; - const GPUFlagsConstant INDEX = 0x0010; - const GPUFlagsConstant VERTEX = 0x0020; - const GPUFlagsConstant UNIFORM = 0x0040; - const GPUFlagsConstant STORAGE = 0x0080; - const GPUFlagsConstant INDIRECT = 0x0100; - const GPUFlagsConstant QUERY_RESOLVE = 0x0200; -}; - -typedef [EnforceRange] unsigned long GPUMapModeFlags; -[Exposed=(Window, Worker), SecureContext] -namespace GPUMapMode { - const GPUFlagsConstant READ = 0x0001; - const GPUFlagsConstant WRITE = 0x0002; -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUTexture { - GPUTextureView createView(optional GPUTextureViewDescriptor descriptor = {}); - - undefined destroy(); - - readonly attribute GPUIntegerCoordinateOut width; - readonly attribute GPUIntegerCoordinateOut height; - readonly attribute GPUIntegerCoordinateOut depthOrArrayLayers; - readonly attribute GPUIntegerCoordinateOut mipLevelCount; - readonly attribute GPUSize32Out sampleCount; - readonly attribute GPUTextureDimension dimension; - readonly attribute GPUTextureFormat format; - readonly attribute GPUFlagsConstant usage; -}; -GPUTexture includes GPUObjectBase; - -dictionary GPUTextureDescriptor - : GPUObjectDescriptorBase { - required GPUExtent3D size; - GPUIntegerCoordinate mipLevelCount = 1; - GPUSize32 sampleCount = 1; - GPUTextureDimension dimension = "2d"; - required GPUTextureFormat format; - required GPUTextureUsageFlags usage; - sequence viewFormats = []; -}; - -enum GPUTextureDimension { - "1d", - "2d", - "3d", -}; - -typedef [EnforceRange] unsigned long GPUTextureUsageFlags; -[Exposed=(Window, Worker), SecureContext] -namespace GPUTextureUsage { - const GPUFlagsConstant COPY_SRC = 0x01; - const GPUFlagsConstant COPY_DST = 0x02; - const GPUFlagsConstant TEXTURE_BINDING = 0x04; - const GPUFlagsConstant STORAGE_BINDING = 0x08; - const GPUFlagsConstant RENDER_ATTACHMENT = 0x10; -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUTextureView { -}; -GPUTextureView includes GPUObjectBase; - -dictionary GPUTextureViewDescriptor - : GPUObjectDescriptorBase { - GPUTextureFormat format; - GPUTextureViewDimension dimension; - GPUTextureUsageFlags usage = 0; - GPUTextureAspect aspect = "all"; - GPUIntegerCoordinate baseMipLevel = 0; - GPUIntegerCoordinate mipLevelCount; - GPUIntegerCoordinate baseArrayLayer = 0; - GPUIntegerCoordinate arrayLayerCount; -}; - -enum GPUTextureViewDimension { - "1d", - "2d", - "2d-array", - "cube", - "cube-array", - "3d", -}; - -enum GPUTextureAspect { - "all", - "stencil-only", - "depth-only", -}; - -enum GPUTextureFormat { - // 8-bit formats - "r8unorm", - "r8snorm", - "r8uint", - "r8sint", - - // 16-bit formats - "r16uint", - "r16sint", - "r16float", - "rg8unorm", - "rg8snorm", - "rg8uint", - "rg8sint", - - // 32-bit formats - "r32uint", - "r32sint", - "r32float", - "rg16uint", - "rg16sint", - "rg16float", - "rgba8unorm", - "rgba8unorm-srgb", - "rgba8snorm", - "rgba8uint", - "rgba8sint", - "bgra8unorm", - "bgra8unorm-srgb", - // Packed 32-bit formats - "rgb9e5ufloat", - "rgb10a2uint", - "rgb10a2unorm", - "rg11b10ufloat", - - // 64-bit formats - "rg32uint", - "rg32sint", - "rg32float", - "rgba16uint", - "rgba16sint", - "rgba16float", - - // 128-bit formats - "rgba32uint", - "rgba32sint", - "rgba32float", - - // Depth/stencil formats - "stencil8", - "depth16unorm", - "depth24plus", - "depth24plus-stencil8", - "depth32float", - - // "depth32float-stencil8" feature - "depth32float-stencil8", - - // BC compressed formats usable if "texture-compression-bc" is both - // supported by the device/user agent and enabled in requestDevice. - "bc1-rgba-unorm", - "bc1-rgba-unorm-srgb", - "bc2-rgba-unorm", - "bc2-rgba-unorm-srgb", - "bc3-rgba-unorm", - "bc3-rgba-unorm-srgb", - "bc4-r-unorm", - "bc4-r-snorm", - "bc5-rg-unorm", - "bc5-rg-snorm", - "bc6h-rgb-ufloat", - "bc6h-rgb-float", - "bc7-rgba-unorm", - "bc7-rgba-unorm-srgb", - - // ETC2 compressed formats usable if "texture-compression-etc2" is both - // supported by the device/user agent and enabled in requestDevice. - "etc2-rgb8unorm", - "etc2-rgb8unorm-srgb", - "etc2-rgb8a1unorm", - "etc2-rgb8a1unorm-srgb", - "etc2-rgba8unorm", - "etc2-rgba8unorm-srgb", - "eac-r11unorm", - "eac-r11snorm", - "eac-rg11unorm", - "eac-rg11snorm", - - // ASTC compressed formats usable if "texture-compression-astc" is both - // supported by the device/user agent and enabled in requestDevice. - "astc-4x4-unorm", - "astc-4x4-unorm-srgb", - "astc-5x4-unorm", - "astc-5x4-unorm-srgb", - "astc-5x5-unorm", - "astc-5x5-unorm-srgb", - "astc-6x5-unorm", - "astc-6x5-unorm-srgb", - "astc-6x6-unorm", - "astc-6x6-unorm-srgb", - "astc-8x5-unorm", - "astc-8x5-unorm-srgb", - "astc-8x6-unorm", - "astc-8x6-unorm-srgb", - "astc-8x8-unorm", - "astc-8x8-unorm-srgb", - "astc-10x5-unorm", - "astc-10x5-unorm-srgb", - "astc-10x6-unorm", - "astc-10x6-unorm-srgb", - "astc-10x8-unorm", - "astc-10x8-unorm-srgb", - "astc-10x10-unorm", - "astc-10x10-unorm-srgb", - "astc-12x10-unorm", - "astc-12x10-unorm-srgb", - "astc-12x12-unorm", - "astc-12x12-unorm-srgb", -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUSampler { -}; -GPUSampler includes GPUObjectBase; - -dictionary GPUSamplerDescriptor - : GPUObjectDescriptorBase { - GPUAddressMode addressModeU = "clamp-to-edge"; - GPUAddressMode addressModeV = "clamp-to-edge"; - GPUAddressMode addressModeW = "clamp-to-edge"; - GPUFilterMode magFilter = "nearest"; - GPUFilterMode minFilter = "nearest"; - GPUMipmapFilterMode mipmapFilter = "nearest"; - float lodMinClamp = 0; - float lodMaxClamp = 32; - GPUCompareFunction compare; - [Clamp] unsigned short maxAnisotropy = 1; -}; - -enum GPUAddressMode { - "clamp-to-edge", - "repeat", - "mirror-repeat", -}; - -enum GPUFilterMode { - "nearest", - "linear", -}; - -enum GPUMipmapFilterMode { - "nearest", - "linear", -}; - -enum GPUCompareFunction { - "never", - "less", - "equal", - "less-equal", - "greater", - "not-equal", - "greater-equal", - "always", -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUBindGroupLayout { -}; -GPUBindGroupLayout includes GPUObjectBase; - -dictionary GPUBindGroupLayoutDescriptor - : GPUObjectDescriptorBase { - required sequence entries; -}; - -dictionary GPUBindGroupLayoutEntry { - required GPUIndex32 binding; - required GPUShaderStageFlags visibility; - - GPUBufferBindingLayout buffer; - GPUSamplerBindingLayout sampler; - GPUTextureBindingLayout texture; - GPUStorageTextureBindingLayout storageTexture; -}; - -typedef [EnforceRange] unsigned long GPUShaderStageFlags; -[Exposed=(Window, Worker), SecureContext] -namespace GPUShaderStage { - const GPUFlagsConstant VERTEX = 0x1; - const GPUFlagsConstant FRAGMENT = 0x2; - const GPUFlagsConstant COMPUTE = 0x4; -}; - -enum GPUBufferBindingType { - "uniform", - "storage", - "read-only-storage", -}; - -dictionary GPUBufferBindingLayout { - GPUBufferBindingType type = "uniform"; - boolean hasDynamicOffset = false; - GPUSize64 minBindingSize = 0; -}; - -enum GPUSamplerBindingType { - "filtering", - "non-filtering", - "comparison", -}; - -dictionary GPUSamplerBindingLayout { - GPUSamplerBindingType type = "filtering"; -}; - -enum GPUTextureSampleType { - "float", - "unfilterable-float", - "depth", - "sint", - "uint", -}; - -dictionary GPUTextureBindingLayout { - GPUTextureSampleType sampleType = "float"; - GPUTextureViewDimension viewDimension = "2d"; - boolean multisampled = false; -}; - -enum GPUStorageTextureAccess { - "write-only", - "read-only", - "read-write", -}; - -dictionary GPUStorageTextureBindingLayout { - GPUStorageTextureAccess access = "write-only"; - required GPUTextureFormat format; - GPUTextureViewDimension viewDimension = "2d"; -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUBindGroup { -}; -GPUBindGroup includes GPUObjectBase; - -dictionary GPUBindGroupDescriptor - : GPUObjectDescriptorBase { - required GPUBindGroupLayout layout; - required sequence entries; -}; - -typedef (GPUSampler or GPUTextureView or GPUBufferBinding) GPUBindingResource; - -dictionary GPUBindGroupEntry { - required GPUIndex32 binding; - required GPUBindingResource resource; -}; - -dictionary GPUBufferBinding { - required GPUBuffer buffer; - GPUSize64 offset = 0; - GPUSize64 size; -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUPipelineLayout { -}; -GPUPipelineLayout includes GPUObjectBase; - -dictionary GPUPipelineLayoutDescriptor - : GPUObjectDescriptorBase { - required sequence bindGroupLayouts; -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUShaderModule { -}; -GPUShaderModule includes GPUObjectBase; - -dictionary GPUShaderModuleDescriptor - : GPUObjectDescriptorBase { - required USVString code; -}; - -enum GPUCompilationMessageType { - "error", - "warning", - "info", -}; - -[Exposed=(Window, Worker), Serializable, SecureContext] -interface GPUCompilationMessage { - readonly attribute DOMString message; - readonly attribute GPUCompilationMessageType type; - readonly attribute unsigned long long lineNum; - readonly attribute unsigned long long linePos; - readonly attribute unsigned long long offset; - readonly attribute unsigned long long length; -}; - -[Exposed=(Window, Worker), Serializable, SecureContext] -interface GPUCompilationInfo { - readonly attribute FrozenArray messages; -}; - -[Exposed=(Window, Worker), SecureContext, Serializable] -interface GPUPipelineError : DOMException { - constructor(optional DOMString message = "", GPUPipelineErrorInit options); - readonly attribute GPUPipelineErrorReason reason; -}; - -dictionary GPUPipelineErrorInit { - required GPUPipelineErrorReason reason; -}; - -enum GPUPipelineErrorReason { - "validation", - "internal", -}; - -enum GPUAutoLayoutMode { - "auto", -}; - -dictionary GPUPipelineDescriptorBase - : GPUObjectDescriptorBase { - required (GPUPipelineLayout or GPUAutoLayoutMode) layout; -}; - -interface mixin GPUPipelineBase { - [NewObject] GPUBindGroupLayout getBindGroupLayout(unsigned long index); -}; - -dictionary GPUProgrammableStage { - required GPUShaderModule module; - USVString entryPoint; - record constants = {}; -}; - -typedef double GPUPipelineConstantValue; // May represent WGSL's bool, f32, i32, u32, and f16 if enabled. - -[Exposed=(Window, Worker), SecureContext] -interface GPUComputePipeline { -}; -GPUComputePipeline includes GPUObjectBase; -GPUComputePipeline includes GPUPipelineBase; - -dictionary GPUComputePipelineDescriptor - : GPUPipelineDescriptorBase { - required GPUProgrammableStage compute; -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPURenderPipeline { -}; -GPURenderPipeline includes GPUObjectBase; -GPURenderPipeline includes GPUPipelineBase; - -dictionary GPURenderPipelineDescriptor - : GPUPipelineDescriptorBase { - required GPUVertexState vertex; - GPUPrimitiveState primitive = {}; - GPUDepthStencilState depthStencil; - GPUMultisampleState multisample = {}; - GPUFragmentState fragment; -}; - -dictionary GPUPrimitiveState { - GPUPrimitiveTopology topology = "triangle-list"; - GPUIndexFormat stripIndexFormat; - GPUFrontFace frontFace = "ccw"; - GPUCullMode cullMode = "none"; - - // Requires "depth-clip-control" feature. - boolean unclippedDepth = false; -}; - -enum GPUPrimitiveTopology { - "point-list", - "line-list", - "line-strip", - "triangle-list", - "triangle-strip", -}; - -enum GPUFrontFace { - "ccw", - "cw", -}; - -enum GPUCullMode { - "none", - "front", - "back", -}; - -dictionary GPUMultisampleState { - GPUSize32 count = 1; - GPUSampleMask mask = 0xFFFFFFFF; - boolean alphaToCoverageEnabled = false; -}; - -dictionary GPUFragmentState - : GPUProgrammableStage { - required sequence targets; -}; - -dictionary GPUColorTargetState { - required GPUTextureFormat format; - - GPUBlendState blend; - GPUColorWriteFlags writeMask = 0xF; // GPUColorWrite.ALL -}; - -dictionary GPUBlendState { - required GPUBlendComponent color; - required GPUBlendComponent alpha; -}; - -typedef [EnforceRange] unsigned long GPUColorWriteFlags; -[Exposed=(Window, Worker), SecureContext] -namespace GPUColorWrite { - const GPUFlagsConstant RED = 0x1; - const GPUFlagsConstant GREEN = 0x2; - const GPUFlagsConstant BLUE = 0x4; - const GPUFlagsConstant ALPHA = 0x8; - const GPUFlagsConstant ALL = 0xF; -}; - -dictionary GPUBlendComponent { - GPUBlendOperation operation = "add"; - GPUBlendFactor srcFactor = "one"; - GPUBlendFactor dstFactor = "zero"; -}; - -enum GPUBlendFactor { - "zero", - "one", - "src", - "one-minus-src", - "src-alpha", - "one-minus-src-alpha", - "dst", - "one-minus-dst", - "dst-alpha", - "one-minus-dst-alpha", - "src-alpha-saturated", - "constant", - "one-minus-constant", - "src1", - "one-minus-src1", - "src1-alpha", - "one-minus-src1-alpha", -}; - -enum GPUBlendOperation { - "add", - "subtract", - "reverse-subtract", - "min", - "max", -}; - -dictionary GPUDepthStencilState { - required GPUTextureFormat format; - - boolean depthWriteEnabled; - GPUCompareFunction depthCompare; - - GPUStencilFaceState stencilFront = {}; - GPUStencilFaceState stencilBack = {}; - - GPUStencilValue stencilReadMask = 0xFFFFFFFF; - GPUStencilValue stencilWriteMask = 0xFFFFFFFF; - - GPUDepthBias depthBias = 0; - float depthBiasSlopeScale = 0; - float depthBiasClamp = 0; -}; - -dictionary GPUStencilFaceState { - GPUCompareFunction compare = "always"; - GPUStencilOperation failOp = "keep"; - GPUStencilOperation depthFailOp = "keep"; - GPUStencilOperation passOp = "keep"; -}; - -enum GPUStencilOperation { - "keep", - "zero", - "replace", - "invert", - "increment-clamp", - "decrement-clamp", - "increment-wrap", - "decrement-wrap", -}; - -enum GPUIndexFormat { - "uint16", - "uint32", -}; - -enum GPUVertexFormat { - "uint8x2", - "uint8x4", - "sint8x2", - "sint8x4", - "unorm8x2", - "unorm8x4", - "snorm8x2", - "snorm8x4", - "uint16x2", - "uint16x4", - "sint16x2", - "sint16x4", - "unorm16x2", - "unorm16x4", - "snorm16x2", - "snorm16x4", - "float16x2", - "float16x4", - "float32", - "float32x2", - "float32x3", - "float32x4", - "uint32", - "uint32x2", - "uint32x3", - "uint32x4", - "sint32", - "sint32x2", - "sint32x3", - "sint32x4", - "unorm10-10-10-2", -}; - -enum GPUVertexStepMode { - "vertex", - "instance", -}; - -dictionary GPUVertexState - : GPUProgrammableStage { - sequence buffers = []; -}; - -dictionary GPUVertexBufferLayout { - required GPUSize64 arrayStride; - GPUVertexStepMode stepMode = "vertex"; - required sequence attributes; -}; - -dictionary GPUVertexAttribute { - required GPUVertexFormat format; - required GPUSize64 offset; - - required GPUIndex32 shaderLocation; -}; - -dictionary GPUTexelCopyBufferLayout { - GPUSize64 offset = 0; - GPUSize32 bytesPerRow; - GPUSize32 rowsPerImage; -}; - -dictionary GPUTexelCopyBufferInfo - : GPUTexelCopyBufferLayout { - required GPUBuffer buffer; -}; - -dictionary GPUTexelCopyTextureInfo { - required GPUTexture texture; - GPUIntegerCoordinate mipLevel = 0; - GPUOrigin3D origin = {}; - GPUTextureAspect aspect = "all"; -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUCommandBuffer { -}; -GPUCommandBuffer includes GPUObjectBase; - -dictionary GPUCommandBufferDescriptor - : GPUObjectDescriptorBase { -}; - -interface mixin GPUCommandsMixin { -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUCommandEncoder { - GPURenderPassEncoder beginRenderPass(GPURenderPassDescriptor descriptor); - GPUComputePassEncoder beginComputePass(optional GPUComputePassDescriptor descriptor = {}); - - undefined copyBufferToBuffer( - GPUBuffer source, - GPUSize64 sourceOffset, - GPUBuffer destination, - GPUSize64 destinationOffset, - GPUSize64 size); - - undefined copyBufferToTexture( - GPUTexelCopyBufferInfo source, - GPUTexelCopyTextureInfo destination, - GPUExtent3D copySize); - - undefined copyTextureToBuffer( - GPUTexelCopyTextureInfo source, - GPUTexelCopyBufferInfo destination, - GPUExtent3D copySize); - - undefined copyTextureToTexture( - GPUTexelCopyTextureInfo source, - GPUTexelCopyTextureInfo destination, - GPUExtent3D copySize); - - undefined clearBuffer( - GPUBuffer buffer, - optional GPUSize64 offset = 0, - optional GPUSize64 size); - - undefined resolveQuerySet( - GPUQuerySet querySet, - GPUSize32 firstQuery, - GPUSize32 queryCount, - GPUBuffer destination, - GPUSize64 destinationOffset); - - GPUCommandBuffer finish(optional GPUCommandBufferDescriptor descriptor = {}); -}; -GPUCommandEncoder includes GPUObjectBase; -GPUCommandEncoder includes GPUCommandsMixin; -GPUCommandEncoder includes GPUDebugCommandsMixin; - -dictionary GPUCommandEncoderDescriptor - : GPUObjectDescriptorBase { -}; - -interface mixin GPUBindingCommandsMixin { - undefined setBindGroup(GPUIndex32 index, GPUBindGroup? bindGroup, - optional sequence dynamicOffsets = []); - - undefined setBindGroup(GPUIndex32 index, GPUBindGroup? bindGroup, - Uint32Array dynamicOffsetsData, - GPUSize64 dynamicOffsetsDataStart, - GPUSize32 dynamicOffsetsDataLength); -}; - -interface mixin GPUDebugCommandsMixin { - undefined pushDebugGroup(USVString groupLabel); - undefined popDebugGroup(); - undefined insertDebugMarker(USVString markerLabel); -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUComputePassEncoder { - undefined setPipeline(GPUComputePipeline pipeline); - undefined dispatchWorkgroups(GPUSize32 workgroupCountX, optional GPUSize32 workgroupCountY = 1, optional GPUSize32 workgroupCountZ = 1); - undefined dispatchWorkgroupsIndirect(GPUBuffer indirectBuffer, GPUSize64 indirectOffset); - - undefined end(); -}; -GPUComputePassEncoder includes GPUObjectBase; -GPUComputePassEncoder includes GPUCommandsMixin; -GPUComputePassEncoder includes GPUDebugCommandsMixin; -GPUComputePassEncoder includes GPUBindingCommandsMixin; - -dictionary GPUComputePassTimestampWrites { - required GPUQuerySet querySet; - GPUSize32 beginningOfPassWriteIndex; - GPUSize32 endOfPassWriteIndex; -}; - -dictionary GPUComputePassDescriptor - : GPUObjectDescriptorBase { - GPUComputePassTimestampWrites timestampWrites; -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPURenderPassEncoder { - undefined setViewport(float x, float y, - float width, float height, - float minDepth, float maxDepth); - - undefined setScissorRect(GPUIntegerCoordinate x, GPUIntegerCoordinate y, - GPUIntegerCoordinate width, GPUIntegerCoordinate height); - - undefined setBlendConstant(GPUColor color); - undefined setStencilReference(GPUStencilValue reference); - - undefined beginOcclusionQuery(GPUSize32 queryIndex); - undefined endOcclusionQuery(); - - undefined executeBundles(sequence bundles); - undefined end(); -}; -GPURenderPassEncoder includes GPUObjectBase; -GPURenderPassEncoder includes GPUCommandsMixin; -GPURenderPassEncoder includes GPUDebugCommandsMixin; -GPURenderPassEncoder includes GPUBindingCommandsMixin; -GPURenderPassEncoder includes GPURenderCommandsMixin; - -dictionary GPURenderPassTimestampWrites { - required GPUQuerySet querySet; - GPUSize32 beginningOfPassWriteIndex; - GPUSize32 endOfPassWriteIndex; -}; - -dictionary GPURenderPassDescriptor - : GPUObjectDescriptorBase { - required sequence colorAttachments; - GPURenderPassDepthStencilAttachment depthStencilAttachment; - GPUQuerySet occlusionQuerySet; - GPURenderPassTimestampWrites timestampWrites; -}; - -dictionary GPURenderPassColorAttachment { - required GPUTextureView view; - GPUTextureView resolveTarget; - - GPUColor clearValue; - required GPULoadOp loadOp; - required GPUStoreOp storeOp; -}; - -dictionary GPURenderPassDepthStencilAttachment { - required GPUTextureView view; - - float depthClearValue; - GPULoadOp depthLoadOp; - GPUStoreOp depthStoreOp; - boolean depthReadOnly = false; - - GPUStencilValue stencilClearValue = 0; - GPULoadOp stencilLoadOp; - GPUStoreOp stencilStoreOp; - boolean stencilReadOnly = false; -}; - -enum GPULoadOp { - "load", - "clear", -}; - -enum GPUStoreOp { - "store", - "discard", -}; - -dictionary GPURenderPassLayout - : GPUObjectDescriptorBase { - required sequence colorFormats; - GPUTextureFormat depthStencilFormat; - GPUSize32 sampleCount = 1; -}; - -interface mixin GPURenderCommandsMixin { - undefined setPipeline(GPURenderPipeline pipeline); - - undefined setIndexBuffer(GPUBuffer buffer, GPUIndexFormat indexFormat, optional GPUSize64 offset = 0, optional GPUSize64 size); - undefined setVertexBuffer(GPUIndex32 slot, GPUBuffer buffer, optional GPUSize64 offset = 0, optional GPUSize64 size); - - undefined draw(GPUSize32 vertexCount, optional GPUSize32 instanceCount = 1, - optional GPUSize32 firstVertex = 0, optional GPUSize32 firstInstance = 0); - undefined drawIndexed(GPUSize32 indexCount, optional GPUSize32 instanceCount = 1, - optional GPUSize32 firstIndex = 0, - optional GPUSignedOffset32 baseVertex = 0, - optional GPUSize32 firstInstance = 0); - - undefined drawIndirect(GPUBuffer indirectBuffer, GPUSize64 indirectOffset); - undefined drawIndexedIndirect(GPUBuffer indirectBuffer, GPUSize64 indirectOffset); -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPURenderBundle { -}; -GPURenderBundle includes GPUObjectBase; - -dictionary GPURenderBundleDescriptor - : GPUObjectDescriptorBase { -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPURenderBundleEncoder { - GPURenderBundle finish(optional GPURenderBundleDescriptor descriptor = {}); -}; -GPURenderBundleEncoder includes GPUObjectBase; -GPURenderBundleEncoder includes GPUCommandsMixin; -GPURenderBundleEncoder includes GPUDebugCommandsMixin; -GPURenderBundleEncoder includes GPUBindingCommandsMixin; -GPURenderBundleEncoder includes GPURenderCommandsMixin; - -dictionary GPURenderBundleEncoderDescriptor - : GPURenderPassLayout { - boolean depthReadOnly = false; - boolean stencilReadOnly = false; -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUQueue { - undefined submit(sequence commandBuffers); - - Promise onSubmittedWorkDone(); - - undefined writeBuffer( - GPUBuffer buffer, - GPUSize64 bufferOffset, - AllowSharedBufferSource data, - optional GPUSize64 dataOffset = 0, - optional GPUSize64 size); - - undefined writeTexture( - GPUTexelCopyTextureInfo destination, - AllowSharedBufferSource data, - GPUTexelCopyBufferLayout dataLayout, - GPUExtent3D size); -}; -GPUQueue includes GPUObjectBase; - -[Exposed=(Window, Worker), SecureContext] -interface GPUQuerySet { - undefined destroy(); - - readonly attribute GPUQueryType type; - readonly attribute GPUSize32Out count; -}; -GPUQuerySet includes GPUObjectBase; - -dictionary GPUQuerySetDescriptor - : GPUObjectDescriptorBase { - required GPUQueryType type; - required GPUSize32 count; -}; - -enum GPUQueryType { - "occlusion", - "timestamp", -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUCanvasContext { - readonly attribute (HTMLCanvasElement or OffscreenCanvas) canvas; - - undefined configure(GPUCanvasConfiguration configuration); - undefined unconfigure(); - - GPUTexture getCurrentTexture(); -}; - -enum GPUCanvasAlphaMode { - "opaque", - "premultiplied", -}; - -dictionary GPUCanvasConfiguration { - required GPUDevice device; - required GPUTextureFormat format; - GPUTextureUsageFlags usage = 0x10; // GPUTextureUsage.RENDER_ATTACHMENT - sequence viewFormats = []; - GPUCanvasAlphaMode alphaMode = "opaque"; -}; - -enum GPUDeviceLostReason { - "unknown", - "destroyed", -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUDeviceLostInfo { - readonly attribute GPUDeviceLostReason reason; - readonly attribute DOMString message; -}; - -partial interface GPUDevice { - readonly attribute Promise lost; -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUError { - readonly attribute DOMString message; -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUValidationError - : GPUError { - constructor(DOMString message); -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUOutOfMemoryError - : GPUError { - constructor(DOMString message); -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUInternalError - : GPUError { - constructor(DOMString message); -}; - -enum GPUErrorFilter { - "validation", - "out-of-memory", - "internal", -}; - -partial interface GPUDevice { - undefined pushErrorScope(GPUErrorFilter filter); - Promise popErrorScope(); -}; - -[Exposed=(Window, Worker), SecureContext] -interface GPUUncapturedErrorEvent : Event { - constructor( - DOMString type, - GPUUncapturedErrorEventInit gpuUncapturedErrorEventInitDict - ); - [SameObject] readonly attribute GPUError error; -}; - -dictionary GPUUncapturedErrorEventInit : EventInit { - required GPUError error; -}; - -partial interface GPUDevice { - attribute EventHandler onuncapturederror; -}; - -typedef [EnforceRange] unsigned long GPUBufferDynamicOffset; -typedef [EnforceRange] unsigned long GPUStencilValue; -typedef [EnforceRange] unsigned long GPUSampleMask; -typedef [EnforceRange] long GPUDepthBias; - -typedef [EnforceRange] unsigned long long GPUSize64; -typedef [EnforceRange] unsigned long GPUIntegerCoordinate; -typedef [EnforceRange] unsigned long GPUIndex32; -typedef [EnforceRange] unsigned long GPUSize32; -typedef [EnforceRange] long GPUSignedOffset32; - -typedef unsigned long long GPUSize64Out; -typedef unsigned long GPUIntegerCoordinateOut; -typedef unsigned long GPUSize32Out; - -typedef unsigned long GPUFlagsConstant; - -dictionary GPUColorDict { - required double r; - required double g; - required double b; - required double a; -}; -typedef (sequence or GPUColorDict) GPUColor; - -dictionary GPUOrigin2DDict { - GPUIntegerCoordinate x = 0; - GPUIntegerCoordinate y = 0; -}; -typedef (sequence or GPUOrigin2DDict) GPUOrigin2D; - -dictionary GPUOrigin3DDict { - GPUIntegerCoordinate x = 0; - GPUIntegerCoordinate y = 0; - GPUIntegerCoordinate z = 0; -}; -typedef (sequence or GPUOrigin3DDict) GPUOrigin3D; - -dictionary GPUExtent3DDict { - required GPUIntegerCoordinate width; - GPUIntegerCoordinate height = 1; - GPUIntegerCoordinate depthOrArrayLayers = 1; -}; -typedef (sequence or GPUExtent3DDict) GPUExtent3D; diff --git a/deno_webgpu/webidl.rs b/deno_webgpu/webidl.rs index 60ab54706..0322dcfe4 100644 --- a/deno_webgpu/webidl.rs +++ b/deno_webgpu/webidl.rs @@ -17,428 +17,459 @@ use deno_error::JsErrorBox; #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUExtent3DDict { - #[options(enforce_range = true)] - width: u32, - #[webidl(default = 1)] - #[options(enforce_range = true)] - height: u32, - #[webidl(default = 1)] - #[options(enforce_range = true)] - depth_or_array_layers: u32, + #[options(enforce_range = true)] + width: u32, + #[webidl(default = 1)] + #[options(enforce_range = true)] + height: u32, + #[webidl(default = 1)] + #[options(enforce_range = true)] + depth_or_array_layers: u32, } pub(crate) enum GPUExtent3D { - Dict(GPUExtent3DDict), - Sequence((u32, u32, u32)), + Dict(GPUExtent3DDict), + Sequence((u32, u32, u32)), } impl<'a> WebIdlConverter<'a> for GPUExtent3D { - type Options = (); + type Options = (); - fn convert<'b>( - scope: &mut v8::HandleScope<'a>, - value: v8::Local<'a, v8::Value>, - prefix: Cow<'static, str>, - context: ContextFn<'b>, - options: &Self::Options, - ) -> Result { - if value.is_null_or_undefined() { - return Ok(GPUExtent3D::Dict(GPUExtent3DDict::convert( - scope, - value, - prefix, - context.borrowed(), - options, - )?)); - } - if let Ok(obj) = value.try_cast::() { - let iter = v8::Symbol::get_iterator(scope); - if let Some(iter) = obj.get(scope, iter.into()) { - if !iter.is_undefined() { - let conv = >::convert( - scope, - value, - prefix.clone(), - context.borrowed(), - &IntOptions { - clamp: false, - enforce_range: true, - }, - )?; - if !(conv.len() > 1 && conv.len() <= 3) { - return Err(WebIdlError::other(prefix, context, JsErrorBox::type_error(format!("A sequence of number used as a GPUExtent3D must have between 1 and 3 elements, received {} elements", conv.len())))); - } - - let mut iter = conv.into_iter(); - return Ok(GPUExtent3D::Sequence(( - iter.next().unwrap(), - iter.next().unwrap_or(1), - iter.next().unwrap_or(1), - ))); - } - } - - return Ok(GPUExtent3D::Dict(GPUExtent3DDict::convert( - scope, value, prefix, context, options, - )?)); - } - - Err(WebIdlError::new( - prefix, - context, - WebIdlErrorKind::ConvertToConverterType( - "sequence or GPUExtent3DDict", - ), - )) + fn convert<'b>( + scope: &mut v8::HandleScope<'a>, + value: v8::Local<'a, v8::Value>, + prefix: Cow<'static, str>, + context: ContextFn<'b>, + options: &Self::Options, + ) -> Result { + if value.is_null_or_undefined() { + return Ok(GPUExtent3D::Dict(GPUExtent3DDict::convert( + scope, + value, + prefix, + context.borrowed(), + options, + )?)); } + if let Ok(obj) = value.try_cast::() { + let iter = v8::Symbol::get_iterator(scope); + if let Some(iter) = obj.get(scope, iter.into()) { + if !iter.is_undefined() { + let conv = >::convert( + scope, + value, + prefix.clone(), + context.borrowed(), + &IntOptions { + clamp: false, + enforce_range: true, + }, + )?; + if conv.is_empty() || conv.len() > 3 { + return Err(WebIdlError::other( + prefix, + context, + JsErrorBox::type_error(format!( + "A sequence of number used as a GPUExtent3D must have between 1 and 3 elements, received {} elements", + conv.len() + )), + )); + } + + let mut iter = conv.into_iter(); + return Ok(GPUExtent3D::Sequence(( + iter.next().unwrap(), + iter.next().unwrap_or(1), + iter.next().unwrap_or(1), + ))); + } + } + + return Ok(GPUExtent3D::Dict(GPUExtent3DDict::convert( + scope, value, prefix, context, options, + )?)); + } + + Err(WebIdlError::new( + prefix, + context, + WebIdlErrorKind::ConvertToConverterType( + "sequence or GPUExtent3DDict", + ), + )) + } } impl From for wgpu_types::Extent3d { - fn from(value: GPUExtent3D) -> Self { - match value { - GPUExtent3D::Dict(dict) => Self { - width: dict.width, - height: dict.height, - depth_or_array_layers: dict.depth_or_array_layers, - }, - GPUExtent3D::Sequence((width, height, depth)) => Self { - width, - height, - depth_or_array_layers: depth, - }, - } + fn from(value: GPUExtent3D) -> Self { + match value { + GPUExtent3D::Dict(dict) => Self { + width: dict.width, + height: dict.height, + depth_or_array_layers: dict.depth_or_array_layers, + }, + GPUExtent3D::Sequence((width, height, depth)) => Self { + width, + height, + depth_or_array_layers: depth, + }, } + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUOrigin3DDict { - #[webidl(default = 0)] - #[options(enforce_range = true)] - x: u32, - #[webidl(default = 0)] - #[options(enforce_range = true)] - y: u32, - #[webidl(default = 0)] - #[options(enforce_range = true)] - z: u32, + #[webidl(default = 0)] + #[options(enforce_range = true)] + x: u32, + #[webidl(default = 0)] + #[options(enforce_range = true)] + y: u32, + #[webidl(default = 0)] + #[options(enforce_range = true)] + z: u32, } pub(crate) enum GPUOrigin3D { - Dict(GPUOrigin3DDict), - Sequence((u32, u32, u32)), + Dict(GPUOrigin3DDict), + Sequence((u32, u32, u32)), } impl Default for GPUOrigin3D { - fn default() -> Self { - GPUOrigin3D::Sequence((0, 0, 0)) - } + fn default() -> Self { + GPUOrigin3D::Sequence((0, 0, 0)) + } } impl<'a> WebIdlConverter<'a> for GPUOrigin3D { - type Options = (); + type Options = (); - fn convert<'b>( - scope: &mut v8::HandleScope<'a>, - value: v8::Local<'a, v8::Value>, - prefix: Cow<'static, str>, - context: ContextFn<'b>, - options: &Self::Options, - ) -> Result { - if value.is_null_or_undefined() { - return Ok(GPUOrigin3D::Dict(GPUOrigin3DDict::convert( - scope, - value, - prefix, - context.borrowed(), - options, - )?)); - } - if let Ok(obj) = value.try_cast::() { - let iter = v8::Symbol::get_iterator(scope); - if let Some(iter) = obj.get(scope, iter.into()) { - if !iter.is_undefined() { - let conv = >::convert( - scope, - value, - prefix.clone(), - context.borrowed(), - &IntOptions { - clamp: false, - enforce_range: true, - }, - )?; - if conv.len() > 3 { - return Err(WebIdlError::other(prefix, context, JsErrorBox::type_error(format!("A sequence of number used as a GPUOrigin3D must have at most 3 elements, received {} elements", conv.len())))); - } - - let mut iter = conv.into_iter(); - return Ok(GPUOrigin3D::Sequence(( - iter.next().unwrap_or(0), - iter.next().unwrap_or(0), - iter.next().unwrap_or(0), - ))); - } - } - - return Ok(GPUOrigin3D::Dict(GPUOrigin3DDict::convert( - scope, value, prefix, context, options, - )?)); - } - - Err(WebIdlError::new( - prefix, - context, - WebIdlErrorKind::ConvertToConverterType( - "sequence or GPUOrigin3DDict", - ), - )) + fn convert<'b>( + scope: &mut v8::HandleScope<'a>, + value: v8::Local<'a, v8::Value>, + prefix: Cow<'static, str>, + context: ContextFn<'b>, + options: &Self::Options, + ) -> Result { + if value.is_null_or_undefined() { + return Ok(GPUOrigin3D::Dict(GPUOrigin3DDict::convert( + scope, + value, + prefix, + context.borrowed(), + options, + )?)); } + if let Ok(obj) = value.try_cast::() { + let iter = v8::Symbol::get_iterator(scope); + if let Some(iter) = obj.get(scope, iter.into()) { + if !iter.is_undefined() { + let conv = >::convert( + scope, + value, + prefix.clone(), + context.borrowed(), + &IntOptions { + clamp: false, + enforce_range: true, + }, + )?; + if conv.len() > 3 { + return Err(WebIdlError::other( + prefix, + context, + JsErrorBox::type_error(format!( + "A sequence of number used as a GPUOrigin3D must have at most 3 elements, received {} elements", + conv.len() + )), + )); + } + + let mut iter = conv.into_iter(); + return Ok(GPUOrigin3D::Sequence(( + iter.next().unwrap_or(0), + iter.next().unwrap_or(0), + iter.next().unwrap_or(0), + ))); + } + } + + return Ok(GPUOrigin3D::Dict(GPUOrigin3DDict::convert( + scope, value, prefix, context, options, + )?)); + } + + Err(WebIdlError::new( + prefix, + context, + WebIdlErrorKind::ConvertToConverterType( + "sequence or GPUOrigin3DDict", + ), + )) + } } impl From for wgpu_types::Origin3d { - fn from(value: GPUOrigin3D) -> Self { - match value { - GPUOrigin3D::Dict(dict) => Self { - x: dict.x, - y: dict.y, - z: dict.z, - }, - GPUOrigin3D::Sequence((x, y, z)) => Self { x, y, z }, - } + fn from(value: GPUOrigin3D) -> Self { + match value { + GPUOrigin3D::Dict(dict) => Self { + x: dict.x, + y: dict.y, + z: dict.z, + }, + GPUOrigin3D::Sequence((x, y, z)) => Self { x, y, z }, } + } } #[derive(WebIDL)] #[webidl(dictionary)] pub(crate) struct GPUColorDict { - r: f64, - g: f64, - b: f64, - a: f64, + r: f64, + g: f64, + b: f64, + a: f64, } pub(crate) enum GPUColor { - Dict(GPUColorDict), - Sequence((f64, f64, f64, f64)), + Dict(GPUColorDict), + Sequence((f64, f64, f64, f64)), } impl<'a> WebIdlConverter<'a> for GPUColor { - type Options = (); + type Options = (); - fn convert<'b>( - scope: &mut v8::HandleScope<'a>, - value: v8::Local<'a, v8::Value>, - prefix: Cow<'static, str>, - context: ContextFn<'b>, - options: &Self::Options, - ) -> Result { - if value.is_null_or_undefined() { - return Ok(GPUColor::Dict(GPUColorDict::convert( - scope, - value, - prefix, - context.borrowed(), - options, - )?)); - } - if let Ok(obj) = value.try_cast::() { - let iter = v8::Symbol::get_iterator(scope); - if let Some(iter) = obj.get(scope, iter.into()) { - if !iter.is_undefined() { - let conv = >::convert( - scope, - value, - prefix.clone(), - context.borrowed(), - options, - )?; - if conv.len() != 4 { - return Err(WebIdlError::other(prefix, context, JsErrorBox::type_error(format!("A sequence of number used as a GPUColor must have exactly 4 elements, received {} elements", conv.len())))); - } - - let mut iter = conv.into_iter(); - return Ok(GPUColor::Sequence(( - iter.next().unwrap(), - iter.next().unwrap(), - iter.next().unwrap(), - iter.next().unwrap(), - ))); - } - } - - return Ok(GPUColor::Dict(GPUColorDict::convert( - scope, value, prefix, context, options, - )?)); - } - - Err(WebIdlError::new( - prefix, - context, - WebIdlErrorKind::ConvertToConverterType( - "sequence or GPUOrigin3DDict", - ), - )) + fn convert<'b>( + scope: &mut v8::HandleScope<'a>, + value: v8::Local<'a, v8::Value>, + prefix: Cow<'static, str>, + context: ContextFn<'b>, + options: &Self::Options, + ) -> Result { + if value.is_null_or_undefined() { + return Ok(GPUColor::Dict(GPUColorDict::convert( + scope, + value, + prefix, + context.borrowed(), + options, + )?)); } + if let Ok(obj) = value.try_cast::() { + let iter = v8::Symbol::get_iterator(scope); + if let Some(iter) = obj.get(scope, iter.into()) { + if !iter.is_undefined() { + let conv = >::convert( + scope, + value, + prefix.clone(), + context.borrowed(), + options, + )?; + if conv.len() != 4 { + return Err(WebIdlError::other( + prefix, + context, + JsErrorBox::type_error(format!( + "A sequence of number used as a GPUColor must have exactly 4 elements, received {} elements", + conv.len() + )), + )); + } + + let mut iter = conv.into_iter(); + return Ok(GPUColor::Sequence(( + iter.next().unwrap(), + iter.next().unwrap(), + iter.next().unwrap(), + iter.next().unwrap(), + ))); + } + } + + return Ok(GPUColor::Dict(GPUColorDict::convert( + scope, value, prefix, context, options, + )?)); + } + + Err(WebIdlError::new( + prefix, + context, + WebIdlErrorKind::ConvertToConverterType( + "sequence or GPUOrigin3DDict", + ), + )) + } } impl From for wgpu_types::Color { - fn from(value: GPUColor) -> Self { - match value { - GPUColor::Dict(dict) => Self { - r: dict.r, - g: dict.g, - b: dict.b, - a: dict.a, - }, - GPUColor::Sequence((r, g, b, a)) => Self { r, g, b, a }, - } + fn from(value: GPUColor) -> Self { + match value { + GPUColor::Dict(dict) => Self { + r: dict.r, + g: dict.g, + b: dict.b, + a: dict.a, + }, + GPUColor::Sequence((r, g, b, a)) => Self { r, g, b, a }, } + } } #[derive(WebIDL)] #[webidl(enum)] pub(crate) enum GPUAutoLayoutMode { - Auto, + Auto, } pub(crate) enum GPUPipelineLayoutOrGPUAutoLayoutMode { - PipelineLayout(Ptr), - AutoLayoutMode(GPUAutoLayoutMode), + PipelineLayout(Ptr), + AutoLayoutMode(GPUAutoLayoutMode), } -impl From for Option { - fn from(value: GPUPipelineLayoutOrGPUAutoLayoutMode) -> Self { - match value { - GPUPipelineLayoutOrGPUAutoLayoutMode::PipelineLayout(layout) => Some(layout.id), - GPUPipelineLayoutOrGPUAutoLayoutMode::AutoLayoutMode(GPUAutoLayoutMode::Auto) => None, - } +impl From + for Option +{ + fn from(value: GPUPipelineLayoutOrGPUAutoLayoutMode) -> Self { + match value { + GPUPipelineLayoutOrGPUAutoLayoutMode::PipelineLayout(layout) => { + Some(layout.id) + } + GPUPipelineLayoutOrGPUAutoLayoutMode::AutoLayoutMode( + GPUAutoLayoutMode::Auto, + ) => None, } + } } impl<'a> WebIdlConverter<'a> for GPUPipelineLayoutOrGPUAutoLayoutMode { - type Options = (); + type Options = (); - fn convert<'b>( - scope: &mut v8::HandleScope<'a>, - value: v8::Local<'a, v8::Value>, - prefix: Cow<'static, str>, - context: ContextFn<'b>, - options: &Self::Options, - ) -> Result { - if value.is_object() { - Ok(Self::PipelineLayout(WebIdlConverter::convert( - scope, value, prefix, context, options, - )?)) - } else { - Ok(Self::AutoLayoutMode(WebIdlConverter::convert( - scope, value, prefix, context, options, - )?)) - } + fn convert<'b>( + scope: &mut v8::HandleScope<'a>, + value: v8::Local<'a, v8::Value>, + prefix: Cow<'static, str>, + context: ContextFn<'b>, + options: &Self::Options, + ) -> Result { + if value.is_object() { + Ok(Self::PipelineLayout(WebIdlConverter::convert( + scope, value, prefix, context, options, + )?)) + } else { + Ok(Self::AutoLayoutMode(WebIdlConverter::convert( + scope, value, prefix, context, options, + )?)) } + } } #[derive(WebIDL, Clone, Hash, Eq, PartialEq)] #[webidl(enum)] pub enum GPUFeatureName { - #[webidl(rename = "depth-clip-control")] - DepthClipControl, - #[webidl(rename = "timestamp-query")] - TimestampQuery, - #[webidl(rename = "indirect-first-instance")] - IndirectFirstInstance, - #[webidl(rename = "shader-f16")] - ShaderF16, - #[webidl(rename = "depth32float-stencil8")] - Depth32floatStencil8, - #[webidl(rename = "texture-compression-bc")] - TextureCompressionBc, - #[webidl(rename = "texture-compression-bc-sliced-3d")] - TextureCompressionBcSliced3d, - #[webidl(rename = "texture-compression-etc2")] - TextureCompressionEtc2, - #[webidl(rename = "texture-compression-astc")] - TextureCompressionAstc, - #[webidl(rename = "rg11b10ufloat-renderable")] - Rg11b10ufloatRenderable, - #[webidl(rename = "bgra8unorm-storage")] - Bgra8unormStorage, - #[webidl(rename = "float32-filterable")] - Float32Filterable, - #[webidl(rename = "dual-source-blending")] - DualSourceBlending, - #[webidl(rename = "subgroups")] - Subgroups, + #[webidl(rename = "depth-clip-control")] + DepthClipControl, + #[webidl(rename = "timestamp-query")] + TimestampQuery, + #[webidl(rename = "indirect-first-instance")] + IndirectFirstInstance, + #[webidl(rename = "shader-f16")] + ShaderF16, + #[webidl(rename = "depth32float-stencil8")] + Depth32floatStencil8, + #[webidl(rename = "texture-compression-bc")] + TextureCompressionBc, + #[webidl(rename = "texture-compression-bc-sliced-3d")] + TextureCompressionBcSliced3d, + #[webidl(rename = "texture-compression-etc2")] + TextureCompressionEtc2, + #[webidl(rename = "texture-compression-astc")] + TextureCompressionAstc, + #[webidl(rename = "texture-compression-astc-sliced-3d")] + TextureCompressionAstcSliced3d, + #[webidl(rename = "rg11b10ufloat-renderable")] + Rg11b10ufloatRenderable, + #[webidl(rename = "bgra8unorm-storage")] + Bgra8unormStorage, + #[webidl(rename = "float32-filterable")] + Float32Filterable, + #[webidl(rename = "dual-source-blending")] + DualSourceBlending, + #[webidl(rename = "subgroups")] + Subgroups, - // extended from spec - #[webidl(rename = "texture-format-16-bit-norm")] - TextureFormat16BitNorm, - #[webidl(rename = "texture-compression-astc-hdr")] - TextureCompressionAstcHdr, - #[webidl(rename = "texture-adapter-specific-format-features")] - TextureAdapterSpecificFormatFeatures, - #[webidl(rename = "pipeline-statistics-query")] - PipelineStatisticsQuery, - #[webidl(rename = "timestamp-query-inside-passes")] - TimestampQueryInsidePasses, - #[webidl(rename = "mappable-primary-buffers")] - MappablePrimaryBuffers, - #[webidl(rename = "texture-binding-array")] - TextureBindingArray, - #[webidl(rename = "buffer-binding-array")] - BufferBindingArray, - #[webidl(rename = "storage-resource-binding-array")] - StorageResourceBindingArray, - #[webidl(rename = "sampled-texture-and-storage-buffer-array-non-uniform-indexing")] - SampledTextureAndStorageBufferArrayNonUniformIndexing, - #[webidl(rename = "storage-texture-array-non-uniform-indexing")] - StorageTextureArrayNonUniformIndexing, - #[webidl(rename = "uniform-buffer-binding-arrays")] - UniformBufferBindingArrays, - #[webidl(rename = "partially-bound-binding-array")] - PartiallyBoundBindingArray, - #[webidl(rename = "multi-draw-indirect")] - MultiDrawIndirect, - #[webidl(rename = "multi-draw-indirect-count")] - MultiDrawIndirectCount, - #[webidl(rename = "push-constants")] - PushConstants, - #[webidl(rename = "address-mode-clamp-to-zero")] - AddressModeClampToZero, - #[webidl(rename = "address-mode-clamp-to-border")] - AddressModeClampToBorder, - #[webidl(rename = "polygon-mode-line")] - PolygonModeLine, - #[webidl(rename = "polygon-mode-point")] - PolygonModePoint, - #[webidl(rename = "conservative-rasterization")] - ConservativeRasterization, - #[webidl(rename = "vertex-writable-storage")] - VertexWritableStorage, - #[webidl(rename = "clear-texture")] - ClearTexture, - #[webidl(rename = "spirv-shader-passthrough")] - SpirvShaderPassthrough, - #[webidl(rename = "multiview")] - Multiview, - #[webidl(rename = "vertex-attribute-64-bit")] - VertexAttribute64Bit, - #[webidl(rename = "shader-f64")] - ShaderF64, - #[webidl(rename = "shader-i16")] - ShaderI16, - #[webidl(rename = "shader-primitive-index")] - ShaderPrimitiveIndex, - #[webidl(rename = "shader-early-depth-test")] - ShaderEarlyDepthTest, + // extended from spec + #[webidl(rename = "texture-format-16-bit-norm")] + TextureFormat16BitNorm, + #[webidl(rename = "texture-compression-astc-hdr")] + TextureCompressionAstcHdr, + #[webidl(rename = "texture-adapter-specific-format-features")] + TextureAdapterSpecificFormatFeatures, + #[webidl(rename = "pipeline-statistics-query")] + PipelineStatisticsQuery, + #[webidl(rename = "timestamp-query-inside-passes")] + TimestampQueryInsidePasses, + #[webidl(rename = "mappable-primary-buffers")] + MappablePrimaryBuffers, + #[webidl(rename = "texture-binding-array")] + TextureBindingArray, + #[webidl(rename = "buffer-binding-array")] + BufferBindingArray, + #[webidl(rename = "storage-resource-binding-array")] + StorageResourceBindingArray, + #[webidl( + rename = "sampled-texture-and-storage-buffer-array-non-uniform-indexing" + )] + SampledTextureAndStorageBufferArrayNonUniformIndexing, + #[webidl(rename = "storage-texture-array-non-uniform-indexing")] + StorageTextureArrayNonUniformIndexing, + #[webidl(rename = "uniform-buffer-binding-arrays")] + UniformBufferBindingArrays, + #[webidl(rename = "partially-bound-binding-array")] + PartiallyBoundBindingArray, + #[webidl(rename = "multi-draw-indirect-count")] + MultiDrawIndirectCount, + #[webidl(rename = "push-constants")] + PushConstants, + #[webidl(rename = "address-mode-clamp-to-zero")] + AddressModeClampToZero, + #[webidl(rename = "address-mode-clamp-to-border")] + AddressModeClampToBorder, + #[webidl(rename = "polygon-mode-line")] + PolygonModeLine, + #[webidl(rename = "polygon-mode-point")] + PolygonModePoint, + #[webidl(rename = "conservative-rasterization")] + ConservativeRasterization, + #[webidl(rename = "vertex-writable-storage")] + VertexWritableStorage, + #[webidl(rename = "clear-texture")] + ClearTexture, + #[webidl(rename = "multiview")] + Multiview, + #[webidl(rename = "vertex-attribute-64-bit")] + VertexAttribute64Bit, + #[webidl(rename = "shader-f64")] + ShaderF64, + #[webidl(rename = "shader-i16")] + ShaderI16, + #[webidl(rename = "shader-primitive-index")] + ShaderPrimitiveIndex, + #[webidl(rename = "shader-early-depth-test")] + ShaderEarlyDepthTest, + #[webidl(rename = "passthrough-shaders")] + PassthroughShaders, } -pub fn feature_names_to_features(names: Vec) -> wgpu_types::Features { - use wgpu_types::Features; - let mut features = Features::empty(); +pub fn feature_names_to_features( + names: Vec, +) -> wgpu_types::Features { + use wgpu_types::Features; + let mut features = Features::empty(); - for name in names { - #[rustfmt::skip] + for name in names { + #[rustfmt::skip] let feature = match name { GPUFeatureName::DepthClipControl => Features::DEPTH_CLIP_CONTROL, GPUFeatureName::TimestampQuery => Features::TIMESTAMP_QUERY, @@ -449,6 +480,7 @@ pub fn feature_names_to_features(names: Vec) -> wgpu_types::Feat GPUFeatureName::TextureCompressionBcSliced3d => Features::TEXTURE_COMPRESSION_BC_SLICED_3D, GPUFeatureName::TextureCompressionEtc2 => Features::TEXTURE_COMPRESSION_ETC2, GPUFeatureName::TextureCompressionAstc => Features::TEXTURE_COMPRESSION_ASTC, + GPUFeatureName::TextureCompressionAstcSliced3d => Features::TEXTURE_COMPRESSION_ASTC_SLICED_3D, GPUFeatureName::Rg11b10ufloatRenderable => Features::RG11B10UFLOAT_RENDERABLE, GPUFeatureName::Bgra8unormStorage => Features::BGRA8UNORM_STORAGE, GPUFeatureName::Float32Filterable => Features::FLOAT32_FILTERABLE, @@ -467,7 +499,6 @@ pub fn feature_names_to_features(names: Vec) -> wgpu_types::Feat GPUFeatureName::StorageTextureArrayNonUniformIndexing => Features::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING, GPUFeatureName::UniformBufferBindingArrays => Features::UNIFORM_BUFFER_BINDING_ARRAYS, GPUFeatureName::PartiallyBoundBindingArray => Features::PARTIALLY_BOUND_BINDING_ARRAY, - GPUFeatureName::MultiDrawIndirect => Features::MULTI_DRAW_INDIRECT, GPUFeatureName::MultiDrawIndirectCount => Features::MULTI_DRAW_INDIRECT_COUNT, GPUFeatureName::PushConstants => Features::PUSH_CONSTANTS, GPUFeatureName::AddressModeClampToZero => Features::ADDRESS_MODE_CLAMP_TO_ZERO, @@ -477,168 +508,175 @@ pub fn feature_names_to_features(names: Vec) -> wgpu_types::Feat GPUFeatureName::ConservativeRasterization => Features::CONSERVATIVE_RASTERIZATION, GPUFeatureName::VertexWritableStorage => Features::VERTEX_WRITABLE_STORAGE, GPUFeatureName::ClearTexture => Features::CLEAR_TEXTURE, - GPUFeatureName::SpirvShaderPassthrough => Features::SPIRV_SHADER_PASSTHROUGH, GPUFeatureName::Multiview => Features::MULTIVIEW, GPUFeatureName::VertexAttribute64Bit => Features::VERTEX_ATTRIBUTE_64BIT, GPUFeatureName::ShaderF64 => Features::SHADER_F64, - GPUFeatureName::ShaderI16 => Features::SHADER_F16, + GPUFeatureName::ShaderI16 => Features::SHADER_I16, GPUFeatureName::ShaderPrimitiveIndex => Features::SHADER_PRIMITIVE_INDEX, GPUFeatureName::ShaderEarlyDepthTest => Features::SHADER_EARLY_DEPTH_TEST, + GPUFeatureName::PassthroughShaders => Features::EXPERIMENTAL_PASSTHROUGH_SHADERS, }; - features.set(feature, true); - } + features.set(feature, true); + } - features + features } #[allow(clippy::disallowed_types)] -pub fn features_to_feature_names(features: wgpu_types::Features) -> HashSet { - use GPUFeatureName::*; - let mut return_features = HashSet::new(); +pub fn features_to_feature_names( + features: wgpu_types::Features, +) -> HashSet { + use GPUFeatureName::*; + let mut return_features = HashSet::new(); - // api - if features.contains(wgpu_types::Features::DEPTH_CLIP_CONTROL) { - return_features.insert(DepthClipControl); - } - if features.contains(wgpu_types::Features::TIMESTAMP_QUERY) { - return_features.insert(TimestampQuery); - } - if features.contains(wgpu_types::Features::INDIRECT_FIRST_INSTANCE) { - return_features.insert(IndirectFirstInstance); - } - // shader - if features.contains(wgpu_types::Features::SHADER_F16) { - return_features.insert(ShaderF16); - } - // texture formats - if features.contains(wgpu_types::Features::DEPTH32FLOAT_STENCIL8) { - return_features.insert(Depth32floatStencil8); - } - if features.contains(wgpu_types::Features::TEXTURE_COMPRESSION_BC) { - return_features.insert(TextureCompressionBc); - } - if features.contains(wgpu_types::Features::TEXTURE_COMPRESSION_BC_SLICED_3D) { - return_features.insert(TextureCompressionBcSliced3d); - } - if features.contains(wgpu_types::Features::TEXTURE_COMPRESSION_ETC2) { - return_features.insert(TextureCompressionEtc2); - } - if features.contains(wgpu_types::Features::TEXTURE_COMPRESSION_ASTC) { - return_features.insert(TextureCompressionAstc); - } - if features.contains(wgpu_types::Features::RG11B10UFLOAT_RENDERABLE) { - return_features.insert(Rg11b10ufloatRenderable); - } - if features.contains(wgpu_types::Features::BGRA8UNORM_STORAGE) { - return_features.insert(Bgra8unormStorage); - } - if features.contains(wgpu_types::Features::FLOAT32_FILTERABLE) { - return_features.insert(Float32Filterable); - } - if features.contains(wgpu_types::Features::DUAL_SOURCE_BLENDING) { - return_features.insert(DualSourceBlending); - } - if features.contains(wgpu_types::Features::SUBGROUP) { - return_features.insert(Subgroups); - } + // api + if features.contains(wgpu_types::Features::DEPTH_CLIP_CONTROL) { + return_features.insert(DepthClipControl); + } + if features.contains(wgpu_types::Features::TIMESTAMP_QUERY) { + return_features.insert(TimestampQuery); + } + if features.contains(wgpu_types::Features::INDIRECT_FIRST_INSTANCE) { + return_features.insert(IndirectFirstInstance); + } + // shader + if features.contains(wgpu_types::Features::SHADER_F16) { + return_features.insert(ShaderF16); + } + // texture formats + if features.contains(wgpu_types::Features::DEPTH32FLOAT_STENCIL8) { + return_features.insert(Depth32floatStencil8); + } + if features.contains(wgpu_types::Features::TEXTURE_COMPRESSION_BC) { + return_features.insert(TextureCompressionBc); + } + if features.contains(wgpu_types::Features::TEXTURE_COMPRESSION_BC_SLICED_3D) { + return_features.insert(TextureCompressionBcSliced3d); + } + if features.contains(wgpu_types::Features::TEXTURE_COMPRESSION_ETC2) { + return_features.insert(TextureCompressionEtc2); + } + if features.contains(wgpu_types::Features::TEXTURE_COMPRESSION_ASTC) { + return_features.insert(TextureCompressionAstc); + } + if features.contains(wgpu_types::Features::TEXTURE_COMPRESSION_ASTC_SLICED_3D) + { + return_features.insert(TextureCompressionAstcSliced3d); + } + if features.contains(wgpu_types::Features::RG11B10UFLOAT_RENDERABLE) { + return_features.insert(Rg11b10ufloatRenderable); + } + if features.contains(wgpu_types::Features::BGRA8UNORM_STORAGE) { + return_features.insert(Bgra8unormStorage); + } + if features.contains(wgpu_types::Features::FLOAT32_FILTERABLE) { + return_features.insert(Float32Filterable); + } + if features.contains(wgpu_types::Features::DUAL_SOURCE_BLENDING) { + return_features.insert(DualSourceBlending); + } + if features.contains(wgpu_types::Features::SUBGROUP) { + return_features.insert(Subgroups); + } - // extended from spec + // extended from spec - // texture formats - if features.contains(wgpu_types::Features::TEXTURE_FORMAT_16BIT_NORM) { - return_features.insert(TextureFormat16BitNorm); - } - if features.contains(wgpu_types::Features::TEXTURE_COMPRESSION_ASTC_HDR) { - return_features.insert(TextureCompressionAstcHdr); - } - if features.contains(wgpu_types::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES) { - return_features.insert(TextureAdapterSpecificFormatFeatures); - } - // api - if features.contains(wgpu_types::Features::PIPELINE_STATISTICS_QUERY) { - return_features.insert(PipelineStatisticsQuery); - } - if features.contains(wgpu_types::Features::TIMESTAMP_QUERY_INSIDE_PASSES) { - return_features.insert(TimestampQueryInsidePasses); - } - if features.contains(wgpu_types::Features::MAPPABLE_PRIMARY_BUFFERS) { - return_features.insert(MappablePrimaryBuffers); - } - if features.contains(wgpu_types::Features::TEXTURE_BINDING_ARRAY) { - return_features.insert(TextureBindingArray); - } - if features.contains(wgpu_types::Features::BUFFER_BINDING_ARRAY) { - return_features.insert(BufferBindingArray); - } - if features.contains(wgpu_types::Features::STORAGE_RESOURCE_BINDING_ARRAY) { - return_features.insert(StorageResourceBindingArray); - } - if features.contains( + // texture formats + if features.contains(wgpu_types::Features::TEXTURE_FORMAT_16BIT_NORM) { + return_features.insert(TextureFormat16BitNorm); + } + if features.contains(wgpu_types::Features::TEXTURE_COMPRESSION_ASTC_HDR) { + return_features.insert(TextureCompressionAstcHdr); + } + if features + .contains(wgpu_types::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES) + { + return_features.insert(TextureAdapterSpecificFormatFeatures); + } + // api + if features.contains(wgpu_types::Features::PIPELINE_STATISTICS_QUERY) { + return_features.insert(PipelineStatisticsQuery); + } + if features.contains(wgpu_types::Features::TIMESTAMP_QUERY_INSIDE_PASSES) { + return_features.insert(TimestampQueryInsidePasses); + } + if features.contains(wgpu_types::Features::MAPPABLE_PRIMARY_BUFFERS) { + return_features.insert(MappablePrimaryBuffers); + } + if features.contains(wgpu_types::Features::TEXTURE_BINDING_ARRAY) { + return_features.insert(TextureBindingArray); + } + if features.contains(wgpu_types::Features::BUFFER_BINDING_ARRAY) { + return_features.insert(BufferBindingArray); + } + if features.contains(wgpu_types::Features::STORAGE_RESOURCE_BINDING_ARRAY) { + return_features.insert(StorageResourceBindingArray); + } + if features.contains( wgpu_types::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING, ) { return_features.insert(SampledTextureAndStorageBufferArrayNonUniformIndexing); } - if features.contains(wgpu_types::Features::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING) { - return_features.insert(StorageTextureArrayNonUniformIndexing); - } - if features.contains(wgpu_types::Features::UNIFORM_BUFFER_BINDING_ARRAYS) { - return_features.insert(UniformBufferBindingArrays); - } - if features.contains(wgpu_types::Features::PARTIALLY_BOUND_BINDING_ARRAY) { - return_features.insert(PartiallyBoundBindingArray); - } - if features.contains(wgpu_types::Features::MULTI_DRAW_INDIRECT) { - return_features.insert(MultiDrawIndirect); - } - if features.contains(wgpu_types::Features::MULTI_DRAW_INDIRECT_COUNT) { - return_features.insert(MultiDrawIndirectCount); - } - if features.contains(wgpu_types::Features::PUSH_CONSTANTS) { - return_features.insert(PushConstants); - } - if features.contains(wgpu_types::Features::ADDRESS_MODE_CLAMP_TO_ZERO) { - return_features.insert(AddressModeClampToZero); - } - if features.contains(wgpu_types::Features::ADDRESS_MODE_CLAMP_TO_BORDER) { - return_features.insert(AddressModeClampToBorder); - } - if features.contains(wgpu_types::Features::POLYGON_MODE_LINE) { - return_features.insert(PolygonModeLine); - } - if features.contains(wgpu_types::Features::POLYGON_MODE_POINT) { - return_features.insert(PolygonModePoint); - } - if features.contains(wgpu_types::Features::CONSERVATIVE_RASTERIZATION) { - return_features.insert(ConservativeRasterization); - } - if features.contains(wgpu_types::Features::VERTEX_WRITABLE_STORAGE) { - return_features.insert(VertexWritableStorage); - } - if features.contains(wgpu_types::Features::CLEAR_TEXTURE) { - return_features.insert(ClearTexture); - } - if features.contains(wgpu_types::Features::SPIRV_SHADER_PASSTHROUGH) { - return_features.insert(SpirvShaderPassthrough); - } - if features.contains(wgpu_types::Features::MULTIVIEW) { - return_features.insert(Multiview); - } - if features.contains(wgpu_types::Features::VERTEX_ATTRIBUTE_64BIT) { - return_features.insert(VertexAttribute64Bit); - } - // shader - if features.contains(wgpu_types::Features::SHADER_F64) { - return_features.insert(ShaderF64); - } - if features.contains(wgpu_types::Features::SHADER_I16) { - return_features.insert(ShaderI16); - } - if features.contains(wgpu_types::Features::SHADER_PRIMITIVE_INDEX) { - return_features.insert(ShaderPrimitiveIndex); - } - if features.contains(wgpu_types::Features::SHADER_EARLY_DEPTH_TEST) { - return_features.insert(ShaderEarlyDepthTest); - } + if features + .contains(wgpu_types::Features::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING) + { + return_features.insert(StorageTextureArrayNonUniformIndexing); + } + if features.contains(wgpu_types::Features::UNIFORM_BUFFER_BINDING_ARRAYS) { + return_features.insert(UniformBufferBindingArrays); + } + if features.contains(wgpu_types::Features::PARTIALLY_BOUND_BINDING_ARRAY) { + return_features.insert(PartiallyBoundBindingArray); + } + if features.contains(wgpu_types::Features::MULTI_DRAW_INDIRECT_COUNT) { + return_features.insert(MultiDrawIndirectCount); + } + if features.contains(wgpu_types::Features::PUSH_CONSTANTS) { + return_features.insert(PushConstants); + } + if features.contains(wgpu_types::Features::ADDRESS_MODE_CLAMP_TO_ZERO) { + return_features.insert(AddressModeClampToZero); + } + if features.contains(wgpu_types::Features::ADDRESS_MODE_CLAMP_TO_BORDER) { + return_features.insert(AddressModeClampToBorder); + } + if features.contains(wgpu_types::Features::POLYGON_MODE_LINE) { + return_features.insert(PolygonModeLine); + } + if features.contains(wgpu_types::Features::POLYGON_MODE_POINT) { + return_features.insert(PolygonModePoint); + } + if features.contains(wgpu_types::Features::CONSERVATIVE_RASTERIZATION) { + return_features.insert(ConservativeRasterization); + } + if features.contains(wgpu_types::Features::VERTEX_WRITABLE_STORAGE) { + return_features.insert(VertexWritableStorage); + } + if features.contains(wgpu_types::Features::CLEAR_TEXTURE) { + return_features.insert(ClearTexture); + } + if features.contains(wgpu_types::Features::MULTIVIEW) { + return_features.insert(Multiview); + } + if features.contains(wgpu_types::Features::VERTEX_ATTRIBUTE_64BIT) { + return_features.insert(VertexAttribute64Bit); + } + // shader + if features.contains(wgpu_types::Features::SHADER_F64) { + return_features.insert(ShaderF64); + } + if features.contains(wgpu_types::Features::SHADER_I16) { + return_features.insert(ShaderI16); + } + if features.contains(wgpu_types::Features::SHADER_PRIMITIVE_INDEX) { + return_features.insert(ShaderPrimitiveIndex); + } + if features.contains(wgpu_types::Features::SHADER_EARLY_DEPTH_TEST) { + return_features.insert(ShaderEarlyDepthTest); + } + if features.contains(wgpu_types::Features::EXPERIMENTAL_PASSTHROUGH_SHADERS) { + return_features.insert(PassthroughShaders); + } - return_features + return_features } diff --git a/docs/api-specs/mesh_shading.md b/docs/api-specs/mesh_shading.md new file mode 100644 index 000000000..4b28ec635 --- /dev/null +++ b/docs/api-specs/mesh_shading.md @@ -0,0 +1,270 @@ +# Mesh Shader Extensions + +🧪Experimental🧪 + +`wgpu` supports an experimental version of mesh shading when `Features::EXPERIMENTAL_MESH_SHADER` is enabled. +Currently `naga` has no support for parsing or writing mesh shaders. +For this reason, all shaders must be created with `Device::create_shader_module_passthrough`. + +**Note**: The features documented here may have major bugs in them and are expected to be subject +to breaking changes, suggestions for the API exposed by this should be posted on [the mesh-shading issue](https://github.com/gfx-rs/wgpu/issues/7197). + +## Mesh shaders overview + +### What are mesh shaders? + +Mesh shaders are a new kind of rasterization pipeline intended to address some of the shortfalls with the vertex shader pipeline. The core idea of mesh shaders is that the GPU decides how to render the many small parts of a scene instead of the CPU issuing a draw call for every small part or issuing an inefficient monolithic draw call for a large part of the scene. + +Mesh shaders are specifically designed to be used with **meshlet rendering**, a technique where every object is split into many subobjects called meshlets that are each rendered with their own parameters. With the standard vertex pipeline, each draw call specifies an exact number of primitives to render and the same parameters for all vertex shaders on an entire object (or even multiple objects). This doesn't leave room for different LODs for different parts of an object, for example a closer part having more detail, nor does it allow culling smaller sections (or primitives) of objects. With mesh shaders, each task workgroup might get assigned to a single object. It can then analyze the different meshlets(sections) of that object, determine which are visible and should actually be rendered, and for those meshlets determine what LOD to use based on the distance from the camera. It can then dispatch a mesh workgroup for each meshlet, with each mesh workgroup then reading the data for that specific LOD of its meshlet, determining which and how many vertices and primitives to output, determining which remaining primitives need to be culled, and passing the resulting primitives to the rasterizer. + +Mesh shaders are most effective in scenes with many polygons. They can allow skipping processing of entire groups of primitives that are facing away from the camera or otherwise occluded, which reduces the number of primitives that need to be processed by more than half in most cases, and they can reduce the number of primitives that need to be processed for more distant objects. Scenes that are not bottlenecked by geometry (perhaps instead by fragment processing or post processing) will not see much benefit from using them. + +Mesh shaders were first shown off in [NVIDIA's asteroids demo](https://www.youtube.com/watch?v=CRfZYJ_sk5E). Now, they form the basis for [Unreal Engine's Nanite](https://www.unrealengine.com/en-US/blog/unreal-engine-5-is-now-available-in-preview#Nanite). + +### Mesh shader pipeline + +With the current pipeline set to a mesh pipeline, a draw command like +`render_pass.draw_mesh_tasks(x, y, z)` takes the following steps: + +* If the pipeline has a task shader stage: + + * Dispatch a grid of task shader workgroups, where `x`, `y`, and `z` give + the number of workgroups along each axis of the grid. Each task shader + workgroup produces a mesh shader workgroup grid size `(mx, my, mz)` and a + task payload value `mp`. + + * For each task shader workgroup, dispatch a grid of mesh shader workgroups, + where `mx`, `my`, and `mz` give the number of workgroups along each axis + of the grid. Pass `mp` to each of these workgroup's mesh shader + invocations. + +* Alternatively, if the pipeline does not have a task shader stage: + + * Dispatch a single grid of mesh shader workgroups, where `x`, `y`, and `z` + give the number of workgroups along each axis of the grid. These mesh + shaders receive no task payload value. + +* Each mesh shader workgroup produces a list of output vertices, and a list of + primitives built from those vertices. The workgroup can supply per-primitive + values as well, if needed. Each primitive selects its vertices by index, like + an indexed draw call, from among the vertices generated by this workgroup. + + Unlike a grid of ordinary compute shader workgroups collaborating to build + vertex and index data in common storage buffers, the vertices and primitives + produced by a mesh shader workgroup are entirely private to that workgroup, + and are not accessible by other workgroups. + +* Primitives produced by a mesh shader workgroup can have a culling flag. If a + primitive's culling flag is false, it is skipped during rasterization. + +* The primitives produced by all mesh shader workgroups are then rasterized in + the usual way, with each fragment shader invocation handling one pixel. + + Attributes from the vertices produced by the mesh shader workgroup are + provided to the fragment shader with interpolation applied as appropriate. + + If the mesh shader workgroup supplied per-primitive values, these are + available to each primitive's fragment shader invocations. Per-primitive + values are never interpolated; fragment shaders simply receive the values + the mesh shader workgroup associated with their primitive. + +## `wgpu` API + +### New `wgpu` functions + +`Device::create_mesh_pipeline` - Creates a mesh shader pipeline. This is very similar to creating a standard render pipeline, except that it takes a mesh shader state and optional task shader state instead of a vertex state. If the task state is omitted, during rendering the number of workgroups is passed directly from the draw call to the mesh shader state, with an empty payload. + +`RenderPass::draw_mesh_tasks` - Dispatches the mesh shader pipeline. This ignores render pipeline specific information, such as vertex buffer bindings and index buffer bindings. The dispatch size must adhere to the limits described below. + +`RenderPass::draw_mesh_tasks_indirect`, `RenderPass::multi_draw_mesh_tasks_indirect` and `RenderPass::multi_draw_mesh_tasks_indirect_count` - Dispatches the mesh shader pipeline with dispatch size taken from a buffer. This ignores render pipeline specific information, such as vertex buffer bindings and index buffer bindings. The dispatch size must adhere to the limits described below. Analogous to `draw_indirect`, `multi_draw_indirect` and `multi_draw_indirect_count`. Requires the corresponding indirect feature to be enabled. + +An example of using mesh shaders to render a single triangle can be seen [here](../../examples/features/src/mesh_shader). + +### Features +* Using mesh shaders requires enabling `Features::EXPERIMENTAL_MESH_SHADER`. +* Using mesh shaders with multiview requires enabling `Features::EXPERIMENTAL_MESH_SHADER_MULTIVIEW`. +* Currently, only triangle rendering is tested +* Line rendering is supported but untested +* Point rendering is supported on vulkan. It is impossible on DirectX. Metal support hasn't been checked. +* Queries are unsupported + +### Limits + +> **NOTE**: More limits will be added when support is added to `naga`. + +* `Limits::max_task_workgroup_total_count` - the maximum total number of workgroups from a `draw_mesh_tasks` command or similar. The dimensions passed must be less than or equal to this limit when multiplied together. +* `Limits::max_task_workgroups_per_dimension` - the maximum for each of the 3 workgroup dimensions in a `draw_mesh_tasks` command. Each dimension passed must be less than or equal to this limit. +* `max_mesh_multiview_count` - The maximum number of views used when multiview rendering with a mesh shader pipeline. +* `max_mesh_output_layers` - the maximum number of output layers for a mesh shader pipeline. + +### Backend specific information +* Only Vulkan is currently supported. +* DirectX 12 doesn't support point rendering. +* DirectX 12 support is planned. +* Metal support is desired but not currently planned. + + +## Naga implementation + + +### Supported frontends +* 🛠️ WGSL +* ❌ SPIR-V +* 🚫 GLSL + +### Supported backends +* 🛠️ SPIR-V +* ❌ HLSL +* ❌ MSL +* 🚫 GLSL +* 🚫 WGSL + +✔️ = Complete +🛠️ = In progress +❌ = Planned +🚫 = Unplanned/impossible + +## `WGSL` extension specification + +The majority of changes relating to mesh shaders will be in WGSL and `naga`. + +Using any of these features in a `wgsl` program will require adding the `enable mesh_shading` directive to the top of a program. + +Two new shader stages will be added to `WGSL`. Fragment shaders are also modified slightly. Both task shaders and mesh shaders are allowed to use any compute-specific functionality, such as subgroup operations. + +### Task shader + +A function with the `@task` attribute is a **task shader entry point**. A mesh shader pipeline may optionally specify a task shader entry point, and if it does, mesh draw commands using that pipeline dispatch a **task shader grid** of workgroups running the task shader entry point. Like compute shader dispatches, the three-component size passed to `draw_mesh_tasks`, or drawn from the indirect buffer for its indirect variants, specifies the size of the task shader grid as the number of workgroups along each of the grid's three axes. + +A task shader entry point must have a `@workgroup_size` attribute, meeting the same requirements as one appearing on a compute shader entry point. + +A task shader entry point must also have a `@payload(G)` property, where `G` is the name of a global variable in the `task_payload` address space. Each task shader workgroup has its own instance of this variable, visible to all invocations in the workgroup. Whatever value the workgroup collectively stores in that global variable becomes the **task payload**, and is provided to all invocations in the mesh shader grid dispatched for the workgroup. + +A task shader entry point must return a `vec3` value. The return value of each workgroup's first invocation (that is, the one whose `local_invocation_index` is `0`) is taken as the size of a **mesh shader grid** to dispatch, measured in workgroups. (If the task shader entry point returns `vec3(0, 0, 0)`, then no mesh shaders are dispatched.) Mesh shader grids are described in the next section. + +Each task shader workgroup dispatches an independent mesh shader grid: in mesh shader invocations, `@builtin` values like `workgroup_id` and `global_invocation_id` describe the position of the workgroup and invocation within that grid; +and `@builtin(num_workgroups)` matches the task shader workgroup's return value. Mesh shaders dispatched for other task shader workgroups are not included in the count. If it is necessary for a mesh shader to know which task shader workgroup dispatched it, the task shader can include its own workgroup id in the task payload. + +### Mesh shader + +A function with the `@mesh` attribute is a **mesh shader entry point**. Mesh shaders must not return anything. + +Like compute shaders, mesh shaders are invoked in a grid of workgroups, called a **mesh shader grid**. If the mesh shader pipeline has a task shader, then each task shader workgroup determines the size of a mesh shader grid to be dispatched, as described above. Otherwise, the three-component size passed to `draw_mesh_tasks`, or drawn from the indirect buffer for its indirect variants, specifies the size of the mesh shader grid directly, as the number of workgroups along each of the grid's three axes. + +If the mesh shader pipeline has a task shader entry point, then the pipeline's mesh shader entry point must also have a `@payload(G)` attribute, naming the same variable, and the sizes must match. Mesh shader invocations can read, but not write, this variable, which is initialized to whatever value was written to it by the task shader workgroup that dispatched this mesh shader grid. + +If the mesh shader pipeline does not have a task shader entry point, then the mesh shader entry point must not have any `@payload` attribute. + +A mesh shader entry point must have the following attributes: + +- `@workgroup_size`: this has the same meaning as when it appears on a compute shader entry point. + +- `@vertex_output(V, NV)`: This indicates that the mesh shader workgroup will generate at most `NV` vertex values, each of type `V`. + +- `@primitive_output(P, NP)`: This indicates that the mesh shader workgroup will generate at most `NP` primitives, each of type `P`. + +Each mesh shader entry point invocation must call the `setMeshOutputs(numVertices: u32, numPrimitives: u32)` builtin function at least once. The values passed by each workgroup's first invocation (that is, the one whose `local_invocation_index` is `0`) determine how many vertices (values of type `V`) and primitives (values of type `P`) the workgroup must produce. The user can still write past these indices, but they won't be used in the output. + +The `numVertices` and `numPrimitives` arguments must be no greater than `NV` and `NP` from the `@vertex_output` and `@primitive_output` attributes. + +To produce vertex data, the workgroup as a whole must make `numVertices` calls to the `setVertex(i: u32, vertex: V)` builtin function. This establishes `vertex` as the value of the `i`'th vertex, where `i` is less than the maximum number of output vertices in the `@vertex_output` attribute. `V` is the type given in the `@vertex_output` attribute. `V` must meet the same requirements as a struct type returned by a `@vertex` entry point: all members must have either `@builtin` or `@location` attributes, there must be a `@builtin(position)`, and so on. + +To produce primitives, the workgroup as a whole must make `numPrimitives` calls to the `setPrimitive(i: u32, primitive: P)` builtin function. This establishes `primitive` as the value of the `i`'th primitive, where `i` is less than the maximum number of output primitives in the `@primitive_output` attribute. `P` is the type given in the `@primitive_output` attribute. `P` must be a struct type, every member of which either has a `@location` or `@builtin` attribute. The following `@builtin` attributes are allowed: + +- `triangle_indices`, `line_indices`, or `point_index`: The annotated member must be of type `vec3`, `vec2`, or `u32`. + + The member's components are indices (or, its value is an index) into the list of vertices generated by this workgroup, identifying the vertices of the primitive to be drawn. These indices must be less than the value of `numVertices` passed to `setMeshOutputs`. + + The type `P` must contain exactly one member with one of these attributes, determining what sort of primitives the mesh shader generates. + +- `cull_primitive`: The annotated member must be of type `bool`. If it is true, then the primitive is skipped during rendering. + +Every member of `P` with a `@location` attribute must either have a `@per_primitive` attribute, or be part of a struct type that appears in the primitive data as a struct member with the `@per_primitive` attribute. + +The `@location` attributes of `P` and `V` must not overlap, since they are merged to produce the user-defined inputs to the fragment shader. + +It is possible to write to the same vertex or primitive index repeatedly. Since the implicit arrays written by `setVertex` and `setPrimitive` are shared by the workgroup, data races on writes to the same index for a given type are undefined behavior. + +### Fragment shader + +Fragment shaders can access vertex output data as if it is from a vertex shader. They can also access primitive output data, provided the input is decorated with `@per_primitive`. The `@per_primitive` attribute can be applied to a value directly, such as `@per_primitive @location(1) value: vec4`, to a struct such as `@per_primitive primitive_input: PrimitiveInput` where `PrimitiveInput` is a struct containing fields decorated with `@location` and `@builtin`, or to members of a struct that are themselves decorated with `@location` or `@builtin`. + +The primitive state is part of the fragment input and must match the output of the mesh shader in the pipeline. Using `@per_primitive` also requires enabling the mesh shader extension. Additionally, the locations of vertex and primitive input cannot overlap. + +### Full example + +The following is a full example of WGSL shaders that could be used to create a mesh shader pipeline, showing off many of the features. + +```wgsl +enable mesh_shading; + +const positions = array( + vec4(0.,1.,0.,1.), + vec4(-1.,-1.,0.,1.), + vec4(1.,-1.,0.,1.) +); +const colors = array( + vec4(0.,1.,0.,1.), + vec4(0.,0.,1.,1.), + vec4(1.,0.,0.,1.) +); +struct TaskPayload { + colorMask: vec4, + visible: bool, +} +var taskPayload: TaskPayload; +var workgroupData: f32; +struct VertexOutput { + @builtin(position) position: vec4, + @location(0) color: vec4, +} +struct PrimitiveOutput { + @builtin(triangle_indices) index: vec3, + @builtin(cull_primitive) cull: bool, + @per_primitive @location(1) colorMask: vec4, +} +struct PrimitiveInput { + @per_primitive @location(1) colorMask: vec4, +} + +@task +@payload(taskPayload) +@workgroup_size(1) +fn ts_main() -> @builtin(mesh_task_size) vec3 { + workgroupData = 1.0; + taskPayload.colorMask = vec4(1.0, 1.0, 0.0, 1.0); + taskPayload.visible = true; + return vec3(3, 1, 1); +} +@mesh +@payload(taskPayload) +@vertex_output(VertexOutput, 3) @primitive_output(PrimitiveOutput, 1) +@workgroup_size(1) +fn ms_main(@builtin(local_invocation_index) index: u32, @builtin(global_invocation_id) id: vec3) { + setMeshOutputs(3, 1); + workgroupData = 2.0; + var v: VertexOutput; + + v.position = positions[0]; + v.color = colors[0] * taskPayload.colorMask; + setVertex(0, v); + + v.position = positions[1]; + v.color = colors[1] * taskPayload.colorMask; + setVertex(1, v); + + v.position = positions[2]; + v.color = colors[2] * taskPayload.colorMask; + setVertex(2, v); + + var p: PrimitiveOutput; + p.index = vec3(0, 1, 2); + p.cull = !taskPayload.visible; + p.colorMask = vec4(1.0, 0.0, 1.0, 1.0); + setPrimitive(0, p); +} +@fragment +fn fs_main(vertex: VertexOutput, primitive: PrimitiveInput) -> @location(0) vec4 { + return vertex.color * primitive.colorMask; +} +``` diff --git a/docs/api-specs/ray_tracing.md b/docs/api-specs/ray_tracing.md index 9d56cf1a6..a4038547d 100644 --- a/docs/api-specs/ray_tracing.md +++ b/docs/api-specs/ray_tracing.md @@ -3,7 +3,7 @@ 🧪Experimental🧪 `wgpu` supports an experimental version of ray tracing which is subject to change. The extensions allow for acceleration structures to be created and built (with -`Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE` enabled) and interacted with in shaders. Currently `naga` only supports ray queries +`Features::EXPERIMENTAL_RAY_QUERY` enabled) and interacted with in shaders. Currently `naga` only supports ray queries (accessible with `Features::EXPERIMENTAL_RAY_QUERY` enabled in wgpu). **Note**: The features documented here may have major bugs in them and are expected to be subject @@ -18,12 +18,13 @@ an [introduction](https://developer.nvidia.com/blog/introduction-nvidia-rtx-dire The documentation and specific details of the functions and structures provided can be found with their definitions. +Acceleration structures do not have a separate feature, instead they are enabled by `Features::EXPERIMENTAL_RAY_QUERY`, unlike vulkan. +When ray tracing pipelines are added, that feature will also enable acceleration structures. + A [`Blas`] can be created with [`Device::create_blas`]. A [`Tlas`] can be created with [`Device::create_tlas`]. -Unless one is planning on using the unsafe building API (not recommended for beginners) a [`Tlas`] should be put inside -a [`TlasPackage`]. After that a reference to the [`Tlas`] can be retrieved by calling [`TlasPackage::tlas`]. -This reference can be placed in a bind group to be used in a shader. A reference to a [`Blas`] can +The [`Tlas`] reference can be placed in a bind group to be used in a shader. A reference to a [`Blas`] can be used to create [`TlasInstance`] alongside a transformation matrix, a custom index (this can be any data that should be given to the shader on a hit) which only the first 24 bits may be set, and a mask to filter hits in the shader. @@ -34,13 +35,61 @@ Before a [`Tlas`] is used in a shader it must - have all [`Blas`]es that it was last built with to have last been built in either the same build as this [`Tlas`] or an earlier build call. +### [`Blas`] compaction + +Once a [`Blas`] has been built, it can be compacted. Acceleration structures are allocated conservatively, without +knowing the exact data that is inside them. Once a [`Blas`] has been built, the driver can make data specific +optimisations to make the [`BLAS`] smaller. To begin compaction call [`Blas::prepare_compaction_async`] on it. This +method waits until all builds operating on the [`Blas`] are finished, prepares the [`Blas`] to be compacted, and runs +the given callback. To check whether the [`Blas`] is ready, you can also call [`Blas::ready_for_compaction`] instead of +waiting for the callback (useful if you are asynchronously compacting a large number of [`Blas`]es). Submitting a +rebuild of a [`Blas`] terminates any [`Blas::prepare_compaction_async`], preventing the callback from being called, and +making the [`Blas`] no longer ready to compact. Once a [`Blas`] is ready for compaction, it can be compacted using +[`Queue::compact_blas`] this returns the new compacted [`Blas`], which is independent of the [`Blas`] passed in. The +other [`Blas`] can be used for other things, including being rebuilt without affecting the new [`Blas`]. The returned +[`Blas`] behaves largely like the [`Blas`] it was created from, except that it can be neither rebuilt, nor compacted +again. + +An example of compaction being run when [`Blas`]es are ready, this would be in a situation when memory was not a major +problem, otherwise (e.g. if you get an out of memory error) you should compact immediately (and switching all +non-compacted [`Blas`]es to compacted ones). +```rust +use std::iter; +use wgpu::Blas; + +struct BlasToBeCompacted { + blas: Blas, + /// The index into the TlasInstance this BLAS is used in. + tlas_index: usize, +} + +fn render(/*whatever args you need to render*/) { + /* additional code to prepare the renderer */ + //An iterator of whatever BLASes you have called `prepare_compaction_async` on. + let blas_s_pending_compaction: impl Iterator = iter::empty(); + for blas_to_be_compacted in blas_s_pending_compaction { + if blas_to_be_compacted.blas.ready_for_compaction() { + let compacted_blas = queue.compact_blas(&blas_to_be_compacted.blas); + tlas_instance[blas_to_be_compacted.tlas_index].set_blas(&compacted_blas); + } + } + let mut encoder = + device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); + /* do other preparations on th TlasInstance.*/ + encoder.build_acceleration_structures(iter::empty(), iter::once(&tlas_package)); + /* more render code */ + queue.submit(Some(encoder.finish())); +} +``` + [`Device::create_blas`]: https://wgpu.rs/doc/wgpu/struct.Device.html#method.create_blas [`Device::create_tlas`]: https://wgpu.rs/doc/wgpu/struct.Device.html#method.create_tlas [`Tlas`]: https://wgpu.rs/doc/wgpu/struct.Tlas.html [`Blas`]: https://wgpu.rs/doc/wgpu/struct.Blas.html [`TlasInstance`]: https://wgpu.rs/doc/wgpu/struct.TlasInstance.html -[`TlasPackage`]: https://wgpu.rs/doc/wgpu/struct.TlasPackage.html -[`TlasPackage::tlas`]: https://wgpu.rs/doc/wgpu/struct.TlasPackage.html#method.tlas +[`Blas::prepare_compaction_async`]: https://wgpu.rs/doc/wgpu/struct.Blas.html#method.prepare_compaction_async +[`Blas::ready_for_compaction`]: https://wgpu.rs/doc/wgpu/struct.Blas.html#method.ready_for_compaction +[`Queue::compact_blas`]: https://wgpu.rs/doc/wgpu/struct.Queue.html#method.compact_blas ## `naga`'s raytracing API: diff --git a/docs/broadcast_license.nu b/docs/broadcast_license.nu new file mode 100644 index 000000000..bd676677f --- /dev/null +++ b/docs/broadcast_license.nu @@ -0,0 +1,23 @@ +# Quick maintenance script which broadcasts the license files to all crates +# that are released on crates.io + +# Change to the root of the repository +cd ($env.FILE_PWD | path dirname) + +let crates = [ + "wgpu", + "wgpu-core", + "wgpu-core/platform-deps/apple", + "wgpu-core/platform-deps/emscripten", + "wgpu-core/platform-deps/wasm", + "wgpu-core/platform-deps/windows-linux-android", + "wgpu-hal", + "wgpu-info", + "wgpu-types", + "naga", + "naga-cli", +] + +for crate in $crates { + cp LICENSE.APACHE LICENSE.MIT $"./($crate)/" +} diff --git a/docs/release-checklist.md b/docs/release-checklist.md index 768167d12..a51e178e7 100644 --- a/docs/release-checklist.md +++ b/docs/release-checklist.md @@ -8,14 +8,13 @@ We do a patch releases as needed in the weeks between major releases. Once a new ## People -Anyone can perform most of these steps, except actually publishing the crates. - -Currently only @kvark and @cwfitzgerald can publish all crates. @grovesNL can also publish `wgpu` crates. @jimblandy can publish `naga` crates. +Anyone in the @gfx-rs/wgpu team can perform these steps. ## Major Release Process Approx 1 Week Before: -- Determine if `glow` (@groves), `metal-rs` (@kvark and @cwfitzgerald) or any other dependant crates will need a release. If so, coordinate with their maintainers. + +- Determine if `glow` (@groves), `metal-rs` (@gfx-rs/wgpu) or any other dependant crates will need a release. If so, coordinate with their maintainers. - Go through the changelog: - Re-categorize miscategorized items. - Edit major changes so a user can easily understand what they need to do. @@ -23,13 +22,13 @@ Approx 1 Week Before: - Copy-edit the changelog for clarity. Day of Release: -- Update all crates to be the new version. We bump all versions even if there were no changes. - - `naga` - - `naga-cli` - - `wgpu-types` - - `wgpu-hal` - - `wgpu-core` - - `Cargo.toml` (this covers the rest of the crates). + +- Update the version number in the root `Cargo.toml` to the new version, this will update all crates to the new version. +- Bump the wgpu dependency numbers in the following places: + - `Cargo.toml` + - `examples/standalone/*` +- Grep for the previous version to ensure various documentation links are updated. + - For example, if the previous version was v24.0.0, grep for `v24` and `24.0` - Ensure `glow` and `metal` are updated to the latest version if needed. - Add a new header for the changelog with the release version and date. - Create a PR with all of the version changes and changelog updates. @@ -37,16 +36,17 @@ Day of Release: - Checkout `trunk` with the merged PR. - Publish! These commands can be pasted directly into your terminal in a single command, and they will publish everything. ```bash - cargo publish -p naga - cargo publish -p naga-cli - cargo publish -p wgpu-types - cargo publish -p wgpu-hal --all-features - cargo publish -p wgpu-core --all-features - cargo publish -p wgpu - cargo publish -p wgpu-info + cargo +stable publish --workspace --exclude deno_webgpu ``` -- Create a new release on the `wgpu` repo with the changelog and a tag called `vX.Y.Z`. -- Create a branch with the with the new version `vX.Y` and push it to the repo. +- If there were any newly published crates, ensure `github:gfx-rs/wgpu` is added as an owner of that crate. +- Create a new tag called `vX.Y.Z` and push it to the repo. + - For each crate being released (viz., every `publish`-able crate that is not `deno*`), create a new tag of the form `{crate_name}-vX.Y.X`. +- Create a new release on the `wgpu` repo with the changelog from this version, targeting that tag +- Create a branch with the with the new version `vX` and push it to the repo. + - On this branch, remove the [!NOTE] at the top of [wgpu/examples/README.md]. +- Complete the release's milestone on GitHub. +- Create a new milestone for the next release, in 12 weeks time. +- Update the release checklist with any needed changes. - Publish the link to the github release in the following places. - [r/rust](https://www.reddit.com/r/rust/). - Add an AMA comment. @@ -58,20 +58,25 @@ Day of Release: - [Bevy Discord](https://discord.com/invite/bevy) in the #rendering-dev channel - [Graphics Programming Discord](https://discord.gg/6mgNGk7) in the #webgpu channel - [Rust Community Discord](https://discord.gg/rust-lang-community) in the #games-and-graphics channel -- Complete the release's milestone on GitHub. -- Create a new milestone for the next release, in 12 weeks time. ## Patch Release Process -- Enumerate all PRs that haven't been backported yet. These use the `needs-backport` label. [GH Link](https://github.com/gfx-rs/wgpu/issues?q=label%3A%22PR%3A+needs+back-porting) + +- Enumerate all PRs that haven't been backported yet. These use the `PR: needs back-porting` label. [GH Link](https://github.com/gfx-rs/wgpu/pulls?q=sort%3Aupdated-desc+is%3Apr+label%3A%22PR%3A+needs+back-porting%22) - On _your own branch_ based on the latest release branch. Cherry-pick the PRs that need to be backported. When modifying the commits, use --append to retain their original authorship. - Remove the `needs-backport` label from the PRs. - Fix the changelogs items and add a new header for the patch release with the release version and date. + - The release section should start with a header saying the following (for example) + ```markdown + This release includes `crate1`, `crate2` and `crate3` version `X.Y.Z`. All other crates remain at their previous versions. + ``` - Once all the PRs are cherry-picked, look at the diff between HEAD and the previous patch release. See what crates changed. - Bump all the versions of the crates that changed. - Create a PR with all of the version changes and changelog updates into the release branch. - Once the PR is CI clean, (force) rebase merge it. - Checkout the release branch with the merged PR. - Publish all relevant crates (see list above). -- Create a new release on the `wgpu` repo with the changelog and a tag called `vX.Y.Z` on the release branch. +- Create a new release on the `wgpu` repo with the relevant changelog included, based on a new tag called `vX.Y.Z` in the release branch. + - For each crate released, also create a tag `{crate_name}-vX.Y.Z`. - Backport the changelog and version bumps to the `trunk` branch. - Ensure that any items in the newly-released changelog don't appear in the "unreleased" section of the trunk changelog. +- Update the release checklist with any needed changes. diff --git a/docs/review-checklist.md b/docs/review-checklist.md index b422b8f58..918075f1b 100644 --- a/docs/review-checklist.md +++ b/docs/review-checklist.md @@ -67,5 +67,5 @@ If your change adds a new operation: identifiers? (This is usually not relevant to the SPIR-V backend.) - [ ] Did you use the `Namer` to generate a fresh identifier? - - [ ] Did you register the identifier as a reserved word with the the `Namer`? + - [ ] Did you register the identifier as a reserved word with the `Namer`? - [ ] Did you use a reserved prefix registered with the `Namer`? diff --git a/docs/testing.md b/docs/testing.md index 1ddf86a56..dcca39404 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -36,10 +36,10 @@ This is a table of contents, in the form of the repository's directory structure - player - [tests](#player-tests) - tests - - [compile-tests](#wgpu-compile-tests) - - [dependency-tests](#wgpu-dependency-tests) - - [gpu-tests](#wgpu-gpu-tests) - - [validation-tests](#wgpu-validation-tests) + - [compile](#wgpu-compile-tests) + - [dependency](#wgpu-dependency-tests) + - [gpu](#wgpu-gpu-tests) + - [validation](#wgpu-validation-tests) And where applicable [unit-tests](#unit-tests) are scatteredthroughout the codebase. @@ -84,16 +84,16 @@ they should be easy to copy into a standalone project. ## `naga` Example Tests -- Located in: `naga/tests/example_wgsl` -- Run with `cargo nextest run --test naga-test example_wgsl` +- Located in: `naga/tests/naga/example_wgsl` +- Run with `cargo nextest run --test naga example_wgsl` This simple test ensures that all wgsl files in the `examples` directory can be parsed by `naga`'s `wgsl` parser and validate correctly. ## `naga` Snapshot Tests -- Located in: `naga/tests/snapshot`, `naga/tests/in`, and `naga/tests/out` -- Run with `cargo nextest run --test naga-test snapshots` +- Located in: `naga/tests/naga/snapshot`, `naga/tests/in`, and `naga/tests/out` +- Run with `cargo nextest run --test naga snapshots` - Data driven snapshot tests for `naga`'s input/output. These tests are snapshot tests for `naga`s parsers and code generators. @@ -118,8 +118,8 @@ will use the respective tool to validate the generated code. ## `naga` SPIR-V Capabilities Tests -- Located in: `naga/tests/spirv_capabilities` -- Run with `cargo nextest run --test naga-test spirv_capabilities` +- Located in: `naga/tests/naga/spirv_capabilities` +- Run with `cargo nextest run --test naga spirv_capabilities` - Uses the standard `#[test]` harness. These tests convert the given wgsl snippet to spirv and @@ -127,8 +127,8 @@ then assert that the spirv has enabled the expected capabilities. ## `naga` Validation Tests -- Located in: `naga/tests/validation` -- Run with `cargo nextest run --test naga-test validation` +- Located in: `naga/tests/naga/validation` +- Run with `cargo nextest run --test naga validation` These are hand rolled tests against the naga's validator. If you don't need to test the validator with a custom module, @@ -137,8 +137,8 @@ the [wgsl errors](#naga-wgsl-error-tests) tests. ## `naga` WGSL Error Tests -- Located in: `naga/tests/wgsl_errors` -- Run with `cargo nextest run --test naga-test wgsl_errors` +- Located in: `naga/tests/naga/wgsl_errors` +- Run with `cargo nextest run --test naga wgsl_errors` These are tests for the error messages that the `wgsl` frontend produces. Additionally you can check that a given validation error @@ -147,7 +147,7 @@ is produced by the validator from a given `wgsl` snippet. ## `player` Tests - Located in: `player/tests` -- Run with `cargo nextest run --test player-test` +- Run with `cargo nextest run --test player` - Data driven tests using the `player`'s replay system. - `wgpu` integration tests. @@ -161,9 +161,9 @@ These tests only run on your system's default GPU. ## `wgpu` Compile Tests -- Located in: `tests/compile-tests` -- Run with `cargo nextest run --test wgpu-compile-test` -- `trybuild` tests of all rust files in `tests/compile-tests/fail` directory. +- Located in: `tests/tests/wgpu-compile` +- Run with `cargo nextest run --test wgpu-compile` +- `trybuild` tests of all rust files in `tests/tests/wgpu-compile/fail` directory. These use the `trybuild` crate to test a few scenarios where the `wgpu` crate is expected to fail to compile. This mainly @@ -172,8 +172,8 @@ dropping passes, etc. ## `wgpu` Dependency Tests -- Located in: `tests/dependency-tests` -- Run with `cargo nextest run --test wgpu-dependency-test` +- Located in: `tests/tests/wgpu-dependency` +- Run with `cargo nextest run --test wgpu-dependency` - Tests against `cargo tree`. These tests ensure that the `wgpu` crate has the correct dependency @@ -184,8 +184,8 @@ This provides a way to ensure that our `toml` files are correct. ## `wgpu` GPU Tests -- Located in: `tests/gpu-tests` -- Run with `cargo xtask test --test wgpu-gpu-test` +- Located in: `tests/tests/wgpu-gpu` +- Run with `cargo xtask test --test wgpu-gpu` - Uses a custom `#[gpu_test]` harness. - `wgpu` integration tests, with access to `wgpu_test` helpers. @@ -209,8 +209,8 @@ See also the [example tests](#example-tests) for additional GPU tests. ## `wgpu` Validation Tests -- Located in: `tests/validation-tests` -- Run with `cargo nextest run --test wgpu-validation-test` +- Located in: `tests/tests/wgpu-validation` +- Run with `cargo nextest run --test wgpu-validation` - Use the standard `#[test]` harness. - `wgpu` integration tests, with access to `wgpu_test` helpers. diff --git a/examples/README.md b/examples/README.md index 2d0cd8bbb..0ebf805b4 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,10 +1,10 @@ > [!NOTE] > These are the examples for the development version of wgpu. If you want to see the examples for the latest crates.io release -> of wgpu, go to the [latest release branch](https://github.com/gfx-rs/wgpu/tree/v24/examples#readme). +> of wgpu, go to the [latest release branch](https://github.com/gfx-rs/wgpu/tree/v27/examples#readme). # Examples -If you are just starting your graphics programming journey entirely, we recommend going through [Learn-WGPU](https://sotrh.github.io/learn-wgpu/) +If you are just starting your graphics programming journey entirely, we recommend going through [Learn-wgpu](https://sotrh.github.io/learn-wgpu/) for a mode guided tutorial, which will also teach you the basics of graphics programming. ## Standalone Examples @@ -23,7 +23,7 @@ be cloned out of the repository to serve as a starting point for your own projec You can also use [`cargo-generate`](https://github.com/cargo-generate/cargo-generate) to easily use these as a basis for your own projects. ```sh -cargo generate gfx-rs/wgpu --branch v24 +cargo generate gfx-rs/wgpu --branch v27 ``` ## Framework Examples @@ -32,17 +32,18 @@ These examples use a common framework to handle wgpu init, window creation, and #### Graphics -- `hello_triangle` - Provides an example of a bare-bones WGPU workflow using the Winit crate that simply renders a red triangle on a green background. +- `hello_triangle` - Provides an example of a bare-bones wgpu workflow using the Winit crate that simply renders a red triangle on a green background. - `uniform_values` - Demonstrates the basics of enabling shaders and the GPU, in general, to access app state through uniform variables. `uniform_values` also serves as an example of rudimentary app building as the app stores state and takes window-captured keyboard events. The app displays the Mandelbrot Set in grayscale (similar to `storage_texture`) but allows the user to navigate and explore it using their arrow keys and scroll wheel. - `cube` - Introduces the user to slightly more advanced models. The example creates a set of triangles to form a cube on the CPU and then uses a vertex and index buffer to send the generated model to the GPU for usage in rendering. It also uses a texture generated on the CPU to shade the sides of the cube and a uniform variable to apply a transformation matrix to the cube in the shader. - `bunnymark` - Demonstrates many things, but chief among them is performing numerous draw calls with different bind groups in one render pass. The example also uses textures for the icon and uniform buffers to transfer both global and per-particle states. - `skybox` - Shows off too many concepts to list here. The name comes from game development where a "skybox" acts as a background for rendering, usually to add a sky texture for immersion, although they can also be used for backdrops to give the idea of a world beyond the game scene. This example does so much more than this, though, as it uses a car model loaded from a file and uses the user's mouse to rotate the car model in 3d. `skybox` also makes use of depth textures and similar app patterns to `uniform_values`. -- `shadow` - Likely by far the most complex example (certainly the largest in lines of code) of the official WGPU examples. `shadow` demonstrates basic scene rendering with the main attraction being lighting and shadows (as the name implies). It is recommended that any user looking into lighting be very familiar with the basic concepts of not only rendering with WGPU but also the primary mathematical ideas of computer graphics. +- `shadow` - Likely by far the most complex example (certainly the largest in lines of code) of the official wgpu examples. `shadow` demonstrates basic scene rendering with the main attraction being lighting and shadows (as the name implies). It is recommended that any user looking into lighting be very familiar with the basic concepts of not only rendering with wgpu but also the primary mathematical ideas of computer graphics. - `multiple-render-targets` - Demonstrates how to render to two texture targets simultaneously from fragment shader. - `render_to_texture` - Renders to an image texture offscreen, demonstrating both off-screen rendering as well as how to add a sort of resolution-agnostic screenshot feature to an engine. This example either outputs an image file of your naming (pass command line arguments after specifying a `--` like `cargo run --bin wgpu-examples -- render_to_texture "test.png"`) or adds an `img` element containing the image to the page in WASM. - `ray_cube_fragment` - Demonstrates using ray queries with a fragment shader. - `ray_scene` - Demonstrates using ray queries and model loading - `ray_shadows` - Demonstrates a simple use of ray queries - high quality shadows - uses a light set with push constants to raytrace through an untransformed scene and detect whether there is something obstructing the light. +- `mesh_shader` - Renders a triangle to a window with mesh shaders, while showcasing most mesh shader related features(task shaders, payloads, per primitive data). #### Compute diff --git a/examples/features/Cargo.toml b/examples/features/Cargo.toml index ec79438af..54998b467 100644 --- a/examples/features/Cargo.toml +++ b/examples/features/Cargo.toml @@ -33,19 +33,20 @@ webgpu = ["wgpu/webgpu"] [dependencies] bytemuck.workspace = true cfg-if.workspace = true -encase = { workspace = true, features = ["glam"] } +encase = { workspace = true } flume.workspace = true -glam = { workspace = true, features = ["bytemuck"] } +getrandom = { workspace = true, features = ["wasm_js"] } +glam = { workspace = true, features = ["bytemuck", "encase"] } ktx2.workspace = true log.workspace = true -nanorand.workspace = true +nanorand = { workspace = true, features = ["getrandom"] } noise.workspace = true obj.workspace = true png.workspace = true pollster.workspace = true web-time.workspace = true -wgpu.workspace = true wgpu-types = { workspace = true, features = [ + "std", "trace", # TODO(#5974): this should be a dep on wgpu/trace and not wgpu-types at all ] } winit.workspace = true @@ -55,6 +56,7 @@ wgpu-test.workspace = true [target.'cfg(not(target_arch = "wasm32"))'.dependencies] env_logger.workspace = true +wgpu.workspace = true [target.'cfg(target_arch = "wasm32")'.dependencies] console_error_panic_hook.workspace = true @@ -62,6 +64,10 @@ console_log.workspace = true fern.workspace = true wasm-bindgen.workspace = true wasm-bindgen-futures.workspace = true +wgpu = { path = "../../wgpu", default-features = false, features = [ + "wgsl", + "std", +] } # We need these features in the framework examples and tests web-sys = { workspace = true, features = [ "Location", diff --git a/examples/features/src/big_compute_buffers/mod.rs b/examples/features/src/big_compute_buffers/mod.rs index 905612718..7a4f658f7 100644 --- a/examples/features/src/big_compute_buffers/mod.rs +++ b/examples/features/src/big_compute_buffers/mod.rs @@ -80,7 +80,7 @@ pub async fn execute_gpu_inner( slice.map_async(wgpu::MapMode::Read, |_| {}); } - device.poll(wgpu::PollType::Wait).unwrap(); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); let mut data = Vec::new(); for staging_buffer in &staging_buffers { @@ -193,7 +193,7 @@ fn create_storage_buffers(device: &wgpu::Device, numbers: &[f32]) -> Vec Vec Option<&Surface> { + fn get(&self) -> Option<&'_ Surface<'static>> { self.surface.as_ref() } @@ -268,9 +270,9 @@ impl ExampleContext { async fn init_async(surface: &mut SurfaceWrapper, window: Arc) -> Self { log::info!("Initializing wgpu..."); - let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor::from_env_or_default()); + let instance_descriptor = wgpu::InstanceDescriptor::from_env_or_default(); + let instance = wgpu::Instance::new(&instance_descriptor); surface.pre_adapter(&instance, window); - let adapter = get_adapter_with_capabilities_or_from_env( &instance, &E::required_features(), @@ -287,6 +289,7 @@ impl ExampleContext { required_features: (E::optional_features() & adapter.features()) | E::required_features(), required_limits: needed_limits, + experimental_features: unsafe { wgpu::ExperimentalFeatures::enabled() }, memory_hints: wgpu::MemoryHints::MemoryUsage, trace: match std::env::var_os("WGPU_TRACE") { Some(path) => wgpu::Trace::Directory(path.into()), @@ -328,7 +331,7 @@ impl FrameCounter { let elapsed_ms = elapsed_secs * 1000.0; let frame_time = elapsed_ms / self.frame_count as f32; let fps = self.frame_count as f32 / elapsed_secs; - log::info!("Frame time {:.2}ms ({:.1} FPS)", frame_time, fps); + log::info!("Frame time {frame_time:.2}ms ({fps:.1} FPS)"); self.last_printed_instant = new_instant; self.frame_count = 0; @@ -596,7 +599,9 @@ impl From> let dst_buffer_slice = dst_buffer.slice(..); dst_buffer_slice.map_async(wgpu::MapMode::Read, |_| ()); - ctx.async_poll(wgpu::PollType::wait()).await.unwrap(); + ctx.async_poll(wgpu::PollType::wait_indefinitely()) + .await + .unwrap(); let bytes = dst_buffer_slice.get_mapped_range().to_vec(); wgpu_test::image::compare_image_output( diff --git a/examples/features/src/hello_synchronization/mod.rs b/examples/features/src/hello_synchronization/mod.rs index 41d51acd5..ea41e4944 100644 --- a/examples/features/src/hello_synchronization/mod.rs +++ b/examples/features/src/hello_synchronization/mod.rs @@ -16,6 +16,7 @@ async fn run() { label: None, required_features: wgpu::Features::empty(), required_limits: wgpu::Limits::downlevel_defaults(), + experimental_features: wgpu::ExperimentalFeatures::disabled(), memory_hints: wgpu::MemoryHints::Performance, trace: wgpu::Trace::Off, }) @@ -28,13 +29,13 @@ async fn run() { } = execute(&device, &queue, ARR_SIZE).await; // Print data - log::info!("Patient results: {:?}", patient_workgroup_results); + log::info!("Patient results: {patient_workgroup_results:?}"); if !patient_workgroup_results.iter().any(|e| *e != 16) { log::info!("patient_main was patient."); } else { log::error!("patient_main was not patient!"); } - log::info!("Hasty results: {:?}", hasty_workgroup_results); + log::info!("Hasty results: {hasty_workgroup_results:?}"); if hasty_workgroup_results.iter().any(|e| *e != 16) { log::info!("hasty_main was not patient."); } else { @@ -181,7 +182,7 @@ async fn get_data( let buffer_slice = staging_buffer.slice(..); let (sender, receiver) = flume::bounded(1); buffer_slice.map_async(wgpu::MapMode::Read, move |r| sender.send(r).unwrap()); - device.poll(wgpu::PollType::wait()).unwrap(); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); receiver.recv_async().await.unwrap().unwrap(); output.copy_from_slice(bytemuck::cast_slice(&buffer_slice.get_mapped_range()[..])); staging_buffer.unmap(); @@ -208,4 +209,4 @@ pub fn main() { } #[cfg(test)] -mod tests; +pub mod tests; diff --git a/examples/features/src/hello_synchronization/tests.rs b/examples/features/src/hello_synchronization/tests.rs index 756289a36..ff34abbd0 100644 --- a/examples/features/src/hello_synchronization/tests.rs +++ b/examples/features/src/hello_synchronization/tests.rs @@ -2,7 +2,7 @@ use super::*; use wgpu_test::{gpu_test, GpuTestConfiguration, TestParameters}; #[gpu_test] -static SYNC: GpuTestConfiguration = GpuTestConfiguration::new() +pub static SYNC: GpuTestConfiguration = GpuTestConfiguration::new() .parameters( // Taken from hello-compute tests. TestParameters::default() diff --git a/examples/features/src/hello_triangle/mod.rs b/examples/features/src/hello_triangle/mod.rs index cba78face..66696dbe8 100644 --- a/examples/features/src/hello_triangle/mod.rs +++ b/examples/features/src/hello_triangle/mod.rs @@ -31,6 +31,7 @@ async fn run(event_loop: EventLoop<()>, window: Window) { // Make sure we use the texture resolution limits from the adapter, so we can support images the size of the swapchain. required_limits: wgpu::Limits::downlevel_webgl2_defaults() .using_resolution(adapter.limits()), + experimental_features: wgpu::ExperimentalFeatures::disabled(), memory_hints: wgpu::MemoryHints::MemoryUsage, trace: wgpu::Trace::Off, }) @@ -70,7 +71,7 @@ async fn run(event_loop: EventLoop<()>, window: Window) { primitive: wgpu::PrimitiveState::default(), depth_stencil: None, multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None, }); @@ -118,6 +119,7 @@ async fn run(event_loop: EventLoop<()>, window: Window) { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::GREEN), @@ -127,6 +129,7 @@ async fn run(event_loop: EventLoop<()>, window: Window) { depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); rpass.set_pipeline(&render_pipeline); rpass.draw(0..3, 0..1); diff --git a/examples/features/src/hello_windows/mod.rs b/examples/features/src/hello_windows/mod.rs index 2fb24a081..c1234e549 100644 --- a/examples/features/src/hello_windows/mod.rs +++ b/examples/features/src/hello_windows/mod.rs @@ -74,6 +74,7 @@ async fn run(event_loop: EventLoop<()>, viewports: Vec<(Arc, wgpu::Color label: None, required_features: wgpu::Features::empty(), required_limits: wgpu::Limits::downlevel_defaults(), + experimental_features: wgpu::ExperimentalFeatures::disabled(), memory_hints: wgpu::MemoryHints::MemoryUsage, trace: wgpu::Trace::Off, }) @@ -119,6 +120,7 @@ async fn run(event_loop: EventLoop<()>, viewports: Vec<(Arc, wgpu::Color color_attachments: &[Some( wgpu::RenderPassColorAttachment { view: &view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear( @@ -131,6 +133,7 @@ async fn run(event_loop: EventLoop<()>, viewports: Vec<(Arc, wgpu::Color depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); } diff --git a/examples/features/src/hello_workgroups/mod.rs b/examples/features/src/hello_workgroups/mod.rs index 5a8e7ffab..a3f3885a9 100644 --- a/examples/features/src/hello_workgroups/mod.rs +++ b/examples/features/src/hello_workgroups/mod.rs @@ -31,6 +31,7 @@ async fn run() { label: None, required_features: wgpu::Features::empty(), required_limits: wgpu::Limits::downlevel_defaults(), + experimental_features: wgpu::ExperimentalFeatures::disabled(), memory_hints: wgpu::MemoryHints::MemoryUsage, trace: wgpu::Trace::Off, }) @@ -170,7 +171,7 @@ async fn get_data( let buffer_slice = staging_buffer.slice(..); let (sender, receiver) = flume::bounded(1); buffer_slice.map_async(wgpu::MapMode::Read, move |r| sender.send(r).unwrap()); - device.poll(wgpu::PollType::wait()).unwrap(); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); receiver.recv_async().await.unwrap().unwrap(); output.copy_from_slice(bytemuck::cast_slice(&buffer_slice.get_mapped_range()[..])); staging_buffer.unmap(); diff --git a/examples/features/src/lib.rs b/examples/features/src/lib.rs index 479f1d12e..2299dded7 100644 --- a/examples/features/src/lib.rs +++ b/examples/features/src/lib.rs @@ -13,9 +13,11 @@ pub mod hello_synchronization; pub mod hello_triangle; pub mod hello_windows; pub mod hello_workgroups; +pub mod mesh_shader; pub mod mipmap; pub mod msaa_line; pub mod multiple_render_targets; +pub mod multiview; pub mod ray_cube_compute; pub mod ray_cube_fragment; pub mod ray_cube_normals; @@ -35,4 +37,52 @@ pub mod uniform_values; pub mod water; #[cfg(test)] -wgpu_test::gpu_test_main!(); +fn all_tests() -> Vec { + #[cfg_attr( + target_arch = "wasm32", + expect(unused_mut, reason = "non-wasm32 needs this mutable") + )] + let mut test_list = vec![ + boids::TEST, + bunnymark::TEST, + conservative_raster::TEST, + cube::TEST, + cube::TEST_LINES, + hello_synchronization::tests::SYNC, + mipmap::TEST, + mipmap::TEST_QUERY, + msaa_line::TEST, + multiple_render_targets::TEST, + ray_cube_compute::TEST, + ray_cube_fragment::TEST, + ray_cube_normals::TEST, + ray_scene::TEST, + ray_shadows::TEST, + ray_traced_triangle::TEST, + shadow::TEST, + skybox::TEST, + skybox::TEST_ASTC, + skybox::TEST_BCN, + skybox::TEST_ETC2, + srgb_blend::TEST_LINEAR, + srgb_blend::TEST_SRGB, + stencil_triangles::TEST, + texture_arrays::TEST, + texture_arrays::TEST_NON_UNIFORM, + texture_arrays::TEST_UNIFORM, + timestamp_queries::tests::TIMESTAMPS_ENCODER, + timestamp_queries::tests::TIMESTAMPS_PASSES, + timestamp_queries::tests::TIMESTAMPS_PASS_BOUNDARIES, + water::TEST, + ]; + + #[cfg(not(target_arch = "wasm32"))] + { + test_list.push(big_compute_buffers::tests::TWO_BUFFERS); + } + + test_list +} + +#[cfg(test)] +wgpu_test::gpu_test_main!(all_tests()); diff --git a/examples/features/src/main.rs b/examples/features/src/main.rs index b90c90d26..c28c7ad5f 100644 --- a/examples/features/src/main.rs +++ b/examples/features/src/main.rs @@ -182,6 +182,18 @@ const EXAMPLES: &[ExampleDesc] = &[ webgl: false, // No Ray-tracing extensions webgpu: false, // No Ray-tracing extensions (yet) }, + ExampleDesc { + name: "mesh_shader", + function: wgpu_examples::mesh_shader::main, + webgl: false, + webgpu: false, + }, + ExampleDesc { + name: "multiview", + function: wgpu_examples::multiview::main, + webgl: false, + webgpu: false, + }, ]; fn get_example_name() -> Option { diff --git a/examples/features/src/mesh_shader/README.md b/examples/features/src/mesh_shader/README.md new file mode 100644 index 000000000..9b57d3e49 --- /dev/null +++ b/examples/features/src/mesh_shader/README.md @@ -0,0 +1,9 @@ +# mesh_shader + +This example renders a triangle to a window with mesh shaders, while showcasing most mesh shader related features(task shaders, payloads, per primitive data). + +## To Run + +``` +cargo run --bin wgpu-examples mesh_shader +``` \ No newline at end of file diff --git a/examples/features/src/mesh_shader/mod.rs b/examples/features/src/mesh_shader/mod.rs new file mode 100644 index 000000000..4b9f735c2 --- /dev/null +++ b/examples/features/src/mesh_shader/mod.rs @@ -0,0 +1,181 @@ +use std::process::Stdio; + +// Same as in mesh shader tests +fn compile_glsl(device: &wgpu::Device, shader_stage: &'static str) -> wgpu::ShaderModule { + let cmd = std::process::Command::new("glslc") + .args([ + &format!( + "{}/src/mesh_shader/shader.{shader_stage}", + env!("CARGO_MANIFEST_DIR") + ), + "-o", + "-", + "--target-env=vulkan1.2", + "--target-spv=spv1.4", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .expect("Failed to call glslc"); + let output = cmd.wait_with_output().expect("Error waiting for glslc"); + assert!(output.status.success()); + unsafe { + device.create_shader_module_passthrough(wgpu::ShaderModuleDescriptorPassthrough { + entry_point: "main".into(), + label: None, + spirv: Some(wgpu::util::make_spirv_raw(&output.stdout)), + ..Default::default() + }) + } +} +fn compile_hlsl(device: &wgpu::Device, entry: &str, stage_str: &str) -> wgpu::ShaderModule { + let out_path = format!( + "{}/src/mesh_shader/shader.{stage_str}.cso", + env!("CARGO_MANIFEST_DIR") + ); + let cmd = std::process::Command::new("dxc") + .args([ + "-T", + &format!("{stage_str}_6_5"), + "-E", + entry, + &format!("{}/src/mesh_shader/shader.hlsl", env!("CARGO_MANIFEST_DIR")), + "-Fo", + &out_path, + ]) + .output() + .unwrap(); + if !cmd.status.success() { + panic!("DXC failed:\n{}", String::from_utf8(cmd.stderr).unwrap()); + } + let file = std::fs::read(&out_path).unwrap(); + std::fs::remove_file(out_path).unwrap(); + unsafe { + device.create_shader_module_passthrough(wgpu::ShaderModuleDescriptorPassthrough { + entry_point: entry.to_owned(), + label: None, + num_workgroups: (1, 1, 1), + dxil: Some(std::borrow::Cow::Owned(file)), + ..Default::default() + }) + } +} + +pub struct Example { + pipeline: wgpu::RenderPipeline, +} +impl crate::framework::Example for Example { + fn init( + config: &wgpu::SurfaceConfiguration, + adapter: &wgpu::Adapter, + device: &wgpu::Device, + _queue: &wgpu::Queue, + ) -> Self { + let (ts, ms, fs) = if adapter.get_info().backend == wgpu::Backend::Vulkan { + ( + compile_glsl(device, "task"), + compile_glsl(device, "mesh"), + compile_glsl(device, "frag"), + ) + } else if adapter.get_info().backend == wgpu::Backend::Dx12 { + ( + compile_hlsl(device, "Task", "as"), + compile_hlsl(device, "Mesh", "ms"), + compile_hlsl(device, "Frag", "ps"), + ) + } else { + panic!("Example can only run on vulkan or dx12"); + }; + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[], + push_constant_ranges: &[], + }); + let pipeline = device.create_mesh_pipeline(&wgpu::MeshPipelineDescriptor { + label: None, + layout: Some(&pipeline_layout), + task: Some(wgpu::TaskState { + module: &ts, + entry_point: Some("main"), + compilation_options: Default::default(), + }), + mesh: wgpu::MeshState { + module: &ms, + entry_point: Some("main"), + compilation_options: Default::default(), + }, + fragment: Some(wgpu::FragmentState { + module: &fs, + entry_point: Some("main"), + compilation_options: Default::default(), + targets: &[Some(config.view_formats[0].into())], + }), + primitive: wgpu::PrimitiveState { + cull_mode: Some(wgpu::Face::Back), + ..Default::default() + }, + depth_stencil: None, + multisample: Default::default(), + multiview: None, + cache: None, + }); + Self { pipeline } + } + fn render(&mut self, view: &wgpu::TextureView, device: &wgpu::Device, queue: &wgpu::Queue) { + let mut encoder = + device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); + { + let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: None, + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color { + r: 0.1, + g: 0.2, + b: 0.3, + a: 1.0, + }), + store: wgpu::StoreOp::Store, + }, + depth_slice: None, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + rpass.push_debug_group("Prepare data for draw."); + rpass.set_pipeline(&self.pipeline); + rpass.pop_debug_group(); + rpass.insert_debug_marker("Draw!"); + rpass.draw_mesh_tasks(1, 1, 1); + } + queue.submit(Some(encoder.finish())); + } + fn required_downlevel_capabilities() -> wgpu::DownlevelCapabilities { + Default::default() + } + fn required_features() -> wgpu::Features { + wgpu::Features::EXPERIMENTAL_MESH_SHADER | wgpu::Features::EXPERIMENTAL_PASSTHROUGH_SHADERS + } + fn required_limits() -> wgpu::Limits { + wgpu::Limits::defaults().using_recommended_minimum_mesh_shader_values() + } + fn resize( + &mut self, + _config: &wgpu::SurfaceConfiguration, + _device: &wgpu::Device, + _queue: &wgpu::Queue, + ) { + // empty + } + fn update(&mut self, _event: winit::event::WindowEvent) { + // empty + } +} + +pub fn main() { + crate::framework::run::("mesh_shader"); +} diff --git a/examples/features/src/mesh_shader/shader.frag b/examples/features/src/mesh_shader/shader.frag new file mode 100644 index 000000000..49624990f --- /dev/null +++ b/examples/features/src/mesh_shader/shader.frag @@ -0,0 +1,11 @@ +#version 450 +#extension GL_EXT_mesh_shader : require + +in VertexInput { layout(location = 0) vec4 color; } +vertexInput; +layout(location = 1) perprimitiveEXT in PrimitiveInput { vec4 colorMask; } +primitiveInput; + +layout(location = 0) out vec4 fragColor; + +void main() { fragColor = vertexInput.color * primitiveInput.colorMask; } \ No newline at end of file diff --git a/examples/features/src/mesh_shader/shader.hlsl b/examples/features/src/mesh_shader/shader.hlsl new file mode 100644 index 000000000..e70961f2d --- /dev/null +++ b/examples/features/src/mesh_shader/shader.hlsl @@ -0,0 +1,53 @@ +struct OutVertex { + float4 Position : SV_POSITION; + float4 Color: COLOR; +}; +struct OutPrimitive { + float4 ColorMask : COLOR_MASK : PRIMITIVE; + bool CullPrimitive: SV_CullPrimitive; +}; +struct InVertex { + float4 Color: COLOR; +}; +struct InPrimitive { + float4 ColorMask : COLOR_MASK : PRIMITIVE; +}; +struct PayloadData { + float4 ColorMask; + bool Visible; +}; + + +static const float4 positions[3] = {float4(0., 1.0, 0., 1.0), float4(-1.0, -1.0, 0., 1.0), float4(1.0, -1.0, 0., 1.0)}; +static const float4 colors[3] = {float4(0., 1., 0., 1.), float4(0., 0., 1., 1.), float4(1., 0., 0., 1.)}; + +groupshared PayloadData outPayload; + +[numthreads(1, 1, 1)] +void Task() { + outPayload.ColorMask = float4(1.0, 1.0, 0.0, 1.0); + outPayload.Visible = true; + DispatchMesh(3, 1, 1, outPayload); +} + +[outputtopology("triangle")] +[numthreads(1, 1, 1)] +void Mesh(out indices uint3 triangles[1], out vertices OutVertex vertices[3], out primitives OutPrimitive primitives[1], in payload PayloadData payload) { + SetMeshOutputCounts(3, 1); + + vertices[0].Position = positions[0]; + vertices[1].Position = positions[1]; + vertices[2].Position = positions[2]; + + vertices[0].Color = colors[0] * payload.ColorMask; + vertices[1].Color = colors[1] * payload.ColorMask; + vertices[2].Color = colors[2] * payload.ColorMask; + + triangles[0] = uint3(0, 1, 2); + primitives[0].ColorMask = float4(1.0, 0.0, 0.0, 1.0); + primitives[0].CullPrimitive = !payload.Visible; +} + +float4 Frag(InVertex vertex, InPrimitive primitive) : SV_Target { + return vertex.Color * primitive.ColorMask; +} diff --git a/examples/features/src/mesh_shader/shader.mesh b/examples/features/src/mesh_shader/shader.mesh new file mode 100644 index 000000000..c2579670d --- /dev/null +++ b/examples/features/src/mesh_shader/shader.mesh @@ -0,0 +1,38 @@ +#version 450 +#extension GL_EXT_mesh_shader : require + +const vec4[3] positions = {vec4(0., 1.0, 0., 1.0), vec4(-1.0, -1.0, 0., 1.0), + vec4(1.0, -1.0, 0., 1.0)}; +const vec4[3] colors = {vec4(0., 1., 0., 1.), vec4(0., 0., 1., 1.), + vec4(1., 0., 0., 1.)}; + +// This is an inefficient workgroup size.Ideally the total thread count would be +// a multiple of 64 +layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; +struct PayloadData { + vec4 colorMask; + bool visible; +}; +taskPayloadSharedEXT PayloadData payloadData; + +out VertexOutput { layout(location = 0) vec4 color; } +vertexOutput[]; +layout(location = 1) perprimitiveEXT out PrimitiveOutput { vec4 colorMask; } +primitiveOutput[]; + +layout(triangles, max_vertices = 3, max_primitives = 1) out; +void main() { + SetMeshOutputsEXT(3, 1); + + gl_MeshVerticesEXT[0].gl_Position = positions[0]; + gl_MeshVerticesEXT[1].gl_Position = positions[1]; + gl_MeshVerticesEXT[2].gl_Position = positions[2]; + + vertexOutput[0].color = colors[0] * payloadData.colorMask; + vertexOutput[1].color = colors[1] * payloadData.colorMask; + vertexOutput[2].color = colors[2] * payloadData.colorMask; + + gl_PrimitiveTriangleIndicesEXT[gl_LocalInvocationIndex] = uvec3(0, 1, 2); + primitiveOutput[0].colorMask = vec4(1.0, 0.0, 1.0, 1.0); + gl_MeshPrimitivesEXT[0].gl_CullPrimitiveEXT = !payloadData.visible; +} \ No newline at end of file diff --git a/examples/features/src/mesh_shader/shader.task b/examples/features/src/mesh_shader/shader.task new file mode 100644 index 000000000..04cdef2d5 --- /dev/null +++ b/examples/features/src/mesh_shader/shader.task @@ -0,0 +1,16 @@ +#version 450 +#extension GL_EXT_mesh_shader : require + +layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; + +struct TaskPayload { + vec4 colorMask; + bool visible; +}; +taskPayloadSharedEXT TaskPayload taskPayload; + +void main() { + taskPayload.colorMask = vec4(1.0, 1.0, 0.0, 1.0); + taskPayload.visible = true; + EmitMeshTasksEXT(3, 1, 1); +} \ No newline at end of file diff --git a/examples/features/src/mipmap/mod.rs b/examples/features/src/mipmap/mod.rs index 569a99923..108413ded 100644 --- a/examples/features/src/mipmap/mod.rs +++ b/examples/features/src/mipmap/mod.rs @@ -104,7 +104,7 @@ impl Example { }, depth_stencil: None, multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None, }); @@ -117,7 +117,7 @@ impl Example { address_mode_w: wgpu::AddressMode::ClampToEdge, mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, - mipmap_filter: wgpu::FilterMode::Nearest, + mipmap_filter: wgpu::MipmapFilterMode::Nearest, ..Default::default() }); @@ -160,6 +160,7 @@ impl Example { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &views[target_mip], + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::WHITE), @@ -169,6 +170,7 @@ impl Example { depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); if let Some(ref query_sets) = query_sets { rpass.write_timestamp(&query_sets.timestamp, timestamp_query_index_base); @@ -267,7 +269,7 @@ impl crate::framework::Example for Example { address_mode_w: wgpu::AddressMode::Repeat, mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, - mipmap_filter: wgpu::FilterMode::Linear, + mipmap_filter: wgpu::MipmapFilterMode::Linear, ..Default::default() }); let mx_total = Self::generate_matrix(config.width as f32 / config.height as f32); @@ -304,7 +306,7 @@ impl crate::framework::Example for Example { }, depth_stencil: None, multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None, }); @@ -410,7 +412,7 @@ impl crate::framework::Example for Example { .slice(..) .map_async(wgpu::MapMode::Read, |_| ()); // Wait for device to be done rendering mipmaps - device.poll(wgpu::PollType::wait()).unwrap(); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); // This is guaranteed to be ready. let timestamp_view = query_sets .mapping_buffer @@ -481,6 +483,7 @@ impl crate::framework::Example for Example { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(clear_color), @@ -490,6 +493,7 @@ impl crate::framework::Example for Example { depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); rpass.set_pipeline(&self.draw_pipeline); rpass.set_bind_group(0, &self.bind_group, &[]); @@ -506,7 +510,7 @@ pub fn main() { #[cfg(test)] #[wgpu_test::gpu_test] -static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { +pub static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { name: "mipmap", image_path: "/examples/features/src/mipmap/screenshot.png", width: 1024, @@ -519,13 +523,21 @@ static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTest #[cfg(test)] #[wgpu_test::gpu_test] -static TEST_QUERY: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { +pub static TEST_QUERY: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { name: "mipmap-query", image_path: "/examples/features/src/mipmap/screenshot_query.png", width: 1024, height: 768, optional_features: QUERY_FEATURES, base_test_parameters: wgpu_test::TestParameters::default(), - comparisons: &[wgpu_test::ComparisonType::Mean(0.025)], + // Somehow, this test on CI lavapipe reasonably often gets error of 0.025341, significantly higher + // than the comparison we usually do with mean 0.005. This only happens when the query is used. + comparisons: &[ + wgpu_test::ComparisonType::Mean(0.03), + wgpu_test::ComparisonType::Percentile { + percentile: 0.99, + threshold: 0.1, + }, + ], _phantom: std::marker::PhantomData::, }; diff --git a/examples/features/src/msaa_line/mod.rs b/examples/features/src/msaa_line/mod.rs index f956235cc..e7e436029 100644 --- a/examples/features/src/msaa_line/mod.rs +++ b/examples/features/src/msaa_line/mod.rs @@ -47,7 +47,7 @@ impl Example { vertex_buffer: &wgpu::Buffer, vertex_count: u32, ) -> wgpu::RenderBundle { - log::info!("sample_count: {}", sample_count); + log::info!("sample_count: {sample_count}"); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: None, layout: Some(pipeline_layout), @@ -77,7 +77,7 @@ impl Example { count: sample_count, ..Default::default() }, - multiview: None, + multiview_mask: None, cache: None, }); let mut encoder = @@ -112,7 +112,7 @@ impl Example { sample_count, dimension: wgpu::TextureDimension::D2, format: config.view_formats[0], - usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TRANSIENT, label: None, view_formats: &[], }; @@ -279,6 +279,7 @@ impl crate::framework::Example for Example { let rpass_color_attachment = if self.sample_count == 1 { wgpu::RenderPassColorAttachment { view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), @@ -288,6 +289,7 @@ impl crate::framework::Example for Example { } else { wgpu::RenderPassColorAttachment { view: &self.multisampled_framebuffer, + depth_slice: None, resolve_target: Some(view), ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), @@ -305,6 +307,7 @@ impl crate::framework::Example for Example { depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }) .execute_bundles(iter::once(&self.bundle)); } @@ -319,7 +322,7 @@ pub fn main() { #[cfg(test)] #[wgpu_test::gpu_test] -static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { +pub static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { name: "msaa-line", image_path: "/examples/features/src/msaa_line/screenshot.png", width: 1024, diff --git a/examples/features/src/multiple_render_targets/mod.rs b/examples/features/src/multiple_render_targets/mod.rs index 37991354b..fbc47258c 100644 --- a/examples/features/src/multiple_render_targets/mod.rs +++ b/examples/features/src/multiple_render_targets/mod.rs @@ -121,7 +121,7 @@ impl MultiTargetRenderer { address_mode_w: wgpu::AddressMode::Repeat, mag_filter: wgpu::FilterMode::Nearest, min_filter: wgpu::FilterMode::Nearest, - mipmap_filter: wgpu::FilterMode::Nearest, + mipmap_filter: wgpu::MipmapFilterMode::Nearest, ..Default::default() }); @@ -161,7 +161,7 @@ impl MultiTargetRenderer { primitive: wgpu::PrimitiveState::default(), depth_stencil: None, multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None, }); @@ -182,6 +182,7 @@ impl MultiTargetRenderer { depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); rpass.set_pipeline(&self.pipeline); rpass.set_bind_group(0, &self.bindgroup, &[]); @@ -240,7 +241,7 @@ impl TargetRenderer { address_mode_w: wgpu::AddressMode::Repeat, mag_filter: wgpu::FilterMode::Nearest, min_filter: wgpu::FilterMode::Nearest, - mipmap_filter: wgpu::FilterMode::Nearest, + mipmap_filter: wgpu::MipmapFilterMode::Nearest, ..Default::default() }); @@ -266,7 +267,7 @@ impl TargetRenderer { primitive: wgpu::PrimitiveState::default(), depth_stencil: None, multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None, }); @@ -329,6 +330,7 @@ impl TargetRenderer { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: surface_view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::GREEN), @@ -338,6 +340,7 @@ impl TargetRenderer { depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); rpass.set_pipeline(&self.pipeline); rpass.set_bind_group(0, &self.bindgroup_left, &[]); @@ -454,12 +457,12 @@ impl crate::framework::Example for Example { // output textures: &[ Some(wgpu::ColorTargetState { - format: config.format, + format: config.view_formats[0], blend: None, write_mask: Default::default(), }), Some(wgpu::ColorTargetState { - format: config.format, + format: config.view_formats[0], blend: None, write_mask: Default::default(), }), @@ -468,10 +471,11 @@ impl crate::framework::Example for Example { // create our target textures that will receive the simultaneous rendering: let texture_targets = - TextureTargets::new(device, config.format, config.width, config.height); + TextureTargets::new(device, config.view_formats[0], config.width, config.height); // helper renderer that displays the results in 2 separate viewports: - let drawer = TargetRenderer::init(device, &shader, config.format, &texture_targets); + let drawer = + TargetRenderer::init(device, &shader, config.view_formats[0], &texture_targets); Self { texture_targets, @@ -491,7 +495,7 @@ impl crate::framework::Example for Example { self.screen_width = config.width; self.screen_height = config.height; self.texture_targets = - TextureTargets::new(device, config.format, config.width, config.height); + TextureTargets::new(device, config.view_formats[0], config.width, config.height); self.drawer.rebuild_resources(device, &self.texture_targets); } @@ -507,11 +511,13 @@ impl crate::framework::Example for Example { &[ Some(wgpu::RenderPassColorAttachment { view: &self.texture_targets.red_view, + depth_slice: None, resolve_target: None, ops: Default::default(), }), Some(wgpu::RenderPassColorAttachment { view: &self.texture_targets.green_view, + depth_slice: None, resolve_target: None, ops: Default::default(), }), @@ -532,7 +538,7 @@ pub fn main() { #[cfg(test)] #[wgpu_test::gpu_test] -static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { +pub static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { name: EXAMPLE_NAME, image_path: "/examples/features/src/multiple_render_targets/screenshot.png", width: 1024, diff --git a/examples/features/src/multiview/mod.rs b/examples/features/src/multiview/mod.rs new file mode 100644 index 000000000..cde3f3c98 --- /dev/null +++ b/examples/features/src/multiview/mod.rs @@ -0,0 +1,182 @@ +//! Renders different content to different layers of an array texture using multiview, +//! a feature commonly used for VR rendering. + +use std::{num::NonZero, time::Instant}; + +use wgpu::util::TextureBlitter; + +const TEXTURE_SIZE: u32 = 512; + +// Change this to demonstrate non-contiguous multiview functionality +const LAYER_MASK: u32 = 0b11; + +const NUM_LAYERS: u32 = 32 - LAYER_MASK.leading_zeros(); + +pub struct Example { + pipeline: wgpu::RenderPipeline, + entire_texture_view: wgpu::TextureView, + views: Vec, + start_time: Instant, + blitter: TextureBlitter, +} + +impl crate::framework::Example for Example { + fn init( + config: &wgpu::SurfaceConfiguration, + _adapter: &wgpu::Adapter, + device: &wgpu::Device, + _queue: &wgpu::Queue, + ) -> Self { + let shader_src = include_str!("shader.wgsl"); + + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(shader_src.into()), + }); + + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: None, + vertex: wgpu::VertexState { + buffers: &[], + module: &shader, + entry_point: Some("vs_main"), + compilation_options: Default::default(), + }, + primitive: wgpu::PrimitiveState::default(), + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_main"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: wgpu::TextureFormat::Rgba8Unorm, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: NonZero::new(LAYER_MASK), + multisample: Default::default(), + layout: None, + depth_stencil: None, + cache: None, + }); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { + width: TEXTURE_SIZE, + height: TEXTURE_SIZE, + depth_or_array_layers: NUM_LAYERS, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::COPY_SRC + | wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }); + let entire_texture_view = texture.create_view(&wgpu::TextureViewDescriptor { + label: None, + format: Some(wgpu::TextureFormat::Rgba8Unorm), + dimension: Some(wgpu::TextureViewDimension::D2Array), + usage: Some(wgpu::TextureUsages::RENDER_ATTACHMENT), + aspect: wgpu::TextureAspect::All, + base_mip_level: 0, + mip_level_count: None, + base_array_layer: 0, + array_layer_count: Some(NUM_LAYERS), + }); + let mut views = Vec::new(); + for i in 0..NUM_LAYERS { + views.push(texture.create_view(&wgpu::TextureViewDescriptor { + label: None, + format: Some(wgpu::TextureFormat::Rgba8Unorm), + dimension: Some(wgpu::TextureViewDimension::D2), + usage: Some(wgpu::TextureUsages::TEXTURE_BINDING), + aspect: wgpu::TextureAspect::All, + base_mip_level: 0, + mip_level_count: None, + base_array_layer: i, + array_layer_count: Some(1), + })); + } + let blitter = wgpu::util::TextureBlitter::new(device, config.format); + Self { + pipeline, + entire_texture_view, + views, + blitter, + start_time: Instant::now(), + } + } + + fn render(&mut self, view: &wgpu::TextureView, device: &wgpu::Device, queue: &wgpu::Queue) { + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default()); + { + let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: None, + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &self.entire_texture_view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color { + r: 0.02, + g: 0.02, + b: 0.02, + a: 1.0, + }), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: NonZero::new(LAYER_MASK), + }); + rpass.set_pipeline(&self.pipeline); + rpass.draw(0..6, 0..1); + } + + let layer = (Instant::now() - self.start_time).as_secs() % NUM_LAYERS as u64; + self.blitter + .copy(device, &mut encoder, &self.views[layer as usize], view); + queue.submit(Some(encoder.finish())); + } + + fn required_downlevel_capabilities() -> wgpu::DownlevelCapabilities { + Default::default() + } + + fn required_features() -> wgpu::Features { + wgpu::Features::MULTIVIEW + | if !(LAYER_MASK + 1).is_power_of_two() { + wgpu::Features::SELECTIVE_MULTIVIEW + } else { + wgpu::Features::empty() + } + } + + fn required_limits() -> wgpu::Limits { + wgpu::Limits { + max_multiview_view_count: NUM_LAYERS, + ..Default::default() + } + } + + fn resize( + &mut self, + _config: &wgpu::SurfaceConfiguration, + _device: &wgpu::Device, + _queue: &wgpu::Queue, + ) { + // empty + } + fn update(&mut self, _event: winit::event::WindowEvent) { + // empty + } +} + +pub fn main() { + crate::framework::run::("multiview"); +} diff --git a/examples/features/src/multiview/shader.wgsl b/examples/features/src/multiview/shader.wgsl new file mode 100644 index 000000000..778807a95 --- /dev/null +++ b/examples/features/src/multiview/shader.wgsl @@ -0,0 +1,11 @@ +const triangles = array(vec2f(-1.0, -1.0), vec2f(3.0, -1.0), vec2f(-1.0, 3.0)); + +@vertex +fn vs_main(@builtin(vertex_index) vertex_index: u32) -> @builtin(position) vec4f { + return vec4f(triangles[vertex_index], 0.0, 1.0); +} + +@fragment +fn fs_main(@builtin(view_index) view_index: u32) -> @location(0) vec4f { + return vec4f(f32(view_index) * 0.25 + 0.125, 1.0 - f32(view_index) * 0.25, 1.0 - 0.5 * f32(view_index), 1.0); +} \ No newline at end of file diff --git a/examples/features/src/ray_cube_compute/mod.rs b/examples/features/src/ray_cube_compute/mod.rs index f43f69531..0ba627757 100644 --- a/examples/features/src/ray_cube_compute/mod.rs +++ b/examples/features/src/ray_cube_compute/mod.rs @@ -1,4 +1,4 @@ -use std::{borrow::Cow, future::Future, iter, mem, pin::Pin, task, time::Instant}; +use std::{borrow::Cow, future::Future, iter, mem, pin::Pin, task}; use bytemuck::{Pod, Zeroable}; use glam::{Affine3A, Mat4, Quat, Vec3}; @@ -6,6 +6,8 @@ use wgpu::util::DeviceExt; use wgpu::StoreOp; +use crate::utils; + // from cube #[repr(C)] #[derive(Clone, Copy, Pod, Zeroable)] @@ -112,7 +114,7 @@ impl>> Future for ErrorFuture { let inner = unsafe { self.map_unchecked_mut(|me| &mut me.inner) }; inner.poll(cx).map(|error| { if let Some(e) = error { - panic!("Rendering {}", e); + panic!("Rendering {e}"); } }) } @@ -130,12 +132,12 @@ struct Example { vertex_buf: wgpu::Buffer, #[expect(dead_code)] index_buf: wgpu::Buffer, - tlas_package: wgpu::TlasPackage, + tlas: wgpu::Tlas, compute_pipeline: wgpu::ComputePipeline, compute_bind_group: wgpu::BindGroup, blit_pipeline: wgpu::RenderPipeline, blit_bind_group: wgpu::BindGroup, - start_inst: Instant, + animation_timer: utils::AnimationTimer, } impl crate::framework::Example for Example { @@ -143,14 +145,17 @@ impl crate::framework::Example for Example { wgpu::Features::TEXTURE_BINDING_ARRAY | wgpu::Features::VERTEX_WRITABLE_STORAGE | wgpu::Features::EXPERIMENTAL_RAY_QUERY - | wgpu::Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE } fn required_downlevel_capabilities() -> wgpu::DownlevelCapabilities { - wgpu::DownlevelCapabilities::default() + wgpu::DownlevelCapabilities { + flags: wgpu::DownlevelFlags::COMPUTE_SHADERS, + ..Default::default() + } } + fn required_limits() -> wgpu::Limits { - wgpu::Limits::default() + wgpu::Limits::default().using_minimum_supported_acceleration_structure_values() } fn init( @@ -195,7 +200,7 @@ impl crate::framework::Example for Example { address_mode_w: wgpu::AddressMode::ClampToEdge, mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, - mipmap_filter: wgpu::FilterMode::Nearest, + mipmap_filter: wgpu::MipmapFilterMode::Nearest, ..Default::default() }); @@ -253,7 +258,7 @@ impl crate::framework::Example for Example { }, ); - let tlas = device.create_tlas(&wgpu::CreateTlasDescriptor { + let mut tlas = device.create_tlas(&wgpu::CreateTlasDescriptor { label: None, flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE, update_mode: wgpu::AccelerationStructureUpdateMode::Build, @@ -321,7 +326,7 @@ impl crate::framework::Example for Example { }, depth_stencil: None, multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None, }); @@ -342,13 +347,11 @@ impl crate::framework::Example for Example { ], }); - let mut tlas_package = wgpu::TlasPackage::new(tlas); - let dist = 3.0; for x in 0..side_count { for y in 0..side_count { - tlas_package[(x + y * side_count) as usize] = Some(wgpu::TlasInstance::new( + tlas[(x + y * side_count) as usize] = Some(wgpu::TlasInstance::new( &blas, affine_to_rows(&Affine3A::from_rotation_translation( Quat::from_rotation_y(45.9_f32.to_radians()), @@ -383,13 +386,11 @@ impl crate::framework::Example for Example { }, ]), }), - iter::once(&tlas_package), + iter::once(&tlas), ); queue.submit(Some(encoder.finish())); - let start_inst = Instant::now(); - Example { rt_target, rt_view, @@ -397,12 +398,12 @@ impl crate::framework::Example for Example { uniform_buf, vertex_buf, index_buf, - tlas_package, + tlas, compute_pipeline, compute_bind_group, blit_pipeline, blit_bind_group, - start_inst, + animation_timer: utils::AnimationTimer::default(), } } @@ -421,9 +422,9 @@ impl crate::framework::Example for Example { fn render(&mut self, view: &wgpu::TextureView, device: &wgpu::Device, queue: &wgpu::Queue) { device.push_error_scope(wgpu::ErrorFilter::Validation); - let anim_time = self.start_inst.elapsed().as_secs_f64() as f32; + let anim_time = self.animation_timer.time(); - self.tlas_package[0].as_mut().unwrap().transform = + self.tlas[0].as_mut().unwrap().transform = affine_to_rows(&Affine3A::from_rotation_translation( Quat::from_euler( glam::EulerRot::XYZ, @@ -441,7 +442,7 @@ impl crate::framework::Example for Example { let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); - encoder.build_acceleration_structures(iter::empty(), iter::once(&self.tlas_package)); + encoder.build_acceleration_structures(iter::empty(), iter::once(&self.tlas)); { let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { @@ -458,6 +459,7 @@ impl crate::framework::Example for Example { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::GREEN), @@ -467,6 +469,7 @@ impl crate::framework::Example for Example { depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); rpass.set_pipeline(&self.blit_pipeline); @@ -484,21 +487,13 @@ pub fn main() { #[cfg(test)] #[wgpu_test::gpu_test] -static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { +pub static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { name: "ray_cube_compute", image_path: "/examples/features/src/ray_cube_compute/screenshot.png", width: 1024, height: 768, optional_features: wgpu::Features::default(), - base_test_parameters: wgpu_test::TestParameters { - required_features: ::required_features(), - required_limits: ::required_limits(), - skips: vec![], - failures: Vec::new(), - required_downlevel_caps: - ::required_downlevel_capabilities(), - ..Default::default() - }, + base_test_parameters: wgpu_test::TestParameters::default(), comparisons: &[wgpu_test::ComparisonType::Mean(0.02)], _phantom: std::marker::PhantomData::, }; diff --git a/examples/features/src/ray_cube_compute/screenshot.png b/examples/features/src/ray_cube_compute/screenshot.png index 6b737f1e2..38421fabe 100644 Binary files a/examples/features/src/ray_cube_compute/screenshot.png and b/examples/features/src/ray_cube_compute/screenshot.png differ diff --git a/examples/features/src/ray_cube_fragment/mod.rs b/examples/features/src/ray_cube_fragment/mod.rs index 41402938e..6cd8fc488 100644 --- a/examples/features/src/ray_cube_fragment/mod.rs +++ b/examples/features/src/ray_cube_fragment/mod.rs @@ -1,7 +1,8 @@ +use crate::utils; use bytemuck::{Pod, Zeroable}; use glam::{Mat4, Quat, Vec3}; use std::ops::IndexMut; -use std::{borrow::Cow, future::Future, iter, mem, pin::Pin, task, time::Instant}; +use std::{borrow::Cow, future::Future, iter, mem, pin::Pin, task}; use wgpu::util::DeviceExt; // from cube @@ -88,7 +89,7 @@ impl>> Future for ErrorFuture { let inner = unsafe { self.map_unchecked_mut(|me| &mut me.inner) }; inner.poll(cx).map(|error| { if let Some(e) = error { - panic!("Rendering {}", e); + panic!("Rendering {e}"); } }) } @@ -98,23 +99,26 @@ struct Example { uniforms: Uniforms, uniform_buf: wgpu::Buffer, blas: wgpu::Blas, - tlas_package: wgpu::TlasPackage, + tlas: wgpu::Tlas, pipeline: wgpu::RenderPipeline, bind_group: wgpu::BindGroup, - start_inst: Instant, + animation_timer: utils::AnimationTimer, } impl crate::framework::Example for Example { fn required_features() -> wgpu::Features { wgpu::Features::EXPERIMENTAL_RAY_QUERY - | wgpu::Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE } fn required_downlevel_capabilities() -> wgpu::DownlevelCapabilities { - wgpu::DownlevelCapabilities::default() + wgpu::DownlevelCapabilities { + flags: wgpu::DownlevelFlags::COMPUTE_SHADERS, + ..Default::default() + } } + fn required_limits() -> wgpu::Limits { - wgpu::Limits::default() + wgpu::Limits::default().using_minimum_supported_acceleration_structure_values() } fn init( @@ -212,7 +216,7 @@ impl crate::framework::Example for Example { }, depth_stencil: None, multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None, }); @@ -233,8 +237,6 @@ impl crate::framework::Example for Example { ], }); - let tlas_package = wgpu::TlasPackage::new(tlas); - let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); @@ -255,21 +257,19 @@ impl crate::framework::Example for Example { ]), }), // iter::empty(), - iter::once(&tlas_package), + iter::once(&tlas), ); queue.submit(Some(encoder.finish())); - let start_inst = Instant::now(); - Example { uniforms, uniform_buf, blas, - tlas_package, + tlas, pipeline, bind_group, - start_inst, + animation_timer: utils::AnimationTimer::default(), } } @@ -302,11 +302,11 @@ impl crate::framework::Example for Example { let side_count = 8; - let anim_time = self.start_inst.elapsed().as_secs_f64() as f32; + let anim_time = self.animation_timer.time(); for x in 0..side_count { for y in 0..side_count { - let instance = self.tlas_package.index_mut((x + y * side_count) as usize); + let instance = self.tlas.index_mut((x + y * side_count) as usize); let x = x as f32 / (side_count - 1) as f32; let y = y as f32 / (side_count - 1) as f32; @@ -338,13 +338,14 @@ impl crate::framework::Example for Example { let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); - encoder.build_acceleration_structures(iter::empty(), iter::once(&self.tlas_package)); + encoder.build_acceleration_structures(iter::empty(), iter::once(&self.tlas)); { let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::GREEN), @@ -354,6 +355,7 @@ impl crate::framework::Example for Example { depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); rpass.set_pipeline(&self.pipeline); @@ -371,21 +373,13 @@ pub fn main() { #[cfg(test)] #[wgpu_test::gpu_test] -static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { +pub static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { name: "ray_cube_fragment", image_path: "/examples/features/src/ray_cube_fragment/screenshot.png", width: 1024, height: 768, optional_features: wgpu::Features::default(), - base_test_parameters: wgpu_test::TestParameters { - required_features: ::required_features(), - required_limits: ::required_limits(), - skips: vec![], - failures: Vec::new(), - required_downlevel_caps: - ::required_downlevel_capabilities(), - ..Default::default() - }, + base_test_parameters: wgpu_test::TestParameters::default(), comparisons: &[wgpu_test::ComparisonType::Mean(0.02)], _phantom: std::marker::PhantomData::, }; diff --git a/examples/features/src/ray_cube_fragment/screenshot.png b/examples/features/src/ray_cube_fragment/screenshot.png index 5e9578675..572d90e22 100644 Binary files a/examples/features/src/ray_cube_fragment/screenshot.png and b/examples/features/src/ray_cube_fragment/screenshot.png differ diff --git a/examples/features/src/ray_cube_normals/mod.rs b/examples/features/src/ray_cube_normals/mod.rs index b039154b3..1c7acf7c3 100644 --- a/examples/features/src/ray_cube_normals/mod.rs +++ b/examples/features/src/ray_cube_normals/mod.rs @@ -1,9 +1,10 @@ -use std::{borrow::Cow, future::Future, iter, mem, pin::Pin, task, time::Instant}; +use std::{borrow::Cow, future::Future, iter, mem, pin::Pin, task}; use bytemuck::{Pod, Zeroable}; use glam::{Affine3A, Mat4, Quat, Vec3}; use wgpu::util::DeviceExt; +use crate::utils; use wgpu::StoreOp; // from cube @@ -112,7 +113,7 @@ impl>> Future for ErrorFuture { let inner = unsafe { self.map_unchecked_mut(|me| &mut me.inner) }; inner.poll(cx).map(|error| { if let Some(e) = error { - panic!("Rendering {}", e); + panic!("Rendering {e}"); } }) } @@ -120,28 +121,30 @@ impl>> Future for ErrorFuture { struct Example { rt_target: wgpu::Texture, - tlas_package: wgpu::TlasPackage, + tlas: wgpu::Tlas, compute_pipeline: wgpu::ComputePipeline, compute_bind_group: wgpu::BindGroup, blit_pipeline: wgpu::RenderPipeline, blit_bind_group: wgpu::BindGroup, - start_inst: Instant, + animation_timer: utils::AnimationTimer, } impl crate::framework::Example for Example { // Don't want srgb, so normals show up better. const SRGB: bool = false; fn required_features() -> wgpu::Features { - wgpu::Features::EXPERIMENTAL_RAY_QUERY - | wgpu::Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE - | wgpu::Features::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN + wgpu::Features::EXPERIMENTAL_RAY_QUERY | wgpu::Features::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN } fn required_downlevel_capabilities() -> wgpu::DownlevelCapabilities { - wgpu::DownlevelCapabilities::default() + wgpu::DownlevelCapabilities { + flags: wgpu::DownlevelFlags::COMPUTE_SHADERS, + ..Default::default() + } } + fn required_limits() -> wgpu::Limits { - wgpu::Limits::default() + wgpu::Limits::default().using_minimum_supported_acceleration_structure_values() } fn init( @@ -186,7 +189,7 @@ impl crate::framework::Example for Example { address_mode_w: wgpu::AddressMode::ClampToEdge, mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, - mipmap_filter: wgpu::FilterMode::Nearest, + mipmap_filter: wgpu::MipmapFilterMode::Nearest, ..Default::default() }); @@ -245,7 +248,7 @@ impl crate::framework::Example for Example { }, ); - let tlas = device.create_tlas(&wgpu::CreateTlasDescriptor { + let mut tlas = device.create_tlas(&wgpu::CreateTlasDescriptor { label: None, flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE | wgpu::AccelerationStructureFlags::ALLOW_RAY_HIT_VERTEX_RETURN, @@ -314,7 +317,7 @@ impl crate::framework::Example for Example { }, depth_stencil: None, multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None, }); @@ -335,13 +338,11 @@ impl crate::framework::Example for Example { ], }); - let mut tlas_package = wgpu::TlasPackage::new(tlas); - let dist = 3.0; for x in 0..side_count { for y in 0..side_count { - tlas_package[(x + y * side_count) as usize] = Some(wgpu::TlasInstance::new( + tlas[(x + y * side_count) as usize] = Some(wgpu::TlasInstance::new( &blas, affine_to_rows(&Affine3A::from_rotation_translation( Quat::from_rotation_y(45.9_f32.to_radians()), @@ -376,21 +377,19 @@ impl crate::framework::Example for Example { }, ]), }), - iter::once(&tlas_package), + iter::once(&tlas), ); queue.submit(Some(encoder.finish())); - let start_inst = Instant::now(); - Example { rt_target, - tlas_package, + tlas, compute_pipeline, compute_bind_group, blit_pipeline, blit_bind_group, - start_inst, + animation_timer: utils::AnimationTimer::default(), } } @@ -409,9 +408,9 @@ impl crate::framework::Example for Example { fn render(&mut self, view: &wgpu::TextureView, device: &wgpu::Device, queue: &wgpu::Queue) { device.push_error_scope(wgpu::ErrorFilter::Validation); - let anim_time = self.start_inst.elapsed().as_secs_f64() as f32; + let anim_time = self.animation_timer.time(); - self.tlas_package[0].as_mut().unwrap().transform = + self.tlas[0].as_mut().unwrap().transform = affine_to_rows(&Affine3A::from_rotation_translation( Quat::from_euler( glam::EulerRot::XYZ, @@ -429,7 +428,7 @@ impl crate::framework::Example for Example { let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); - encoder.build_acceleration_structures(iter::empty(), iter::once(&self.tlas_package)); + encoder.build_acceleration_structures(iter::empty(), iter::once(&self.tlas)); { let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { @@ -446,6 +445,7 @@ impl crate::framework::Example for Example { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::GREEN), @@ -455,6 +455,7 @@ impl crate::framework::Example for Example { depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); rpass.set_pipeline(&self.blit_pipeline); @@ -472,22 +473,16 @@ pub fn main() { #[cfg(test)] #[wgpu_test::gpu_test] -static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { +pub static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { name: "ray_cube_normals", - image_path: "/examples/src/ray_cube_normals/screenshot.png", + image_path: "/examples/features/src/ray_cube_normals/screenshot.png", width: 1024, height: 768, optional_features: wgpu::Features::default(), - base_test_parameters: wgpu_test::TestParameters { - required_features: ::required_features(), - required_limits: ::required_limits(), - force_fxc: false, - skips: vec![], - failures: Vec::new(), - required_downlevel_caps: - ::required_downlevel_capabilities(), - ..Default::default() - }, + base_test_parameters: wgpu_test::TestParameters::default().expect_fail( + wgpu_test::FailureCase::backend_adapter(wgpu::Backends::VULKAN, "AMD") + .panic("Image data mismatch"), + ), comparisons: &[wgpu_test::ComparisonType::Mean(0.02)], _phantom: std::marker::PhantomData::, }; diff --git a/examples/features/src/ray_scene/mod.rs b/examples/features/src/ray_scene/mod.rs index 4cd97bb67..ab3996240 100644 --- a/examples/features/src/ray_scene/mod.rs +++ b/examples/features/src/ray_scene/mod.rs @@ -1,8 +1,9 @@ +use crate::utils; use bytemuck::{Pod, Zeroable}; use glam::{Mat4, Quat, Vec3}; use std::f32::consts::PI; use std::ops::IndexMut; -use std::{borrow::Cow, future::Future, iter, mem, ops::Range, pin::Pin, task, time::Instant}; +use std::{borrow::Cow, future::Future, iter, mem, ops::Range, pin::Pin, task}; use wgpu::util::DeviceExt; // from cube @@ -40,7 +41,7 @@ impl>> Future for ErrorFuture { let inner = unsafe { self.map_unchecked_mut(|me| &mut me.inner) }; inner.poll(cx).map(|error| { if let Some(e) = error { - panic!("Rendering {}", e); + panic!("Rendering {e}"); } }) } @@ -92,7 +93,7 @@ struct Material { fn load_model(scene: &mut RawSceneComponents, path: &str) { let path = env!("CARGO_MANIFEST_DIR").to_string() + "/src" + path; - println!("{}", path); + println!("{path}"); let mut object = obj::Obj::load(path).unwrap(); object.load_mtls().unwrap(); @@ -307,24 +308,27 @@ fn load_scene(device: &wgpu::Device, queue: &wgpu::Queue) -> SceneComponents { struct Example { uniforms: Uniforms, uniform_buf: wgpu::Buffer, - tlas_package: wgpu::TlasPackage, + tlas: wgpu::Tlas, pipeline: wgpu::RenderPipeline, bind_group: wgpu::BindGroup, - start_inst: Instant, scene_components: SceneComponents, + animation_timer: utils::AnimationTimer, } impl crate::framework::Example for Example { fn required_features() -> wgpu::Features { wgpu::Features::EXPERIMENTAL_RAY_QUERY - | wgpu::Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE } fn required_downlevel_capabilities() -> wgpu::DownlevelCapabilities { - wgpu::DownlevelCapabilities::default() + wgpu::DownlevelCapabilities { + flags: wgpu::DownlevelFlags::COMPUTE_SHADERS, + ..Default::default() + } } + fn required_limits() -> wgpu::Limits { - wgpu::Limits::default() + wgpu::Limits::default().using_minimum_supported_acceleration_structure_values() } fn init( @@ -365,8 +369,6 @@ impl crate::framework::Example for Example { max_instances: side_count * side_count, }); - let tlas_package = wgpu::TlasPackage::new(tlas); - let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))), @@ -393,7 +395,7 @@ impl crate::framework::Example for Example { }, depth_stencil: None, multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None, }); @@ -409,7 +411,7 @@ impl crate::framework::Example for Example { }, wgpu::BindGroupEntry { binding: 5, - resource: tlas_package.as_binding(), + resource: tlas.as_binding(), }, wgpu::BindGroupEntry { binding: 1, @@ -430,16 +432,14 @@ impl crate::framework::Example for Example { ], }); - let start_inst = Instant::now(); - Example { uniforms, uniform_buf, - tlas_package, + tlas, pipeline, bind_group, - start_inst, scene_components, + animation_timer: utils::AnimationTimer::default(), } } @@ -472,11 +472,11 @@ impl crate::framework::Example for Example { let side_count = 2; - let anim_time = self.start_inst.elapsed().as_secs_f64() as f32; + let anim_time = self.animation_timer.time(); for x in 0..side_count { for y in 0..side_count { - let instance = self.tlas_package.index_mut(x + y * side_count); + let instance = self.tlas.index_mut(x + y * side_count); let blas_index = (x + y) % self @@ -518,13 +518,14 @@ impl crate::framework::Example for Example { let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); - encoder.build_acceleration_structures(iter::empty(), iter::once(&self.tlas_package)); + encoder.build_acceleration_structures(iter::empty(), iter::once(&self.tlas)); { let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::GREEN), @@ -534,6 +535,7 @@ impl crate::framework::Example for Example { depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); rpass.set_pipeline(&self.pipeline); @@ -551,21 +553,16 @@ pub fn main() { #[cfg(test)] #[wgpu_test::gpu_test] -static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { +pub static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { name: "ray_scene", image_path: "/examples/features/src/ray_scene/screenshot.png", width: 1024, height: 768, optional_features: wgpu::Features::default(), - base_test_parameters: wgpu_test::TestParameters { - required_features: ::required_features(), - required_limits: ::required_limits(), - skips: vec![], - failures: Vec::new(), - required_downlevel_caps: - ::required_downlevel_capabilities(), - ..Default::default() - }, + base_test_parameters: wgpu_test::TestParameters::default().expect_fail( + wgpu_test::FailureCase::backend_adapter(wgpu::Backends::VULKAN, "llvmpipe") + .panic("Image data mismatch"), + ), comparisons: &[wgpu_test::ComparisonType::Mean(0.02)], _phantom: std::marker::PhantomData::, }; diff --git a/examples/features/src/ray_scene/screenshot.png b/examples/features/src/ray_scene/screenshot.png index 288bdf206..17ccc90d3 100644 Binary files a/examples/features/src/ray_scene/screenshot.png and b/examples/features/src/ray_scene/screenshot.png differ diff --git a/examples/features/src/ray_shadows/mod.rs b/examples/features/src/ray_shadows/mod.rs index ea5ee31c8..5a3305ee3 100644 --- a/examples/features/src/ray_shadows/mod.rs +++ b/examples/features/src/ray_shadows/mod.rs @@ -1,10 +1,12 @@ -use std::{borrow::Cow, future::Future, iter, mem, pin::Pin, task, time::Instant}; +use std::{borrow::Cow, future::Future, iter, mem, pin::Pin, task}; use bytemuck::{Pod, Zeroable}; use glam::{Mat4, Vec3}; use wgpu::util::DeviceExt; use wgpu::{vertex_attr_array, IndexFormat, VertexBufferLayout}; +use crate::utils; + // from cube #[repr(C)] #[derive(Clone, Copy, Pod, Zeroable)] @@ -66,7 +68,7 @@ impl>> Future for ErrorFuture { let inner = unsafe { self.map_unchecked_mut(|me| &mut me.inner) }; inner.poll(cx).map(|error| { if let Some(e) = error { - panic!("Rendering {}", e); + panic!("Rendering {e}"); } }) } @@ -79,7 +81,7 @@ struct Example { index_buf: wgpu::Buffer, pipeline: wgpu::RenderPipeline, bind_group: wgpu::BindGroup, - start_inst: Instant, + animation_timer: utils::AnimationTimer, } const CAM_LOOK_AT: Vec3 = Vec3::new(0.0, 1.0, -1.5); @@ -102,19 +104,22 @@ fn create_matrix(config: &wgpu::SurfaceConfiguration) -> Uniforms { impl crate::framework::Example for Example { fn required_features() -> wgpu::Features { - wgpu::Features::EXPERIMENTAL_RAY_QUERY - | wgpu::Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE - | wgpu::Features::PUSH_CONSTANTS + wgpu::Features::EXPERIMENTAL_RAY_QUERY | wgpu::Features::PUSH_CONSTANTS } fn required_downlevel_capabilities() -> wgpu::DownlevelCapabilities { - wgpu::DownlevelCapabilities::default() + wgpu::DownlevelCapabilities { + flags: wgpu::DownlevelFlags::COMPUTE_SHADERS, + ..Default::default() + } } + fn required_limits() -> wgpu::Limits { wgpu::Limits { max_push_constant_size: 12, ..wgpu::Limits::default() } + .using_minimum_supported_acceleration_structure_values() } fn init( @@ -164,7 +169,7 @@ impl crate::framework::Example for Example { }, ); - let tlas = device.create_tlas(&wgpu::CreateTlasDescriptor { + let mut tlas = device.create_tlas(&wgpu::CreateTlasDescriptor { label: None, flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE, update_mode: wgpu::AccelerationStructureUpdateMode::Build, @@ -234,13 +239,11 @@ impl crate::framework::Example for Example { }, depth_stencil: None, multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None, }); - let mut tlas_package = wgpu::TlasPackage::new(tlas); - - tlas_package[0] = Some(wgpu::TlasInstance::new( + tlas[0] = Some(wgpu::TlasInstance::new( &blas, [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0], 0, @@ -266,7 +269,7 @@ impl crate::framework::Example for Example { }, ]), }), - iter::once(&tlas_package), + iter::once(&tlas), ); queue.submit(Some(encoder.finish())); @@ -281,12 +284,12 @@ impl crate::framework::Example for Example { }, wgpu::BindGroupEntry { binding: 1, - resource: tlas_package.as_binding(), + resource: tlas.as_binding(), }, ], }); - let start_inst = Instant::now(); + let animation_timer = utils::AnimationTimer::default(); Example { uniforms, @@ -295,7 +298,7 @@ impl crate::framework::Example for Example { index_buf, pipeline, bind_group, - start_inst, + animation_timer, } } @@ -318,10 +321,9 @@ impl crate::framework::Example for Example { const LIGHT_DISTANCE: f32 = 5.0; const TIME_SCALE: f32 = -0.2; const INITIAL_TIME: f32 = 1.0; - let cos = (self.start_inst.elapsed().as_secs_f32() * TIME_SCALE + INITIAL_TIME).cos() - * LIGHT_DISTANCE; - let sin = (self.start_inst.elapsed().as_secs_f32() * TIME_SCALE + INITIAL_TIME).sin() - * LIGHT_DISTANCE; + let time = self.animation_timer.time(); + let cos = (time * TIME_SCALE + INITIAL_TIME).cos() * LIGHT_DISTANCE; + let sin = (time * TIME_SCALE + INITIAL_TIME).sin() * LIGHT_DISTANCE; let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); @@ -331,6 +333,7 @@ impl crate::framework::Example for Example { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { @@ -345,6 +348,7 @@ impl crate::framework::Example for Example { depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); rpass.set_pipeline(&self.pipeline); @@ -357,7 +361,7 @@ impl crate::framework::Example for Example { rpass.draw_indexed(0..12, 0, 0..1); } queue.submit(Some(encoder.finish())); - device.poll(wgpu::PollType::Wait).unwrap(); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); } } @@ -367,21 +371,13 @@ pub fn main() { #[cfg(test)] #[wgpu_test::gpu_test] -static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { - name: "ray_cube_shadows", +pub static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { + name: "ray_shadows", image_path: "/examples/features/src/ray_shadows/screenshot.png", width: 1024, height: 768, optional_features: wgpu::Features::default(), - base_test_parameters: wgpu_test::TestParameters { - required_features: ::required_features(), - required_limits: ::required_limits(), - skips: vec![], - failures: Vec::new(), - required_downlevel_caps: - ::required_downlevel_capabilities(), - ..Default::default() - }, + base_test_parameters: wgpu_test::TestParameters::default(), comparisons: &[wgpu_test::ComparisonType::Mean(0.02)], _phantom: std::marker::PhantomData::, }; diff --git a/examples/features/src/ray_shadows/screenshot.png b/examples/features/src/ray_shadows/screenshot.png index 53e99aa7f..dfbe203c1 100644 Binary files a/examples/features/src/ray_shadows/screenshot.png and b/examples/features/src/ray_shadows/screenshot.png differ diff --git a/examples/features/src/ray_shadows/shader.wgsl b/examples/features/src/ray_shadows/shader.wgsl index fb36f1045..4ba5d42f7 100644 --- a/examples/features/src/ray_shadows/shader.wgsl +++ b/examples/features/src/ray_shadows/shader.wgsl @@ -33,7 +33,10 @@ var uniforms: Uniforms; @group(0) @binding(1) var acc_struct: acceleration_structure; -var light: vec3; +struct PushConstants { + light: vec3, +} +var pc: PushConstants; const SURFACE_BRIGHTNESS = 0.5; @@ -45,7 +48,7 @@ fn fs_main(vertex: VertexOutput) -> @location(0) vec4 { let d = vertex.tex_coords * 2.0 - 1.0; let origin = vertex.world_position; - let direction = normalize(light - vertex.world_position); + let direction = normalize(pc.light - vertex.world_position); var normal: vec3; let dir_cam = normalize(camera - vertex.world_position); diff --git a/examples/features/src/ray_traced_triangle/mod.rs b/examples/features/src/ray_traced_triangle/mod.rs index 8a6926458..698ccfab1 100644 --- a/examples/features/src/ray_traced_triangle/mod.rs +++ b/examples/features/src/ray_traced_triangle/mod.rs @@ -1,22 +1,23 @@ use glam::{Mat4, Vec3}; use std::mem; -use std::time::Instant; use wgpu::util::{BufferInitDescriptor, DeviceExt}; use wgpu::{include_wgsl, BufferUsages, IndexFormat, SamplerDescriptor}; use wgpu::{ AccelerationStructureFlags, AccelerationStructureUpdateMode, BlasBuildEntry, BlasGeometries, BlasGeometrySizeDescriptors, BlasTriangleGeometry, BlasTriangleGeometrySizeDescriptor, - CreateBlasDescriptor, CreateTlasDescriptor, TlasInstance, TlasPackage, + CreateBlasDescriptor, CreateTlasDescriptor, Tlas, TlasInstance, }; +use crate::utils; + struct Example { - tlas_package: TlasPackage, + tlas: Tlas, compute_pipeline: wgpu::ComputePipeline, blit_pipeline: wgpu::RenderPipeline, bind_group: wgpu::BindGroup, blit_bind_group: wgpu::BindGroup, storage_texture: wgpu::Texture, - start: Instant, + animation_timer: utils::AnimationTimer, } #[repr(C)] @@ -28,12 +29,18 @@ struct Uniforms { impl crate::framework::Example for Example { fn required_features() -> wgpu::Features { - wgpu::Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE - | wgpu::Features::EXPERIMENTAL_RAY_QUERY + wgpu::Features::EXPERIMENTAL_RAY_QUERY } fn required_limits() -> wgpu::Limits { - wgpu::Limits::default() + wgpu::Limits::default().using_minimum_supported_acceleration_structure_values() + } + + fn required_downlevel_capabilities() -> wgpu::DownlevelCapabilities { + wgpu::DownlevelCapabilities { + flags: wgpu::DownlevelFlags::COMPUTE_SHADERS, + ..Default::default() + } } fn init( @@ -138,16 +145,14 @@ impl crate::framework::Example for Example { }, ); - let tlas = device.create_tlas(&CreateTlasDescriptor { + let mut tlas = device.create_tlas(&CreateTlasDescriptor { label: None, max_instances: 3, flags: AccelerationStructureFlags::PREFER_FAST_TRACE, update_mode: AccelerationStructureUpdateMode::Build, }); - let mut tlas_package = TlasPackage::new(tlas); - - tlas_package[0] = Some(TlasInstance::new( + tlas[0] = Some(TlasInstance::new( &blas, Mat4::from_translation(Vec3 { x: 0.0, @@ -162,7 +167,7 @@ impl crate::framework::Example for Example { 0xff, )); - tlas_package[1] = Some(TlasInstance::new( + tlas[1] = Some(TlasInstance::new( &blas, Mat4::from_translation(Vec3 { x: -1.0, @@ -177,7 +182,7 @@ impl crate::framework::Example for Example { 0xff, )); - tlas_package[2] = Some(TlasInstance::new( + tlas[2] = Some(TlasInstance::new( &blas, Mat4::from_translation(Vec3 { x: 1.0, @@ -225,7 +230,7 @@ impl crate::framework::Example for Example { transform_buffer_offset: None, }]), }), - Some(&tlas_package), + Some(&tlas), ); queue.submit(Some(encoder.finish())); @@ -252,7 +257,7 @@ impl crate::framework::Example for Example { address_mode_w: Default::default(), mag_filter: wgpu::FilterMode::Nearest, min_filter: wgpu::FilterMode::Nearest, - mipmap_filter: wgpu::FilterMode::Nearest, + mipmap_filter: wgpu::MipmapFilterMode::Nearest, lod_min_clamp: 1.0, lod_max_clamp: 1.0, compare: None, @@ -304,7 +309,7 @@ impl crate::framework::Example for Example { write_mask: Default::default(), })], }), - multiview: None, + multiview_mask: None, cache: None, }); @@ -324,7 +329,7 @@ impl crate::framework::Example for Example { }, wgpu::BindGroupEntry { binding: 2, - resource: wgpu::BindingResource::AccelerationStructure(tlas_package.tlas()), + resource: wgpu::BindingResource::AccelerationStructure(&tlas), }, ], }); @@ -347,13 +352,13 @@ impl crate::framework::Example for Example { }); Self { - tlas_package, + tlas, compute_pipeline, blit_pipeline, bind_group, blit_bind_group, storage_texture: storage_tex, - start: Instant::now(), + animation_timer: utils::AnimationTimer::default(), } } @@ -368,8 +373,8 @@ impl crate::framework::Example for Example { fn update(&mut self, _event: winit::event::WindowEvent) {} fn render(&mut self, view: &wgpu::TextureView, device: &wgpu::Device, queue: &wgpu::Queue) { - self.tlas_package[0].as_mut().unwrap().transform = - Mat4::from_rotation_y(self.start.elapsed().as_secs_f32()) + self.tlas[0].as_mut().unwrap().transform = + Mat4::from_rotation_y(self.animation_timer.time()) .transpose() .to_cols_array()[..12] .try_into() @@ -378,7 +383,7 @@ impl crate::framework::Example for Example { let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); - encoder.build_acceleration_structures(None, Some(&self.tlas_package)); + encoder.build_acceleration_structures(None, Some(&self.tlas)); { let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { @@ -399,6 +404,7 @@ impl crate::framework::Example for Example { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::GREEN), @@ -408,6 +414,7 @@ impl crate::framework::Example for Example { depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); rpass.set_pipeline(&self.blit_pipeline); @@ -425,22 +432,13 @@ pub fn main() { #[cfg(test)] #[wgpu_test::gpu_test] -static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { +pub static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { name: "ray_traced_triangle", image_path: "/examples/features/src/ray_traced_triangle/screenshot.png", width: 1024, height: 768, optional_features: wgpu::Features::default(), - base_test_parameters: wgpu_test::TestParameters { - required_features: ::required_features(), - required_limits: ::required_limits(), - force_fxc: false, - skips: vec![], - failures: Vec::new(), - required_downlevel_caps: - ::required_downlevel_capabilities(), - ..Default::default() - }, + base_test_parameters: wgpu_test::TestParameters::default(), comparisons: &[wgpu_test::ComparisonType::Mean(0.02)], _phantom: std::marker::PhantomData::, }; diff --git a/examples/features/src/ray_traced_triangle/screenshot.png b/examples/features/src/ray_traced_triangle/screenshot.png index 888f674b8..ee7eb8108 100644 Binary files a/examples/features/src/ray_traced_triangle/screenshot.png and b/examples/features/src/ray_traced_triangle/screenshot.png differ diff --git a/examples/features/src/render_to_texture/mod.rs b/examples/features/src/render_to_texture/mod.rs index 917ac7310..e06c8d638 100644 --- a/examples/features/src/render_to_texture/mod.rs +++ b/examples/features/src/render_to_texture/mod.rs @@ -20,6 +20,7 @@ async fn run(_path: Option) { label: None, required_features: wgpu::Features::empty(), required_limits: wgpu::Limits::downlevel_defaults(), + experimental_features: wgpu::ExperimentalFeatures::disabled(), memory_hints: wgpu::MemoryHints::MemoryUsage, trace: wgpu::Trace::Off, }) @@ -67,7 +68,7 @@ async fn run(_path: Option) { primitive: wgpu::PrimitiveState::default(), depth_stencil: None, multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None, }); @@ -84,6 +85,7 @@ async fn run(_path: Option) { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &texture_view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::GREEN), @@ -93,6 +95,7 @@ async fn run(_path: Option) { depth_stencil_attachment: None, occlusion_query_set: None, timestamp_writes: None, + multiview_mask: None, }); render_pass.set_pipeline(&pipeline); render_pass.draw(0..3, 0..1); @@ -130,7 +133,7 @@ async fn run(_path: Option) { let buffer_slice = output_staging_buffer.slice(..); let (sender, receiver) = flume::bounded(1); buffer_slice.map_async(wgpu::MapMode::Read, move |r| sender.send(r).unwrap()); - device.poll(wgpu::PollType::wait()).unwrap(); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); receiver.recv_async().await.unwrap().unwrap(); log::info!("Output buffer mapped."); { diff --git a/examples/features/src/repeated_compute/mod.rs b/examples/features/src/repeated_compute/mod.rs index 2b9b19995..414a53390 100644 --- a/examples/features/src/repeated_compute/mod.rs +++ b/examples/features/src/repeated_compute/mod.rs @@ -13,9 +13,11 @@ async fn run() { let mut numbers = [0u32; 256]; let context = WgpuContext::new(size_of_val(&numbers)).await; + let mut rand = nanorand::WyRand::new(); + for _ in 0..10 { for p in numbers.iter_mut() { - *p = nanorand::tls_rng().generate::() as u32; + *p = rand.generate::() as u32; } compute(&mut numbers, &context).await; @@ -103,7 +105,10 @@ async fn compute(local_buffer: &mut [u32], context: &WgpuContext) { // One of those can be calling `Device::poll`. This isn't necessary on the web as devices // are polled automatically but natively, we need to make sure this happens manually. // `PollType::Wait` will cause the thread to wait on native but not on WebGpu. - context.device.poll(wgpu::PollType::wait()).unwrap(); + context + .device + .poll(wgpu::PollType::wait_indefinitely()) + .unwrap(); log::info!("Device polled."); // Now we await the receiving and panic if anything went wrong because we're lazy. receiver.recv_async().await.unwrap().unwrap(); @@ -162,6 +167,7 @@ impl WgpuContext { label: None, required_features: wgpu::Features::empty(), required_limits: wgpu::Limits::downlevel_defaults(), + experimental_features: wgpu::ExperimentalFeatures::disabled(), memory_hints: wgpu::MemoryHints::Performance, trace: wgpu::Trace::Off, }) diff --git a/examples/features/src/shadow/mod.rs b/examples/features/src/shadow/mod.rs index 797ded1ff..169e1e917 100644 --- a/examples/features/src/shadow/mod.rs +++ b/examples/features/src/shadow/mod.rs @@ -192,7 +192,7 @@ impl Example { sample_count: 1, dimension: wgpu::TextureDimension::D2, format: Self::DEPTH_FORMAT, - usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TRANSIENT, label: None, view_formats: &[], }); @@ -366,7 +366,7 @@ impl crate::framework::Example for Example { address_mode_w: wgpu::AddressMode::ClampToEdge, mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, - mipmap_filter: wgpu::FilterMode::Nearest, + mipmap_filter: wgpu::MipmapFilterMode::Nearest, compare: Some(wgpu::CompareFunction::LessEqual), ..Default::default() }); @@ -518,7 +518,7 @@ impl crate::framework::Example for Example { }, }), multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None, }); @@ -653,7 +653,7 @@ impl crate::framework::Example for Example { bias: wgpu::DepthBiasState::default(), }), multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None, }); @@ -771,6 +771,7 @@ impl crate::framework::Example for Example { }), timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); pass.set_pipeline(&self.shadow_pass.pipeline); pass.set_bind_group(0, &self.shadow_pass.bind_group, &[]); @@ -794,6 +795,7 @@ impl crate::framework::Example for Example { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { @@ -815,6 +817,7 @@ impl crate::framework::Example for Example { }), timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); pass.set_pipeline(&self.forward_pass.pipeline); pass.set_bind_group(0, &self.forward_pass.bind_group, &[]); @@ -838,7 +841,7 @@ pub fn main() { #[cfg(test)] #[wgpu_test::gpu_test] -static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { +pub static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { name: "shadow", image_path: "/examples/features/src/shadow/screenshot.png", width: 1024, diff --git a/examples/features/src/skybox/mod.rs b/examples/features/src/skybox/mod.rs index a17a99656..3a3d988e9 100644 --- a/examples/features/src/skybox/mod.rs +++ b/examples/features/src/skybox/mod.rs @@ -80,7 +80,7 @@ impl Example { sample_count: 1, dimension: wgpu::TextureDimension::D2, format: Self::DEPTH_FORMAT, - usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TRANSIENT, label: None, view_formats: &[], }); @@ -218,7 +218,7 @@ impl crate::framework::Example for Example { bias: wgpu::DepthBiasState::default(), }), multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None, }); let entity_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { @@ -252,7 +252,7 @@ impl crate::framework::Example for Example { bias: wgpu::DepthBiasState::default(), }), multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None, }); @@ -263,7 +263,7 @@ impl crate::framework::Example for Example { address_mode_w: wgpu::AddressMode::ClampToEdge, mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, - mipmap_filter: wgpu::FilterMode::Linear, + mipmap_filter: wgpu::MipmapFilterMode::Linear, ..Default::default() }); @@ -299,11 +299,7 @@ impl crate::framework::Example for Example { let max_mips = layer_size.max_mips(wgpu::TextureDimension::D2); log::debug!( - "Copying {:?} skybox images of size {}, {}, 6 with {} mips to gpu", - skybox_format, - IMAGE_SIZE, - IMAGE_SIZE, - max_mips, + "Copying {skybox_format:?} skybox images of size {IMAGE_SIZE}, {IMAGE_SIZE}, 6 with {max_mips} mips to gpu", ); let bytes = match skybox_format { @@ -322,7 +318,7 @@ impl crate::framework::Example for Example { let mut image = Vec::with_capacity(reader.data().len()); for level in reader.levels() { - image.extend_from_slice(level); + image.extend_from_slice(level.data); } let texture = device.create_texture_with_data( @@ -376,7 +372,7 @@ impl crate::framework::Example for Example { uniform_buf, entities, depth_view, - staging_belt: wgpu::util::StagingBelt::new(0x100), + staging_belt: wgpu::util::StagingBelt::new(device.clone(), 0x100), } } @@ -415,7 +411,6 @@ impl crate::framework::Example for Example { &self.uniform_buf, 0, wgpu::BufferSize::new((raw_uniforms.len() * 4) as wgpu::BufferAddress).unwrap(), - device, ) .copy_from_slice(bytemuck::cast_slice(&raw_uniforms)); @@ -426,6 +421,7 @@ impl crate::framework::Example for Example { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { @@ -447,6 +443,7 @@ impl crate::framework::Example for Example { }), timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); rpass.set_bind_group(0, &self.bind_group, &[]); @@ -473,7 +470,7 @@ pub fn main() { #[cfg(test)] #[wgpu_test::gpu_test] -static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { +pub static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { name: "skybox", image_path: "/examples/features/src/skybox/screenshot.png", width: 1024, @@ -482,45 +479,45 @@ static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTest base_test_parameters: wgpu_test::TestParameters::default().expect_fail( wgpu_test::FailureCase::backend_adapter(wgpu::Backends::GL, "ANGLE"), ), - comparisons: &[wgpu_test::ComparisonType::Mean(0.015)], - _phantom: std::marker::PhantomData::, -}; - -#[cfg(test)] -#[wgpu_test::gpu_test] -static TEST_BCN: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { - name: "skybox-bc7", - image_path: "/examples/features/src/skybox/screenshot_bc7.png", - width: 1024, - height: 768, - optional_features: wgpu::Features::TEXTURE_COMPRESSION_BC, - base_test_parameters: wgpu_test::TestParameters::default(), // https://bugs.chromium.org/p/angleproject/issues/detail?id=7056 comparisons: &[wgpu_test::ComparisonType::Mean(0.02)], _phantom: std::marker::PhantomData::, }; #[cfg(test)] #[wgpu_test::gpu_test] -static TEST_ETC2: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { +pub static TEST_BCN: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { + name: "skybox-bc7", + image_path: "/examples/features/src/skybox/screenshot_bc7.png", + width: 1024, + height: 768, + optional_features: wgpu::Features::TEXTURE_COMPRESSION_BC, + base_test_parameters: wgpu_test::TestParameters::default(), + comparisons: &[wgpu_test::ComparisonType::Mean(0.02)], + _phantom: std::marker::PhantomData::, +}; + +#[cfg(test)] +#[wgpu_test::gpu_test] +pub static TEST_ETC2: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { name: "skybox-etc2", image_path: "/examples/features/src/skybox/screenshot_etc2.png", width: 1024, height: 768, optional_features: wgpu::Features::TEXTURE_COMPRESSION_ETC2, - base_test_parameters: wgpu_test::TestParameters::default(), // https://bugs.chromium.org/p/angleproject/issues/detail?id=7056 + base_test_parameters: wgpu_test::TestParameters::default(), comparisons: &[wgpu_test::ComparisonType::Mean(0.015)], _phantom: std::marker::PhantomData::, }; #[cfg(test)] #[wgpu_test::gpu_test] -static TEST_ASTC: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { +pub static TEST_ASTC: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { name: "skybox-astc", image_path: "/examples/features/src/skybox/screenshot_astc.png", width: 1024, height: 768, optional_features: wgpu::Features::TEXTURE_COMPRESSION_ASTC, - base_test_parameters: wgpu_test::TestParameters::default(), // https://bugs.chromium.org/p/angleproject/issues/detail?id=7056 + base_test_parameters: wgpu_test::TestParameters::default(), comparisons: &[wgpu_test::ComparisonType::Mean(0.016)], _phantom: std::marker::PhantomData::, }; diff --git a/examples/features/src/skybox/screenshot-vulkan.png b/examples/features/src/skybox/screenshot-vulkan.png deleted file mode 100644 index 495a21ecb..000000000 Binary files a/examples/features/src/skybox/screenshot-vulkan.png and /dev/null differ diff --git a/examples/features/src/srgb_blend/mod.rs b/examples/features/src/srgb_blend/mod.rs index 8471b3cc5..cabf4cec5 100644 --- a/examples/features/src/srgb_blend/mod.rs +++ b/examples/features/src/srgb_blend/mod.rs @@ -146,7 +146,7 @@ impl crate::framework::Example for Example { }, depth_stencil: None, multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None, }); @@ -181,6 +181,7 @@ impl crate::framework::Example for Example { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { @@ -195,6 +196,7 @@ impl crate::framework::Example for Example { depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); rpass.push_debug_group("Prepare data for draw."); rpass.set_pipeline(&self.pipeline); @@ -222,7 +224,7 @@ pub fn main() { #[cfg(test)] #[wgpu_test::gpu_test] -static TEST_SRGB: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { +pub static TEST_SRGB: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { name: "srgb-blend-srg", // Generated on WARP/Windows image_path: "/examples/features/src/srgb_blend/screenshot-srgb.png", @@ -236,7 +238,7 @@ static TEST_SRGB: crate::framework::ExampleTestParams = crate::framework::Exampl #[cfg(test)] #[wgpu_test::gpu_test] -static TEST_LINEAR: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { +pub static TEST_LINEAR: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { name: "srgb-blend-linear", // Generated on WARP/Windows image_path: "/examples/features/src/srgb_blend/screenshot-linear.png", diff --git a/examples/features/src/stencil_triangles/mod.rs b/examples/features/src/stencil_triangles/mod.rs index b03aedd5e..1a20669e9 100644 --- a/examples/features/src/stencil_triangles/mod.rs +++ b/examples/features/src/stencil_triangles/mod.rs @@ -100,7 +100,7 @@ impl crate::framework::Example for Example { bias: Default::default(), }), multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None, }); @@ -136,7 +136,7 @@ impl crate::framework::Example for Example { bias: Default::default(), }), multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None, }); @@ -200,6 +200,7 @@ impl crate::framework::Example for Example { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { @@ -221,6 +222,7 @@ impl crate::framework::Example for Example { }), timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); rpass.set_stencil_reference(1); @@ -244,7 +246,7 @@ pub fn main() { #[cfg(test)] #[wgpu_test::gpu_test] -static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { +pub static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { name: "stencil-triangles", image_path: "/examples/features/src/stencil_triangles/screenshot.png", width: 1024, diff --git a/examples/features/src/storage_texture/mod.rs b/examples/features/src/storage_texture/mod.rs index b028e09a9..7db46770e 100644 --- a/examples/features/src/storage_texture/mod.rs +++ b/examples/features/src/storage_texture/mod.rs @@ -4,7 +4,7 @@ //! //! Storage textures work like normal textures but they operate similar to storage buffers //! in that they can be written to. The issue is that as it stands, write-only is the -//! only valid access mode for storage textures in WGSL and although there is a WGPU feature +//! only valid access mode for storage textures in WGSL and although there is a wgpu feature //! to allow for read-write access, this is unfortunately a native-only feature and thus //! we won't be using it here. If we needed a reference texture, we would need to add a //! second texture to act as a reference and attach that as well. Luckily, we don't need @@ -34,6 +34,7 @@ async fn run(_path: Option) { label: None, required_features: wgpu::Features::empty(), required_limits: wgpu::Limits::downlevel_defaults(), + experimental_features: wgpu::ExperimentalFeatures::disabled(), memory_hints: wgpu::MemoryHints::MemoryUsage, trace: wgpu::Trace::Off, }) @@ -141,7 +142,7 @@ async fn run(_path: Option) { let buffer_slice = output_staging_buffer.slice(..); let (sender, receiver) = flume::bounded(1); buffer_slice.map_async(wgpu::MapMode::Read, move |r| sender.send(r).unwrap()); - device.poll(wgpu::PollType::wait()).unwrap(); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); receiver.recv_async().await.unwrap().unwrap(); log::info!("Output buffer mapped"); { diff --git a/examples/features/src/texture_arrays/mod.rs b/examples/features/src/texture_arrays/mod.rs index c20eeb885..45942f9a1 100644 --- a/examples/features/src/texture_arrays/mod.rs +++ b/examples/features/src/texture_arrays/mod.rs @@ -358,7 +358,7 @@ impl crate::framework::Example for Example { }, depth_stencil: None, multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None }); @@ -392,6 +392,7 @@ impl crate::framework::Example for Example { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), @@ -401,6 +402,7 @@ impl crate::framework::Example for Example { depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); rpass.set_pipeline(&self.pipeline); @@ -428,45 +430,36 @@ pub fn main() { crate::framework::run::("texture-arrays"); } -#[cfg(test)] -fn test_parameters() -> wgpu_test::TestParameters { - wgpu_test::TestParameters::default() - // https://github.com/gfx-rs/wgpu/issues/7287 - .expect_fail(wgpu_test::FailureCase::backend_adapter( - wgpu::Backends::METAL, - "Apple M", - )) -} - #[cfg(test)] #[wgpu_test::gpu_test] -static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { +pub static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { name: "texture-arrays", image_path: "/examples/features/src/texture_arrays/screenshot.png", width: 1024, height: 768, optional_features: wgpu::Features::empty(), - base_test_parameters: test_parameters(), + base_test_parameters: wgpu_test::TestParameters::default(), comparisons: &[wgpu_test::ComparisonType::Mean(0.0)], _phantom: std::marker::PhantomData::, }; #[cfg(test)] #[wgpu_test::gpu_test] -static TEST_UNIFORM: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { - name: "texture-arrays-uniform", - image_path: "/examples/features/src/texture_arrays/screenshot.png", - width: 1024, - height: 768, - optional_features: wgpu::Features::empty(), - base_test_parameters: test_parameters(), - comparisons: &[wgpu_test::ComparisonType::Mean(0.0)], - _phantom: std::marker::PhantomData::, -}; +pub static TEST_UNIFORM: crate::framework::ExampleTestParams = + crate::framework::ExampleTestParams { + name: "texture-arrays-uniform", + image_path: "/examples/features/src/texture_arrays/screenshot.png", + width: 1024, + height: 768, + optional_features: wgpu::Features::empty(), + base_test_parameters: wgpu_test::TestParameters::default(), + comparisons: &[wgpu_test::ComparisonType::Mean(0.0)], + _phantom: std::marker::PhantomData::, + }; #[cfg(test)] #[wgpu_test::gpu_test] -static TEST_NON_UNIFORM: crate::framework::ExampleTestParams = +pub static TEST_NON_UNIFORM: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { name: "texture-arrays-non-uniform", image_path: "/examples/features/src/texture_arrays/screenshot.png", @@ -474,7 +467,7 @@ static TEST_NON_UNIFORM: crate::framework::ExampleTestParams = height: 768, optional_features: wgpu::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING, - base_test_parameters: test_parameters(), + base_test_parameters: wgpu_test::TestParameters::default(), comparisons: &[wgpu_test::ComparisonType::Mean(0.0)], _phantom: std::marker::PhantomData::, }; diff --git a/examples/features/src/timestamp_queries/mod.rs b/examples/features/src/timestamp_queries/mod.rs index 7bac87e1a..b15977156 100644 --- a/examples/features/src/timestamp_queries/mod.rs +++ b/examples/features/src/timestamp_queries/mod.rs @@ -161,7 +161,7 @@ impl Queries { self.destination_buffer .slice(..) .map_async(wgpu::MapMode::Read, |_| ()); - device.poll(wgpu::PollType::wait()).unwrap(); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); let timestamps = { let timestamp_view = self @@ -210,6 +210,7 @@ async fn run() { label: None, required_features: features, required_limits: wgpu::Limits::downlevel_defaults(), + experimental_features: wgpu::ExperimentalFeatures::disabled(), memory_hints: wgpu::MemoryHints::MemoryUsage, trace: wgpu::Trace::Off, }) @@ -357,7 +358,7 @@ fn render_pass( primitive: wgpu::PrimitiveState::default(), depth_stencil: None, multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None, }); let render_target = device.create_texture(&wgpu::TextureDescriptor { @@ -380,6 +381,7 @@ fn render_pass( label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &render_target_view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::GREEN), @@ -393,6 +395,7 @@ fn render_pass( end_of_pass_write_index: Some(*next_unused_query + 1), }), occlusion_query_set: None, + multiview_mask: None, }); *next_unused_query += 2; @@ -425,13 +428,13 @@ pub fn main() { } #[cfg(test)] -mod tests { +pub mod tests { use wgpu_test::{gpu_test, FailureCase, GpuTestConfiguration}; use super::{submit_render_and_compute_pass_with_queries, QueryResults}; #[gpu_test] - static TIMESTAMPS_PASS_BOUNDARIES: GpuTestConfiguration = GpuTestConfiguration::new() + pub static TIMESTAMPS_PASS_BOUNDARIES: GpuTestConfiguration = GpuTestConfiguration::new() .parameters( wgpu_test::TestParameters::default() .limits(wgpu::Limits::downlevel_defaults()) @@ -440,7 +443,7 @@ mod tests { .run_sync(|ctx| test_timestamps(ctx, false, false)); #[gpu_test] - static TIMESTAMPS_ENCODER: GpuTestConfiguration = GpuTestConfiguration::new() + pub static TIMESTAMPS_ENCODER: GpuTestConfiguration = GpuTestConfiguration::new() .parameters( wgpu_test::TestParameters::default() .limits(wgpu::Limits::downlevel_defaults()) @@ -454,7 +457,7 @@ mod tests { .run_sync(|ctx| test_timestamps(ctx, true, false)); #[gpu_test] - static TIMESTAMPS_PASSES: GpuTestConfiguration = GpuTestConfiguration::new() + pub static TIMESTAMPS_PASSES: GpuTestConfiguration = GpuTestConfiguration::new() .parameters( wgpu_test::TestParameters::default() .limits(wgpu::Limits::downlevel_defaults()) diff --git a/examples/features/src/uniform_values/mod.rs b/examples/features/src/uniform_values/mod.rs index 3a6933bf1..e4510ab4e 100644 --- a/examples/features/src/uniform_values/mod.rs +++ b/examples/features/src/uniform_values/mod.rs @@ -18,7 +18,7 @@ use std::sync::Arc; // We won't bring StorageBuffer into scope as that might be too easy to confuse -// with actual GPU-allocated WGPU storage buffers. +// with actual GPU-allocated wgpu storage buffers. use encase::ShaderType; use winit::{ event::{Event, KeyEvent, WindowEvent}, @@ -114,6 +114,7 @@ impl WgpuContext { label: None, required_features: wgpu::Features::empty(), required_limits: wgpu::Limits::downlevel_defaults(), + experimental_features: wgpu::ExperimentalFeatures::disabled(), memory_hints: wgpu::MemoryHints::MemoryUsage, trace: wgpu::Trace::Off, }) @@ -185,7 +186,7 @@ impl WgpuContext { primitive: wgpu::PrimitiveState::default(), depth_stencil: None, multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None, }); let surface_config = surface @@ -307,6 +308,7 @@ async fn run(event_loop: EventLoop<()>, window: Arc) { color_attachments: &[Some( wgpu::RenderPassColorAttachment { view: &view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::GREEN), @@ -317,6 +319,7 @@ async fn run(event_loop: EventLoop<()>, window: Arc) { depth_stencil_attachment: None, occlusion_query_set: None, timestamp_writes: None, + multiview_mask: None, }); render_pass.set_pipeline(&wgpu_context_ref.pipeline); // (9) diff --git a/examples/features/src/utils.rs b/examples/features/src/utils.rs index bbc727582..94bbdb838 100644 --- a/examples/features/src/utils.rs +++ b/examples/features/src/utils.rs @@ -1,16 +1,23 @@ #[cfg(not(target_arch = "wasm32"))] use std::io::Write; +use std::time::Instant; #[cfg(target_arch = "wasm32")] use wasm_bindgen::prelude::*; +#[cfg(target_arch = "wasm32")] +fn get_content_div() -> web_sys::Element { + web_sys::window() + .and_then(|window| window.document()) + .and_then(|document| document.get_element_by_id("content")) + .expect("Could not get document / content.") +} + /// Replaces the site body with a message telling the user to open the console and use that. #[cfg(target_arch = "wasm32")] pub fn add_web_nothing_to_see_msg() { - web_sys::window() - .and_then(|window| window.document()) - .and_then(|document| document.body()) - .expect("Could not get document / body.") - .set_inner_html("

Nothing to see here! Open the console!

"); + get_content_div().set_inner_html( + "

This is a compute example, so there's nothing to see here. Open the console!

", + ); } /// Outputs a vector of RGBA bytes as a png image with the given dimensions on the given path. @@ -30,7 +37,7 @@ pub fn output_image_native(image_data: Vec, texture_dims: (usize, usize), pa let mut file = std::fs::File::create(&path).unwrap(); file.write_all(&png_data[..]).unwrap(); - log::info!("PNG file written to disc as \"{}\".", path); + log::info!("PNG file written to disc as \"{path}\"."); } /// Effectively a version of `output_image_native` but meant for web browser contexts. @@ -43,7 +50,7 @@ pub fn output_image_native(image_data: Vec, texture_dims: (usize, usize), pa #[cfg(target_arch = "wasm32")] pub fn output_image_wasm(image_data: Vec, texture_dims: (usize, usize)) { let document = web_sys::window().unwrap().document().unwrap(); - let body = document.body().unwrap(); + let content_div = get_content_div(); let canvas = if let Some(found_canvas) = document.get_element_by_id("staging-canvas") { match found_canvas.dyn_into::() { @@ -51,9 +58,8 @@ pub fn output_image_wasm(image_data: Vec, texture_dims: (usize, usize)) { Err(e) => { log::error!( "In searching for a staging canvas for outputting an image \ - (element with id \"staging-canvas\"), found non-canvas element: {:?}. - Replacing with standard staging canvas.", - e + (element with id \"staging-canvas\"), found non-canvas element: {e:?}. + Replacing with standard staging canvas." ); e.remove(); create_staging_canvas(&document) @@ -94,9 +100,8 @@ pub fn output_image_wasm(image_data: Vec, texture_dims: (usize, usize)) { Ok(e) => e, Err(e) => { log::error!( - "Found an element with the id \"output-image-target\" but it was not an image: {:?}. + "Found an element with the id \"output-image-target\" but it was not an image: {e:?}. Replacing with default image output element.", - e ); e.remove(); create_output_image_element(&document) @@ -121,14 +126,15 @@ pub fn output_image_wasm(image_data: Vec, texture_dims: (usize, usize)) { You can drag it to your desktop to download.", )); p.set_id("image-for-you-text"); - body.append_child(&p) - .expect("Failed to append \"image for you text\" to document body."); + content_div + .append_child(&p) + .expect("Failed to append \"image for you text\" to document."); } } #[cfg(target_arch = "wasm32")] fn create_staging_canvas(document: &web_sys::Document) -> web_sys::HtmlCanvasElement { - let body = document.body().expect("Failed to get document body."); + let content_div = get_content_div(); let new_canvas = document .create_element("canvas") .expect("Failed to create staging canvas.") @@ -137,22 +143,21 @@ fn create_staging_canvas(document: &web_sys::Document) -> web_sys::HtmlCanvasEle // We don't want to show the canvas, we just want it to exist in the background. new_canvas.set_attribute("hidden", "true").unwrap(); new_canvas.set_attribute("background-color", "red").unwrap(); - body.append_child(&new_canvas).unwrap(); + content_div.append_child(&new_canvas).unwrap(); log::info!("Created new staging canvas: {:?}", &new_canvas); new_canvas } #[cfg(target_arch = "wasm32")] fn create_output_image_element(document: &web_sys::Document) -> web_sys::HtmlImageElement { - let body = document.body().expect("Failed to get document body."); + let content_div = get_content_div(); let new_image = document .create_element("img") .expect("Failed to create output image element.") .dyn_into::() .unwrap(); new_image.set_id("output-image-target"); - body.append_child(&new_image) - .expect("Failed to append output image target to document body."); + content_div.replace_children_with_node_1(&new_image); log::info!("Created new output target image: {:?}", &new_image); new_image } @@ -198,7 +203,7 @@ pub(crate) async fn get_adapter_with_capabilities_or_from_env( ); adapter } else { - let adapters = instance.enumerate_adapters(Backends::all()); + let adapters = instance.enumerate_adapters(Backends::all()).await; let mut chosen_adapter = None; for adapter in adapters { @@ -258,3 +263,23 @@ pub(crate) async fn get_adapter_with_capabilities_or_from_env( ); adapter } + +/// A custom timer that only starts counting after the first call to get its time value. +/// Useful because some examples have animations that would otherwise get started at initialization +/// leading to random CI fails. +#[derive(Default)] +pub struct AnimationTimer { + start_time: Option, +} + +impl AnimationTimer { + pub fn time(&mut self) -> f32 { + match self.start_time { + None => { + self.start_time = Some(Instant::now()); + 0.0 + } + Some(ref instant) => instant.elapsed().as_secs_f32(), + } + } +} diff --git a/examples/features/src/water/mod.rs b/examples/features/src/water/mod.rs index 1e4b16402..dc8bccfa4 100644 --- a/examples/features/src/water/mod.rs +++ b/examples/features/src/water/mod.rs @@ -217,7 +217,7 @@ impl Example { address_mode_w: wgpu::AddressMode::ClampToEdge, mag_filter: wgpu::FilterMode::Nearest, min_filter: wgpu::FilterMode::Linear, - mipmap_filter: wgpu::FilterMode::Nearest, + mipmap_filter: wgpu::MipmapFilterMode::Nearest, ..Default::default() }); @@ -567,7 +567,7 @@ impl crate::framework::Example for Example { }), // No multisampling is used. multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, // No pipeline caching is used cache: None, }); @@ -605,7 +605,7 @@ impl crate::framework::Example for Example { bias: wgpu::DepthBiasState::default(), }), multisample: wgpu::MultisampleState::default(), - multiview: None, + multiview_mask: None, cache: None }); @@ -731,6 +731,7 @@ impl crate::framework::Example for Example { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &self.reflect_view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(back_color), @@ -749,6 +750,7 @@ impl crate::framework::Example for Example { }), timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); rpass.execute_bundles([&self.terrain_bundle]); @@ -760,6 +762,7 @@ impl crate::framework::Example for Example { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(back_color), @@ -776,6 +779,7 @@ impl crate::framework::Example for Example { }), timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); rpass.set_pipeline(&self.terrain_pipeline); rpass.set_bind_group(0, &self.terrain_normal_bind_group, &[]); @@ -789,6 +793,7 @@ impl crate::framework::Example for Example { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Load, @@ -802,6 +807,7 @@ impl crate::framework::Example for Example { }), timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); rpass.set_pipeline(&self.water_pipeline); @@ -820,7 +826,7 @@ pub fn main() { #[cfg(test)] #[wgpu_test::gpu_test] -static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { +pub static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams { name: "water", image_path: "/examples/features/src/water/screenshot.png", width: 1024, @@ -832,7 +838,7 @@ static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTest .expect_fail(wgpu_test::FailureCase { backends: Some(wgpu::Backends::VULKAN), reasons: vec![wgpu_test::FailureReason::validation_error() - .with_message(concat!("Hazard WRITE_AFTER_"))], + .with_message("WRITE_AFTER_WRITE hazard detected.")], behavior: wgpu_test::FailureBehavior::AssertFailure, ..Default::default() }), diff --git a/examples/features/web-static/index.html b/examples/features/web-static/index.html index 135c04d81..3a2349cdf 100644 --- a/examples/features/web-static/index.html +++ b/examples/features/web-static/index.html @@ -50,6 +50,11 @@ margin: 0.5em 0; } + h1 { + margin-left: 0.75em; + margin-right: 0.75em; + } + .backend-list-container { display: flex; flex-direction: row; @@ -99,14 +104,18 @@ text-align: center; } - .main-canvas { - margin: 0; + #content { /* This allows the flexbox to grow to max size, this is needed for WebGPU */ - flex: 1; + flex: 1 1 100%; /* This forces CSS to ignore the width/height of the canvas, this is needed for WebGL */ contain: size; } + .main-canvas { + margin: 0; + width: 100%; + height: 100%; + } #menu-button { display: none; @@ -158,7 +167,9 @@ - +
+ +
- \ No newline at end of file + diff --git a/examples/standalone/01_hello_compute/Cargo.toml b/examples/standalone/01_hello_compute/Cargo.toml index e4e0fedce..a7c36f913 100644 --- a/examples/standalone/01_hello_compute/Cargo.toml +++ b/examples/standalone/01_hello_compute/Cargo.toml @@ -1,11 +1,11 @@ [package] name = "wgpu-example-01-hello-compute" edition = "2021" -rust-version = "1.84" +rust-version = "1.88" publish = false [dependencies] -bytemuck = "1" -env_logger = "0.11.6" +bytemuck = "1.22.0" +env_logger = "0.11" pollster = "0.4" -wgpu = "24.0.0" +wgpu = "27.0.0" diff --git a/examples/standalone/01_hello_compute/src/main.rs b/examples/standalone/01_hello_compute/src/main.rs index 19d95620c..35b6b3c69 100644 --- a/examples/standalone/01_hello_compute/src/main.rs +++ b/examples/standalone/01_hello_compute/src/main.rs @@ -70,6 +70,7 @@ fn main() { label: None, required_features: wgpu::Features::empty(), required_limits: wgpu::Limits::downlevel_defaults(), + experimental_features: wgpu::ExperimentalFeatures::disabled(), memory_hints: wgpu::MemoryHints::MemoryUsage, trace: wgpu::Trace::Off, })) @@ -241,7 +242,7 @@ fn main() { // Wait for the GPU to finish working on the submitted work. This doesn't work on WebGPU, so we would need // to rely on the callback to know when the buffer is mapped. - device.poll(wgpu::PollType::Wait).unwrap(); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); // We can now read the data from the buffer. let data = buffer_slice.get_mapped_range(); @@ -249,5 +250,5 @@ fn main() { let result: &[f32] = bytemuck::cast_slice(&data); // Print out the result. - println!("Result: {:?}", result); + println!("Result: {result:?}"); } diff --git a/examples/standalone/02_hello_window/Cargo.toml b/examples/standalone/02_hello_window/Cargo.toml index c0bec2123..a5f351f95 100644 --- a/examples/standalone/02_hello_window/Cargo.toml +++ b/examples/standalone/02_hello_window/Cargo.toml @@ -1,11 +1,11 @@ [package] name = "wgpu-example-02-hello-window" edition = "2021" -rust-version = "1.84" +rust-version = "1.88" publish = false [dependencies] -env_logger = "0.11.6" +env_logger = "0.11" pollster = "0.4" -wgpu = "24.0.0" +wgpu = "27.0.0" winit = { version = "0.30.8", features = ["android-native-activity"] } diff --git a/examples/standalone/02_hello_window/src/main.rs b/examples/standalone/02_hello_window/src/main.rs index 83687e281..6da07c9f7 100644 --- a/examples/standalone/02_hello_window/src/main.rs +++ b/examples/standalone/02_hello_window/src/main.rs @@ -97,6 +97,7 @@ impl State { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &texture_view, + depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::GREEN), @@ -106,6 +107,7 @@ impl State { depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); // If you wanted to call any drawing commands, they would go here. diff --git a/examples/standalone/custom_backend/Cargo.toml b/examples/standalone/custom_backend/Cargo.toml index ec37bca11..5c05a981e 100644 --- a/examples/standalone/custom_backend/Cargo.toml +++ b/examples/standalone/custom_backend/Cargo.toml @@ -1,11 +1,15 @@ [package] name = "wgpu-example-custom-backend" edition = "2021" -rust-version = "1.84" +rust-version = "1.88" publish = false +[features] +default = ["web"] +web = ["wgpu/web"] + [dependencies] -wgpu = { version = "24.0.0", features = [ +wgpu = { version = "27.0.0", features = [ "custom", "wgsl", ], default-features = false } diff --git a/examples/standalone/custom_backend/src/custom.rs b/examples/standalone/custom_backend/src/custom.rs index 6a30b8f7d..7b2403611 100644 --- a/examples/standalone/custom_backend/src/custom.rs +++ b/examples/standalone/custom_backend/src/custom.rs @@ -3,9 +3,9 @@ use std::pin::Pin; use std::sync::Arc; use wgpu::custom::{ - AdapterInterface, DeviceInterface, DispatchAdapter, DispatchDevice, DispatchQueue, - DispatchShaderModule, DispatchSurface, InstanceInterface, QueueInterface, RequestAdapterFuture, - ShaderModuleInterface, + AdapterInterface, ComputePipelineInterface, DeviceInterface, DispatchAdapter, DispatchBlas, + DispatchDevice, DispatchQueue, DispatchShaderModule, DispatchSurface, InstanceInterface, + QueueInterface, RequestAdapterFuture, ShaderModuleInterface, }; #[derive(Debug, Clone)] @@ -55,6 +55,13 @@ impl InstanceInterface for CustomInstance { fn wgsl_language_features(&self) -> wgpu::WgslLanguageFeatures { unimplemented!() } + + fn enumerate_adapters( + &self, + _backends: wgpu::Backends, + ) -> Pin> { + unimplemented!() + } } #[derive(Debug)] @@ -126,9 +133,9 @@ impl DeviceInterface for CustomDevice { DispatchShaderModule::custom(CustomShaderModule(self.0.clone())) } - unsafe fn create_shader_module_spirv( + unsafe fn create_shader_module_passthrough( &self, - _desc: &wgpu::ShaderModuleDescriptorSpirV<'_>, + _desc: &wgpu::ShaderModuleDescriptorPassthrough<'_>, ) -> DispatchShaderModule { unimplemented!() } @@ -161,11 +168,19 @@ impl DeviceInterface for CustomDevice { unimplemented!() } + fn create_mesh_pipeline( + &self, + _desc: &wgpu::MeshPipelineDescriptor<'_>, + ) -> wgpu::custom::DispatchRenderPipeline { + unimplemented!() + } + fn create_compute_pipeline( &self, - _desc: &wgpu::ComputePipelineDescriptor<'_>, + desc: &wgpu::ComputePipelineDescriptor<'_>, ) -> wgpu::custom::DispatchComputePipeline { - unimplemented!() + let module = desc.module.as_custom::().unwrap(); + wgpu::custom::DispatchComputePipeline::custom(CustomComputePipeline(module.0.clone())) } unsafe fn create_pipeline_cache( @@ -183,6 +198,14 @@ impl DeviceInterface for CustomDevice { unimplemented!() } + fn create_external_texture( + &self, + _desc: &wgpu::ExternalTextureDescriptor<'_>, + _planes: &[&wgpu::TextureView], + ) -> wgpu::custom::DispatchExternalTexture { + unimplemented!() + } + fn create_blas( &self, _desc: &wgpu::CreateBlasDescriptor<'_>, @@ -224,7 +247,7 @@ impl DeviceInterface for CustomDevice { unimplemented!() } - fn on_uncaptured_error(&self, _handler: Box) { + fn on_uncaptured_error(&self, _handler: Arc) { unimplemented!() } @@ -236,15 +259,18 @@ impl DeviceInterface for CustomDevice { unimplemented!() } - fn start_capture(&self) { + unsafe fn start_graphics_debugger_capture(&self) { unimplemented!() } - fn stop_capture(&self) { + unsafe fn stop_graphics_debugger_capture(&self) { unimplemented!() } - fn poll(&self, _maintain: wgpu::PollType) -> Result { + fn poll( + &self, + _maintain: wgpu::wgt::PollType, + ) -> Result { unimplemented!() } @@ -262,7 +288,7 @@ impl DeviceInterface for CustomDevice { } #[derive(Debug)] -struct CustomShaderModule(Counter); +pub struct CustomShaderModule(pub Counter); impl ShaderModuleInterface for CustomShaderModule { fn get_compilation_info(&self) -> Pin> { @@ -333,7 +359,7 @@ impl QueueInterface for CustomQueue { unimplemented!() } - #[cfg(target_arch = "wasm32")] + #[cfg(all(target_arch = "wasm32", feature = "web"))] fn copy_external_image_to_texture( &self, _source: &wgpu::CopyExternalImageSourceInfo, @@ -342,4 +368,17 @@ impl QueueInterface for CustomQueue { ) { unimplemented!() } + + fn compact_blas(&self, _blas: &DispatchBlas) -> (Option, DispatchBlas) { + unimplemented!() + } +} + +#[derive(Debug)] +pub struct CustomComputePipeline(pub Counter); + +impl ComputePipelineInterface for CustomComputePipeline { + fn get_bind_group_layout(&self, _index: u32) -> wgpu::custom::DispatchBindGroupLayout { + unimplemented!() + } } diff --git a/examples/standalone/custom_backend/src/main.rs b/examples/standalone/custom_backend/src/main.rs index 11f05e98e..1582bcc7d 100644 --- a/examples/standalone/custom_backend/src/main.rs +++ b/examples/standalone/custom_backend/src/main.rs @@ -1,6 +1,6 @@ use std::marker::PhantomData; -use custom::Counter; +use custom::{Counter, CustomShaderModule}; use wgpu::{DeviceDescriptor, RequestAdapterOptions}; mod custom; @@ -31,12 +31,26 @@ async fn main() { .unwrap(); assert_eq!(counter.count(), 5); - let _module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("shader"), source: wgpu::ShaderSource::Dummy(PhantomData), }); + let custom_module = module.as_custom::().unwrap(); + assert_eq!(custom_module.0.count(), 6); + let _module_clone = module.clone(); assert_eq!(counter.count(), 6); + + let _pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: None, + module: &module, + entry_point: None, + compilation_options: Default::default(), + cache: None, + }); + + assert_eq!(counter.count(), 7); } assert_eq!(counter.count(), 1); } diff --git a/naga-cli/Cargo.toml b/naga-cli/Cargo.toml index 21255b367..e1e708ddf 100644 --- a/naga-cli/Cargo.toml +++ b/naga-cli/Cargo.toml @@ -1,12 +1,12 @@ [package] name = "naga-cli" -version = "24.0.0" -authors = ["gfx-rs developers"] -edition = "2021" +version.workspace = true +authors.workspace = true +edition.workspace = true description = "CLI for the naga shader translator and validator. Part of the wgpu project" -repository = "https://github.com/gfx-rs/wgpu/tree/trunk/naga-cli" +repository.workspace = true keywords = ["shader", "SPIR-V", "GLSL", "MSL"] -license = "MIT OR Apache-2.0" +license.workspace = true # Override the workspace's `rust-version` key. Firefox uses `cargo vendor` to # copy the crates it actually uses out of the workspace, so it's meaningful for @@ -25,7 +25,6 @@ test = false [dependencies] naga = { workspace = true, features = [ - "compact", "wgsl-in", "wgsl-out", "glsl-in", @@ -37,9 +36,12 @@ naga = { workspace = true, features = [ "dot-out", "serialize", "deserialize", + "termcolor", + "stderr", + "fs", ] } -bincode.workspace = true +bincode = { workspace = true, features = ["serde"] } codespan-reporting = { workspace = true, default-features = false, features = [ "std", "termcolor", diff --git a/naga-cli/LICENSE.APACHE b/naga-cli/LICENSE.APACHE new file mode 100644 index 000000000..d9a10c0d8 --- /dev/null +++ b/naga-cli/LICENSE.APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/naga-cli/LICENSE.MIT b/naga-cli/LICENSE.MIT new file mode 100644 index 000000000..8d02e4dbd --- /dev/null +++ b/naga-cli/LICENSE.MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 The gfx-rs developers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/naga-cli/src/bin/naga.rs b/naga-cli/src/bin/naga.rs index a39640dc3..e22e44bad 100644 --- a/naga-cli/src/bin/naga.rs +++ b/naga-cli/src/bin/naga.rs @@ -42,7 +42,15 @@ struct Args { #[argh(option)] block_ctx_dir: Option, - /// the shader entrypoint to use when compiling to GLSL + /// the shader entrypoint. + /// + /// When specified along with the `--compact` option, anything not reachable + /// from the selected entry point will not appear in the output module. + /// + /// When specified without the `--compact` option, alternate entry points + /// will not appear in the output module, and other declarations referenced + /// by alternate entrypoints may or may not appear, depending on whether + /// the module contains overrides. #[argh(option)] entry_point: Option, @@ -56,6 +64,12 @@ struct Args { #[argh(option)] shader_model: Option, + /// the SPIR-V version to use if targeting SPIR-V + /// + /// For example, 1.0, 1.4, etc + #[argh(option)] + spirv_version: Option, + /// the shader stage, for example 'frag', 'vert', or 'compute'. /// if the shader stage is unspecified it will be derived from /// the file extension. @@ -91,6 +105,9 @@ struct Args { /// /// Output files will reflect the compacted IR. If you want to see the IR as /// it was before compaction, use the `--before-compaction` option. + /// + /// Even when this option is not active, compaction may still occur as part + /// of override processing. #[argh(switch)] compact: bool, @@ -178,6 +195,22 @@ impl FromStr for ShaderModelArg { } } +#[derive(Debug, Clone)] +struct SpirvVersionArg(u8, u8); + +impl FromStr for SpirvVersionArg { + type Err = String; + + fn from_str(s: &str) -> Result { + let dot = s + .find(".") + .ok_or_else(|| "Missing dot separator".to_owned())?; + let major = s[..dot].parse::().map_err(|e| e.to_string())?; + let minor = s[dot + 1..].parse::().map_err(|e| e.to_string())?; + Ok(Self(major, minor)) + } +} + /// Newtype so we can implement [`FromStr`] for `ShaderSource`. #[derive(Debug, Clone, Copy)] struct ShaderStage(naga::ShaderStage); @@ -319,6 +352,14 @@ struct Parameters<'a> { input_kind: Option, shader_stage: Option, defines: FastHashMap, + + /// We use this copy of `args.compact` to know whether we should pass the + /// entrypoint to `process_overrides`, which will result in removal from + /// the module of anything not reachable from that entry point. + /// + /// When we don't know an entrypoint, we still compact the module as a whole + /// if `args.compact` is set, but we don't use this copy for anything. + compact: bool, } trait PrettyResult { @@ -381,7 +422,16 @@ fn run() -> anyhow::Result<()> { .init(); // Parse commandline arguments - let args: Args = argh::from_env(); + let args = { + let mut args: Args = argh::from_env(); + + if args.before_compaction.is_some() { + args.compact = true; + } + + args + }; + if args.version { println!("{}", env!("CARGO_PKG_VERSION")); return Ok(()); @@ -424,7 +474,7 @@ fn run() -> anyhow::Result<()> { params.spv_in = naga::front::spv::Options { adjust_coordinate_space: !args.keep_coordinate_space, strict_capabilities: false, - block_ctx_dump_prefix: args.block_ctx_dir.clone().map(std::path::PathBuf::from), + block_ctx_dump_prefix: args.block_ctx_dir.clone(), }; params.entry_point.clone_from(&args.entry_point); @@ -437,6 +487,9 @@ fn run() -> anyhow::Result<()> { if let Some(ref version) = args.metal_version { params.msl.lang_version = version.0; } + if let Some(ref version) = args.spirv_version { + params.spv_out.lang_version = (version.0, version.1); + } params.keep_coordinate_space = args.keep_coordinate_space; params.dot.cfg_only = args.dot_cfg_only; @@ -451,8 +504,10 @@ fn run() -> anyhow::Result<()> { !params.keep_coordinate_space, ); + params.compact = args.compact; + if args.bulk_validate { - return bulk_validate(args, ¶ms); + return bulk_validate(&args, ¶ms); } let mut files = args.files.iter(); @@ -468,6 +523,8 @@ fn run() -> anyhow::Result<()> { return Err(CliError("Input file path is not specified").into()); }; + let file_name = input_path.to_string_lossy(); + params.input_kind = args.input_kind; params.shader_stage = args.shader_stage; @@ -486,7 +543,7 @@ fn run() -> anyhow::Result<()> { .set(naga::back::spv::WriterFlags::DEBUG, true); params.spv_out.debug_info = Some(naga::back::spv::DebugInfo { source_code: input_text, - file_name: input_path, + file_name: &file_name, language, }) } else { @@ -509,7 +566,8 @@ fn run() -> anyhow::Result<()> { let missing = match Path::new(path).extension().and_then(|ex| ex.to_str()) { Some("wgsl") => C::CLIP_DISTANCE | C::CULL_DISTANCE, Some("metal") => C::CULL_DISTANCE, - _ => C::empty(), + Some("hlsl") => C::empty(), + _ => C::TEXTURE_EXTERNAL, }; caps & !missing }); @@ -534,7 +592,11 @@ fn run() -> anyhow::Result<()> { }; // Compact the module, if requested. - let info = if args.compact || args.before_compaction.is_some() { + // + // Note that when output is to a non-WGSL shader language, we will call + // `process_overrides`, which does its own compaction even if it is not + // explicitly requested on the command line. + let info = if args.compact { // Compact only if validation succeeded. Otherwise, compaction may panic. if info.is_some() { // Write out the module state before compaction, if requested. @@ -542,7 +604,7 @@ fn run() -> anyhow::Result<()> { write_output(&module, &info, ¶ms, before_compaction)?; } - naga::compact::compact(&mut module); + naga::compact::compact(&mut module, KeepUnused::No); // Re-validate the IR after compaction. match naga::valid::Validator::new(params.validation_flags, validation_caps) @@ -609,7 +671,7 @@ fn parse_input(input_path: &Path, input: Vec, params: &Parameters) -> anyhow Ok(match input_kind { InputKind::Bincode => Parsed { - module: bincode::deserialize(&input)?, + module: bincode::serde::decode_from_slice(&input, bincode::config::standard())?.0, input_text: None, language: naga::back::spv::SourceLanguage::Unknown, }, @@ -686,6 +748,16 @@ fn write_output( params: &Parameters, output_path: &str, ) -> anyhow::Result<()> { + let entry_point = params.entry_point.as_deref().map(|name| { + let ep_index = module + .entry_points + .iter() + .position(|ep| ep.name == *name) + .expect("Unable to find the entry point"); + + (module.entry_points[ep_index].stage, name) + }); + match Path::new(&output_path) .extension() .ok_or(CliError("Output filename has no extension"))? @@ -703,8 +775,8 @@ fn write_output( } } "bin" => { - let file = fs::File::create(output_path)?; - bincode::serialize_into(file, module)?; + let mut file = fs::File::create(output_path)?; + bincode::serde::encode_into_std_write(module, &mut file, bincode::config::standard())?; } "metal" => { use naga::back::msl; @@ -717,9 +789,13 @@ fn write_output( succeed, and it failed in a previous step", ))?; - let (module, info) = - naga::back::pipeline_constants::process_overrides(module, info, ¶ms.overrides) - .unwrap_pretty(); + let (module, info) = naga::back::pipeline_constants::process_overrides( + module, + info, + entry_point.filter(|_| params.compact), + ¶ms.overrides, + ) + .unwrap_pretty(); let pipeline_options = msl::PipelineOptions::default(); let (msl, _) = @@ -729,34 +805,26 @@ fn write_output( "spv" => { use naga::back::spv; - let pipeline_options_owned; - let pipeline_options = match params.entry_point { - Some(ref name) => { - let ep_index = module - .entry_points - .iter() - .position(|ep| ep.name == *name) - .expect("Unable to find the entry point"); - pipeline_options_owned = spv::PipelineOptions { - entry_point: name.clone(), - shader_stage: module.entry_points[ep_index].stage, - }; - Some(&pipeline_options_owned) - } - None => None, - }; + let pipeline_options = entry_point.map(|(shader_stage, name)| spv::PipelineOptions { + entry_point: name.to_owned(), + shader_stage, + }); let info = info.as_ref().ok_or(CliError( "Generating SPIR-V output requires validation to \ succeed, and it failed in a previous step", ))?; - let (module, info) = - naga::back::pipeline_constants::process_overrides(module, info, ¶ms.overrides) - .unwrap_pretty(); + let (module, info) = naga::back::pipeline_constants::process_overrides( + module, + info, + entry_point.filter(|_| params.compact), + ¶ms.overrides, + ) + .unwrap_pretty(); - let spv = - spv::write_vec(&module, &info, ¶ms.spv_out, pipeline_options).unwrap_pretty(); + let spv = spv::write_vec(&module, &info, ¶ms.spv_out, pipeline_options.as_ref()) + .unwrap_pretty(); let bytes = spv .iter() .fold(Vec::with_capacity(spv.len() * 4), |mut v, w| { @@ -769,17 +837,30 @@ fn write_output( stage @ ("vert" | "frag" | "comp") => { use naga::back::glsl; + let file_ext_stage = match stage { + "vert" => naga::ShaderStage::Vertex, + "frag" => naga::ShaderStage::Fragment, + "comp" => naga::ShaderStage::Compute, + _ => unreachable!(), + }; + + let (ep_stage, ep_name) = match entry_point { + Some((stage, name)) => { + if stage != file_ext_stage { + eprintln!( + "warning: the shader stage `{stage:?}` of the selected entry point \ + `{name}` in the input file does not match the shader stage \ + implied by the file name", + ); + } + (stage, name.to_string()) + } + _ => (file_ext_stage, "main".to_string()), + }; + let pipeline_options = glsl::PipelineOptions { - entry_point: match params.entry_point { - Some(ref name) => name.clone(), - None => "main".to_string(), - }, - shader_stage: match stage { - "vert" => naga::ShaderStage::Vertex, - "frag" => naga::ShaderStage::Fragment, - "comp" => naga::ShaderStage::Compute, - _ => unreachable!(), - }, + entry_point: ep_name, + shader_stage: ep_stage, multiview: None, }; @@ -788,9 +869,13 @@ fn write_output( succeed, and it failed in a previous step", ))?; - let (module, info) = - naga::back::pipeline_constants::process_overrides(module, info, ¶ms.overrides) - .unwrap_pretty(); + let (module, info) = naga::back::pipeline_constants::process_overrides( + module, + info, + entry_point.filter(|_| params.compact), + ¶ms.overrides, + ) + .unwrap_pretty(); let mut buffer = String::new(); let mut writer = glsl::Writer::new( @@ -819,12 +904,17 @@ fn write_output( succeed, and it failed in a previous step", ))?; - let (module, info) = - naga::back::pipeline_constants::process_overrides(module, info, ¶ms.overrides) - .unwrap_pretty(); + let (module, info) = naga::back::pipeline_constants::process_overrides( + module, + info, + entry_point.filter(|_| params.compact), + ¶ms.overrides, + ) + .unwrap_pretty(); let mut buffer = String::new(); - let mut writer = hlsl::Writer::new(&mut buffer, ¶ms.hlsl); + let pipeline_options = Default::default(); + let mut writer = hlsl::Writer::new(&mut buffer, ¶ms.hlsl, &pipeline_options); writer.write(&module, &info, None).unwrap_pretty(); fs::write(output_path, buffer)?; } @@ -850,9 +940,9 @@ fn write_output( Ok(()) } -fn bulk_validate(args: Args, params: &Parameters) -> anyhow::Result<()> { +fn bulk_validate(args: &Args, params: &Parameters) -> anyhow::Result<()> { let mut invalid = vec![]; - for input_path in args.files { + for input_path in &args.files { let path = Path::new(&input_path); let input = fs::read(path)?; @@ -905,4 +995,4 @@ fn bulk_validate(args: Args, params: &Parameters) -> anyhow::Result<()> { } use codespan_reporting::term::termcolor::{ColorChoice, StandardStream}; -use naga::FastHashMap; +use naga::{compact::KeepUnused, FastHashMap}; diff --git a/naga-test/Cargo.toml b/naga-test/Cargo.toml new file mode 100644 index 000000000..b750e84b9 --- /dev/null +++ b/naga-test/Cargo.toml @@ -0,0 +1,36 @@ +[package] +name = "naga-test" +version.workspace = true +authors.workspace = true +edition.workspace = true +description = "common code for naga tests" +homepage.workspace = true +repository.workspace = true +keywords.workspace = true +license.workspace = true +rust-version.workspace = true +publish = false + + +[features] + +[dependencies] +naga = { workspace = true, features = [ + "serialize", + "deserialize", + "glsl-in", + "glsl-out", + "spv-in", + "spv-out", + "wgsl-in", + "wgsl-out", + "msl-out", + "dot-out", + "hlsl-out", +] } +spirv = { workspace = true, features = ["deserialize"] } +ron.workspace = true +toml.workspace = true +bitflags.workspace = true +serde_json.workspace = true +serde.workspace = true diff --git a/naga-test/src/lib.rs b/naga-test/src/lib.rs new file mode 100644 index 000000000..078aa27c4 --- /dev/null +++ b/naga-test/src/lib.rs @@ -0,0 +1,453 @@ +// A lot of the code can be unused based on configuration flags, +// the corresponding warnings aren't helpful. +#![allow(dead_code, unused_imports)] + +use core::fmt::Write; + +use std::{ + fs, + path::{Path, PathBuf}, +}; + +use naga::compact::KeepUnused; +use ron::de; + +bitflags::bitflags! { + #[derive(Clone, Copy, serde::Deserialize)] + #[serde(transparent)] + #[derive(Debug, Eq, PartialEq)] + pub struct Targets: u32 { + /// A serialization of the `naga::Module`, in RON format. + const IR = 1; + + /// A serialization of the `naga::valid::ModuleInfo`, in RON format. + const ANALYSIS = 1 << 1; + + const SPIRV = 1 << 2; + const METAL = 1 << 3; + const GLSL = 1 << 4; + const DOT = 1 << 5; + const HLSL = 1 << 6; + const WGSL = 1 << 7; + const NO_VALIDATION = 1 << 8; + } +} + +impl Targets { + /// Defaults for `spv` and `glsl` snapshots. + pub fn non_wgsl_default() -> Self { + Targets::WGSL + } + + /// Defaults for `wgsl` snapshots. + pub fn wgsl_default() -> Self { + Targets::HLSL | Targets::SPIRV | Targets::GLSL | Targets::METAL | Targets::WGSL + } +} + +#[derive(serde::Deserialize)] +pub struct SpvOutVersion(pub u8, pub u8); +impl Default for SpvOutVersion { + fn default() -> Self { + SpvOutVersion(1, 1) + } +} + +#[derive(serde::Deserialize)] +pub struct BindingMapSerialization { + pub resource_binding: naga::ResourceBinding, + pub bind_target: naga::back::spv::BindingInfo, +} + +pub fn deserialize_binding_map<'de, D>( + deserializer: D, +) -> Result +where + D: serde::Deserializer<'de>, +{ + use serde::Deserialize; + + let vec = Vec::::deserialize(deserializer)?; + let mut map = naga::back::spv::BindingMap::default(); + for item in vec { + map.insert(item.resource_binding, item.bind_target); + } + Ok(map) +} + +#[derive(Default, serde::Deserialize)] +#[serde(default)] +pub struct WgslInParameters { + pub parse_doc_comments: bool, +} +impl From<&WgslInParameters> for naga::front::wgsl::Options { + fn from(value: &WgslInParameters) -> Self { + Self { + parse_doc_comments: value.parse_doc_comments, + } + } +} + +#[derive(Default, serde::Deserialize)] +#[serde(default)] +pub struct SpirvInParameters { + pub adjust_coordinate_space: bool, +} +impl From<&SpirvInParameters> for naga::front::spv::Options { + fn from(value: &SpirvInParameters) -> Self { + Self { + adjust_coordinate_space: value.adjust_coordinate_space, + ..Default::default() + } + } +} + +#[derive(serde::Deserialize)] +#[serde(default)] +pub struct SpirvOutParameters { + pub version: SpvOutVersion, + pub capabilities: naga::FastHashSet, + pub debug: bool, + pub adjust_coordinate_space: bool, + pub force_point_size: bool, + pub clamp_frag_depth: bool, + pub separate_entry_points: bool, + #[serde(deserialize_with = "deserialize_binding_map")] + pub binding_map: naga::back::spv::BindingMap, + pub use_storage_input_output_16: bool, +} +impl Default for SpirvOutParameters { + fn default() -> Self { + Self { + version: SpvOutVersion::default(), + capabilities: naga::FastHashSet::default(), + debug: false, + adjust_coordinate_space: false, + force_point_size: false, + clamp_frag_depth: false, + separate_entry_points: false, + use_storage_input_output_16: true, + binding_map: naga::back::spv::BindingMap::default(), + } + } +} +impl SpirvOutParameters { + pub fn to_options<'a>( + &'a self, + bounds_check_policies: naga::proc::BoundsCheckPolicies, + debug_info: Option>, + ) -> naga::back::spv::Options<'a> { + use naga::back::spv; + let mut flags = spv::WriterFlags::LABEL_VARYINGS; + flags.set(spv::WriterFlags::DEBUG, self.debug); + flags.set( + spv::WriterFlags::ADJUST_COORDINATE_SPACE, + self.adjust_coordinate_space, + ); + flags.set(spv::WriterFlags::FORCE_POINT_SIZE, self.force_point_size); + flags.set(spv::WriterFlags::CLAMP_FRAG_DEPTH, self.clamp_frag_depth); + naga::back::spv::Options { + lang_version: (self.version.0, self.version.1), + flags, + capabilities: if self.capabilities.is_empty() { + None + } else { + Some(self.capabilities.clone()) + }, + bounds_check_policies, + fake_missing_bindings: true, + binding_map: self.binding_map.clone(), + zero_initialize_workgroup_memory: spv::ZeroInitializeWorkgroupMemoryMode::Polyfill, + force_loop_bounding: true, + debug_info, + use_storage_input_output_16: self.use_storage_input_output_16, + } + } +} + +#[derive(Default, serde::Deserialize)] +#[serde(default)] +pub struct WgslOutParameters { + pub explicit_types: bool, +} +impl From<&WgslOutParameters> for naga::back::wgsl::WriterFlags { + fn from(value: &WgslOutParameters) -> Self { + let mut flags = Self::empty(); + flags.set(Self::EXPLICIT_TYPES, value.explicit_types); + flags + } +} + +#[derive(Default, serde::Deserialize)] +pub struct FragmentModule { + pub path: String, + pub entry_point: String, +} + +#[derive(Default, serde::Deserialize)] +#[serde(default)] +pub struct Parameters { + // -- GOD MODE -- + pub god_mode: bool, + + // -- wgsl-in options -- + #[serde(rename = "wgsl-in")] + pub wgsl_in: WgslInParameters, + + // -- spirv-in options -- + #[serde(rename = "spv-in")] + pub spv_in: SpirvInParameters, + + // -- SPIR-V options -- + pub spv: SpirvOutParameters, + + /// Defaults to [`Targets::non_wgsl_default()`] for `spv` and `glsl` snapshots, + /// and [`Targets::wgsl_default()`] for `wgsl` snapshots. + pub targets: Option, + + // -- MSL options -- + pub msl: naga::back::msl::Options, + #[serde(default)] + pub msl_pipeline: naga::back::msl::PipelineOptions, + + // -- GLSL options -- + pub glsl: naga::back::glsl::Options, + pub glsl_exclude_list: naga::FastHashSet, + pub glsl_multiview: Option, + + // -- HLSL options -- + pub hlsl: naga::back::hlsl::Options, + + // -- WGSL options -- + pub wgsl: WgslOutParameters, + + // -- General options -- + + // Allow backends to be aware of the fragment module. + // Is the name of a WGSL file in the same directory as the test file. + pub fragment_module: Option, + + pub bounds_check_policies: naga::proc::BoundsCheckPolicies, + pub pipeline_constants: naga::back::PipelineConstants, +} + +/// Information about a shader input file. +#[derive(Debug)] +pub struct Input { + /// The subdirectory of `tests/in` to which this input belongs, if any. + /// + /// If the subdirectory is omitted, we assume that the output goes + /// to "wgsl". + pub subdirectory: PathBuf, + + /// The input filename name, without a directory. + pub file_name: PathBuf, + + /// True if output filenames should add the output extension on top of + /// `file_name`'s existing extension, rather than replacing it. + /// + /// This is used by `convert_snapshots_glsl`, which wants to take input files + /// like `210-bevy-2d-shader.frag` and just add `.wgsl` to it, producing + /// `210-bevy-2d-shader.frag.wgsl`. + pub keep_input_extension: bool, +} + +impl Input { + /// Read an input file and its corresponding parameters file. + /// + /// Given `input`, the relative path of a shader input file, return + /// a `Source` value containing its path, code, and parameters. + /// + /// The `input` path is interpreted relative to the `BASE_DIR_IN` + /// subdirectory of the directory given by the `CARGO_MANIFEST_DIR` + /// environment variable. + pub fn new(subdirectory: &str, name: &str, extension: &str) -> Input { + Input { + subdirectory: PathBuf::from(subdirectory), + // Don't wipe out any extensions on `name`, as + // `with_extension` would do. + file_name: PathBuf::from(format!("{name}.{extension}")), + keep_input_extension: false, + } + } + + /// Return an iterator that produces an `Input` for each entry in `subdirectory`. + pub fn files_in_dir<'a>( + subdirectory: &'a str, + file_extensions: &'a [&'a str], + dir_in: &str, + ) -> impl Iterator + 'a { + let input_directory = Path::new(dir_in).join(subdirectory); + + let entries = match std::fs::read_dir(&input_directory) { + Ok(entries) => entries, + Err(err) => panic!( + "Error opening directory '{}': {}", + input_directory.display(), + err + ), + }; + + entries.filter_map(move |result| { + let entry = result.expect("error reading directory"); + if !entry.file_type().unwrap().is_file() { + return None; + } + + let file_name = PathBuf::from(entry.file_name()); + let extension = file_name + .extension() + .expect("all files in snapshot input directory should have extensions"); + + if !file_extensions.contains(&extension.to_str().unwrap()) { + return None; + } + + if let Ok(pat) = std::env::var("NAGA_SNAPSHOT") { + if !file_name.to_string_lossy().contains(&pat) { + return None; + } + } + + let input = Input::new( + subdirectory, + file_name.file_stem().unwrap().to_str().unwrap(), + extension.to_str().unwrap(), + ); + Some(input) + }) + } + + /// Return the path to the input directory. + pub fn input_directory(&self, dir_in: &str) -> PathBuf { + Path::new(dir_in).join(&self.subdirectory) + } + + /// Return the path to the output directory. + pub fn output_directory(subdirectory: &str, dir_out: &str) -> PathBuf { + Path::new(dir_out).join(subdirectory) + } + + /// Return the path to the input file. + pub fn input_path(&self, dir_in: &str) -> PathBuf { + let mut input = self.input_directory(dir_in); + input.push(&self.file_name); + input + } + + pub fn output_path(&self, subdirectory: &str, extension: &str, dir_out: &str) -> PathBuf { + let mut output = Self::output_directory(subdirectory, dir_out); + if self.keep_input_extension { + let file_name = format!( + "{}-{}.{}", + self.subdirectory.display(), + self.file_name.display(), + extension + ); + + output.push(&file_name); + } else { + let file_name = format!( + "{}-{}", + self.subdirectory.display(), + self.file_name.display() + ); + + output.push(&file_name); + output.set_extension(extension); + } + output + } + + /// Return the contents of the input file as a string. + pub fn read_source(&self, dir_in: &str, print: bool) -> String { + if print { + println!("Processing '{}'", self.file_name.display()); + } + let input_path = self.input_path(dir_in); + match fs::read_to_string(&input_path) { + Ok(source) => source, + Err(err) => { + panic!( + "Couldn't read shader input file `{}`: {}", + input_path.display(), + err + ); + } + } + } + + /// Return the contents of the input file as a vector of bytes. + pub fn read_bytes(&self, dir_in: &str, print: bool) -> Vec { + if print { + println!("Processing '{}'", self.file_name.display()); + } + let input_path = self.input_path(dir_in); + match fs::read(&input_path) { + Ok(bytes) => bytes, + Err(err) => { + panic!( + "Couldn't read shader input file `{}`: {}", + input_path.display(), + err + ); + } + } + } + + pub fn bytes(&self, dir_in: &str) -> u64 { + let input_path = self.input_path(dir_in); + std::fs::metadata(input_path).unwrap().len() + } + + /// Return this input's parameter file, parsed. + pub fn read_parameters(&self, dir_in: &str) -> Parameters { + let mut param_path = self.input_path(dir_in); + param_path.set_extension("toml"); + let mut params = match fs::read_to_string(¶m_path) { + Ok(string) => match toml::de::from_str(&string) { + Ok(params) => params, + Err(e) => panic!( + "Couldn't parse param file: {} due to: {e}", + param_path.display() + ), + }, + Err(_) => Parameters::default(), + }; + + if params.targets.is_none() { + match self + .input_path(dir_in) + .extension() + .unwrap() + .to_str() + .unwrap() + { + "wgsl" => params.targets = Some(Targets::wgsl_default()), + "spvasm" => params.targets = Some(Targets::non_wgsl_default()), + "vert" | "frag" | "comp" => params.targets = Some(Targets::non_wgsl_default()), + e => { + panic!("Unknown extension: {e}"); + } + } + } + + params + } + + /// Write `data` to a file corresponding to this input file in + /// `subdirectory`, with `extension`. + pub fn write_output_file( + &self, + subdirectory: &str, + extension: &str, + data: impl AsRef<[u8]>, + dir_out: &str, + ) { + let output_path = self.output_path(subdirectory, extension, dir_out); + fs::create_dir_all(output_path.parent().unwrap()).unwrap(); + if let Err(err) = fs::write(&output_path, data) { + panic!("Error writing {}: {}", output_path.display(), err); + } + } +} diff --git a/naga/.cargo/config.toml b/naga/.cargo/config.toml index 4b0140061..501d38532 100644 --- a/naga/.cargo/config.toml +++ b/naga/.cargo/config.toml @@ -1,2 +1,2 @@ [alias] -xtask = "run --manifest-path xtask/Cargo.toml --" +xtask = "run -p naga-xtask --" diff --git a/naga/.gitattributes b/naga/.gitattributes index 622c348d1..1f0bd06f0 100644 --- a/naga/.gitattributes +++ b/naga/.gitattributes @@ -1 +1 @@ -tests/out/**/* text eol=lf +tests/naga/out/**/* text eol=lf diff --git a/naga/Cargo.toml b/naga/Cargo.toml index 1aa53e57a..0b139f54d 100644 --- a/naga/Cargo.toml +++ b/naga/Cargo.toml @@ -1,15 +1,13 @@ [package] name = "naga" -version = "24.0.0" -authors = ["gfx-rs developers"] -edition = "2021" +version.workspace = true +authors.workspace = true +edition.workspace = true description = "Shader translator and validator. Part of the wgpu project" -repository = "https://github.com/gfx-rs/wgpu/tree/trunk/naga" +repository.workspace = true keywords = ["shader", "SPIR-V", "GLSL", "MSL"] -license = "MIT OR Apache-2.0" +license.workspace = true exclude = ["bin/**/*", "tests/**/*", "Cargo.lock", "target/**/*"] -resolver = "2" -autotests = false # Override the workspace's `rust-version` key. Firefox uses `cargo vendor` to # copy the crates it actually uses out of the workspace, so it's meaningful for @@ -17,10 +15,6 @@ autotests = false # whole, if their code permits. See `../README.md` for details. rust-version = "1.82.0" -[[test]] -name = "naga-test" -path = "tests/root.rs" - [package.metadata.docs.rs] all-features = true @@ -55,16 +49,16 @@ deserialize = [ "hashbrown/serde", "indexmap/serde", ] -arbitrary = ["dep:arbitrary", "bitflags/arbitrary", "indexmap/arbitrary"] -spv-in = ["dep:petgraph", "dep:spirv"] -spv-out = ["dep:spirv"] -wgsl-in = [ - "dep:hexf-parse", - "dep:strum", - "dep:unicode-ident", - "indexmap/std", - "compact", +arbitrary = [ + "dep:arbitrary", + "bitflags/arbitrary", + "indexmap/arbitrary", + "half/arbitrary", + "half/std", ] +spv-in = ["dep:petgraph", "petgraph/graphmap", "dep:spirv"] +spv-out = ["dep:spirv"] +wgsl-in = ["dep:hexf-parse", "dep:unicode-ident"] wgsl-out = [] ## Enables outputting to HLSL (Microsoft's High-Level Shader Language). @@ -78,53 +72,58 @@ hlsl-out = [] ## If you want to enable HLSL output it regardless of the target platform, use `naga/hlsl-out`. hlsl-out-if-target-windows = [] -compact = [] +## Enables colored output through codespan-reporting and termcolor. +termcolor = ["codespan-reporting/termcolor"] + +## Enables writing output to stderr. +stderr = ["codespan-reporting/std"] + +## Enables integration with the underlying filesystem. +fs = [] [dependencies] -arbitrary = { version = "1.4", features = ["derive"], optional = true } +arbitrary = { workspace = true, features = ["derive"], optional = true } arrayvec.workspace = true bitflags.workspace = true bit-set.workspace = true -codespan-reporting = { workspace = true, default-features = false, features = [ - "std", - "termcolor", -] } +cfg-if.workspace = true +codespan-reporting = { workspace = true } hashbrown.workspace = true -half = { workspace = true, features = ["arbitrary", "num-traits"] } +half = { workspace = true, features = ["num-traits"] } rustc-hash.workspace = true indexmap.workspace = true -log = "0.4" -# `half` requires 0.2.16 for `FromBytes` and `ToBytes`. -num-traits = "0.2.16" -strum = { workspace = true, optional = true } -spirv = { version = "0.3", optional = true } +libm = { workspace = true, default-features = false } +log.workspace = true +num-traits.workspace = true +once_cell = { workspace = true, features = ["alloc", "race"] } +spirv = { workspace = true, optional = true } thiserror.workspace = true -serde = { version = "1.0.219", features = [ - "default", - "derive", -], optional = true } -petgraph = { version = "0.7", optional = true } -pp-rs = { version = "0.2.1", optional = true } -hexf-parse = { version = "0.2.1", optional = true } -unicode-ident = { version = "1.0", optional = true } +serde = { workspace = true, features = ["alloc", "derive"], optional = true } +petgraph = { workspace = true, optional = true } +pp-rs = { workspace = true, optional = true } +hexf-parse = { workspace = true, optional = true } +unicode-ident = { workspace = true, optional = true } [build-dependencies] cfg_aliases.workspace = true [dev-dependencies] -diff = "0.1" +diff.workspace = true env_logger.workspace = true hashbrown = { workspace = true, features = ["serde"] } -# This _cannot_ have a version specified. If it does, crates.io will look -# for a version of the package on crates when we publish naga. Path dependencies -# are allowed through though. -hlsl-snapshots = { path = "./hlsl-snapshots" } +hlsl-snapshots.workspace = true itertools.workspace = true +naga-test.workspace = true ron.workspace = true -rspirv = { version = "0.11", git = "https://github.com/gfx-rs/rspirv", rev = "b969f175d5663258b4891e44b76c1544da9661ab" } +rspirv.workspace = true +# So we don't actually need this, however if we remove this, it +# brakes calling `--features spirv` at the workspace level. I think +# this is because there is a `dep:spirv` in the regular feature set, +# so cargo tries to match the feature against that, fails as it's a optional dep, +# and then refuses to build instead of ignoring it. +spirv.workspace = true serde = { workspace = true, features = ["default", "derive"] } -spirv = { version = "0.3", features = ["deserialize"] } -toml = "0.8" +strum = { workspace = true } walkdir.workspace = true [lints.clippy] diff --git a/naga/LICENSE.APACHE b/naga/LICENSE.APACHE new file mode 100644 index 000000000..d9a10c0d8 --- /dev/null +++ b/naga/LICENSE.APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/naga/LICENSE.MIT b/naga/LICENSE.MIT new file mode 100644 index 000000000..8d02e4dbd --- /dev/null +++ b/naga/LICENSE.MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 The gfx-rs developers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/naga/build.rs b/naga/build.rs index e647f1fdd..b2a6d0b8c 100644 --- a/naga/build.rs +++ b/naga/build.rs @@ -6,5 +6,7 @@ fn main() { msl_out: { any(feature = "msl-out", all(target_vendor = "apple", feature = "msl-out-if-target-apple")) }, spv_out: { feature = "spv-out" }, wgsl_out: { feature = "wgsl-out" }, + std: { any(test, feature = "wgsl-in", feature = "stderr", feature = "fs") }, + no_std: { not(std) }, } } diff --git a/naga/fuzz/Cargo.toml b/naga/fuzz/Cargo.toml index 5d8647f19..0e63bc4a2 100644 --- a/naga/fuzz/Cargo.toml +++ b/naga/fuzz/Cargo.toml @@ -1,23 +1,21 @@ [package] name = "naga-fuzz" -version = "0.0.0" -authors = ["Automatically generated"] +version.workspace = true +authors.workspace = true publish = false -edition = "2018" -license = "MIT OR Apache-2.0" +edition.workspace = true +license.workspace = true build = "build.rs" [package.metadata] cargo-fuzz = true [target.'cfg(not(any(target_arch = "wasm32", target_os = "ios")))'.dependencies] -arbitrary = { version = "1.4.1", features = ["derive"] } -# See https://github.com/rust-fuzz/libfuzzer/issues/126 -libfuzzer-sys = ">0.4.0,<=0.4.7" +arbitrary = { workspace = true, features = ["derive"] } +libfuzzer-sys.workspace = true [target.'cfg(not(any(target_arch = "wasm32", target_os = "ios", target_os = "visionos")))'.dependencies.naga] -path = ".." -version = "24.0.0" +workspace = true features = ["arbitrary", "spv-in", "wgsl-in", "glsl-in"] [build-dependencies] diff --git a/naga/hlsl-snapshots/Cargo.toml b/naga/hlsl-snapshots/Cargo.toml index 2bcc4f9ce..1e7ca2853 100644 --- a/naga/hlsl-snapshots/Cargo.toml +++ b/naga/hlsl-snapshots/Cargo.toml @@ -1,9 +1,9 @@ [package] name = "hlsl-snapshots" -version = "0.1.0" -edition = "2021" +version.workspace = true +edition.workspace = true publish = false -license = "MIT OR Apache-2.0" +license.workspace = true [lib] name = "hlsl_snapshots" @@ -11,5 +11,5 @@ path = "src/lib.rs" test = false [dependencies] -anyhow = "1" -nanoserde = "0.2.1" +anyhow.workspace = true +nanoserde.workspace = true diff --git a/naga/src/arena/handle_set.rs b/naga/src/arena/handle_set.rs index 239dc4293..62691ff6c 100644 --- a/naga/src/arena/handle_set.rs +++ b/naga/src/arena/handle_set.rs @@ -77,6 +77,11 @@ impl HandleSet { } } + /// Add all of the handles that can be included in this set. + pub fn add_all(&mut self) { + self.members.get_mut().set_all(); + } + pub fn contains(&self, handle: Handle) -> bool { self.members.contains(handle.index()) } @@ -85,6 +90,23 @@ impl HandleSet { pub fn iter(&self) -> impl '_ + Iterator> { self.members.iter().map(Handle::from_usize) } + + /// Removes and returns the numerically largest handle in the set, or `None` + /// if the set is empty. + pub fn pop(&mut self) -> Option> { + let members = core::mem::take(&mut self.members); + let mut vec = members.into_bit_vec(); + let result = vec.iter_mut().enumerate().rev().find_map(|(i, mut bit)| { + if *bit { + *bit = false; + Some(i) + } else { + None + } + }); + self.members = bit_set::BitSet::from_bit_vec(vec); + result.map(Handle::from_usize) + } } impl Default for HandleSet { diff --git a/naga/src/arena/handlevec.rs b/naga/src/arena/handlevec.rs index ba3b3c0aa..506c125b0 100644 --- a/naga/src/arena/handlevec.rs +++ b/naga/src/arena/handlevec.rs @@ -14,7 +14,7 @@ use core::ops; /// Rather than a `push` method, `HandleVec` has an [`insert`] method, analogous /// to [`HashMap::insert`], that requires you to provide the handle at which the /// new value should appear. However, since `HandleVec` only supports insertion -/// at the end, the given handle's index must be equal to the the `HandleVec`'s +/// at the end, the given handle's index must be equal to the `HandleVec`'s /// current length; otherwise, the insertion will panic. /// /// [`insert`]: HandleVec::insert diff --git a/naga/src/arena/mod.rs b/naga/src/arena/mod.rs index 4fbfe7cc6..84abf92a7 100644 --- a/naga/src/arena/mod.rs +++ b/naga/src/arena/mod.rs @@ -234,7 +234,6 @@ impl Arena { Ok(()) } - #[cfg(feature = "compact")] pub(crate) fn retain_mut

(&mut self, mut predicate: P) where P: FnMut(Handle, &mut T) -> bool, diff --git a/naga/src/arena/unique_arena.rs b/naga/src/arena/unique_arena.rs index c93fb6bb6..5b9f52976 100644 --- a/naga/src/arena/unique_arena.rs +++ b/naga/src/arena/unique_arena.rs @@ -16,7 +16,8 @@ use crate::{FastIndexSet, Span}; /// The element type must implement `Eq` and `Hash`. Insertions of equivalent /// elements, according to `Eq`, all return the same `Handle`. /// -/// Once inserted, elements may not be mutated. +/// Once inserted, elements generally may not be mutated, although a `replace` +/// method exists to support rare cases. /// /// `UniqueArena` is similar to [`Arena`]: If `Arena` is vector-like, /// `UniqueArena` is `HashSet`-like. @@ -71,8 +72,7 @@ impl UniqueArena { .unwrap_or(&Span::default()) } - #[cfg(feature = "compact")] - pub(crate) fn drain_all(&mut self) -> UniqueArenaDrain { + pub(crate) fn drain_all(&mut self) -> UniqueArenaDrain<'_, T> { UniqueArenaDrain { inner_elts: self.set.drain(..), inner_spans: self.span_info.drain(..), @@ -81,14 +81,12 @@ impl UniqueArena { } } -#[cfg(feature = "compact")] pub struct UniqueArenaDrain<'a, T> { inner_elts: indexmap::set::Drain<'a, T>, inner_spans: alloc::vec::Drain<'a, Span>, index: Index, } -#[cfg(feature = "compact")] impl Iterator for UniqueArenaDrain<'_, T> { type Item = (Handle, T, Span); diff --git a/naga/src/back/dot/mod.rs b/naga/src/back/dot/mod.rs index dd8246f90..1f1396ecc 100644 --- a/naga/src/back/dot/mod.rs +++ b/naga/src/back/dot/mod.rs @@ -112,7 +112,8 @@ impl StatementGraph { } "Continue" } - S::Barrier(_flags) => "Barrier", + S::ControlBarrier(_flags) => "ControlBarrier", + S::MemoryBarrier(_flags) => "MemoryBarrier", S::Block(ref b) => { let (other, last) = self.add(b, targets); self.flow.push((id, other, "")); @@ -306,6 +307,25 @@ impl StatementGraph { crate::RayQueryFunction::Terminate => "RayQueryTerminate", } } + S::MeshFunction(crate::MeshFunction::SetMeshOutputs { + vertex_count, + primitive_count, + }) => { + self.dependencies.push((id, vertex_count, "vertex_count")); + self.dependencies + .push((id, primitive_count, "primitive_count")); + "SetMeshOutputs" + } + S::MeshFunction(crate::MeshFunction::SetVertex { index, value }) => { + self.dependencies.push((id, index, "index")); + self.dependencies.push((id, value, "value")); + "SetVertex" + } + S::MeshFunction(crate::MeshFunction::SetPrimitive { index, value }) => { + self.dependencies.push((id, index, "index")); + self.dependencies.push((id, value, "value")); + "SetPrimitive" + } S::SubgroupBallot { result, predicate } => { if let Some(predicate) = predicate { self.dependencies.push((id, predicate, "predicate")); @@ -379,9 +399,11 @@ impl StatementGraph { | crate::GatherMode::Shuffle(index) | crate::GatherMode::ShuffleDown(index) | crate::GatherMode::ShuffleUp(index) - | crate::GatherMode::ShuffleXor(index) => { + | crate::GatherMode::ShuffleXor(index) + | crate::GatherMode::QuadBroadcast(index) => { self.dependencies.push((id, index, "index")) } + crate::GatherMode::QuadSwap(_) => {} } self.dependencies.push((id, argument, "arg")); self.emits.push((id, result)); @@ -392,6 +414,12 @@ impl StatementGraph { crate::GatherMode::ShuffleDown(_) => "SubgroupShuffleDown", crate::GatherMode::ShuffleUp(_) => "SubgroupShuffleUp", crate::GatherMode::ShuffleXor(_) => "SubgroupShuffleXor", + crate::GatherMode::QuadBroadcast(_) => "SubgroupQuadBroadcast", + crate::GatherMode::QuadSwap(direction) => match direction { + crate::Direction::X => "SubgroupQuadSwapX", + crate::Direction::Y => "SubgroupQuadSwapY", + crate::Direction::Diagonal => "SubgroupQuadSwapDiagonal", + }, } } }; @@ -591,6 +619,7 @@ fn write_function_expressions( offset: _, level, depth_ref, + clamp_to_edge: _, } => { edges.insert("image", image); edges.insert("sampler", sampler); @@ -730,7 +759,7 @@ fn write_function_expressions( E::RayQueryVertexPositions { query, committed } => { edges.insert("", query); let ty = if committed { "Committed" } else { "Candidate" }; - (format!("get{}HitVertexPositions", ty).into(), 4) + (format!("get{ty}HitVertexPositions").into(), 4) } }; diff --git a/naga/src/back/glsl/features.rs b/naga/src/back/glsl/features.rs index 0a083e859..2d8870b79 100644 --- a/naga/src/back/glsl/features.rs +++ b/naga/src/back/glsl/features.rs @@ -55,6 +55,8 @@ bitflags::bitflags! { const SUBGROUP_OPERATIONS = 1 << 24; /// Image atomics const TEXTURE_ATOMICS = 1 << 25; + /// Image atomics + const SHADER_BARYCENTRICS = 1 << 26; } } @@ -280,6 +282,7 @@ impl FeaturesManager { out, "#extension GL_KHR_shader_subgroup_shuffle_relative : require" )?; + writeln!(out, "#extension GL_KHR_shader_subgroup_quad : require")?; } if self.0.contains(Features::TEXTURE_ATOMICS) { @@ -287,6 +290,14 @@ impl FeaturesManager { writeln!(out, "#extension GL_OES_shader_image_atomic : require")?; } + if self.0.contains(Features::SHADER_BARYCENTRICS) { + // https://github.com/KhronosGroup/GLSL/blob/main/extensions/ext/GLSL_EXT_fragment_shader_barycentric.txt + writeln!( + out, + "#extension GL_EXT_fragment_shader_barycentric : require" + )?; + } + Ok(()) } } @@ -300,14 +311,16 @@ impl Writer<'_, W> { pub(super) fn collect_required_features(&mut self) -> BackendResult { let ep_info = self.info.get_entry_point(self.entry_point_idx as usize); - if let Some(depth_test) = self.entry_point.early_depth_test { - // If IMAGE_LOAD_STORE is supported for this version of GLSL - if self.options.version.supports_early_depth_test() { - self.features.request(Features::IMAGE_LOAD_STORE); - } - - if depth_test.conservative.is_some() { - self.features.request(Features::CONSERVATIVE_DEPTH); + if let Some(early_depth_test) = self.entry_point.early_depth_test { + match early_depth_test { + crate::EarlyDepthTest::Force => { + if self.options.version.supports_early_depth_test() { + self.features.request(Features::IMAGE_LOAD_STORE); + } + } + crate::EarlyDepthTest::Allow { .. } => { + self.features.request(Features::CONSERVATIVE_DEPTH); + } } } @@ -418,7 +431,8 @@ impl Writer<'_, W> { _ => {} }, ImageClass::Sampled { multi: false, .. } - | ImageClass::Depth { multi: false } => {} + | ImageClass::Depth { multi: false } + | ImageClass::External => {} } } _ => {} @@ -599,6 +613,9 @@ impl Writer<'_, W> { crate::BuiltIn::InstanceIndex | crate::BuiltIn::DrawID => { self.features.request(Features::INSTANCE_INDEX) } + crate::BuiltIn::Barycentric => { + self.features.request(Features::SHADER_BARYCENTRICS) + } _ => {} }, Binding::Location { @@ -606,6 +623,7 @@ impl Writer<'_, W> { interpolation, sampling, blend_src, + per_primitive: _, } => { if interpolation == Some(Interpolation::Linear) { self.features.request(Features::NOPERSPECTIVE_QUALIFIER); diff --git a/naga/src/back/glsl/keywords.rs b/naga/src/back/glsl/keywords.rs index b8f620dae..aeaec5b03 100644 --- a/naga/src/back/glsl/keywords.rs +++ b/naga/src/back/glsl/keywords.rs @@ -1,6 +1,5 @@ -use std::sync::LazyLock; - -use hashbrown::HashSet; +use crate::proc::KeywordSet; +use crate::racy_lock::RacyLock; pub const RESERVED_KEYWORDS: &[&str] = &[ // @@ -499,11 +498,5 @@ pub const RESERVED_KEYWORDS: &[&str] = &[ /// significant time during [`Namer::reset`](crate::proc::Namer::reset). /// /// See for benchmarks. -pub static RESERVED_KEYWORD_SET: LazyLock> = LazyLock::new(|| { - let mut set = HashSet::default(); - set.reserve(RESERVED_KEYWORDS.len()); - for &word in RESERVED_KEYWORDS { - set.insert(word); - } - set -}); +pub static RESERVED_KEYWORD_SET: RacyLock = + RacyLock::new(|| KeywordSet::from_iter(RESERVED_KEYWORDS)); diff --git a/naga/src/back/glsl/mod.rs b/naga/src/back/glsl/mod.rs index 256fceb5e..521e2dcad 100644 --- a/naga/src/back/glsl/mod.rs +++ b/naga/src/back/glsl/mod.rs @@ -64,7 +64,7 @@ use thiserror::Error; use crate::{ back::{self, Baked}, common, - proc::{self, ExpressionKindTracker, NameKey}, + proc::{self, NameKey}, valid, Handle, ShaderStage, TypeInner, }; use features::FeaturesManager; @@ -139,7 +139,8 @@ impl crate::AddressSpace { | crate::AddressSpace::Uniform | crate::AddressSpace::Storage { .. } | crate::AddressSpace::Handle - | crate::AddressSpace::PushConstant => false, + | crate::AddressSpace::PushConstant + | crate::AddressSpace::TaskPayload => false, } } } @@ -211,6 +212,10 @@ impl Version { *self >= Version::Desktop(130) || *self >= Version::new_gles(310) } + fn supports_std140_layout(&self) -> bool { + *self >= Version::Desktop(140) || *self >= Version::new_gles(300) + } + fn supports_std430_layout(&self) -> bool { *self >= Version::Desktop(430) || *self >= Version::new_gles(310) } @@ -345,7 +350,8 @@ pub struct PipelineOptions { pub shader_stage: ShaderStage, /// The name of the entry point. /// - /// If no entry point that matches is found while creating a [`Writer`], a error will be thrown. + /// If no entry point that matches is found while creating a [`Writer`], an + /// error will be thrown. pub entry_point: String, /// How many views to render to, if doing multiview rendering. pub multiview: Option, @@ -372,6 +378,8 @@ pub struct ReflectionInfo { pub varying: crate::FastHashMap, /// List of push constant items in the shader. pub push_constant_items: Vec, + /// Number of user-defined clip planes. Only applicable to vertex shaders. + pub clip_distance_count: u32, } /// Mapping between a texture and its sampler, if it exists. @@ -470,7 +478,7 @@ impl VaryingOptions { /// Helper wrapper used to get a name for a varying /// /// Varying have different naming schemes depending on their binding: -/// - Varyings with builtin bindings get the from [`glsl_built_in`]. +/// - Varyings with builtin bindings get their name from [`glsl_built_in`]. /// - Varyings with location bindings are named `_S_location_X` where `S` is a /// prefix identifying which pipeline stage the varying connects, and `X` is /// the location. @@ -616,6 +624,8 @@ pub struct Writer<'a, W> { multiview: Option, /// Mapping of varying variables to their location. Needed for reflections. varying: crate::FastHashMap, + /// Number of user-defined clip planes. Only non-zero for vertex shaders. + clip_distance_count: u32, } impl<'a, W: Write> Writer<'a, W> { @@ -654,7 +664,7 @@ impl<'a, W: Write> Writer<'a, W> { namer.reset( module, &keywords::RESERVED_KEYWORD_SET, - &[], + proc::CaseInsensitiveKeywordSet::empty(), &[ "gl_", // all GL built-in variables "_group", // all normal bindings @@ -683,6 +693,7 @@ impl<'a, W: Write> Writer<'a, W> { need_bake_expressions: Default::default(), continue_ctx: back::continue_forward::ContinueCtx::default(), varying: Default::default(), + clip_distance_count: 0, }; // Find all features required to print this module @@ -745,22 +756,23 @@ impl<'a, W: Write> Writer<'a, W> { } // Enable early depth tests if needed - if let Some(depth_test) = self.entry_point.early_depth_test { + if let Some(early_depth_test) = self.entry_point.early_depth_test { // If early depth test is supported for this version of GLSL if self.options.version.supports_early_depth_test() { - writeln!(self.out, "layout(early_fragment_tests) in;")?; - - if let Some(conservative) = depth_test.conservative { - use crate::ConservativeDepth as Cd; - - let depth = match conservative { - Cd::GreaterEqual => "greater", - Cd::LessEqual => "less", - Cd::Unchanged => "unchanged", - }; - writeln!(self.out, "layout (depth_{depth}) out float gl_FragDepth;")?; + match early_depth_test { + crate::EarlyDepthTest::Force => { + writeln!(self.out, "layout(early_fragment_tests) in;")?; + } + crate::EarlyDepthTest::Allow { conservative, .. } => { + use crate::ConservativeDepth as Cd; + let depth = match conservative { + Cd::GreaterEqual => "greater", + Cd::LessEqual => "less", + Cd::Unchanged => "unchanged", + }; + writeln!(self.out, "layout (depth_{depth}) out float gl_FragDepth;")?; + } } - writeln!(self.out)?; } else { log::warn!( "Early depth testing is not supported for this version of GLSL: {}", @@ -782,6 +794,8 @@ impl<'a, W: Write> Writer<'a, W> { // you can't make a struct without adding all of its members first. for (handle, ty) in self.module.types.iter() { if let TypeInner::Struct { ref members, .. } = ty.inner { + let struct_name = &self.names[&NameKey::Type(handle)]; + // Structures ending with runtime-sized arrays can only be // rendered as shader storage blocks in GLSL, not stand-alone // struct types. @@ -789,19 +803,19 @@ impl<'a, W: Write> Writer<'a, W> { .inner .is_dynamically_sized(&self.module.types) { - let name = &self.names[&NameKey::Type(handle)]; - write!(self.out, "struct {name} ")?; + write!(self.out, "struct {struct_name} ")?; self.write_struct_body(handle, members)?; writeln!(self.out, ";")?; } } } - // Write functions to create special types. + // Write functions for special types. for (type_key, struct_ty) in self.module.special_types.predeclared_types.iter() { match type_key { &crate::PredeclaredType::ModfResult { size, scalar } | &crate::PredeclaredType::FrexpResult { size, scalar } => { + let struct_name = &self.names[&NameKey::Type(*struct_ty)]; let arg_type_name_owner; let arg_type_name = if let Some(size) = size { arg_type_name_owner = format!( @@ -830,8 +844,6 @@ impl<'a, W: Write> Writer<'a, W> { (FREXP_FUNCTION, "frexp", other_type_name) }; - let struct_name = &self.names[&NameKey::Type(*struct_ty)]; - writeln!(self.out)?; if !self.options.version.supports_frexp_function() && matches!(type_key, &crate::PredeclaredType::FrexpResult { .. }) @@ -855,7 +867,9 @@ impl<'a, W: Write> Writer<'a, W> { )?; } } - &crate::PredeclaredType::AtomicCompareExchangeWeakResult { .. } => {} + &crate::PredeclaredType::AtomicCompareExchangeWeakResult(_) => { + // Handled by the general struct writing loop earlier. + } } } @@ -1163,6 +1177,7 @@ impl<'a, W: Write> Writer<'a, W> { Ic::Depth { multi: true } => ("sampler", float, "MS", ""), Ic::Depth { multi: false } => ("sampler", float, "", "Shadow"), Ic::Storage { format, .. } => ("image", format.into(), "", ""), + Ic::External => unimplemented!(), }; let precision = if self.options.version.is_es() { @@ -1186,6 +1201,68 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } + /// Helper method used by [Self::write_global] to write just the layout part of + /// a non image/sampler global variable, if applicable. + /// + /// # Notes + /// + /// Adds trailing whitespace if any layout qualifier is written + fn write_global_layout(&mut self, global: &crate::GlobalVariable) -> BackendResult { + // Determine which (if any) explicit memory layout to use, and whether we support it + let layout = match global.space { + crate::AddressSpace::Uniform => { + if !self.options.version.supports_std140_layout() { + return Err(Error::Custom( + "Uniform address space requires std140 layout support".to_string(), + )); + } + + Some("std140") + } + crate::AddressSpace::Storage { .. } => { + if !self.options.version.supports_std430_layout() { + return Err(Error::Custom( + "Storage address space requires std430 layout support".to_string(), + )); + } + + Some("std430") + } + _ => None, + }; + + // If our version supports explicit layouts, we can also output the explicit binding + // if we have it + if self.options.version.supports_explicit_locations() { + if let Some(ref br) = global.binding { + match self.options.binding_map.get(br) { + Some(binding) => { + write!(self.out, "layout(")?; + + if let Some(layout) = layout { + write!(self.out, "{layout}, ")?; + } + + write!(self.out, "binding = {binding}) ")?; + + return Ok(()); + } + None => { + log::debug!("unassigned binding for {:?}", global.name); + } + } + } + } + + // Either no explicit bindings are supported or we didn't have any. + // Write just the memory layout. + if let Some(layout) = layout { + write!(self.out, "layout({layout}) ")?; + } + + Ok(()) + } + /// Helper method used to write non images/sampler globals /// /// # Notes @@ -1198,34 +1275,7 @@ impl<'a, W: Write> Writer<'a, W> { handle: Handle, global: &crate::GlobalVariable, ) -> BackendResult { - if self.options.version.supports_explicit_locations() { - if let Some(ref br) = global.binding { - match self.options.binding_map.get(br) { - Some(binding) => { - let layout = match global.space { - crate::AddressSpace::Storage { .. } => { - if self.options.version.supports_std430_layout() { - "std430, " - } else { - "std140, " - } - } - crate::AddressSpace::Uniform => "std140, ", - _ => "", - }; - write!(self.out, "layout({layout}binding = {binding}) ")? - } - None => { - log::debug!("unassigned binding for {:?}", global.name); - if let crate::AddressSpace::Storage { .. } = global.space { - if self.options.version.supports_std430_layout() { - write!(self.out, "layout(std430) ")? - } - } - } - } - } - } + self.write_global_layout(global)?; if let crate::AddressSpace::Storage { access } = global.space { self.write_storage_access(access)?; @@ -1251,6 +1301,9 @@ impl<'a, W: Write> Writer<'a, W> { crate::AddressSpace::Storage { .. } => { self.write_interface_block(handle, global)?; } + crate::AddressSpace::TaskPayload => { + self.write_interface_block(handle, global)?; + } // A global variable in the `Function` address space is a // contradiction in terms. crate::AddressSpace::Function => unreachable!(), @@ -1386,8 +1439,14 @@ impl<'a, W: Write> Writer<'a, W> { self.need_bake_expressions.insert(arg1.unwrap()); } } + crate::MathFunction::Dot4U8Packed | crate::MathFunction::Dot4I8Packed => { + self.need_bake_expressions.insert(arg); + self.need_bake_expressions.insert(arg1.unwrap()); + } crate::MathFunction::Pack4xI8 | crate::MathFunction::Pack4xU8 + | crate::MathFunction::Pack4xI8Clamp + | crate::MathFunction::Pack4xU8Clamp | crate::MathFunction::Unpack4xI8 | crate::MathFunction::Unpack4xU8 | crate::MathFunction::QuantizeToF16 => { @@ -1435,6 +1494,18 @@ impl<'a, W: Write> Writer<'a, W> { } } } + + for statement in func.body.iter() { + match *statement { + crate::Statement::Atomic { + fun: crate::AtomicFunction::Exchange { compare: Some(cmp) }, + .. + } => { + self.need_bake_expressions.insert(cmp); + } + _ => {} + } + } } /// Helper method used to get a name for a global @@ -1547,33 +1618,50 @@ impl<'a, W: Write> Writer<'a, W> { interpolation, sampling, blend_src, + per_primitive: _, } => (location, interpolation, sampling, blend_src), crate::Binding::BuiltIn(built_in) => { - if let crate::BuiltIn::Position { invariant: true } = built_in { - match (self.options.version, self.entry_point.stage) { - ( - Version::Embedded { - version: 300, - is_webgl: true, - }, - ShaderStage::Fragment, - ) => { - // `invariant gl_FragCoord` is not allowed in WebGL2 and possibly - // OpenGL ES in general (waiting on confirmation). - // - // See https://github.com/KhronosGroup/WebGL/issues/3518 - } - _ => { - writeln!( - self.out, - "invariant {};", - glsl_built_in( - built_in, - VaryingOptions::from_writer_options(self.options, output) - ) - )?; + match built_in { + crate::BuiltIn::Position { invariant: true } => { + match (self.options.version, self.entry_point.stage) { + ( + Version::Embedded { + version: 300, + is_webgl: true, + }, + ShaderStage::Fragment, + ) => { + // `invariant gl_FragCoord` is not allowed in WebGL2 and possibly + // OpenGL ES in general (waiting on confirmation). + // + // See https://github.com/KhronosGroup/WebGL/issues/3518 + } + _ => { + writeln!( + self.out, + "invariant {};", + glsl_built_in( + built_in, + VaryingOptions::from_writer_options(self.options, output) + ) + )?; + } } } + crate::BuiltIn::ClipDistance => { + // Re-declare `gl_ClipDistance` with number of clip planes. + let TypeInner::Array { size, .. } = self.module.types[ty].inner else { + unreachable!(); + }; + let proc::IndexableLength::Known(size) = + size.resolve(self.module.to_ctx())? + else { + unreachable!(); + }; + self.clip_distance_count = size; + writeln!(self.out, "out float gl_ClipDistance[{size}];")?; + } + _ => {} } return Ok(()); } @@ -1649,6 +1737,7 @@ impl<'a, W: Write> Writer<'a, W> { interpolation: None, sampling: None, blend_src, + per_primitive: false, }, stage: self.entry_point.stage, options: VaryingOptions::from_writer_options(self.options, output), @@ -1678,7 +1767,6 @@ impl<'a, W: Write> Writer<'a, W> { info, expressions: &func.expressions, named_expressions: &func.named_expressions, - expr_kind_tracker: ExpressionKindTracker::from_arena(&func.expressions), }; self.named_expressions.clear(); @@ -1791,7 +1879,7 @@ impl<'a, W: Write> Writer<'a, W> { writeln!(self.out, ") {{")?; if self.options.zero_initialize_workgroup_memory - && ctx.ty.is_compute_entry_point(self.module) + && ctx.ty.is_compute_like_entry_point(self.module) { self.write_workgroup_variables_initialization(&ctx)?; } @@ -1908,7 +1996,7 @@ impl<'a, W: Write> Writer<'a, W> { } writeln!(self.out, "{level}}}")?; - self.write_barrier(crate::Barrier::WORK_GROUP, level)?; + self.write_control_barrier(crate::Barrier::WORK_GROUP, level)?; } Ok(()) @@ -2452,8 +2540,11 @@ impl<'a, W: Write> Writer<'a, W> { // keyword which ceases all further processing in a fragment shader, it's called OpKill // in spir-v that's why it's called `Statement::Kill` Statement::Kill => writeln!(self.out, "{level}discard;")?, - Statement::Barrier(flags) => { - self.write_barrier(flags, level)?; + Statement::ControlBarrier(flags) => { + self.write_control_barrier(flags, level)?; + } + Statement::MemoryBarrier(flags) => { + self.write_memory_barrier(flags, level)?; } // Stores in glsl are just variable assignments written as `pointer = value;` Statement::Store { pointer, value } => { @@ -2467,14 +2558,14 @@ impl<'a, W: Write> Writer<'a, W> { // GLSL doesn't have pointers, which means that this backend needs to ensure that // the actual "loading" is happening between the two barriers. // This is done in `Emit` by never emitting a variable name for pointer variables - self.write_barrier(crate::Barrier::WORK_GROUP, level)?; + self.write_control_barrier(crate::Barrier::WORK_GROUP, level)?; let result_name = Baked(result).to_string(); write!(self.out, "{level}")?; // Expressions cannot have side effects, so just writing the expression here is fine. self.write_named_expr(pointer, result_name, result, ctx)?; - self.write_barrier(crate::Barrier::WORK_GROUP, level)?; + self.write_control_barrier(crate::Barrier::WORK_GROUP, level)?; } // Stores a value into an image. Statement::ImageStore { @@ -2527,33 +2618,50 @@ impl<'a, W: Write> Writer<'a, W> { result, } => { write!(self.out, "{level}")?; - if let Some(result) = result { - let res_name = Baked(result).to_string(); - let res_ty = ctx.resolve_type(result, &self.module.types); - self.write_value_type(res_ty)?; - write!(self.out, " {res_name} = ")?; - self.named_expressions.insert(result, res_name); - } - let fun_str = fun.to_glsl(); - write!(self.out, "atomic{fun_str}(")?; - self.write_expr(pointer, ctx)?; - write!(self.out, ", ")?; - // handle the special cases match *fun { - crate::AtomicFunction::Subtract => { - // we just wrote `InterlockedAdd`, so negate the argument - write!(self.out, "-")?; + crate::AtomicFunction::Exchange { + compare: Some(compare_expr), + } => { + let result_handle = result.expect("CompareExchange must have a result"); + let res_name = Baked(result_handle).to_string(); + self.write_type(ctx.info[result_handle].ty.handle().unwrap())?; + write!(self.out, " {res_name};")?; + write!(self.out, " {res_name}.old_value = atomicCompSwap(")?; + self.write_expr(pointer, ctx)?; + write!(self.out, ", ")?; + self.write_expr(compare_expr, ctx)?; + write!(self.out, ", ")?; + self.write_expr(value, ctx)?; + writeln!(self.out, ");")?; + + write!( + self.out, + "{level}{res_name}.exchanged = ({res_name}.old_value == " + )?; + self.write_expr(compare_expr, ctx)?; + writeln!(self.out, ");")?; + self.named_expressions.insert(result_handle, res_name); } - crate::AtomicFunction::Exchange { compare: Some(_) } => { - return Err(Error::Custom( - "atomic CompareExchange is not implemented".to_string(), - )); + _ => { + if let Some(result) = result { + let res_name = Baked(result).to_string(); + self.write_type(ctx.info[result].ty.handle().unwrap())?; + write!(self.out, " {res_name} = ")?; + self.named_expressions.insert(result, res_name); + } + let fun_str = fun.to_glsl(); + write!(self.out, "atomic{fun_str}(")?; + self.write_expr(pointer, ctx)?; + write!(self.out, ", ")?; + if let crate::AtomicFunction::Subtract = *fun { + // Emulate `atomicSub` with `atomicAdd` by negating the value. + write!(self.out, "-")?; + } + self.write_expr(value, ctx)?; + writeln!(self.out, ");")?; } - _ => {} } - self.write_expr(value, ctx)?; - writeln!(self.out, ");")?; } // Stores a value into an image. Statement::ImageAtomic { @@ -2567,6 +2675,11 @@ impl<'a, W: Write> Writer<'a, W> { self.write_image_atomic(ctx, image, coordinate, array_index, fun, value)? } Statement::RayQuery { .. } => unreachable!(), + Statement::MeshFunction( + crate::MeshFunction::SetMeshOutputs { .. } + | crate::MeshFunction::SetVertex { .. } + | crate::MeshFunction::SetPrimitive { .. }, + ) => unreachable!(), Statement::SubgroupBallot { result, predicate } => { write!(self.out, "{level}")?; let res_name = Baked(result).to_string(); @@ -2671,6 +2784,20 @@ impl<'a, W: Write> Writer<'a, W> { crate::GatherMode::ShuffleXor(_) => { write!(self.out, "subgroupShuffleXor(")?; } + crate::GatherMode::QuadBroadcast(_) => { + write!(self.out, "subgroupQuadBroadcast(")?; + } + crate::GatherMode::QuadSwap(direction) => match direction { + crate::Direction::X => { + write!(self.out, "subgroupQuadSwapHorizontal(")?; + } + crate::Direction::Y => { + write!(self.out, "subgroupQuadSwapVertical(")?; + } + crate::Direction::Diagonal => { + write!(self.out, "subgroupQuadSwapDiagonal(")?; + } + }, } self.write_expr(argument, ctx)?; match mode { @@ -2679,10 +2806,12 @@ impl<'a, W: Write> Writer<'a, W> { | crate::GatherMode::Shuffle(index) | crate::GatherMode::ShuffleDown(index) | crate::GatherMode::ShuffleUp(index) - | crate::GatherMode::ShuffleXor(index) => { + | crate::GatherMode::ShuffleXor(index) + | crate::GatherMode::QuadBroadcast(index) => { write!(self.out, ", ")?; self.write_expr(index, ctx)?; } + crate::GatherMode::QuadSwap(_) => {} } writeln!(self.out, ");")?; } @@ -2939,6 +3068,7 @@ impl<'a, W: Write> Writer<'a, W> { offset, level, depth_ref, + clamp_to_edge: _, } => { let (dim, class, arrayed) = match *ctx.resolve_type(image, &self.module.types) { TypeInner::Image { @@ -2997,6 +3127,9 @@ impl<'a, W: Write> Writer<'a, W> { // The space here isn't required but it helps with readability write!(self.out, ", ")?; + // TODO: handle clamp_to_edge + // https://github.com/gfx-rs/wgpu/issues/7791 + // We need to get the coordinates vector size to later build a vector that's `size + 1` // if `depth_ref` is some, if it isn't a vector we panic as that's not a valid expression let mut coord_dim = match *ctx.resolve_type(coordinate, &self.module.types) { @@ -3181,6 +3314,7 @@ impl<'a, W: Write> Writer<'a, W> { write!(self.out, "imageSize(")?; self.write_expr(image, ctx)?; } + ImageClass::External => unimplemented!(), } write!(self.out, ")")?; if components != 1 || self.options.version.is_es() { @@ -3196,6 +3330,7 @@ impl<'a, W: Write> Writer<'a, W> { let fun_name = match class { ImageClass::Sampled { .. } | ImageClass::Depth { .. } => "textureSize", ImageClass::Storage { .. } => "imageSize", + ImageClass::External => unimplemented!(), }; write!(self.out, "{fun_name}(")?; self.write_expr(image, ctx)?; @@ -3215,6 +3350,7 @@ impl<'a, W: Write> Writer<'a, W> { "textureSamples" } ImageClass::Storage { .. } => "imageSamples", + ImageClass::External => unimplemented!(), }; write!(self.out, "{fun_name}(")?; self.write_expr(image, ctx)?; @@ -3559,6 +3695,40 @@ impl<'a, W: Write> Writer<'a, W> { "Correct TypeInner for dot product should be already validated" ), }, + fun @ (Mf::Dot4I8Packed | Mf::Dot4U8Packed) => { + let conversion = match fun { + Mf::Dot4I8Packed => "int", + Mf::Dot4U8Packed => "", + _ => unreachable!(), + }; + + let arg1 = arg1.unwrap(); + + // Write parentheses around the dot product expression to prevent operators + // with different precedences from applying earlier. + write!(self.out, "(")?; + for i in 0..4 { + // Since `bitfieldExtract` only sign extends if the value is signed, we + // need to convert the inputs to `int` in case of `Dot4I8Packed`. For + // `Dot4U8Packed`, the code below only introduces parenthesis around + // each factor, which aren't strictly needed because both operands are + // baked, but which don't hurt either. + write!(self.out, "bitfieldExtract({conversion}(")?; + self.write_expr(arg, ctx)?; + write!(self.out, "), {}, 8)", i * 8)?; + + write!(self.out, " * bitfieldExtract({conversion}(")?; + self.write_expr(arg1, ctx)?; + write!(self.out, "), {}, 8)", i * 8)?; + + if i != 3 { + write!(self.out, " + ")?; + } + } + write!(self.out, ")")?; + + return Ok(()); + } Mf::Outer => "outerProduct", Mf::Cross => "cross", Mf::Distance => "distance", @@ -3842,24 +4012,35 @@ impl<'a, W: Write> Writer<'a, W> { } } - fun @ (Mf::Pack4xI8 | Mf::Pack4xU8) => { - let was_signed = match fun { - Mf::Pack4xI8 => true, - Mf::Pack4xU8 => false, - _ => unreachable!(), + fun @ (Mf::Pack4xI8 | Mf::Pack4xU8 | Mf::Pack4xI8Clamp | Mf::Pack4xU8Clamp) => { + let was_signed = matches!(fun, Mf::Pack4xI8 | Mf::Pack4xI8Clamp); + let clamp_bounds = match fun { + Mf::Pack4xI8Clamp => Some(("-128", "127")), + Mf::Pack4xU8Clamp => Some(("0", "255")), + _ => None, }; let const_suffix = if was_signed { "" } else { "u" }; if was_signed { write!(self.out, "uint(")?; } + let write_arg = |this: &mut Self| -> BackendResult { + if let Some((min, max)) = clamp_bounds { + write!(this.out, "clamp(")?; + this.write_expr(arg, ctx)?; + write!(this.out, ", {min}{const_suffix}, {max}{const_suffix})")?; + } else { + this.write_expr(arg, ctx)?; + } + Ok(()) + }; write!(self.out, "(")?; - self.write_expr(arg, ctx)?; + write_arg(self)?; write!(self.out, "[0] & 0xFF{const_suffix}) | ((")?; - self.write_expr(arg, ctx)?; + write_arg(self)?; write!(self.out, "[1] & 0xFF{const_suffix}) << 8) | ((")?; - self.write_expr(arg, ctx)?; + write_arg(self)?; write!(self.out, "[2] & 0xFF{const_suffix}) << 16) | ((")?; - self.write_expr(arg, ctx)?; + write_arg(self)?; write!(self.out, "[3] & 0xFF{const_suffix}) << 24)")?; if was_signed { write!(self.out, ")")?; @@ -4452,6 +4633,7 @@ impl<'a, W: Write> Writer<'a, W> { "WGSL `textureLoad` from depth textures is not supported in GLSL".to_string(), )) } + crate::ImageClass::External => unimplemented!(), }; // openGL es doesn't have 1D images so we need workaround it @@ -4774,9 +4956,19 @@ impl<'a, W: Write> Writer<'a, W> { Ok(()) } - /// Issue a memory barrier. Please note that to ensure visibility, - /// OpenGL always requires a call to the `barrier()` function after a `memoryBarrier*()` - fn write_barrier(&mut self, flags: crate::Barrier, level: back::Level) -> BackendResult { + /// Issue a control barrier. + fn write_control_barrier( + &mut self, + flags: crate::Barrier, + level: back::Level, + ) -> BackendResult { + self.write_memory_barrier(flags, level)?; + writeln!(self.out, "{level}barrier();")?; + Ok(()) + } + + /// Issue a memory barrier. + fn write_memory_barrier(&mut self, flags: crate::Barrier, level: back::Level) -> BackendResult { if flags.contains(crate::Barrier::STORAGE) { writeln!(self.out, "{level}memoryBarrierBuffer();")?; } @@ -4789,7 +4981,6 @@ impl<'a, W: Write> Writer<'a, W> { if flags.contains(crate::Barrier::TEXTURE) { writeln!(self.out, "{level}memoryBarrierImage();")?; } - writeln!(self.out, "{level}barrier();")?; Ok(()) } @@ -4899,6 +5090,7 @@ impl<'a, W: Write> Writer<'a, W> { uniforms, varying: mem::take(&mut self.varying), push_constant_items, + clip_distance_count: self.clip_distance_count, }) } @@ -5023,8 +5215,13 @@ const fn glsl_built_in(built_in: crate::BuiltIn, options: VaryingOptions) -> &'s "gl_FragCoord" } } - Bi::ViewIndex if options.targeting_webgl => "int(gl_ViewID_OVR)", - Bi::ViewIndex => "gl_ViewIndex", + Bi::ViewIndex => { + if options.targeting_webgl { + "gl_ViewID_OVR" + } else { + "uint(gl_ViewIndex)" + } + } // vertex Bi::BaseInstance => "uint(gl_BaseInstance)", Bi::BaseVertex => "uint(gl_BaseVertex)", @@ -5046,6 +5243,7 @@ const fn glsl_built_in(built_in: crate::BuiltIn, options: VaryingOptions) -> &'s Bi::PointCoord => "gl_PointCoord", Bi::FrontFacing => "gl_FrontFacing", Bi::PrimitiveIndex => "uint(gl_PrimitiveID)", + Bi::Barycentric => "gl_BaryCoordEXT", Bi::SampleIndex => "gl_SampleID", Bi::SampleMask => { if options.output { @@ -5066,6 +5264,15 @@ const fn glsl_built_in(built_in: crate::BuiltIn, options: VaryingOptions) -> &'s Bi::SubgroupId => "gl_SubgroupID", Bi::SubgroupSize => "gl_SubgroupSize", Bi::SubgroupInvocationId => "gl_SubgroupInvocationID", + // mesh + // TODO: figure out how to map these to glsl things as glsl treats them as arrays + Bi::CullPrimitive + | Bi::PointIndex + | Bi::LineIndices + | Bi::TriangleIndices + | Bi::MeshTaskSize => { + unimplemented!() + } } } @@ -5081,6 +5288,7 @@ const fn glsl_storage_qualifier(space: crate::AddressSpace) -> Option<&'static s As::Handle => Some("uniform"), As::WorkGroup => Some("shared"), As::PushConstant => Some("uniform"), + As::TaskPayload => unreachable!(), } } diff --git a/naga/src/back/hlsl/conv.rs b/naga/src/back/hlsl/conv.rs index 3b8fb8fb3..b4d7af86e 100644 --- a/naga/src/back/hlsl/conv.rs +++ b/naga/src/back/hlsl/conv.rs @@ -161,6 +161,7 @@ impl crate::BuiltIn { Self::FragDepth => "SV_Depth", Self::FrontFacing => "SV_IsFrontFace", Self::PrimitiveIndex => "SV_PrimitiveID", + Self::Barycentric => "SV_Barycentrics", Self::SampleIndex => "SV_SampleIndex", Self::SampleMask => "SV_Coverage", // compute @@ -172,6 +173,7 @@ impl crate::BuiltIn { // to this field will get replaced with references to `SPECIAL_CBUF_VAR` // in `Writer::write_expr`. Self::NumWorkGroups => "SV_GroupID", + Self::ViewIndex => "SV_ViewID", // These builtins map to functions Self::SubgroupSize | Self::SubgroupInvocationId @@ -180,9 +182,12 @@ impl crate::BuiltIn { Self::BaseInstance | Self::BaseVertex | Self::WorkGroupSize => { return Err(Error::Unimplemented(format!("builtin {self:?}"))) } - Self::PointSize | Self::ViewIndex | Self::PointCoord | Self::DrawID => { + Self::PointSize | Self::PointCoord | Self::DrawID => { return Err(Error::Custom(format!("Unsupported builtin {self:?}"))) } + Self::CullPrimitive => "SV_CullPrimitive", + Self::PointIndex | Self::LineIndices | Self::TriangleIndices => unimplemented!(), + Self::MeshTaskSize => unreachable!(), }) } } @@ -222,7 +227,7 @@ impl crate::AtomicFunction { Self::Min => "Min", Self::Max => "Max", Self::Exchange { compare: None } => "Exchange", - Self::Exchange { .. } => "", //TODO + Self::Exchange { .. } => "CompareExchange", } } } diff --git a/naga/src/back/hlsl/help.rs b/naga/src/back/hlsl/help.rs index 058d39692..8083d15e8 100644 --- a/naga/src/back/hlsl/help.rs +++ b/naga/src/back/hlsl/help.rs @@ -33,7 +33,8 @@ use super::{ super::FunctionCtx, writer::{ ABS_FUNCTION, DIV_FUNCTION, EXTRACT_BITS_FUNCTION, F2I32_FUNCTION, F2I64_FUNCTION, - F2U32_FUNCTION, F2U64_FUNCTION, INSERT_BITS_FUNCTION, MOD_FUNCTION, NEG_FUNCTION, + F2U32_FUNCTION, F2U64_FUNCTION, IMAGE_LOAD_EXTERNAL_FUNCTION, + IMAGE_SAMPLE_BASE_CLAMP_TO_EDGE_FUNCTION, INSERT_BITS_FUNCTION, MOD_FUNCTION, NEG_FUNCTION, }, BackendResult, WrappedType, }; @@ -44,6 +45,17 @@ pub(super) struct WrappedArrayLength { pub(super) writable: bool, } +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] +pub(super) struct WrappedImageLoad { + pub(super) class: crate::ImageClass, +} + +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] +pub(super) struct WrappedImageSample { + pub(super) class: crate::ImageClass, + pub(super) clamp_to_edge: bool, +} + #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] pub(super) struct WrappedImageQuery { pub(super) dim: crate::ImageDimension, @@ -189,6 +201,11 @@ impl super::Writer<'_, W> { let storage_format_str = format.to_hlsl_str(); write!(self.out, "<{storage_format_str}>")? } + crate::ImageClass::External => { + unreachable!( + "external images should be handled by `write_global_external_texture`" + ); + } } Ok(()) } @@ -247,6 +264,302 @@ impl super::Writer<'_, W> { Ok(()) } + /// Helper function used by [`Self::write_wrapped_image_load_function`] and + /// [`Self::write_wrapped_image_sample_function`] to write the shared YUV + /// to RGB conversion code for external textures. Expects the preceding + /// code to declare the Y component as a `float` variable of name `y`, the + /// UV components as a `float2` variable of name `uv`, and the external + /// texture params as a variable of name `params`. The emitted code will + /// return the result. + fn write_convert_yuv_to_rgb_and_return( + &mut self, + level: crate::back::Level, + y: &str, + uv: &str, + params: &str, + ) -> BackendResult { + let l1 = level; + let l2 = l1.next(); + + // Convert from YUV to non-linear RGB in the source color space. We + // declare our matrices as row_major in HLSL, therefore we must reverse + // the order of this multiplication + writeln!( + self.out, + "{l1}float3 srcGammaRgb = mul(float4({y}, {uv}, 1.0), {params}.yuv_conversion_matrix).rgb;" + )?; + + // Apply the inverse of the source transfer function to convert to + // linear RGB in the source color space. + writeln!( + self.out, + "{l1}float3 srcLinearRgb = srcGammaRgb < {params}.src_tf.k * {params}.src_tf.b ?" + )?; + writeln!(self.out, "{l2}srcGammaRgb / {params}.src_tf.k :")?; + writeln!(self.out, "{l2}pow((srcGammaRgb + {params}.src_tf.a - 1.0) / {params}.src_tf.a, {params}.src_tf.g);")?; + + // Multiply by the gamut conversion matrix to convert to linear RGB in + // the destination color space. We declare our matrices as row_major in + // HLSL, therefore we must reverse the order of this multiplication. + writeln!( + self.out, + "{l1}float3 dstLinearRgb = mul(srcLinearRgb, {params}.gamut_conversion_matrix);" + )?; + + // Finally, apply the dest transfer function to convert to non-linear + // RGB in the destination color space, and return the result. + writeln!( + self.out, + "{l1}float3 dstGammaRgb = dstLinearRgb < {params}.dst_tf.b ?" + )?; + writeln!(self.out, "{l2}{params}.dst_tf.k * dstLinearRgb :")?; + writeln!(self.out, "{l2}{params}.dst_tf.a * pow(dstLinearRgb, 1.0 / {params}.dst_tf.g) - ({params}.dst_tf.a - 1);")?; + + writeln!(self.out, "{l1}return float4(dstGammaRgb, 1.0);")?; + Ok(()) + } + + pub(super) fn write_wrapped_image_load_function( + &mut self, + module: &crate::Module, + load: WrappedImageLoad, + ) -> BackendResult { + match load { + WrappedImageLoad { + class: crate::ImageClass::External, + } => { + let l1 = crate::back::Level(1); + let l2 = l1.next(); + let l3 = l2.next(); + let params_ty_name = &self.names + [&NameKey::Type(module.special_types.external_texture_params.unwrap())]; + writeln!(self.out, "float4 {IMAGE_LOAD_EXTERNAL_FUNCTION}(")?; + writeln!(self.out, "{l1}Texture2D plane0,")?; + writeln!(self.out, "{l1}Texture2D plane1,")?; + writeln!(self.out, "{l1}Texture2D plane2,")?; + writeln!(self.out, "{l1}{params_ty_name} params,")?; + writeln!(self.out, "{l1}uint2 coords)")?; + writeln!(self.out, "{{")?; + writeln!(self.out, "{l1}uint2 plane0_size;")?; + writeln!( + self.out, + "{l1}plane0.GetDimensions(plane0_size.x, plane0_size.y);" + )?; + // Clamp coords to provided size of external texture to prevent OOB read. + // If params.size is zero then clamp to the actual size of the texture. + writeln!( + self.out, + "{l1}uint2 cropped_size = any(params.size) ? params.size : plane0_size;" + )?; + writeln!(self.out, "{l1}coords = min(coords, cropped_size - 1);")?; + + // Apply load transformation. We declare our matrices as row_major in + // HLSL, therefore we must reverse the order of this multiplication + writeln!(self.out, "{l1}float3x2 load_transform = float3x2(")?; + writeln!(self.out, "{l2}params.load_transform_0,")?; + writeln!(self.out, "{l2}params.load_transform_1,")?; + writeln!(self.out, "{l2}params.load_transform_2")?; + writeln!(self.out, "{l1});")?; + writeln!(self.out, "{l1}uint2 plane0_coords = uint2(round(mul(float3(coords, 1.0), load_transform)));")?; + writeln!(self.out, "{l1}if (params.num_planes == 1u) {{")?; + // For single plane, simply read from plane0 + writeln!( + self.out, + "{l2}return plane0.Load(uint3(plane0_coords, 0u));" + )?; + writeln!(self.out, "{l1}}} else {{")?; + + // Chroma planes may be subsampled so we must scale the coords accordingly. + writeln!(self.out, "{l2}uint2 plane1_size;")?; + writeln!( + self.out, + "{l2}plane1.GetDimensions(plane1_size.x, plane1_size.y);" + )?; + writeln!(self.out, "{l2}uint2 plane1_coords = uint2(floor(float2(plane0_coords) * float2(plane1_size) / float2(plane0_size)));")?; + + // For multi-plane, read the Y value from plane 0 + writeln!( + self.out, + "{l2}float y = plane0.Load(uint3(plane0_coords, 0u)).x;" + )?; + + writeln!(self.out, "{l2}float2 uv;")?; + writeln!(self.out, "{l2}if (params.num_planes == 2u) {{")?; + // Read UV from interleaved plane 1 + writeln!( + self.out, + "{l3}uv = plane1.Load(uint3(plane1_coords, 0u)).xy;" + )?; + writeln!(self.out, "{l2}}} else {{")?; + // Read U and V from planes 1 and 2 respectively + writeln!(self.out, "{l3}uint2 plane2_size;")?; + writeln!( + self.out, + "{l3}plane2.GetDimensions(plane2_size.x, plane2_size.y);" + )?; + writeln!(self.out, "{l3}uint2 plane2_coords = uint2(floor(float2(plane0_coords) * float2(plane2_size) / float2(plane0_size)));")?; + writeln!(self.out, "{l3}uv = float2(plane1.Load(uint3(plane1_coords, 0u)).x, plane2.Load(uint3(plane2_coords, 0u)).x);")?; + writeln!(self.out, "{l2}}}")?; + + self.write_convert_yuv_to_rgb_and_return(l2, "y", "uv", "params")?; + + writeln!(self.out, "{l1}}}")?; + writeln!(self.out, "}}")?; + writeln!(self.out)?; + } + _ => {} + } + + Ok(()) + } + + pub(super) fn write_wrapped_image_sample_function( + &mut self, + module: &crate::Module, + sample: WrappedImageSample, + ) -> BackendResult { + match sample { + WrappedImageSample { + class: crate::ImageClass::External, + clamp_to_edge: true, + } => { + let l1 = crate::back::Level(1); + let l2 = l1.next(); + let l3 = l2.next(); + let params_ty_name = &self.names + [&NameKey::Type(module.special_types.external_texture_params.unwrap())]; + writeln!( + self.out, + "float4 {IMAGE_SAMPLE_BASE_CLAMP_TO_EDGE_FUNCTION}(" + )?; + writeln!(self.out, "{l1}Texture2D plane0,")?; + writeln!(self.out, "{l1}Texture2D plane1,")?; + writeln!(self.out, "{l1}Texture2D plane2,")?; + writeln!(self.out, "{l1}{params_ty_name} params,")?; + writeln!(self.out, "{l1}SamplerState samp,")?; + writeln!(self.out, "{l1}float2 coords)")?; + writeln!(self.out, "{{")?; + writeln!(self.out, "{l1}float2 plane0_size;")?; + writeln!( + self.out, + "{l1}plane0.GetDimensions(plane0_size.x, plane0_size.y);" + )?; + writeln!(self.out, "{l1}float3x2 sample_transform = float3x2(")?; + writeln!(self.out, "{l2}params.sample_transform_0,")?; + writeln!(self.out, "{l2}params.sample_transform_1,")?; + writeln!(self.out, "{l2}params.sample_transform_2")?; + writeln!(self.out, "{l1});")?; + // Apply sample transformation. We declare our matrices as row_major in + // HLSL, therefore we must reverse the order of this multiplication + writeln!( + self.out, + "{l1}coords = mul(float3(coords, 1.0), sample_transform);" + )?; + // Calculate the sample bounds. The purported size of the texture + // (params.size) is irrelevant here as we are dealing with normalized + // coordinates. Usually we would clamp to (0,0)..(1,1). However, we must + // apply the sample transformation to that, also bearing in mind that it + // may contain a flip on either axis. We calculate and adjust for the + // half-texel separately for each plane as it depends on the actual + // texture size which may vary between planes. + writeln!( + self.out, + "{l1}float2 bounds_min = mul(float3(0.0, 0.0, 1.0), sample_transform);" + )?; + writeln!( + self.out, + "{l1}float2 bounds_max = mul(float3(1.0, 1.0, 1.0), sample_transform);" + )?; + writeln!(self.out, "{l1}float4 bounds = float4(min(bounds_min, bounds_max), max(bounds_min, bounds_max));")?; + writeln!( + self.out, + "{l1}float2 plane0_half_texel = float2(0.5, 0.5) / plane0_size;" + )?; + writeln!( + self.out, + "{l1}float2 plane0_coords = clamp(coords, bounds.xy + plane0_half_texel, bounds.zw - plane0_half_texel);" + )?; + writeln!(self.out, "{l1}if (params.num_planes == 1u) {{")?; + // For single plane, simply sample from plane0 + writeln!( + self.out, + "{l2}return plane0.SampleLevel(samp, plane0_coords, 0.0f);" + )?; + writeln!(self.out, "{l1}}} else {{")?; + + writeln!(self.out, "{l2}float2 plane1_size;")?; + writeln!( + self.out, + "{l2}plane1.GetDimensions(plane1_size.x, plane1_size.y);" + )?; + writeln!( + self.out, + "{l2}float2 plane1_half_texel = float2(0.5, 0.5) / plane1_size;" + )?; + writeln!( + self.out, + "{l2}float2 plane1_coords = clamp(coords, bounds.xy + plane1_half_texel, bounds.zw - plane1_half_texel);" + )?; + + // For multi-plane, sample the Y value from plane 0 + writeln!( + self.out, + "{l2}float y = plane0.SampleLevel(samp, plane0_coords, 0.0f).x;" + )?; + writeln!(self.out, "{l2}float2 uv;")?; + writeln!(self.out, "{l2}if (params.num_planes == 2u) {{")?; + // Sample UV from interleaved plane 1 + writeln!( + self.out, + "{l3}uv = plane1.SampleLevel(samp, plane1_coords, 0.0f).xy;" + )?; + writeln!(self.out, "{l2}}} else {{")?; + // Sample U and V from planes 1 and 2 respectively + writeln!(self.out, "{l3}float2 plane2_size;")?; + writeln!( + self.out, + "{l3}plane2.GetDimensions(plane2_size.x, plane2_size.y);" + )?; + writeln!( + self.out, + "{l3}float2 plane2_half_texel = float2(0.5, 0.5) / plane2_size;" + )?; + writeln!(self.out, "{l3}float2 plane2_coords = clamp(coords, bounds.xy + plane2_half_texel, bounds.zw - plane2_half_texel);")?; + writeln!(self.out, "{l3}uv = float2(plane1.SampleLevel(samp, plane1_coords, 0.0f).x, plane2.SampleLevel(samp, plane2_coords, 0.0f).x);")?; + writeln!(self.out, "{l2}}}")?; + + self.write_convert_yuv_to_rgb_and_return(l2, "y", "uv", "params")?; + + writeln!(self.out, "{l1}}}")?; + writeln!(self.out, "}}")?; + writeln!(self.out)?; + } + WrappedImageSample { + class: + crate::ImageClass::Sampled { + kind: ScalarKind::Float, + multi: false, + }, + clamp_to_edge: true, + } => { + writeln!(self.out, "float4 {IMAGE_SAMPLE_BASE_CLAMP_TO_EDGE_FUNCTION}(Texture2D tex, SamplerState samp, float2 coords) {{")?; + let l1 = crate::back::Level(1); + writeln!(self.out, "{l1}float2 size;")?; + writeln!(self.out, "{l1}tex.GetDimensions(size.x, size.y);")?; + writeln!(self.out, "{l1}float2 half_texel = float2(0.5, 0.5) / size;")?; + writeln!( + self.out, + "{l1}return tex.SampleLevel(samp, clamp(coords, half_texel, 1.0 - half_texel), 0.0);" + )?; + writeln!(self.out, "}}")?; + writeln!(self.out)?; + } + _ => {} + } + + Ok(()) + } + pub(super) fn write_wrapped_image_query_function_name( &mut self, query: WrappedImageQuery, @@ -258,6 +571,7 @@ impl super::Writer<'_, W> { crate::ImageClass::Depth { multi: false } => "Depth", crate::ImageClass::Sampled { multi: false, .. } => "", crate::ImageClass::Storage { .. } => "RW", + crate::ImageClass::External => "External", }; let arrayed_str = if query.arrayed { "Array" } else { "" }; let query_str = match query.query { @@ -288,101 +602,133 @@ impl super::Writer<'_, W> { ImageDimension as IDim, }; - const ARGUMENT_VARIABLE_NAME: &str = "tex"; - const RETURN_VARIABLE_NAME: &str = "ret"; - const MIP_LEVEL_PARAM: &str = "mip_level"; + match wiq.class { + crate::ImageClass::External => { + if wiq.query != ImageQuery::Size { + return Err(super::Error::Custom( + "External images only support `Size` queries".into(), + )); + } - // Write function return type and name - let ret_ty = func_ctx.resolve_type(expr_handle, &module.types); - self.write_value_type(module, ret_ty)?; - write!(self.out, " ")?; - self.write_wrapped_image_query_function_name(wiq)?; + write!(self.out, "uint2 ")?; + self.write_wrapped_image_query_function_name(wiq)?; + let params_name = &self.names + [&NameKey::Type(module.special_types.external_texture_params.unwrap())]; + // Only plane0 and params are used by this implementation, but it's easier to + // always take all of them as arguments so that we can unconditionally expand an + // external texture expression each of its parts. + writeln!(self.out, "(Texture2D plane0, Texture2D plane1, Texture2D plane2, {params_name} params) {{")?; + let l1 = crate::back::Level(1); + let l2 = l1.next(); + writeln!(self.out, "{l1}if (any(params.size)) {{")?; + writeln!(self.out, "{l2}return params.size;")?; + writeln!(self.out, "{l1}}} else {{")?; + // params.size == (0, 0) indicates to query and return plane 0's actual size + writeln!(self.out, "{l2}uint2 ret;")?; + writeln!(self.out, "{l2}plane0.GetDimensions(ret.x, ret.y);")?; + writeln!(self.out, "{l2}return ret;")?; + writeln!(self.out, "{l1}}}")?; + writeln!(self.out, "}}")?; + writeln!(self.out)?; + } + _ => { + const ARGUMENT_VARIABLE_NAME: &str = "tex"; + const RETURN_VARIABLE_NAME: &str = "ret"; + const MIP_LEVEL_PARAM: &str = "mip_level"; - // Write function parameters - write!(self.out, "(")?; - // Texture always first parameter - self.write_image_type(wiq.dim, wiq.arrayed, wiq.class)?; - write!(self.out, " {ARGUMENT_VARIABLE_NAME}")?; - // Mipmap is a second parameter if exists - if let ImageQuery::SizeLevel = wiq.query { - write!(self.out, ", uint {MIP_LEVEL_PARAM}")?; - } - writeln!(self.out, ")")?; + // Write function return type and name + let ret_ty = func_ctx.resolve_type(expr_handle, &module.types); + self.write_value_type(module, ret_ty)?; + write!(self.out, " ")?; + self.write_wrapped_image_query_function_name(wiq)?; - // Write function body - writeln!(self.out, "{{")?; + // Write function parameters + write!(self.out, "(")?; + // Texture always first parameter + self.write_image_type(wiq.dim, wiq.arrayed, wiq.class)?; + write!(self.out, " {ARGUMENT_VARIABLE_NAME}")?; + // Mipmap is a second parameter if exists + if let ImageQuery::SizeLevel = wiq.query { + write!(self.out, ", uint {MIP_LEVEL_PARAM}")?; + } + writeln!(self.out, ")")?; - let array_coords = usize::from(wiq.arrayed); - // extra parameter is the mip level count or the sample count - let extra_coords = match wiq.class { - crate::ImageClass::Storage { .. } => 0, - crate::ImageClass::Sampled { .. } | crate::ImageClass::Depth { .. } => 1, - }; + // Write function body + writeln!(self.out, "{{")?; - // GetDimensions Overloaded Methods - // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions#overloaded-methods - let (ret_swizzle, number_of_params) = match wiq.query { - ImageQuery::Size | ImageQuery::SizeLevel => { - let ret = match wiq.dim { - IDim::D1 => "x", - IDim::D2 => "xy", - IDim::D3 => "xyz", - IDim::Cube => "xy", + let array_coords = usize::from(wiq.arrayed); + // extra parameter is the mip level count or the sample count + let extra_coords = match wiq.class { + crate::ImageClass::Storage { .. } => 0, + crate::ImageClass::Sampled { .. } | crate::ImageClass::Depth { .. } => 1, + crate::ImageClass::External => unreachable!(), }; - (ret, ret.len() + array_coords + extra_coords) - } - ImageQuery::NumLevels | ImageQuery::NumSamples | ImageQuery::NumLayers => { - if wiq.arrayed || wiq.dim == IDim::D3 { - ("w", 4) - } else { - ("z", 3) + + // GetDimensions Overloaded Methods + // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions#overloaded-methods + let (ret_swizzle, number_of_params) = match wiq.query { + ImageQuery::Size | ImageQuery::SizeLevel => { + let ret = match wiq.dim { + IDim::D1 => "x", + IDim::D2 => "xy", + IDim::D3 => "xyz", + IDim::Cube => "xy", + }; + (ret, ret.len() + array_coords + extra_coords) + } + ImageQuery::NumLevels | ImageQuery::NumSamples | ImageQuery::NumLayers => { + if wiq.arrayed || wiq.dim == IDim::D3 { + ("w", 4) + } else { + ("z", 3) + } + } + }; + + // Write `GetDimensions` function. + writeln!(self.out, "{INDENT}uint4 {RETURN_VARIABLE_NAME};")?; + write!(self.out, "{INDENT}{ARGUMENT_VARIABLE_NAME}.GetDimensions(")?; + match wiq.query { + ImageQuery::SizeLevel => { + write!(self.out, "{MIP_LEVEL_PARAM}, ")?; + } + _ => match wiq.class { + crate::ImageClass::Sampled { multi: true, .. } + | crate::ImageClass::Depth { multi: true } + | crate::ImageClass::Storage { .. } => {} + _ => { + // Write zero mipmap level for supported types + write!(self.out, "0, ")?; + } + }, } - } - }; - // Write `GetDimensions` function. - writeln!(self.out, "{INDENT}uint4 {RETURN_VARIABLE_NAME};")?; - write!(self.out, "{INDENT}{ARGUMENT_VARIABLE_NAME}.GetDimensions(")?; - match wiq.query { - ImageQuery::SizeLevel => { - write!(self.out, "{MIP_LEVEL_PARAM}, ")?; - } - _ => match wiq.class { - crate::ImageClass::Sampled { multi: true, .. } - | crate::ImageClass::Depth { multi: true } - | crate::ImageClass::Storage { .. } => {} - _ => { - // Write zero mipmap level for supported types - write!(self.out, "0, ")?; + for component in COMPONENTS[..number_of_params - 1].iter() { + write!(self.out, "{RETURN_VARIABLE_NAME}.{component}, ")?; } - }, + + // write last parameter without comma and space for last parameter + write!( + self.out, + "{}.{}", + RETURN_VARIABLE_NAME, + COMPONENTS[number_of_params - 1] + )?; + + writeln!(self.out, ");")?; + + // Write return value + writeln!( + self.out, + "{INDENT}return {RETURN_VARIABLE_NAME}.{ret_swizzle};" + )?; + + // End of function body + writeln!(self.out, "}}")?; + // Write extra new line + writeln!(self.out)?; + } } - - for component in COMPONENTS[..number_of_params - 1].iter() { - write!(self.out, "{RETURN_VARIABLE_NAME}.{component}, ")?; - } - - // write last parameter without comma and space for last parameter - write!( - self.out, - "{}.{}", - RETURN_VARIABLE_NAME, - COMPONENTS[number_of_params - 1] - )?; - - writeln!(self.out, ");")?; - - // Write return value - writeln!( - self.out, - "{INDENT}return {RETURN_VARIABLE_NAME}.{ret_swizzle};" - )?; - - // End of function body - writeln!(self.out, "}}")?; - // Write extra new line - writeln!(self.out)?; - Ok(()) } @@ -1283,8 +1629,16 @@ impl super::Writer<'_, W> { let level = crate::back::Level(1); match scalar.kind { ScalarKind::Sint => { - let min = -1i64 << (scalar.width as u32 * 8 - 1); - writeln!(self.out, "{level}return lhs / (((lhs == {min} & rhs == -1) | (rhs == 0)) ? 1 : rhs);")? + let min_val = match scalar.width { + 4 => crate::Literal::I32(i32::MIN), + 8 => crate::Literal::I64(i64::MIN), + _ => { + return Err(super::Error::UnsupportedScalar(scalar)); + } + }; + write!(self.out, "{level}return lhs / (((lhs == ")?; + self.write_literal(min_val)?; + writeln!(self.out, " & rhs == -1) | (rhs == 0)) ? 1 : rhs);")? } ScalarKind::Uint => { writeln!(self.out, "{level}return lhs / (rhs == 0u ? 1u : rhs);")? @@ -1310,7 +1664,7 @@ impl super::Writer<'_, W> { crate::BinaryOperator::Modulo, Some( scalar @ crate::Scalar { - kind: ScalarKind::Sint | ScalarKind::Uint, + kind: ScalarKind::Sint | ScalarKind::Uint | ScalarKind::Float, .. }, ), @@ -1339,10 +1693,18 @@ impl super::Writer<'_, W> { let level = crate::back::Level(1); match scalar.kind { ScalarKind::Sint => { - let min = -1i64 << (scalar.width as u32 * 8 - 1); + let min_val = match scalar.width { + 4 => crate::Literal::I32(i32::MIN), + 8 => crate::Literal::I64(i64::MIN), + _ => { + return Err(super::Error::UnsupportedScalar(scalar)); + } + }; write!(self.out, "{level}")?; self.write_value_type(module, right_ty)?; - writeln!(self.out, " divisor = ((lhs == {min} & rhs == -1) | (rhs == 0)) ? 1 : rhs;")?; + write!(self.out, " divisor = ((lhs == ")?; + self.write_literal(min_val)?; + writeln!(self.out, " & rhs == -1) | (rhs == 0)) ? 1 : rhs;")?; writeln!( self.out, "{level}return lhs - (lhs / divisor) * divisor;" @@ -1351,6 +1713,14 @@ impl super::Writer<'_, W> { ScalarKind::Uint => { writeln!(self.out, "{level}return lhs % (rhs == 0u ? 1u : rhs);")? } + // HLSL's fmod has the same definition as WGSL's % operator but due + // to its implementation in DXC it is not as accurate as the WGSL spec + // requires it to be. See: + // - https://shader-playground.timjones.io/0c8572816dbb6fc4435cc5d016a978a7 + // - https://github.com/llvm/llvm-project/blob/50f9b8acafdca48e87e6b8e393c1f116a2d193ee/clang/lib/Headers/hlsl/hlsl_intrinsic_helpers.h#L78-L81 + ScalarKind::Float => { + writeln!(self.out, "{level}return lhs - rhs * trunc(lhs / rhs);")? + } _ => unreachable!(), } writeln!(self.out, "}}")?; @@ -1498,6 +1868,33 @@ impl super::Writer<'_, W> { self.write_wrapped_array_length_function(wal)?; } } + crate::Expression::ImageLoad { image, .. } => { + let class = match *func_ctx.resolve_type(image, &module.types) { + crate::TypeInner::Image { class, .. } => class, + _ => unreachable!(), + }; + let wrapped = WrappedImageLoad { class }; + if self.wrapped.insert(WrappedType::ImageLoad(wrapped)) { + self.write_wrapped_image_load_function(module, wrapped)?; + } + } + crate::Expression::ImageSample { + image, + clamp_to_edge, + .. + } => { + let class = match *func_ctx.resolve_type(image, &module.types) { + crate::TypeInner::Image { class, .. } => class, + _ => unreachable!(), + }; + let wrapped = WrappedImageSample { + class, + clamp_to_edge, + }; + if self.wrapped.insert(WrappedType::ImageSample(wrapped)) { + self.write_wrapped_image_sample_function(module, wrapped)?; + } + } crate::Expression::ImageQuery { image, query } => { let wiq = match *func_ctx.resolve_type(image, &module.types) { crate::TypeInner::Image { diff --git a/naga/src/back/hlsl/keywords.rs b/naga/src/back/hlsl/keywords.rs index d3b9ad8cf..13f48cef8 100644 --- a/naga/src/back/hlsl/keywords.rs +++ b/naga/src/back/hlsl/keywords.rs @@ -1,6 +1,5 @@ -use std::sync::LazyLock; - -use hashbrown::HashSet; +use crate::proc::{CaseInsensitiveKeywordSet, KeywordSet}; +use crate::racy_lock::RacyLock; // When compiling with FXC without strict mode, these keywords are actually case insensitive. // If you compile with strict mode and specify a different casing like "Pass" instead in an identifier, FXC will give this error: @@ -826,6 +825,7 @@ pub const RESERVED: &[&str] = &[ super::writer::INSERT_BITS_FUNCTION, super::writer::SAMPLER_HEAP_VAR, super::writer::COMPARISON_SAMPLER_HEAP_VAR, + super::writer::SAMPLE_EXTERNAL_TEXTURE_FUNCTION, super::writer::ABS_FUNCTION, super::writer::DIV_FUNCTION, super::writer::MOD_FUNCTION, @@ -834,6 +834,8 @@ pub const RESERVED: &[&str] = &[ super::writer::F2U32_FUNCTION, super::writer::F2I64_FUNCTION, super::writer::F2U64_FUNCTION, + super::writer::IMAGE_LOAD_EXTERNAL_FUNCTION, + super::writer::IMAGE_SAMPLE_BASE_CLAMP_TO_EDGE_FUNCTION, ]; // DXC scalar types, from https://github.com/microsoft/DirectXShaderCompiler/blob/18c9e114f9c314f93e68fbc72ce207d4ed2e65ae/tools/clang/lib/AST/ASTContextHLSL.cpp#L48-L254 @@ -924,17 +926,11 @@ pub const TYPES: &[&str] = &{ /// significant time during [`Namer::reset`](crate::proc::Namer::reset). /// /// See for benchmarks. -pub static RESERVED_SET: LazyLock> = LazyLock::new(|| { - let mut set = HashSet::default(); - set.reserve(RESERVED.len() + TYPES.len()); - for &word in RESERVED { - set.insert(word); - } - for &word in TYPES { - set.insert(word); - } - set -}); +pub static RESERVED_SET: RacyLock = + RacyLock::new(|| KeywordSet::from_iter(RESERVED.iter().chain(TYPES))); + +pub static RESERVED_CASE_INSENSITIVE_SET: RacyLock = + RacyLock::new(|| CaseInsensitiveKeywordSet::from_iter(RESERVED_CASE_INSENSITIVE)); pub const RESERVED_PREFIXES: &[&str] = &[ "__dynamic_buffer_offsets", diff --git a/naga/src/back/hlsl/mod.rs b/naga/src/back/hlsl/mod.rs index 9e041ff73..7fca96709 100644 --- a/naga/src/back/hlsl/mod.rs +++ b/naga/src/back/hlsl/mod.rs @@ -13,11 +13,17 @@ type should be stored in `uniform` and `storage` buffers. The HLSL we generate must access values in that form, even when it is not what HLSL would use normally. -The rules described here only apply to WGSL `uniform` variables. WGSL -`storage` buffers are translated as HLSL `ByteAddressBuffers`, for -which we generate `Load` and `Store` method calls with explicit byte -offsets. WGSL pipeline inputs must be scalars or vectors; they cannot -be matrices, which is where the interesting problems arise. +Matching the WGSL memory layout is a concern only for `uniform` +variables. WGSL `storage` buffers are translated as HLSL +`ByteAddressBuffers`, for which we generate `Load` and `Store` method +calls with explicit byte offsets. WGSL pipeline inputs must be scalars +or vectors; they cannot be matrices, which is where the interesting +problems arise. However, when an affected type appears in a struct +definition, the transformations described here are applied without +consideration of where the struct is used. + +Access to storage buffers is implemented in `storage.rs`. Access to +uniform buffers is implemented where applicable in `writer.rs`. ## Row- and column-major ordering for matrices @@ -57,10 +63,9 @@ that the columns of a `matKx2` need only be [aligned as required for `vec2`][ilov], which is [eight-byte alignment][8bb]. To compensate for this, any time a `matKx2` appears in a WGSL -`uniform` variable, whether directly as the variable's type or as part -of a struct/array, we actually emit `K` separate `float2` members, and -assemble/disassemble the matrix from its columns (in WGSL; rows in -HLSL) upon load and store. +`uniform` value or as part of a struct/array, we actually emit `K` +separate `float2` members, and assemble/disassemble the matrix from its +columns (in WGSL; rows in HLSL) upon load and store. For example, the following WGSL struct type: @@ -101,6 +106,37 @@ index buffer for each bind group. This buffer is accessed in the shader to get t sampler index within the heap. See the wgpu_hal dx12 backend documentation for more information. +# External textures + +Support for [`crate::ImageClass::External`] textures is implemented by lowering +each external texture global variable to 3 `Texture2D`s, and a `cbuffer` +of type `NagaExternalTextureParams`. This provides up to 3 planes of texture +data (for example single planar RGBA, or separate Y, Cb, and Cr planes), and the +parameters buffer containing information describing how to handle these +correctly. The bind target to use for each of these globals is specified via +[`Options::external_texture_binding_map`]. + +External textures are supported by WGSL's `textureDimensions()`, +`textureLoad()`, and `textureSampleBaseClampToEdge()` built-in functions. These +are implemented using helper functions. See the following functions for how +these are generated: + * `Writer::write_wrapped_image_query_function` + * `Writer::write_wrapped_image_load_function` + * `Writer::write_wrapped_image_sample_function` + +Ideally the set of global variables could be wrapped in a single struct that +could conveniently be passed around. But, alas, HLSL does not allow structs to +have `Texture2D` members. Fortunately, however, external textures can only be +used as arguments to either built-in or user-defined functions. We therefore +expand any external texture function argument to four consecutive arguments (3 +textures and the params struct) when declaring user-defined functions, and +ensure our built-in function implementations take the same arguments. Then, +whenever we need to emit an external texture in `Writer::write_expr`, which +fortunately can only ever be for a global variable or function argument, we +simply emit the variable name of each of the three textures and the parameters +struct in a comma-separated list. This won't win any awards for elegance, but +it works for our purposes. + [hlsl]: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl [ilov]: https://gpuweb.github.io/gpuweb/wgsl/#internal-value-layout [16bb]: https://github.com/microsoft/DirectXShaderCompiler/wiki/Buffer-Packing#constant-buffer-packing @@ -119,8 +155,37 @@ use core::fmt::Error as FmtError; use thiserror::Error; -use crate::{back, proc}; +use crate::{back, ir, proc}; +/// Direct3D 12 binding information for a global variable. +/// +/// This type provides the HLSL-specific information Naga needs to declare and +/// access an HLSL global variable that cannot be derived from the `Module` +/// itself. +/// +/// An HLSL global variable declaration includes details that the Direct3D API +/// will use to refer to it. For example: +/// +/// RWByteAddressBuffer s_sasm : register(u0, space2); +/// +/// This defines a global `s_sasm` that a Direct3D root signature would refer to +/// as register `0` in register space `2` in a `UAV` descriptor range. Naga can +/// infer the register's descriptor range type from the variable's address class +/// (writable [`Storage`] variables are implemented by Direct3D Unordered Access +/// Views, the `u` register type), but the register number and register space +/// must be supplied by the user. +/// +/// The [`back::hlsl::Options`] structure provides `BindTarget`s for various +/// situations in which Naga may need to generate an HLSL global variable, like +/// [`binding_map`] for Naga global variables, or [`push_constants_target`] for +/// a module's sole [`PushConstant`] variable. See those fields' documentation +/// for details. +/// +/// [`Storage`]: crate::ir::AddressSpace::Storage +/// [`back::hlsl::Options`]: Options +/// [`binding_map`]: Options::binding_map +/// [`push_constants_target`]: Options::push_constants_target +/// [`PushConstant`]: crate::ir::AddressSpace::PushConstant #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] @@ -218,7 +283,8 @@ impl crate::ShaderStage { Self::Vertex => "vs", Self::Fragment => "ps", Self::Compute => "cs", - Self::Task | Self::Mesh => unreachable!(), + Self::Task => "as", + Self::Mesh => "ms", } } } @@ -330,6 +396,62 @@ where pub type DynamicStorageBufferOffsetsTargets = alloc::collections::BTreeMap; +/// HLSL binding information for a Naga [`External`] image global variable. +/// +/// See the module documentation's section on [External textures][mod] for details. +/// +/// [`External`]: crate::ir::ImageClass::External +/// [mod]: #external-textures +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +pub struct ExternalTextureBindTarget { + /// HLSL binding information for the individual plane textures. + /// + /// Each of these should refer to an HLSL `Texture2D` holding one + /// plane of data for the external texture. The exact meaning of each plane + /// varies at runtime depending on where the external texture's data + /// originated. + pub planes: [BindTarget; 3], + + /// HLSL binding information for a buffer holding the sampling parameters. + /// + /// This should refer to a cbuffer of type `NagaExternalTextureParams`, that + /// the code Naga generates for `textureSampleBaseClampToEdge` consults to + /// decide how to combine the data in [`planes`] to get the result required + /// by the spec. + /// + /// [`planes`]: Self::planes + pub params: BindTarget, +} + +#[cfg(any(feature = "serialize", feature = "deserialize"))] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +struct ExternalTextureBindingMapSerialization { + resource_binding: crate::ResourceBinding, + bind_target: ExternalTextureBindTarget, +} + +#[cfg(feature = "deserialize")] +fn deserialize_external_texture_binding_map<'de, D>( + deserializer: D, +) -> Result +where + D: serde::Deserializer<'de>, +{ + use serde::Deserialize; + + let vec = Vec::::deserialize(deserializer)?; + let mut map = ExternalTextureBindingMap::default(); + for item in vec { + map.insert(item.resource_binding, item.bind_target); + } + Ok(map) +} +pub type ExternalTextureBindingMap = + alloc::collections::BTreeMap; + /// Shorthand result used internally by the backend type BackendResult = Result<(), Error>; @@ -349,21 +471,47 @@ pub enum EntryPointError { pub struct Options { /// The hlsl shader model to be used pub shader_model: ShaderModel, - /// Map of resources association to binding locations. + + /// HLSL binding information for each Naga global variable. + /// + /// This maps Naga [`GlobalVariable`]'s [`ResourceBinding`]s to a + /// [`BindTarget`] specifying its register number and space, along with + /// other details necessary to generate a full HLSL declaration for it, + /// or to access its value. + /// + /// This must provide a [`BindTarget`] for every [`GlobalVariable`] in the + /// [`Module`] that has a [`binding`]. + /// + /// [`GlobalVariable`]: crate::ir::GlobalVariable + /// [`ResourceBinding`]: crate::ir::ResourceBinding + /// [`Module`]: crate::ir::Module + /// [`binding`]: crate::ir::GlobalVariable::binding #[cfg_attr( feature = "deserialize", serde(deserialize_with = "deserialize_binding_map") )] pub binding_map: BindingMap, + /// Don't panic on missing bindings, instead generate any HLSL. pub fake_missing_bindings: bool, /// Add special constants to `SV_VertexIndex` and `SV_InstanceIndex`, /// to make them work like in Vulkan/Metal, with help of the host. pub special_constants_binding: Option, - /// Bind target of the push constant buffer + + /// HLSL binding information for the [`PushConstant`] global, if present. + /// + /// If a module contains a global in the [`PushConstant`] address space, the + /// `dx12` backend stores its value directly in the root signature as a + /// series of [`D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS`], whose binding + /// information is given here. + /// + /// [`PushConstant`]: crate::ir::AddressSpace::PushConstant + /// [`D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS`]: https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_root_parameter_type pub push_constants_target: Option, - /// Bind target of the sampler heap and comparison sampler heap. + + /// HLSL binding information for the sampler heap and comparison sampler heap. pub sampler_heap_target: SamplerHeapBindTargets, + /// Mapping of each bind group's sampler index buffer to a bind target. #[cfg_attr( feature = "deserialize", @@ -376,6 +524,18 @@ pub struct Options { serde(deserialize_with = "deserialize_storage_buffer_offsets") )] pub dynamic_storage_buffer_offsets_targets: DynamicStorageBufferOffsetsTargets, + #[cfg_attr( + feature = "deserialize", + serde(deserialize_with = "deserialize_external_texture_binding_map") + )] + + /// HLSL binding information for [`External`] image global variables. + /// + /// See [`ExternalTextureBindTarget`] for details. + /// + /// [`External`]: crate::ir::ImageClass::External + pub external_texture_binding_map: ExternalTextureBindingMap, + /// Should workgroup variables be zero initialized (by polyfilling)? pub zero_initialize_workgroup_memory: bool, /// Should we restrict indexing of vectors, matrices and arrays? @@ -396,6 +556,7 @@ impl Default for Options { sampler_buffer_binding_map: alloc::collections::BTreeMap::default(), push_constants_target: None, dynamic_storage_buffer_offsets_targets: alloc::collections::BTreeMap::new(), + external_texture_binding_map: ExternalTextureBindingMap::default(), zero_initialize_workgroup_memory: true, restrict_indexing: true, force_loop_bounding: true, @@ -420,6 +581,29 @@ impl Options { None => Err(EntryPointError::MissingBinding(*res_binding)), } } + + fn resolve_external_texture_resource_binding( + &self, + res_binding: &crate::ResourceBinding, + ) -> Result { + match self.external_texture_binding_map.get(res_binding) { + Some(target) => Ok(*target), + None if self.fake_missing_bindings => { + let fake = BindTarget { + space: res_binding.group as u8, + register: res_binding.binding, + binding_array_size: None, + dynamic_storage_buffer_offsets_index: None, + restrict_indexing: false, + }; + Ok(ExternalTextureBindTarget { + planes: [fake, fake, fake], + params: fake, + }) + } + None => Err(EntryPointError::MissingBinding(*res_binding)), + } + } } /// Reflection info for entry point names. @@ -434,6 +618,22 @@ pub struct ReflectionInfo { pub entry_point_names: Vec>, } +/// A subset of options that are meant to be changed per pipeline. +#[derive(Debug, Default, Clone)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +#[cfg_attr(feature = "deserialize", serde(default))] +pub struct PipelineOptions { + /// The entry point to write. + /// + /// Entry points are identified by a shader stage specification, + /// and a name. + /// + /// If `None`, all entry points will be written. If `Some` and the entry + /// point is not found, an error will be thrown while writing. + pub entry_point: Option<(ir::ShaderStage, String)>, +} + #[derive(Error, Debug)] pub enum Error { #[error(transparent)] @@ -448,13 +648,19 @@ pub enum Error { Override, #[error(transparent)] ResolveArraySizeError(#[from] proc::ResolveArraySizeError), + #[error("entry point with stage {0:?} and name '{1}' not found")] + EntryPointNotFound(ir::ShaderStage, String), + #[error("requires shader model {1:?} for reason: {0}")] + ShaderModelTooLow(String, ShaderModel), } #[derive(PartialEq, Eq, Hash)] enum WrappedType { ZeroValue(help::WrappedZeroValue), ArrayLength(help::WrappedArrayLength), + ImageSample(help::WrappedImageSample), ImageQuery(help::WrappedImageQuery), + ImageLoad(help::WrappedImageLoad), ImageLoadScalar(crate::Scalar), Constructor(help::WrappedConstructor), StructMatrixAccess(help::WrappedStructMatrixAccess), @@ -519,8 +725,10 @@ pub struct Writer<'a, W> { namer: proc::Namer, /// HLSL backend options options: &'a Options, + /// Per-stage backend options + pipeline_options: &'a PipelineOptions, /// Information about entry point arguments and result types. - entry_point_io: Vec, + entry_point_io: crate::FastHashMap, /// Set of expressions that have associated temporary variables named_expressions: crate::NamedExpressions, wrapped: Wrapped, diff --git a/naga/src/back/hlsl/storage.rs b/naga/src/back/hlsl/storage.rs index 9f92d8663..5d66af000 100644 --- a/naga/src/back/hlsl/storage.rs +++ b/naga/src/back/hlsl/storage.rs @@ -108,6 +108,13 @@ pub(super) enum StoreValue { base: Handle, member_index: u32, }, + // Access to a single column of a Cx2 matrix within a struct + TempColumnAccess { + depth: usize, + base: Handle, + member_index: u32, + column: u32, + }, } impl super::Writer<'_, W> { @@ -290,6 +297,15 @@ impl super::Writer<'_, W> { let name = &self.names[&NameKey::StructMember(base, member_index)]; write!(self.out, "{STORE_TEMP_NAME}{depth}.{name}")? } + StoreValue::TempColumnAccess { + depth, + base, + member_index, + column, + } => { + let name = &self.names[&NameKey::StructMember(base, member_index)]; + write!(self.out, "{STORE_TEMP_NAME}{depth}.{name}_{column}")? + } } Ok(()) } @@ -302,6 +318,7 @@ impl super::Writer<'_, W> { value: StoreValue, func_ctx: &FunctionCtx, level: crate::back::Level, + within_struct: Option>, ) -> BackendResult { let temp_resolution; let ty_resolution = match value { @@ -325,6 +342,9 @@ impl super::Writer<'_, W> { temp_resolution = TypeResolution::Handle(ty_handle); &temp_resolution } + StoreValue::TempColumnAccess { .. } => { + unreachable!("attempting write_storage_store for TempColumnAccess"); + } }; match *ty_resolution.inner_with(&module.types) { crate::TypeInner::Scalar(scalar) => { @@ -372,37 +392,92 @@ impl super::Writer<'_, W> { rows, scalar, } => { - // first, assign the value to a temporary - writeln!(self.out, "{level}{{")?; - let depth = level.0 + 1; - write!( - self.out, - "{}{}{}x{} {}{} = ", - level.next(), - scalar.to_hlsl_str()?, - columns as u8, - rows as u8, - STORE_TEMP_NAME, - depth, - )?; - self.write_store_value(module, &value, func_ctx)?; - writeln!(self.out, ";")?; - // Note: Matrices containing vec3s, due to padding, act like they contain vec4s. let row_stride = Alignment::from(rows) * scalar.width as u32; - // then iterate the stores - for i in 0..columns as u32 { - self.temp_access_chain - .push(SubAccess::Offset(i * row_stride)); - let ty_inner = crate::TypeInner::Vector { size: rows, scalar }; - let sv = StoreValue::TempIndex { - depth, - index: i, - ty: TypeResolution::Value(ty_inner), - }; - self.write_storage_store(module, var_handle, sv, func_ctx, level.next())?; - self.temp_access_chain.pop(); + writeln!(self.out, "{level}{{")?; + + match within_struct { + Some(containing_struct) if rows == crate::VectorSize::Bi => { + // If we are within a struct, then the struct was already assigned to + // a temporary, we don't need to make another. + let mut chain = mem::take(&mut self.temp_access_chain); + for i in 0..columns as u32 { + chain.push(SubAccess::Offset(i * row_stride)); + // working around the borrow checker in `self.write_expr` + let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; + let StoreValue::TempAccess { member_index, .. } = value else { + unreachable!( + "write_storage_store within_struct but not TempAccess" + ); + }; + let column_value = StoreValue::TempColumnAccess { + depth: level.0, // note not incrementing, b/c no temp + base: containing_struct, + member_index, + column: i, + }; + // See note about DXC and Load/Store in the module's documentation. + if scalar.width == 4 { + write!( + self.out, + "{}{}.Store{}(", + level.next(), + var_name, + rows as u8 + )?; + self.write_storage_address(module, &chain, func_ctx)?; + write!(self.out, ", asuint(")?; + self.write_store_value(module, &column_value, func_ctx)?; + writeln!(self.out, "));")?; + } else { + write!(self.out, "{}{var_name}.Store(", level.next())?; + self.write_storage_address(module, &chain, func_ctx)?; + write!(self.out, ", ")?; + self.write_store_value(module, &column_value, func_ctx)?; + writeln!(self.out, ");")?; + } + chain.pop(); + } + self.temp_access_chain = chain; + } + _ => { + // first, assign the value to a temporary + let depth = level.0 + 1; + write!( + self.out, + "{}{}{}x{} {}{} = ", + level.next(), + scalar.to_hlsl_str()?, + columns as u8, + rows as u8, + STORE_TEMP_NAME, + depth, + )?; + self.write_store_value(module, &value, func_ctx)?; + writeln!(self.out, ";")?; + + // then iterate the stores + for i in 0..columns as u32 { + self.temp_access_chain + .push(SubAccess::Offset(i * row_stride)); + let ty_inner = crate::TypeInner::Vector { size: rows, scalar }; + let sv = StoreValue::TempIndex { + depth, + index: i, + ty: TypeResolution::Value(ty_inner), + }; + self.write_storage_store( + module, + var_handle, + sv, + func_ctx, + level.next(), + None, + )?; + self.temp_access_chain.pop(); + } + } } // done writeln!(self.out, "{level}}}")?; @@ -415,7 +490,7 @@ impl super::Writer<'_, W> { // first, assign the value to a temporary writeln!(self.out, "{level}{{")?; write!(self.out, "{}", level.next())?; - self.write_value_type(module, &module.types[base].inner)?; + self.write_type(module, base)?; let depth = level.next().0; write!(self.out, " {STORE_TEMP_NAME}{depth}")?; self.write_array_size(module, base, crate::ArraySize::Constant(size))?; @@ -430,7 +505,7 @@ impl super::Writer<'_, W> { index: i, ty: TypeResolution::Handle(base), }; - self.write_storage_store(module, var_handle, sv, func_ctx, level.next())?; + self.write_storage_store(module, var_handle, sv, func_ctx, level.next(), None)?; self.temp_access_chain.pop(); } // done @@ -461,7 +536,14 @@ impl super::Writer<'_, W> { base: struct_ty, member_index: i as u32, }; - self.write_storage_store(module, var_handle, sv, func_ctx, level.next())?; + self.write_storage_store( + module, + var_handle, + sv, + func_ctx, + level.next(), + Some(struct_ty), + )?; self.temp_access_chain.pop(); } // done diff --git a/naga/src/back/hlsl/writer.rs b/naga/src/back/hlsl/writer.rs index dd79174ac..f13601bff 100644 --- a/naga/src/back/hlsl/writer.rs +++ b/naga/src/back/hlsl/writer.rs @@ -12,12 +12,12 @@ use super::{ WrappedZeroValue, }, storage::StoreValue, - BackendResult, Error, FragmentEntryPoint, Options, + BackendResult, Error, FragmentEntryPoint, Options, PipelineOptions, ShaderModel, }; use crate::{ - back::{self, Baked}, + back::{self, get_entry_points, Baked}, common, - proc::{self, index, ExpressionKindTracker, NameKey}, + proc::{self, index, ExternalTextureNameKey, NameKey}, valid, Handle, Module, RayQueryFunction, Scalar, ScalarKind, ShaderStage, TypeInner, }; @@ -34,6 +34,7 @@ pub(crate) const EXTRACT_BITS_FUNCTION: &str = "naga_extractBits"; pub(crate) const INSERT_BITS_FUNCTION: &str = "naga_insertBits"; pub(crate) const SAMPLER_HEAP_VAR: &str = "nagaSamplerHeap"; pub(crate) const COMPARISON_SAMPLER_HEAP_VAR: &str = "nagaComparisonSamplerHeap"; +pub(crate) const SAMPLE_EXTERNAL_TEXTURE_FUNCTION: &str = "nagaSampleExternalTexture"; pub(crate) const ABS_FUNCTION: &str = "naga_abs"; pub(crate) const DIV_FUNCTION: &str = "naga_div"; pub(crate) const MOD_FUNCTION: &str = "naga_mod"; @@ -42,6 +43,14 @@ pub(crate) const F2I32_FUNCTION: &str = "naga_f2i32"; pub(crate) const F2U32_FUNCTION: &str = "naga_f2u32"; pub(crate) const F2I64_FUNCTION: &str = "naga_f2i64"; pub(crate) const F2U64_FUNCTION: &str = "naga_f2u64"; +pub(crate) const IMAGE_SAMPLE_BASE_CLAMP_TO_EDGE_FUNCTION: &str = + "nagaTextureSampleBaseClampToEdge"; +pub(crate) const IMAGE_LOAD_EXTERNAL_FUNCTION: &str = "nagaTextureLoadExternal"; + +enum Index { + Expression(Handle), + Static(u32), +} struct EpStructMember { name: String, @@ -123,13 +132,14 @@ struct BindingArraySamplerInfo { } impl<'a, W: fmt::Write> super::Writer<'a, W> { - pub fn new(out: W, options: &'a Options) -> Self { + pub fn new(out: W, options: &'a Options, pipeline_options: &'a PipelineOptions) -> Self { Self { out, names: crate::FastHashMap::default(), namer: proc::Namer::default(), options, - entry_point_io: Vec::new(), + pipeline_options, + entry_point_io: crate::FastHashMap::default(), named_expressions: crate::NamedExpressions::default(), wrapped: super::Wrapped::default(), written_committed_intersection: false, @@ -145,7 +155,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.namer.reset( module, &super::keywords::RESERVED_SET, - super::keywords::RESERVED_CASE_INSENSITIVE, + &super::keywords::RESERVED_CASE_INSENSITIVE_SET, super::keywords::RESERVED_PREFIXES, &mut self.names, ); @@ -206,7 +216,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.need_bake_expressions.insert(exp_handle); } - if let Expression::Math { fun, arg, .. } = *expr { + if let Expression::Math { fun, arg, arg1, .. } = *expr { match fun { crate::MathFunction::Asinh | crate::MathFunction::Acosh @@ -224,7 +234,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { | crate::MathFunction::Pack4x8snorm | crate::MathFunction::Pack4x8unorm | crate::MathFunction::Pack4xI8 - | crate::MathFunction::Pack4xU8 => { + | crate::MathFunction::Pack4xU8 + | crate::MathFunction::Pack4xI8Clamp + | crate::MathFunction::Pack4xU8Clamp => { self.need_bake_expressions.insert(arg); } crate::MathFunction::CountLeadingZeros => { @@ -233,6 +245,10 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.need_bake_expressions.insert(arg); } } + crate::MathFunction::Dot4U8Packed | crate::MathFunction::Dot4I8Packed => { + self.need_bake_expressions.insert(arg); + self.need_bake_expressions.insert(arg1.unwrap()); + } _ => {} } } @@ -262,6 +278,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } => { self.need_bake_expressions.insert(argument); } + crate::Statement::Atomic { + fun: crate::AtomicFunction::Exchange { compare: Some(cmp) }, + .. + } => { + self.need_bake_expressions.insert(cmp); + } _ => {} } } @@ -297,7 +319,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } for (group, bt) in self.options.dynamic_storage_buffer_offsets_targets.iter() { - writeln!(self.out, "struct __dynamic_buffer_offsetsTy{} {{", group)?; + writeln!(self.out, "struct __dynamic_buffer_offsetsTy{group} {{")?; for i in 0..bt.size { writeln!(self.out, "{}uint _{};", back::INDENT, i)?; } @@ -372,8 +394,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } // Write all globals - for (ty, _) in module.global_variables.iter() { - self.write_global(module, ty)?; + for (global, _) in module.global_variables.iter() { + self.write_global(module, global)?; } if !module.global_variables.is_empty() { @@ -381,8 +403,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { writeln!(self.out)?; } + let ep_range = get_entry_points(module, self.pipeline_options.entry_point.as_ref()) + .map_err(|(stage, name)| Error::EntryPointNotFound(stage, name))?; + // Write all entry points wrapped structs - for (index, ep) in module.entry_points.iter().enumerate() { + for index in ep_range.clone() { + let ep = &module.entry_points[index]; let ep_name = self.names[&NameKey::EntryPoint(index as u16)].clone(); let ep_io = self.write_ep_interface( module, @@ -391,7 +417,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { &ep_name, fragment_entry_point, )?; - self.entry_point_io.push(ep_io); + self.entry_point_io.insert(index, ep_io); } // Write all regular functions @@ -407,6 +433,10 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { .find(|&(var_handle, var)| match var.binding { Some(ref binding) if !info[var_handle].is_empty() => { self.options.resolve_resource_binding(binding).is_err() + && self + .options + .resolve_external_texture_resource_binding(binding) + .is_err() } _ => false, }) @@ -426,7 +456,6 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { info, expressions: &function.expressions, named_expressions: &function.named_expressions, - expr_kind_tracker: ExpressionKindTracker::from_arena(&function.expressions), }; let name = self.names[&NameKey::Function(handle)].clone(); @@ -437,10 +466,11 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { writeln!(self.out)?; } - let mut entry_point_names = Vec::with_capacity(module.entry_points.len()); + let mut translated_ep_names = Vec::with_capacity(ep_range.len()); // Write all entry points - for (index, ep) in module.entry_points.iter().enumerate() { + for index in ep_range { + let ep = &module.entry_points[index]; let info = module_info.get_entry_point(index); if !self.options.fake_missing_bindings { @@ -449,15 +479,21 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { match var.binding { Some(ref binding) if !info[var_handle].is_empty() => { if let Err(err) = self.options.resolve_resource_binding(binding) { - ep_error = Some(err); - break; + if self + .options + .resolve_external_texture_resource_binding(binding) + .is_err() + { + ep_error = Some(err); + break; + } } } _ => {} } } if let Some(err) = ep_error { - entry_point_names.push(Err(err)); + translated_ep_names.push(Err(err)); continue; } } @@ -467,12 +503,11 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { info, expressions: &ep.function.expressions, named_expressions: &ep.function.named_expressions, - expr_kind_tracker: ExpressionKindTracker::from_arena(&ep.function.expressions), }; self.write_wrapped_functions(module, &ctx)?; - if ep.stage == ShaderStage::Compute { + if ep.stage.compute_like() { // HLSL is calling workgroup size "num threads" let num_threads = ep.workgroup_size; writeln!( @@ -489,10 +524,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { writeln!(self.out)?; } - entry_point_names.push(Ok(name)); + translated_ep_names.push(Ok(name)); } - Ok(super::ReflectionInfo { entry_point_names }) + Ok(super::ReflectionInfo { + entry_point_names: translated_ep_names, + }) } fn write_modifier(&mut self, binding: &crate::Binding) -> BackendResult { @@ -532,6 +569,14 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ) -> BackendResult { match *binding { Some(crate::Binding::BuiltIn(builtin)) if !is_subgroup_builtin_binding(binding) => { + if builtin == crate::BuiltIn::ViewIndex + && self.options.shader_model < ShaderModel::V6_1 + { + return Err(Error::ShaderModelTooLow( + "used @builtin(view_index) or SV_ViewID".to_string(), + ShaderModel::V6_1, + )); + } let builtin_str = builtin.to_hlsl_str()?; write!(self.out, " : {builtin_str}")?; } @@ -681,7 +726,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let members = match module.types[result.ty].inner { TypeInner::Struct { ref members, .. } => members, ref other => { - log::error!("Unexpected {:?} output type without a binding", other); + log::error!("Unexpected {other:?} output type without a binding"); &empty[..] } }; @@ -812,7 +857,13 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ep_index: u16, ) -> BackendResult { let ep = &module.entry_points[ep_index as usize]; - let ep_input = match self.entry_point_io[ep_index as usize].input.take() { + let ep_input = match self + .entry_point_io + .get_mut(&(ep_index as usize)) + .unwrap() + .input + .take() + { Some(ep_input) => ep_input, None => return Ok(()), }; @@ -873,6 +924,25 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let global = &module.global_variables[handle]; let inner = &module.types[global.ty].inner; + let handle_ty = match *inner { + TypeInner::BindingArray { ref base, .. } => &module.types[*base].inner, + _ => inner, + }; + + // External textures are handled entirely differently, so defer entirely to that method. + // We do so prior to calling resolve_resource_binding() below, as we even need to resolve + // their bindings separately. + let is_external_texture = matches!( + *handle_ty, + TypeInner::Image { + class: crate::ImageClass::External, + .. + } + ); + if is_external_texture { + return self.write_global_external_texture(module, handle, global); + } + if let Some(ref binding) = global.binding { if let Err(err) = self.options.resolve_resource_binding(binding) { log::info!( @@ -885,11 +955,6 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } - let handle_ty = match *inner { - TypeInner::BindingArray { ref base, .. } => &module.types[*base].inner, - _ => inner, - }; - // Samplers are handled entirely differently, so defer entirely to that method. let is_sampler = matches!(*handle_ty, TypeInner::Sampler { .. }); @@ -910,6 +975,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_type(module, global.ty)?; "" } + crate::AddressSpace::TaskPayload => unimplemented!(), crate::AddressSpace::Uniform => { // constant buffer declarations are expected to be inlined, e.g. // `cbuffer foo: register(b0) { field1: type1; }` @@ -964,6 +1030,15 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // Push constants need to be assigned a binding explicitly by the consumer // since naga has no way to know the binding from the shader alone if global.space == crate::AddressSpace::PushConstant { + match module.types[global.ty].inner { + TypeInner::Struct { .. } => {} + _ => { + return Err(Error::Unimplemented(format!( + "push-constant '{name}' has non-struct type; tracked by: https://github.com/gfx-rs/wgpu/issues/5683" + ))); + } + } + let target = self .options .push_constants_target @@ -1093,6 +1168,70 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Ok(()) } + /// Write the declarations for an external texture global variable. + /// These are emitted as multiple global variables: Three `Texture2D`s + /// (one for each plane) and a parameters cbuffer. + fn write_global_external_texture( + &mut self, + module: &Module, + handle: Handle, + global: &crate::GlobalVariable, + ) -> BackendResult { + let res_binding = global + .binding + .as_ref() + .expect("External texture global variables must have a resource binding"); + let ext_tex_bindings = match self + .options + .resolve_external_texture_resource_binding(res_binding) + { + Ok(bindings) => bindings, + Err(err) => { + log::info!( + "Skipping global {:?} (name {:?}) for being inaccessible: {}", + handle, + global.name, + err, + ); + return Ok(()); + } + }; + + let mut write_plane = |bt: &super::BindTarget, name| -> BackendResult { + write!( + self.out, + "Texture2D {}: register(t{}", + name, bt.register + )?; + if bt.space != 0 { + write!(self.out, ", space{}", bt.space)?; + } + writeln!(self.out, ");")?; + Ok(()) + }; + for (i, bt) in ext_tex_bindings.planes.iter().enumerate() { + let plane_name = &self.names + [&NameKey::ExternalTextureGlobalVariable(handle, ExternalTextureNameKey::Plane(i))]; + write_plane(bt, plane_name)?; + } + + let params_name = &self.names + [&NameKey::ExternalTextureGlobalVariable(handle, ExternalTextureNameKey::Params)]; + let params_ty_name = + &self.names[&NameKey::Type(module.special_types.external_texture_params.unwrap())]; + write!( + self.out, + "cbuffer {}: register(b{}", + params_name, ext_tex_bindings.params.register + )?; + if ext_tex_bindings.params.space != 0 { + write!(self.out, ", space{}", ext_tex_bindings.params.space)?; + } + writeln!(self.out, ") {{ {params_ty_name} {params_name}; }};")?; + + Ok(()) + } + /// Helper method used to write global constants /// /// # Notes @@ -1393,7 +1532,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let array_return_type = self.namer.call(&format!("ret_{name}")); write!(self.out, "typedef ")?; self.write_type(module, result.ty)?; - write!(self.out, " {}", array_return_type)?; + write!(self.out, " {array_return_type}")?; self.write_array_size(module, base, size)?; writeln!(self.out, ";")?; Some(array_return_type) @@ -1419,7 +1558,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } back::FunctionType::EntryPoint(index) => { - if let Some(ref ep_output) = self.entry_point_io[index as usize].output { + if let Some(ref ep_output) = + self.entry_point_io.get(&(index as usize)).unwrap().output + { write!(self.out, "{}", ep_output.ty_name)?; } else { self.write_type(module, result.ty)?; @@ -1443,30 +1584,14 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { if index != 0 { write!(self.out, ", ")?; } - // Write argument type - let arg_ty = match module.types[arg.ty].inner { - // pointers in function arguments are expected and resolve to `inout` - TypeInner::Pointer { base, .. } => { - //TODO: can we narrow this down to just `in` when possible? - write!(self.out, "inout ")?; - base - } - _ => arg.ty, - }; - self.write_type(module, arg_ty)?; - let argument_name = - &self.names[&NameKey::FunctionArgument(handle, index as u32)]; - - // Write argument name. Space is important. - write!(self.out, " {argument_name}")?; - if let TypeInner::Array { base, size, .. } = module.types[arg_ty].inner { - self.write_array_size(module, base, size)?; - } + self.write_function_argument(module, handle, arg, index)?; } } back::FunctionType::EntryPoint(ep_index) => { - if let Some(ref ep_input) = self.entry_point_io[ep_index as usize].input { + if let Some(ref ep_input) = + self.entry_point_io.get(&(ep_index as usize)).unwrap().input + { write!(self.out, "{} {}", ep_input.ty_name, ep_input.arg_name)?; } else { let stage = module.entry_points[ep_index as usize].stage; @@ -1488,7 +1613,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } if need_workgroup_variables_initialization { - if self.entry_point_io[ep_index as usize].input.is_some() + if self + .entry_point_io + .get(&(ep_index as usize)) + .unwrap() + .input + .is_some() || !func.arguments.is_empty() { write!(self.out, ", ")?; @@ -1569,13 +1699,81 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Ok(()) } + fn write_function_argument( + &mut self, + module: &Module, + handle: Handle, + arg: &crate::FunctionArgument, + index: usize, + ) -> BackendResult { + // External texture arguments must be expanded into separate + // arguments for each plane and the params buffer. + if let TypeInner::Image { + class: crate::ImageClass::External, + .. + } = module.types[arg.ty].inner + { + return self.write_function_external_texture_argument(module, handle, index); + } + + // Write argument type + let arg_ty = match module.types[arg.ty].inner { + // pointers in function arguments are expected and resolve to `inout` + TypeInner::Pointer { base, .. } => { + //TODO: can we narrow this down to just `in` when possible? + write!(self.out, "inout ")?; + base + } + _ => arg.ty, + }; + self.write_type(module, arg_ty)?; + + let argument_name = &self.names[&NameKey::FunctionArgument(handle, index as u32)]; + + // Write argument name. Space is important. + write!(self.out, " {argument_name}")?; + if let TypeInner::Array { base, size, .. } = module.types[arg_ty].inner { + self.write_array_size(module, base, size)?; + } + + Ok(()) + } + + fn write_function_external_texture_argument( + &mut self, + module: &Module, + handle: Handle, + index: usize, + ) -> BackendResult { + let plane_names = [0, 1, 2].map(|i| { + &self.names[&NameKey::ExternalTextureFunctionArgument( + handle, + index as u32, + ExternalTextureNameKey::Plane(i), + )] + }); + let params_name = &self.names[&NameKey::ExternalTextureFunctionArgument( + handle, + index as u32, + ExternalTextureNameKey::Params, + )]; + let params_ty_name = + &self.names[&NameKey::Type(module.special_types.external_texture_params.unwrap())]; + write!( + self.out, + "Texture2D {}, Texture2D {}, Texture2D {}, {params_ty_name} {params_name}", + plane_names[0], plane_names[1], plane_names[2], + )?; + Ok(()) + } + fn need_workgroup_variables_initialization( &mut self, func_ctx: &back::FunctionCtx, module: &Module, ) -> bool { self.options.zero_initialize_workgroup_memory - && func_ctx.ty.is_compute_entry_point(module) + && func_ctx.ty.is_compute_like_entry_point(module) && module.global_variables.iter().any(|(handle, var)| { !func_ctx.info[handle].is_empty() && var.space == crate::AddressSpace::WorkGroup }) @@ -1605,7 +1803,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } writeln!(self.out, "{level}}}")?; - self.write_barrier(crate::Barrier::WORK_GROUP, level) + self.write_control_barrier(crate::Barrier::WORK_GROUP, level) } /// Helper method used to write switches @@ -1753,6 +1951,23 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Ok(()) } + fn write_index( + &mut self, + module: &Module, + index: Index, + func_ctx: &back::FunctionCtx<'_>, + ) -> BackendResult { + match index { + Index::Static(index) => { + write!(self.out, "{index}")?; + } + Index::Expression(index) => { + self.write_expr(module, index, func_ctx)?; + } + } + Ok(()) + } + /// Helper method used to write statements /// /// # Notes @@ -1857,9 +2072,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // for entry point returns, we may need to reshuffle the outputs into a different struct let ep_output = match func_ctx.ty { back::FunctionType::Function(_) => None, - back::FunctionType::EntryPoint(index) => { - self.entry_point_io[index as usize].output.as_ref() - } + back::FunctionType::EntryPoint(index) => self + .entry_point_io + .get(&(index as usize)) + .unwrap() + .output + .as_ref(), }; let final_name = match ep_output { Some(ep_output) => { @@ -1898,6 +2116,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { StoreValue::Expression(value), func_ctx, level, + None, )?; } else { // We treat matrices of the form `matCx2` as a sequence of C `vec2`s. @@ -1905,13 +2124,15 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { // // We handle matrix Stores here directly (including sub accesses for Vectors and Scalars). // Loads are handled by `Expression::AccessIndex` (since sub accesses work fine for Loads). - struct MatrixAccess { - base: Handle, - index: u32, - } - enum Index { - Expression(Handle), - Static(u32), + enum MatrixAccess { + Direct { + base: Handle, + index: u32, + }, + Struct { + columns: crate::VectorSize, + base: Handle, + }, } let get_members = |expr: Handle| { @@ -1925,187 +2146,28 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } }; - let mut matrix = None; - let mut vector = None; - let mut scalar = None; - - let mut current_expr = pointer; - for _ in 0..3 { - let resolved = func_ctx.resolve_type(current_expr, &module.types); - - match (resolved, &func_ctx.expressions[current_expr]) { - ( - &TypeInner::Pointer { base: ty, .. }, - &crate::Expression::AccessIndex { base, index }, - ) if matches!( - module.types[ty].inner, - TypeInner::Matrix { - rows: crate::VectorSize::Bi, - .. - } - ) && get_members(base) - .map(|members| members[index as usize].binding.is_none()) - == Some(true) => - { - matrix = Some(MatrixAccess { base, index }); - break; - } - ( - &TypeInner::ValuePointer { - size: Some(crate::VectorSize::Bi), - .. - }, - &crate::Expression::Access { base, index }, - ) => { - vector = Some(Index::Expression(index)); - current_expr = base; - } - ( - &TypeInner::ValuePointer { - size: Some(crate::VectorSize::Bi), - .. - }, - &crate::Expression::AccessIndex { base, index }, - ) => { - vector = Some(Index::Static(index)); - current_expr = base; - } - ( - &TypeInner::ValuePointer { size: None, .. }, - &crate::Expression::Access { base, index }, - ) => { - scalar = Some(Index::Expression(index)); - current_expr = base; - } - ( - &TypeInner::ValuePointer { size: None, .. }, - &crate::Expression::AccessIndex { base, index }, - ) => { - scalar = Some(Index::Static(index)); - current_expr = base; - } - _ => break, - } - } - write!(self.out, "{level}")?; - if let Some(MatrixAccess { index, base }) = matrix { - let base_ty_res = &func_ctx.info[base].ty; - let resolved = base_ty_res.inner_with(&module.types); - let ty = match *resolved { - TypeInner::Pointer { base, .. } => base, - _ => base_ty_res.handle().unwrap(), - }; - - if let Some(Index::Static(vec_index)) = vector { - self.write_expr(module, base, func_ctx)?; - write!( - self.out, - ".{}_{}", - &self.names[&NameKey::StructMember(ty, index)], - vec_index - )?; - - if let Some(scalar_index) = scalar { - write!(self.out, "[")?; - match scalar_index { - Index::Static(index) => { - write!(self.out, "{index}")?; - } - Index::Expression(index) => { - self.write_expr(module, index, func_ctx)?; - } - } - write!(self.out, "]")?; - } - - write!(self.out, " = ")?; - self.write_expr(module, value, func_ctx)?; - writeln!(self.out, ";")?; - } else { - let access = WrappedStructMatrixAccess { ty, index }; - match (&vector, &scalar) { - (&Some(_), &Some(_)) => { - self.write_wrapped_struct_matrix_set_scalar_function_name( - access, - )?; - } - (&Some(_), &None) => { - self.write_wrapped_struct_matrix_set_vec_function_name(access)?; - } - (&None, _) => { - self.write_wrapped_struct_matrix_set_function_name(access)?; - } - } - - write!(self.out, "(")?; - self.write_expr(module, base, func_ctx)?; - write!(self.out, ", ")?; - self.write_expr(module, value, func_ctx)?; - - if let Some(Index::Expression(vec_index)) = vector { - write!(self.out, ", ")?; - self.write_expr(module, vec_index, func_ctx)?; - - if let Some(scalar_index) = scalar { - write!(self.out, ", ")?; - match scalar_index { - Index::Static(index) => { - write!(self.out, "{index}")?; - } - Index::Expression(index) => { - self.write_expr(module, index, func_ctx)?; - } - } - } - } - writeln!(self.out, ");")?; - } - } else { - // We handle `Store`s to __matCx2 column vectors and scalar elements via - // the previously injected functions __set_col_of_matCx2 / __set_el_of_matCx2. - struct MatrixData { - columns: crate::VectorSize, - base: Handle, - } - - enum Index { - Expression(Handle), - Static(u32), - } - - let mut matrix = None; - let mut vector = None; - let mut scalar = None; - - let mut current_expr = pointer; - for _ in 0..3 { - let resolved = func_ctx.resolve_type(current_expr, &module.types); - match (resolved, &func_ctx.expressions[current_expr]) { + let matrix_access_on_lhs = + find_matrix_in_access_chain(module, pointer, func_ctx).and_then( + |(matrix_expr, vector, scalar)| match ( + func_ctx.resolve_type(matrix_expr, &module.types), + &func_ctx.expressions[matrix_expr], + ) { ( - &TypeInner::ValuePointer { - size: Some(crate::VectorSize::Bi), - .. - }, - &crate::Expression::Access { base, index }, - ) => { - vector = Some(index); - current_expr = base; - } - ( - &TypeInner::ValuePointer { size: None, .. }, - &crate::Expression::Access { base, index }, - ) => { - scalar = Some(Index::Expression(index)); - current_expr = base; - } - ( - &TypeInner::ValuePointer { size: None, .. }, + &TypeInner::Pointer { base: ty, .. }, &crate::Expression::AccessIndex { base, index }, - ) => { - scalar = Some(Index::Static(index)); - current_expr = base; + ) if matches!( + module.types[ty].inner, + TypeInner::Matrix { + rows: crate::VectorSize::Bi, + .. + } + ) && get_members(base) + .map(|members| members[index as usize].binding.is_none()) + == Some(true) => + { + Some((MatrixAccess::Direct { base, index }, vector, scalar)) } _ => { if let Some(MatrixType { @@ -2114,24 +2176,95 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { width: 4, }) = get_inner_matrix_of_struct_array_member( module, - current_expr, + matrix_expr, func_ctx, true, ) { - matrix = Some(MatrixData { - columns, - base: current_expr, - }); + Some(( + MatrixAccess::Struct { + columns, + base: matrix_expr, + }, + vector, + scalar, + )) + } else { + None } - - break; } + }, + ); + + match matrix_access_on_lhs { + Some((MatrixAccess::Direct { index, base }, vector, scalar)) => { + let base_ty_res = &func_ctx.info[base].ty; + let resolved = base_ty_res.inner_with(&module.types); + let ty = match *resolved { + TypeInner::Pointer { base, .. } => base, + _ => base_ty_res.handle().unwrap(), + }; + + if let Some(Index::Static(vec_index)) = vector { + self.write_expr(module, base, func_ctx)?; + write!( + self.out, + ".{}_{}", + &self.names[&NameKey::StructMember(ty, index)], + vec_index + )?; + + if let Some(scalar_index) = scalar { + write!(self.out, "[")?; + self.write_index(module, scalar_index, func_ctx)?; + write!(self.out, "]")?; + } + + write!(self.out, " = ")?; + self.write_expr(module, value, func_ctx)?; + writeln!(self.out, ";")?; + } else { + let access = WrappedStructMatrixAccess { ty, index }; + match (&vector, &scalar) { + (&Some(_), &Some(_)) => { + self.write_wrapped_struct_matrix_set_scalar_function_name( + access, + )?; + } + (&Some(_), &None) => { + self.write_wrapped_struct_matrix_set_vec_function_name( + access, + )?; + } + (&None, _) => { + self.write_wrapped_struct_matrix_set_function_name(access)?; + } + } + + write!(self.out, "(")?; + self.write_expr(module, base, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, value, func_ctx)?; + + if let Some(Index::Expression(vec_index)) = vector { + write!(self.out, ", ")?; + self.write_expr(module, vec_index, func_ctx)?; + + if let Some(scalar_index) = scalar { + write!(self.out, ", ")?; + self.write_index(module, scalar_index, func_ctx)?; + } + } + writeln!(self.out, ");")?; } } + Some(( + MatrixAccess::Struct { columns, base }, + Some(Index::Expression(vec_index)), + scalar, + )) => { + // We handle `Store`s to __matCx2 column vectors and scalar elements via + // the previously injected functions __set_col_of_matCx2 / __set_el_of_matCx2. - if let (Some(MatrixData { columns, base }), Some(vec_index)) = - (matrix, vector) - { if scalar.is_some() { write!(self.out, "__set_el_of_mat{}x2", columns as u8)?; } else { @@ -2144,21 +2277,17 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { if let Some(scalar_index) = scalar { write!(self.out, ", ")?; - match scalar_index { - Index::Static(index) => { - write!(self.out, "{index}")?; - } - Index::Expression(index) => { - self.write_expr(module, index, func_ctx)?; - } - } + self.write_index(module, scalar_index, func_ctx)?; } write!(self.out, ", ")?; self.write_expr(module, value, func_ctx)?; writeln!(self.out, ");")?; - } else { + } + Some((MatrixAccess::Struct { .. }, Some(Index::Static(_)), _)) + | Some((MatrixAccess::Struct { .. }, None, _)) + | None => { self.write_expr(module, pointer, func_ctx)?; write!(self.out, " = ")?; @@ -2246,8 +2375,11 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { writeln!(self.out, "{level}continue;")? } } - Statement::Barrier(barrier) => { - self.write_barrier(barrier, level)?; + Statement::ControlBarrier(barrier) => { + self.write_control_barrier(barrier, level)?; + } + Statement::MemoryBarrier(barrier) => { + self.write_memory_barrier(barrier, level)?; } Statement::ImageStore { image, @@ -2319,49 +2451,61 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { result, } => { write!(self.out, "{level}")?; - let res_name = match result { - None => None, - Some(result) => { - let name = Baked(result).to_string(); - match func_ctx.info[result].ty { - proc::TypeResolution::Handle(handle) => { - self.write_type(module, handle)? - } - proc::TypeResolution::Value(ref value) => { - self.write_value_type(module, value)? - } - }; - write!(self.out, " {name}; ")?; - Some((result, name)) - } + let res_var_info = if let Some(res_handle) = result { + let name = Baked(res_handle).to_string(); + match func_ctx.info[res_handle].ty { + proc::TypeResolution::Handle(handle) => self.write_type(module, handle)?, + proc::TypeResolution::Value(ref value) => { + self.write_value_type(module, value)? + } + }; + write!(self.out, " {name}; ")?; + self.named_expressions.insert(res_handle, name.clone()); + Some((res_handle, name)) + } else { + None }; - - // Validation ensures that `pointer` has a `Pointer` type. let pointer_space = func_ctx .resolve_type(pointer, &module.types) .pointer_space() .unwrap(); - let fun_str = fun.to_hlsl_suffix(); + let compare_expr = match *fun { + crate::AtomicFunction::Exchange { compare: Some(cmp) } => Some(cmp), + _ => None, + }; match pointer_space { crate::AddressSpace::WorkGroup => { write!(self.out, "Interlocked{fun_str}(")?; self.write_expr(module, pointer, func_ctx)?; + self.emit_hlsl_atomic_tail( + module, + func_ctx, + fun, + compare_expr, + value, + &res_var_info, + )?; } crate::AddressSpace::Storage { .. } => { let var_handle = self.fill_access_chain(module, pointer, func_ctx)?; - // The call to `self.write_storage_address` wants - // mutable access to all of `self`, so temporarily take - // ownership of our reusable access chain buffer. - let chain = mem::take(&mut self.temp_access_chain); let var_name = &self.names[&NameKey::GlobalVariable(var_handle)]; let width = match func_ctx.resolve_type(value, &module.types) { &TypeInner::Scalar(Scalar { width: 8, .. }) => "64", _ => "", }; write!(self.out, "{var_name}.Interlocked{fun_str}{width}(")?; + let chain = mem::take(&mut self.temp_access_chain); self.write_storage_address(module, &chain, func_ctx)?; self.temp_access_chain = chain; + self.emit_hlsl_atomic_tail( + module, + func_ctx, + fun, + compare_expr, + value, + &res_var_info, + )?; } ref other => { return Err(Error::Custom(format!( @@ -2369,29 +2513,16 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ))) } } - write!(self.out, ", ")?; - // handle the special cases - match *fun { - crate::AtomicFunction::Subtract => { - // we just wrote `InterlockedAdd`, so negate the argument - write!(self.out, "-")?; + if let Some(cmp) = compare_expr { + if let Some(&(_res_handle, ref res_name)) = res_var_info.as_ref() { + write!( + self.out, + "{level}{res_name}.exchanged = ({res_name}.old_value == " + )?; + self.write_expr(module, cmp, func_ctx)?; + writeln!(self.out, ");")?; } - crate::AtomicFunction::Exchange { compare: Some(_) } => { - return Err(Error::Unimplemented("atomic CompareExchange".to_string())); - } - _ => {} } - self.write_expr(module, value, func_ctx)?; - - // The `original_value` out parameter is optional for all the - // `Interlocked` functions we generate other than - // `InterlockedExchange`. - if let Some((result, name)) = res_name { - write!(self.out, ", {name}")?; - self.named_expressions.insert(result, name); - } - - writeln!(self.out, ");")?; } Statement::ImageAtomic { image, @@ -2420,12 +2551,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { writeln!(self.out, ");")?; } Statement::WorkGroupUniformLoad { pointer, result } => { - self.write_barrier(crate::Barrier::WORK_GROUP, level)?; + self.write_control_barrier(crate::Barrier::WORK_GROUP, level)?; write!(self.out, "{level}")?; let name = Baked(result).to_string(); self.write_named_expr(module, pointer, name, result, func_ctx)?; - self.write_barrier(crate::Barrier::WORK_GROUP, level)?; + self.write_control_barrier(crate::Barrier::WORK_GROUP, level)?; } Statement::Switch { selector, @@ -2477,6 +2608,19 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { writeln!(self.out, ".Abort();")?; } }, + Statement::MeshFunction(crate::MeshFunction::SetMeshOutputs { + vertex_count, + primitive_count, + }) => { + write!(self.out, "{level}SetMeshOutputCounts(")?; + self.write_expr(module, vertex_count, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, primitive_count, func_ctx)?; + write!(self.out, ");")?; + } + Statement::MeshFunction( + crate::MeshFunction::SetVertex { .. } | crate::MeshFunction::SetPrimitive { .. }, + ) => unimplemented!(), Statement::SubgroupBallot { result, predicate } => { write!(self.out, "{level}")?; let name = Baked(result).to_string(); @@ -2571,30 +2715,55 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { }; write!(self.out, " {name} = ")?; self.named_expressions.insert(result, name); - - if matches!(mode, crate::GatherMode::BroadcastFirst) { - write!(self.out, "WaveReadLaneFirst(")?; - self.write_expr(module, argument, func_ctx)?; - } else { - write!(self.out, "WaveReadLaneAt(")?; - self.write_expr(module, argument, func_ctx)?; - write!(self.out, ", ")?; - match mode { - crate::GatherMode::BroadcastFirst => unreachable!(), - crate::GatherMode::Broadcast(index) | crate::GatherMode::Shuffle(index) => { - self.write_expr(module, index, func_ctx)?; + match mode { + crate::GatherMode::BroadcastFirst => { + write!(self.out, "WaveReadLaneFirst(")?; + self.write_expr(module, argument, func_ctx)?; + } + crate::GatherMode::QuadBroadcast(index) => { + write!(self.out, "QuadReadLaneAt(")?; + self.write_expr(module, argument, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, index, func_ctx)?; + } + crate::GatherMode::QuadSwap(direction) => { + match direction { + crate::Direction::X => { + write!(self.out, "QuadReadAcrossX(")?; + } + crate::Direction::Y => { + write!(self.out, "QuadReadAcrossY(")?; + } + crate::Direction::Diagonal => { + write!(self.out, "QuadReadAcrossDiagonal(")?; + } } - crate::GatherMode::ShuffleDown(index) => { - write!(self.out, "WaveGetLaneIndex() + ")?; - self.write_expr(module, index, func_ctx)?; - } - crate::GatherMode::ShuffleUp(index) => { - write!(self.out, "WaveGetLaneIndex() - ")?; - self.write_expr(module, index, func_ctx)?; - } - crate::GatherMode::ShuffleXor(index) => { - write!(self.out, "WaveGetLaneIndex() ^ ")?; - self.write_expr(module, index, func_ctx)?; + self.write_expr(module, argument, func_ctx)?; + } + _ => { + write!(self.out, "WaveReadLaneAt(")?; + self.write_expr(module, argument, func_ctx)?; + write!(self.out, ", ")?; + match mode { + crate::GatherMode::BroadcastFirst => unreachable!(), + crate::GatherMode::Broadcast(index) + | crate::GatherMode::Shuffle(index) => { + self.write_expr(module, index, func_ctx)?; + } + crate::GatherMode::ShuffleDown(index) => { + write!(self.out, "WaveGetLaneIndex() + ")?; + self.write_expr(module, index, func_ctx)?; + } + crate::GatherMode::ShuffleUp(index) => { + write!(self.out, "WaveGetLaneIndex() - ")?; + self.write_expr(module, index, func_ctx)?; + } + crate::GatherMode::ShuffleXor(index) => { + write!(self.out, "WaveGetLaneIndex() ^ ")?; + self.write_expr(module, index, func_ctx)?; + } + crate::GatherMode::QuadBroadcast(_) => unreachable!(), + crate::GatherMode::QuadSwap(_) => unreachable!(), } } } @@ -2622,11 +2791,23 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { crate::Literal::F32(value) => write!(self.out, "{value:?}")?, crate::Literal::F16(value) => write!(self.out, "{value:?}h")?, crate::Literal::U32(value) => write!(self.out, "{value}u")?, + // `-2147483648` is parsed by some compilers as unary negation of + // positive 2147483648, which is too large for an int, causing + // issues for some compilers. Neither DXC nor FXC appear to have + // this problem, but this is not specified and could change. We + // therefore use `-2147483647 - 1` as a precaution. + crate::Literal::I32(value) if value == i32::MIN => { + write!(self.out, "int({} - 1)", value + 1)? + } // HLSL has no suffix for explicit i32 literals, but not using any suffix // makes the type ambiguous which prevents overload resolution from // working. So we explicitly use the int() constructor syntax. crate::Literal::I32(value) => write!(self.out, "int({value})")?, crate::Literal::U64(value) => write!(self.out, "{value}uL")?, + // I64 version of the minimum I32 value issue described above. + crate::Literal::I64(value) if value == i64::MIN => { + write!(self.out, "({}L - 1L)", value + 1)?; + } crate::Literal::I64(value) => write!(self.out, "{value}L")?, crate::Literal::Bool(value) => write!(self.out, "{value}")?, crate::Literal::AbstractInt(_) | crate::Literal::AbstractFloat(_) => { @@ -2843,7 +3024,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { right, } if matches!( func_ctx.resolve_type(expr, &module.types).scalar_kind(), - Some(ScalarKind::Sint | ScalarKind::Uint) + Some(ScalarKind::Sint | ScalarKind::Uint | ScalarKind::Float) ) => { write!(self.out, "{MOD_FUNCTION}(")?; @@ -2853,21 +3034,6 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { write!(self.out, ")")?; } - // While HLSL supports float operands with the % operator it is only - // defined in cases where both sides are either positive or negative. - Expression::Binary { - op: crate::BinaryOperator::Modulo, - left, - right, - } if func_ctx.resolve_type(left, &module.types).scalar_kind() - == Some(ScalarKind::Float) => - { - write!(self.out, "fmod(")?; - self.write_expr(module, left, func_ctx)?; - write!(self.out, ", ")?; - self.write_expr(module, right, func_ctx)?; - write!(self.out, ")")?; - } Expression::Binary { op, left, right } => { write!(self.out, "(")?; self.write_expr(module, left, func_ctx)?; @@ -2892,6 +3058,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { rows: crate::VectorSize::Bi, width: 4, }) = get_inner_matrix_of_struct_array_member(module, base, func_ctx, true) + .or_else(|| get_global_uniform_matrix(module, base, func_ctx)) { write!(self.out, "__get_col_of_mat{}x2(", columns as u8)?; self.write_expr(module, base, func_ctx)?; @@ -2931,7 +3098,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { crate::AddressSpace::Function | crate::AddressSpace::Private | crate::AddressSpace::WorkGroup - | crate::AddressSpace::PushConstant, + | crate::AddressSpace::PushConstant + | crate::AddressSpace::TaskPayload, ) | None => true, Some(crate::AddressSpace::Uniform) => { @@ -3004,13 +3172,15 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { { // do nothing, the chain is written on `Load`/`Store` } else { - // We write the matrix column access in a special way since - // the type of `base` is our special __matCx2 struct. + // See if we need to write the matrix column access in a + // special way since the type of `base` is our special + // __matCx2 struct. if let Some(MatrixType { rows: crate::VectorSize::Bi, width: 4, .. }) = get_inner_matrix_of_struct_array_member(module, base, func_ctx, true) + .or_else(|| get_global_uniform_matrix(module, base, func_ctx)) { self.write_expr(module, base, func_ctx)?; write!(self.out, "._{index}")?; @@ -3110,9 +3280,53 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } } Expression::FunctionArgument(pos) => { - let key = func_ctx.argument_key(pos); - let name = &self.names[&key]; - write!(self.out, "{name}")?; + let ty = func_ctx.resolve_type(expr, &module.types); + + // We know that any external texture function argument has been expanded into + // separate consecutive arguments for each plane and the parameters buffer. And we + // also know that external textures can only ever be used as an argument to another + // function. Therefore we can simply emit each of the expanded arguments in a + // consecutive comma-separated list. + if let TypeInner::Image { + class: crate::ImageClass::External, + .. + } = *ty + { + let plane_names = [0, 1, 2].map(|i| { + &self.names[&func_ctx + .external_texture_argument_key(pos, ExternalTextureNameKey::Plane(i))] + }); + let params_name = &self.names[&func_ctx + .external_texture_argument_key(pos, ExternalTextureNameKey::Params)]; + write!( + self.out, + "{}, {}, {}, {}", + plane_names[0], plane_names[1], plane_names[2], params_name + )?; + } else { + let key = func_ctx.argument_key(pos); + let name = &self.names[&key]; + write!(self.out, "{name}")?; + } + } + Expression::ImageSample { + coordinate, + image, + sampler, + clamp_to_edge: true, + gather: None, + array_index: None, + offset: None, + level: crate::SampleLevel::Zero, + depth_ref: None, + } => { + write!(self.out, "{IMAGE_SAMPLE_BASE_CLAMP_TO_EDGE_FUNCTION}(")?; + self.write_expr(module, image, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, sampler, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, coordinate, func_ctx)?; + write!(self.out, ")")?; } Expression::ImageSample { image, @@ -3123,7 +3337,14 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { offset, level, depth_ref, + clamp_to_edge, } => { + if clamp_to_edge { + return Err(Error::Custom( + "ImageSample::clamp_to_edge should have been validated out".to_string(), + )); + } + use crate::SampleLevel as Sl; const COMPONENTS: [&str; 4] = ["", "Green", "Blue", "Alpha"]; @@ -3249,7 +3470,34 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { let is_storage_space = matches!(global_variable.space, crate::AddressSpace::Storage { .. }); - if !is_binding_array_of_samplers && !is_storage_space { + // Our external texture global variable has been expanded into multiple + // global variables, one for each plane and the parameters buffer. + // External textures can only ever be used as arguments to a function + // call, and we know that an external texture argument to any function + // will have been expanded to separate consecutive arguments for each + // plane and the parameters buffer. Therefore we can simply emit each of + // the expanded global variables in a consecutive comma-separated list. + if let TypeInner::Image { + class: crate::ImageClass::External, + .. + } = *ty + { + let plane_names = [0, 1, 2].map(|i| { + &self.names[&NameKey::ExternalTextureGlobalVariable( + handle, + ExternalTextureNameKey::Plane(i), + )] + }); + let params_name = &self.names[&NameKey::ExternalTextureGlobalVariable( + handle, + ExternalTextureNameKey::Params, + )]; + write!( + self.out, + "{}, {}, {}, {}", + plane_names[0], plane_names[1], plane_names[2], params_name + )?; + } else if !is_binding_array_of_samplers && !is_storage_space { let name = &self.names[&NameKey::GlobalVariable(handle)]; write!(self.out, "{name}")?; } @@ -3284,8 +3532,11 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { .or_else(|| get_inner_matrix_of_global_uniform(module, pointer, func_ctx)) { let mut resolved = func_ctx.resolve_type(pointer, &module.types); - if let TypeInner::Pointer { base, .. } = *resolved { - resolved = &module.types[base].inner; + let ptr_tr = resolved.pointer_base_type(); + if let Some(ptr_ty) = + ptr_tr.as_ref().map(|tr| tr.inner_with(&module.types)) + { + resolved = ptr_ty; } write!(self.out, "((")?; @@ -3416,6 +3667,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Pack4x8unorm, Pack4xI8, Pack4xU8, + Pack4xI8Clamp, + Pack4xU8Clamp, Unpack2x16float, Unpack2x16snorm, Unpack2x16unorm, @@ -3423,6 +3676,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Unpack4x8unorm, Unpack4xI8, Unpack4xU8, + Dot4I8Packed, + Dot4U8Packed, QuantizeToF16, Regular(&'static str), MissingIntOverload(&'static str), @@ -3474,6 +3729,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Mf::Pow => Function::Regular("pow"), // geometry Mf::Dot => Function::Regular("dot"), + Mf::Dot4I8Packed => Function::Dot4I8Packed, + Mf::Dot4U8Packed => Function::Dot4U8Packed, //Mf::Outer => , Mf::Cross => Function::Regular("cross"), Mf::Distance => Function::Regular("distance"), @@ -3511,6 +3768,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Mf::Pack4x8unorm => Function::Pack4x8unorm, Mf::Pack4xI8 => Function::Pack4xI8, Mf::Pack4xU8 => Function::Pack4xU8, + Mf::Pack4xI8Clamp => Function::Pack4xI8Clamp, + Mf::Pack4xU8Clamp => Function::Pack4xU8Clamp, // Data Unpacking Mf::Unpack2x16float => Function::Unpack2x16float, Mf::Unpack2x16snorm => Function::Unpack2x16snorm, @@ -3611,19 +3870,38 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_expr(module, arg, func_ctx)?; write!(self.out, "[3], 0.0, 1.0) * {scale}.0)) << 24)")?; } - fun @ (Function::Pack4xI8 | Function::Pack4xU8) => { - let was_signed = matches!(fun, Function::Pack4xI8); + fun @ (Function::Pack4xI8 + | Function::Pack4xU8 + | Function::Pack4xI8Clamp + | Function::Pack4xU8Clamp) => { + let was_signed = + matches!(fun, Function::Pack4xI8 | Function::Pack4xI8Clamp); + let clamp_bounds = match fun { + Function::Pack4xI8Clamp => Some(("-128", "127")), + Function::Pack4xU8Clamp => Some(("0", "255")), + _ => None, + }; if was_signed { write!(self.out, "uint(")?; } + let write_arg = |this: &mut Self| -> BackendResult { + if let Some((min, max)) = clamp_bounds { + write!(this.out, "clamp(")?; + this.write_expr(module, arg, func_ctx)?; + write!(this.out, ", {min}, {max})")?; + } else { + this.write_expr(module, arg, func_ctx)?; + } + Ok(()) + }; write!(self.out, "(")?; - self.write_expr(module, arg, func_ctx)?; + write_arg(self)?; write!(self.out, "[0] & 0xFF) | ((")?; - self.write_expr(module, arg, func_ctx)?; + write_arg(self)?; write!(self.out, "[1] & 0xFF) << 8) | ((")?; - self.write_expr(module, arg, func_ctx)?; + write_arg(self)?; write!(self.out, "[2] & 0xFF) << 16) | ((")?; - self.write_expr(module, arg, func_ctx)?; + write_arg(self)?; write!(self.out, "[3] & 0xFF) << 24)")?; if was_signed { write!(self.out, ")")?; @@ -3696,6 +3974,52 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { self.write_expr(module, arg, func_ctx)?; write!(self.out, " >> 24) << 24 >> 24)")?; } + fun @ (Function::Dot4I8Packed | Function::Dot4U8Packed) => { + let arg1 = arg1.unwrap(); + + if self.options.shader_model >= ShaderModel::V6_4 { + // Intrinsics `dot4add_{i, u}8packed` are available in SM 6.4 and later. + let function_name = match fun { + Function::Dot4I8Packed => "dot4add_i8packed", + Function::Dot4U8Packed => "dot4add_u8packed", + _ => unreachable!(), + }; + write!(self.out, "{function_name}(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, arg1, func_ctx)?; + write!(self.out, ", 0)")?; + } else { + // Fall back to a polyfill as `dot4add_u8packed` is not available. + write!(self.out, "dot(")?; + + if matches!(fun, Function::Dot4U8Packed) { + write!(self.out, "u")?; + } + write!(self.out, "int4(")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, " >> 8, ")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, " >> 16, ")?; + self.write_expr(module, arg, func_ctx)?; + write!(self.out, " >> 24) << 24 >> 24, ")?; + + if matches!(fun, Function::Dot4U8Packed) { + write!(self.out, "u")?; + } + write!(self.out, "int4(")?; + self.write_expr(module, arg1, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, arg1, func_ctx)?; + write!(self.out, " >> 8, ")?; + self.write_expr(module, arg1, func_ctx)?; + write!(self.out, " >> 16, ")?; + self.write_expr(module, arg1, func_ctx)?; + write!(self.out, " >> 24) << 24 >> 24)")?; + } + } Function::QuantizeToF16 => { write!(self.out, "f16tof32(f32tof16(")?; self.write_expr(module, arg, func_ctx)?; @@ -4004,6 +4328,17 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ) -> Result<(), Error> { let mut wrapping_type = None; match *func_ctx.resolve_type(image, &module.types) { + TypeInner::Image { + class: crate::ImageClass::External, + .. + } => { + write!(self.out, "{IMAGE_LOAD_EXTERNAL_FUNCTION}(")?; + self.write_expr(module, image, func_ctx)?; + write!(self.out, ", ")?; + self.write_expr(module, coordinate, func_ctx)?; + write!(self.out, ")")?; + return Ok(()); + } TypeInner::Image { class: crate::ImageClass::Storage { format, .. }, .. @@ -4148,7 +4483,11 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { Ok(()) } - fn write_barrier(&mut self, barrier: crate::Barrier, level: back::Level) -> BackendResult { + fn write_control_barrier( + &mut self, + barrier: crate::Barrier, + level: back::Level, + ) -> BackendResult { if barrier.contains(crate::Barrier::STORAGE) { writeln!(self.out, "{level}DeviceMemoryBarrierWithGroupSync();")?; } @@ -4163,6 +4502,58 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { } Ok(()) } + + fn write_memory_barrier( + &mut self, + barrier: crate::Barrier, + level: back::Level, + ) -> BackendResult { + if barrier.contains(crate::Barrier::STORAGE) { + writeln!(self.out, "{level}DeviceMemoryBarrier();")?; + } + if barrier.contains(crate::Barrier::WORK_GROUP) { + writeln!(self.out, "{level}GroupMemoryBarrier();")?; + } + if barrier.contains(crate::Barrier::SUB_GROUP) { + // Does not exist in DirectX + } + if barrier.contains(crate::Barrier::TEXTURE) { + writeln!(self.out, "{level}DeviceMemoryBarrier();")?; + } + Ok(()) + } + + /// Helper to emit the shared tail of an HLSL atomic call (arguments, value, result) + fn emit_hlsl_atomic_tail( + &mut self, + module: &Module, + func_ctx: &back::FunctionCtx<'_>, + fun: &crate::AtomicFunction, + compare_expr: Option>, + value: Handle, + res_var_info: &Option<(Handle, String)>, + ) -> BackendResult { + if let Some(cmp) = compare_expr { + write!(self.out, ", ")?; + self.write_expr(module, cmp, func_ctx)?; + } + write!(self.out, ", ")?; + if let crate::AtomicFunction::Subtract = *fun { + // we just wrote `InterlockedAdd`, so negate the argument + write!(self.out, "-")?; + } + self.write_expr(module, value, func_ctx)?; + if let Some(&(_res_handle, ref res_name)) = res_var_info.as_ref() { + write!(self.out, ", ")?; + if compare_expr.is_some() { + write!(self.out, "{res_name}.old_value")?; + } else { + write!(self.out, "{res_name}")?; + } + } + writeln!(self.out, ");")?; + Ok(()) + } } pub(super) struct MatrixType { @@ -4190,6 +4581,44 @@ pub(super) fn get_inner_matrix_data( } } +/// If `base` is an access chain of the form `mat`, `mat[col]`, or `mat[col][row]`, +/// returns a tuple of the matrix, the column (vector) index (if present), and +/// the row (scalar) index (if present). +fn find_matrix_in_access_chain( + module: &Module, + base: Handle, + func_ctx: &back::FunctionCtx<'_>, +) -> Option<(Handle, Option, Option)> { + let mut current_base = base; + let mut vector = None; + let mut scalar = None; + loop { + let resolved_tr = func_ctx + .resolve_type(current_base, &module.types) + .pointer_base_type(); + let resolved = resolved_tr.as_ref()?.inner_with(&module.types); + + match *resolved { + TypeInner::Matrix { .. } => return Some((current_base, vector, scalar)), + TypeInner::Scalar(_) | TypeInner::Vector { .. } => {} + _ => return None, + } + + let index; + (current_base, index) = match func_ctx.expressions[current_base] { + crate::Expression::Access { base, index } => (base, Index::Expression(index)), + crate::Expression::AccessIndex { base, index } => (base, Index::Static(index)), + _ => return None, + }; + + match *resolved { + TypeInner::Scalar(_) => scalar = Some(index), + TypeInner::Vector { .. } => vector = Some(index), + _ => unreachable!(), + } + } +} + /// Returns the matrix data if the access chain starting at `base`: /// - starts with an expression with resolved type of [`TypeInner::Matrix`] if `direct = true` /// - contains one or more expressions with resolved type of [`TypeInner::Array`] of [`TypeInner::Matrix`] @@ -4248,6 +4677,36 @@ pub(super) fn get_inner_matrix_of_struct_array_member( None } +/// Simpler version of get_inner_matrix_of_global_uniform that only looks at the +/// immediate expression, rather than traversing an access chain. +fn get_global_uniform_matrix( + module: &Module, + base: Handle, + func_ctx: &back::FunctionCtx<'_>, +) -> Option { + let base_tr = func_ctx + .resolve_type(base, &module.types) + .pointer_base_type(); + let base_ty = base_tr.as_ref().map(|tr| tr.inner_with(&module.types)); + match (&func_ctx.expressions[base], base_ty) { + ( + &crate::Expression::GlobalVariable(handle), + Some(&TypeInner::Matrix { + columns, + rows, + scalar, + }), + ) if module.global_variables[handle].space == crate::AddressSpace::Uniform => { + Some(MatrixType { + columns, + rows, + width: scalar.width, + }) + } + _ => None, + } +} + /// Returns the matrix data if the access chain starting at `base`: /// - starts with an expression with resolved type of [`TypeInner::Matrix`] /// - contains zero or more expressions with resolved type of [`TypeInner::Array`] of [`TypeInner::Matrix`] diff --git a/naga/src/back/mod.rs b/naga/src/back/mod.rs index dd9c7bd93..8be763234 100644 --- a/naga/src/back/mod.rs +++ b/naga/src/back/mod.rs @@ -11,8 +11,6 @@ Backend functions that export shader [`Module`](super::Module)s into binary and use alloc::string::String; -use crate::proc::ExpressionKindTracker; - #[cfg(dot_out)] pub mod dot; #[cfg(glsl_out)] @@ -48,6 +46,13 @@ pub type NeedBakeExpressions = crate::FastHashSet); impl core::fmt::Display for Baked { @@ -81,6 +86,33 @@ impl core::fmt::Display for Level { } } +/// Locate the entry point(s) to write. +/// +/// If `entry_point` is given, and the specified entry point exists, returns a +/// length-1 `Range` containing the index of that entry point. If no +/// `entry_point` is given, returns the complete range of entry point indices. +/// If `entry_point` is given but does not exist, returns an error. +#[cfg(any(hlsl_out, msl_out))] +fn get_entry_points( + module: &crate::ir::Module, + entry_point: Option<&(crate::ir::ShaderStage, String)>, +) -> Result, (crate::ir::ShaderStage, String)> { + use alloc::borrow::ToOwned; + + if let Some(&(stage, ref name)) = entry_point { + let Some(ep_index) = module + .entry_points + .iter() + .position(|ep| ep.stage == stage && ep.name == *name) + else { + return Err((stage, name.to_owned())); + }; + Ok(ep_index..ep_index + 1) + } else { + Ok(0..module.entry_points.len()) + } +} + /// Whether we're generating an entry point or a regular function. /// /// Backend languages often require different code for a [`Function`] @@ -107,11 +139,11 @@ pub enum FunctionType { } impl FunctionType { - /// Returns true if the function is an entry point for a compute shader. - pub fn is_compute_entry_point(&self, module: &crate::Module) -> bool { + /// Returns true if the function is an entry point for a compute-like shader. + pub fn is_compute_like_entry_point(&self, module: &crate::Module) -> bool { match *self { FunctionType::EntryPoint(index) => { - module.entry_points[index as usize].stage == crate::ShaderStage::Compute + module.entry_points[index as usize].stage.compute_like() } FunctionType::Function(_) => false, } @@ -128,8 +160,6 @@ pub struct FunctionCtx<'a> { pub expressions: &'a crate::Arena, /// Map of expressions that have associated variable names pub named_expressions: &'a crate::NamedExpressions, - /// For constness checks - pub expr_kind_tracker: ExpressionKindTracker, } impl FunctionCtx<'_> { @@ -166,6 +196,31 @@ impl FunctionCtx<'_> { } } + /// Helper method that generates a [`NameKey`](crate::proc::NameKey) for an external texture + /// function argument. + /// + /// # Panics + /// - If the function arguments are less or equal to `arg` + /// - If `self.ty` is not `FunctionType::Function`. + pub const fn external_texture_argument_key( + &self, + arg: u32, + external_texture_key: crate::proc::ExternalTextureNameKey, + ) -> crate::proc::NameKey { + match self.ty { + FunctionType::Function(handle) => { + crate::proc::NameKey::ExternalTextureFunctionArgument( + handle, + arg, + external_texture_key, + ) + } + FunctionType::EntryPoint(_) => { + panic!("External textures cannot be used as arguments to entry points") + } + } + } + /// Returns true if the given expression points to a fixed-function pipeline input. pub fn is_fixed_function_input( &self, diff --git a/naga/src/back/msl/keywords.rs b/naga/src/back/msl/keywords.rs index 4feb6004f..315af754e 100644 --- a/naga/src/back/msl/keywords.rs +++ b/naga/src/back/msl/keywords.rs @@ -1,6 +1,5 @@ -use std::sync::LazyLock; - -use hashbrown::HashSet; +use crate::proc::KeywordSet; +use crate::racy_lock::RacyLock; // MSLS - Metal Shading Language Specification: // https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf @@ -353,18 +352,15 @@ pub const RESERVED: &[&str] = &[ super::writer::F2U32_FUNCTION, super::writer::F2I64_FUNCTION, super::writer::F2U64_FUNCTION, + super::writer::IMAGE_LOAD_EXTERNAL_FUNCTION, + super::writer::IMAGE_SAMPLE_BASE_CLAMP_TO_EDGE_FUNCTION, + super::writer::IMAGE_SIZE_EXTERNAL_FUNCTION, super::writer::ARGUMENT_BUFFER_WRAPPER_STRUCT, + super::writer::EXTERNAL_TEXTURE_WRAPPER_STRUCT, ]; /// The above set of reserved keywords, turned into a cached HashSet. This saves /// significant time during [`Namer::reset`](crate::proc::Namer::reset). /// /// See for benchmarks. -pub static RESERVED_SET: LazyLock> = LazyLock::new(|| { - let mut set = HashSet::default(); - set.reserve(RESERVED.len()); - for &word in RESERVED { - set.insert(word); - } - set -}); +pub static RESERVED_SET: RacyLock = RacyLock::new(|| KeywordSet::from_iter(RESERVED)); diff --git a/naga/src/back/msl/mod.rs b/naga/src/back/msl/mod.rs index 376662a7d..f2df74d8c 100644 --- a/naga/src/back/msl/mod.rs +++ b/naga/src/back/msl/mod.rs @@ -29,6 +29,43 @@ holding the result. [msl]: https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf [all-atom]: crate::valid::Capabilities::SHADER_INT64_ATOMIC_ALL_OPS +## Pointer-typed bounds-checked expressions and OOB locals + +MSL (unlike HLSL and GLSL) has native support for pointer-typed function +arguments. When the [`BoundsCheckPolicy`] is `ReadZeroSkipWrite` and an +out-of-bounds index expression is used for such an argument, our strategy is to +pass a pointer to a dummy variable. These dummy variables are called "OOB +locals". We emit at most one OOB local per function for each type, since all +expressions producing a result of that type can share the same OOB local. (Note +that the OOB local mechanism is not actually implementing "skip write", nor even +"read zero" in some cases of read-after-write, but doing so would require +additional effort and the difference is unlikely to matter.) + +[`BoundsCheckPolicy`]: crate::proc::BoundsCheckPolicy + +## External textures + +Support for [`crate::ImageClass::External`] textures is implemented by lowering +each external texture global variable to 3 `texture2d`s, and a +constant buffer of type `NagaExternalTextureParams`. This provides up to 3 +planes of texture data (for example single planar RGBA, or separate Y, Cb, and +Cr planes), and the parameters buffer containing information describing how to +handle these correctly. The bind target to use for each of these globals is +specified via the [`BindTarget::external_texture`] field of the relevant +entries in [`EntryPointResources::resources`]. + +External textures are supported by WGSL's `textureDimensions()`, +`textureLoad()`, and `textureSampleBaseClampToEdge()` built-in functions. These +are implemented using helper functions. See the following functions for how +these are generated: + * `Writer::write_wrapped_image_query` + * `Writer::write_wrapped_image_load` + * `Writer::write_wrapped_image_sample` + +The lowered global variables for each external texture global are passed to the +entry point as separate arguments (see "Entry points" above). However, they are +then wrapped in a struct to allow them to be conveniently passed to user +defined and helper functions. See `writer::EXTERNAL_TEXTURE_WRAPPER_STRUCT`. */ use alloc::{ @@ -38,7 +75,7 @@ use alloc::{ }; use core::fmt::{Error as FmtError, Write}; -use crate::{arena::Handle, proc::index, valid::ModuleInfo}; +use crate::{arena::Handle, ir, proc::index, valid::ModuleInfo}; mod keywords; pub mod sampler; @@ -57,6 +94,19 @@ pub enum BindSamplerTarget { Inline(InlineSamplerIndex), } +/// Binding information for a Naga [`External`] image global variable. +/// +/// See the module documentation's section on external textures for details. +/// +/// [`External`]: crate::ir::ImageClass::External +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +pub struct BindExternalTextureTarget { + pub planes: [Slot; 3], + pub params: Slot, +} + #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] @@ -65,12 +115,12 @@ pub struct BindTarget { pub buffer: Option, pub texture: Option, pub sampler: Option, + pub external_texture: Option, pub mutable: bool, } -#[cfg(any(feature = "serialize", feature = "deserialize"))] -#[cfg_attr(feature = "serialize", derive(serde::Serialize))] -#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +#[cfg(feature = "deserialize")] +#[derive(serde::Deserialize)] struct BindingMapSerialization { resource_binding: crate::ResourceBinding, bind_target: BindTarget, @@ -170,7 +220,7 @@ pub enum Error { #[error("can not use writeable storage buffers in fragment stage prior to MSL 1.2")] UnsupportedWriteableStorageBuffer, #[error("can not use writeable storage textures in {0:?} stage prior to MSL 1.2")] - UnsupportedWriteableStorageTexture(crate::ShaderStage), + UnsupportedWriteableStorageTexture(ir::ShaderStage), #[error("can not use read-write storage textures prior to MSL 1.2")] UnsupportedRWStorageTexture, #[error("array of '{0}' is not supported for target MSL version")] @@ -185,6 +235,8 @@ pub enum Error { UnsupportedBitCast(crate::TypeInner), #[error(transparent)] ResolveArraySizeError(#[from] crate::proc::ResolveArraySizeError), + #[error("entry point with stage {0:?} and name '{1}' not found")] + EntryPointNotFound(ir::ShaderStage, String), } #[derive(Clone, Debug, PartialEq, thiserror::Error)] @@ -365,6 +417,17 @@ pub enum VertexFormat { Unorm8x4Bgra = 44, } +/// Defines how to advance the data in vertex buffers. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +pub enum VertexBufferStepMode { + Constant, + #[default] + ByVertex, + ByInstance, +} + /// A mapping of vertex buffers and their attributes to shader /// locations. #[derive(Debug, Clone, PartialEq, Eq, Hash)] @@ -393,9 +456,8 @@ pub struct VertexBufferMapping { pub id: u32, /// Size of the structure in bytes pub stride: u32, - /// True if the buffer is indexed by vertex, false if indexed - /// by instance. - pub indexed_by_vertex: bool, + /// Vertex buffer step mode + pub step_mode: VertexBufferStepMode, /// Vec of the attributes within the structure pub attributes: Vec, } @@ -406,6 +468,15 @@ pub struct VertexBufferMapping { #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] #[cfg_attr(feature = "deserialize", serde(default))] pub struct PipelineOptions { + /// The entry point to write. + /// + /// Entry points are identified by a shader stage specification, + /// and a name. + /// + /// If `None`, all entry points will be written. If `Some` and the entry + /// point is not found, an error will be thrown while writing. + pub entry_point: Option<(ir::ShaderStage, String)>, + /// Allow `BuiltIn::PointSize` and inject it if doesn't exist. /// /// Metal doesn't like this for non-point primitive topologies and requires it for @@ -455,10 +526,21 @@ impl Options { return Err(Error::UnsupportedAttribute("instance_id".to_string())); } // macOS: Since Metal 2.2 - // iOS: Since Metal 2.3 (check depends on https://github.com/gfx-rs/naga/issues/2164) - crate::BuiltIn::PrimitiveIndex if self.lang_version < (2, 2) => { + // iOS: Since Metal 2.3 (check depends on https://github.com/gfx-rs/wgpu/issues/4414) + crate::BuiltIn::PrimitiveIndex if self.lang_version < (2, 3) => { return Err(Error::UnsupportedAttribute("primitive_id".to_string())); } + // macOS: since Metal 2.3 + // iOS: Since Metal 2.2 + // https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf#page=114 + crate::BuiltIn::ViewIndex if self.lang_version < (2, 2) => { + return Err(Error::UnsupportedAttribute("amplification_id".to_string())); + } + // macOS: Since Metal 2.2 + // iOS: Since Metal 2.3 (check depends on https://github.com/gfx-rs/wgpu/issues/4414) + crate::BuiltIn::Barycentric if self.lang_version < (2, 3) => { + return Err(Error::UnsupportedAttribute("barycentric_coord".to_string())); + } _ => {} } @@ -469,6 +551,7 @@ impl Options { interpolation, sampling, blend_src, + per_primitive: _, } => match mode { LocationMode::VertexInput => Ok(ResolvedBinding::Attribute(location)), LocationMode::FragmentOutput => { @@ -597,6 +680,7 @@ impl ResolvedBinding { let name = match built_in { Bi::Position { invariant: false } => "position", Bi::Position { invariant: true } => "position, invariant", + Bi::ViewIndex => "amplification_id", // vertex Bi::BaseInstance => "base_instance", Bi::BaseVertex => "base_vertex", @@ -609,6 +693,7 @@ impl ResolvedBinding { Bi::PointCoord => "point_coord", Bi::FrontFacing => "front_facing", Bi::PrimitiveIndex => "primitive_id", + Bi::Barycentric => "barycentric_coord", Bi::SampleIndex => "sample_id", Bi::SampleMask => "sample_mask", // compute @@ -623,9 +708,13 @@ impl ResolvedBinding { Bi::SubgroupId => "simdgroup_index_in_threadgroup", Bi::SubgroupSize => "threads_per_simdgroup", Bi::SubgroupInvocationId => "thread_index_in_simdgroup", - Bi::CullDistance | Bi::ViewIndex | Bi::DrawID => { + Bi::CullDistance | Bi::DrawID => { return Err(Error::UnsupportedBuiltIn(built_in)) } + Bi::CullPrimitive => "primitive_culled", + // TODO: figure out how to make this written as a function call + Bi::PointIndex | Bi::LineIndices | Bi::TriangleIndices => unimplemented!(), + Bi::MeshTaskSize => unreachable!(), }; write!(out, "{name}")?; } @@ -723,5 +812,5 @@ pub fn write_string( #[test] fn test_error_size() { - assert_eq!(size_of::(), 32); + assert_eq!(size_of::(), 40); } diff --git a/naga/src/back/msl/writer.rs b/naga/src/back/msl/writer.rs index 83b8bd43d..484142630 100644 --- a/naga/src/back/msl/writer.rs +++ b/naga/src/back/msl/writer.rs @@ -5,6 +5,7 @@ use alloc::{ vec::Vec, }; use core::{ + cmp::Ordering, fmt::{Display, Error as FmtError, Formatter, Write}, iter, }; @@ -15,9 +16,13 @@ use half::f16; use super::{sampler as sm, Error, LocationMode, Options, PipelineOptions, TranslationInfo}; use crate::{ arena::{Handle, HandleSet}, - back::{self, Baked}, + back::{self, get_entry_points, Baked}, common, - proc::{self, index, ExpressionKindTracker, NameKey, TypeResolution}, + proc::{ + self, + index::{self, BoundsCheck}, + ExternalTextureNameKey, NameKey, TypeResolution, + }, valid, FastHashMap, FastHashSet, }; @@ -56,6 +61,10 @@ pub(crate) const F2I32_FUNCTION: &str = "naga_f2i32"; pub(crate) const F2U32_FUNCTION: &str = "naga_f2u32"; pub(crate) const F2I64_FUNCTION: &str = "naga_f2i64"; pub(crate) const F2U64_FUNCTION: &str = "naga_f2u64"; +pub(crate) const IMAGE_LOAD_EXTERNAL_FUNCTION: &str = "nagaTextureLoadExternal"; +pub(crate) const IMAGE_SIZE_EXTERNAL_FUNCTION: &str = "nagaTextureDimensionsExternal"; +pub(crate) const IMAGE_SAMPLE_BASE_CLAMP_TO_EDGE_FUNCTION: &str = + "nagaTextureSampleBaseClampToEdge"; /// For some reason, Metal does not let you have `metal::texture<..>*` as a buffer argument. /// However, if you put that texture inside a struct, everything is totally fine. This /// baffles me to no end. @@ -64,6 +73,11 @@ pub(crate) const F2U64_FUNCTION: &str = "naga_f2u64"; /// This allows `NagaArgumentBufferWrapper>*` to work. The astute among /// you have noticed that this should be exactly the same to the compiler, and you're correct. pub(crate) const ARGUMENT_BUFFER_WRAPPER_STRUCT: &str = "NagaArgumentBufferWrapper"; +/// Name of the struct that is declared to wrap the 3 textures and parameters +/// buffer that [`crate::ImageClass::External`] variables are lowered to, +/// allowing them to be conveniently passed to user-defined or wrapper +/// functions. The struct is declared in [`Writer::write_type_defs`]. +pub(crate) const EXTERNAL_TEXTURE_WRAPPER_STRUCT: &str = "NagaExternalTextureWrapper"; /// Write the Metal name for a Naga numeric type: scalar, vector, or matrix. /// @@ -116,6 +130,9 @@ const fn scalar_is_int(scalar: crate::Scalar) -> bool { /// Prefix for cached clamped level-of-detail values for `ImageLoad` expressions. const CLAMPED_LOD_LOAD_PREFIX: &str = "clamped_lod_e"; +/// Prefix for reinterpreted expressions using `as_type(...)`. +const REINTERPRET_PREFIX: &str = "reinterpreted_"; + /// Wrapper for identifier names for clamped level-of-detail values /// /// Values of this type implement [`core::fmt::Display`], formatting as @@ -151,6 +168,30 @@ impl Display for ArraySizeMember { } } +/// Wrapper for reinterpreted variables using `as_type(orig)`. +/// +/// Implements [`core::fmt::Display`], formatting as a name derived from +/// `target_type` and the variable name of `orig`. +#[derive(Clone, Copy)] +struct Reinterpreted<'a> { + target_type: &'a str, + orig: Handle, +} + +impl<'a> Reinterpreted<'a> { + const fn new(target_type: &'a str, orig: Handle) -> Self { + Self { target_type, orig } + } +} + +impl Display for Reinterpreted<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { + f.write_str(REINTERPRET_PREFIX)?; + f.write_str(self.target_type)?; + self.orig.write_prefixed(f, "_e") + } +} + struct TypeContext<'a> { handle: Handle, gctx: proc::GlobalCtx<'a>, @@ -287,6 +328,9 @@ impl Display for TypeContext<'_> { }; ("texture", "", format.into(), access) } + crate::ImageClass::External => { + return write!(out, "{EXTERNAL_TEXTURE_WRAPPER_STRUCT}"); + } }; let base_name = scalar.to_msl_name(); let array_str = if arrayed { "_array" } else { "" }; @@ -414,6 +458,16 @@ enum WrappedFunction { vector_size: Option, dst_scalar: crate::Scalar, }, + ImageLoad { + class: crate::ImageClass, + }, + ImageSample { + class: crate::ImageClass, + clamp_to_edge: bool, + }, + ImageQuerySize { + class: crate::ImageClass, + }, } pub struct Writer { @@ -540,7 +594,8 @@ impl crate::AddressSpace { | Self::Private | Self::WorkGroup | Self::PushConstant - | Self::Handle => true, + | Self::Handle + | Self::TaskPayload => true, Self::Function => false, } } @@ -553,6 +608,7 @@ impl crate::AddressSpace { // may end up with "const" even if the binding is read-write, // and that should be OK. Self::Storage { .. } => true, + Self::TaskPayload => unimplemented!(), // These should always be read-write. Self::Private | Self::WorkGroup => false, // These translate to `constant` address space, no need for qualifiers. @@ -569,6 +625,7 @@ impl crate::AddressSpace { Self::Storage { .. } => Some("device"), Self::Private | Self::Function => Some("thread"), Self::WorkGroup => Some("threadgroup"), + Self::TaskPayload => Some("object_data"), } } } @@ -598,11 +655,34 @@ impl crate::Type { } } +#[derive(Clone, Copy)] enum FunctionOrigin { Handle(Handle), EntryPoint(proc::EntryPointIndex), } +trait NameKeyExt { + fn local(origin: FunctionOrigin, local_handle: Handle) -> NameKey { + match origin { + FunctionOrigin::Handle(handle) => NameKey::FunctionLocal(handle, local_handle), + FunctionOrigin::EntryPoint(idx) => NameKey::EntryPointLocal(idx, local_handle), + } + } + + /// Return the name key for a local variable used by ReadZeroSkipWrite bounds-check + /// policy when it needs to produce a pointer-typed result for an OOB access. These + /// are unique per accessed type, so the second argument is a type handle. See docs + /// for [`crate::back::msl`]. + fn oob_local_for_type(origin: FunctionOrigin, ty: Handle) -> NameKey { + match origin { + FunctionOrigin::Handle(handle) => NameKey::FunctionOobLocal(handle, ty), + FunctionOrigin::EntryPoint(idx) => NameKey::EntryPointOobLocal(idx, ty), + } + } +} + +impl NameKeyExt for NameKey {} + /// A level of detail argument. /// /// When [`BoundsCheckPolicy::Restrict`] applies to an [`ImageLoad`] access, we @@ -680,6 +760,7 @@ impl<'a> ExpressionContext<'a> { .choose_policy(pointer, &self.module.types, self.info) } + /// See docs for [`proc::index::access_needs_check`]. fn access_needs_check( &self, base: Handle, @@ -694,6 +775,19 @@ impl<'a> ExpressionContext<'a> { ) } + /// See docs for [`proc::index::bounds_check_iter`]. + fn bounds_check_iter( + &self, + chain: Handle, + ) -> impl Iterator + '_ { + index::bounds_check_iter(chain, self.module, self.function, self.info) + } + + /// See docs for [`proc::index::oob_local_types`]. + fn oob_local_types(&self) -> FastHashSet> { + index::oob_local_types(self.module, self.function, self.info, self.policies) + } + fn get_packed_vec_kind(&self, expr_handle: Handle) -> Option { match self.function.expressions[expr_handle] { crate::Expression::AccessIndex { base, index } => { @@ -901,6 +995,59 @@ impl Writer { Ok(()) } + /// Writes the local variables of the given function, as well as any extra + /// out-of-bounds locals that are needed. + /// + /// The names of the OOB locals are also added to `self.names` at the same + /// time. + fn put_locals(&mut self, context: &ExpressionContext) -> BackendResult { + let oob_local_types = context.oob_local_types(); + for &ty in oob_local_types.iter() { + let name_key = NameKey::oob_local_for_type(context.origin, ty); + self.names.insert(name_key, self.namer.call("oob")); + } + + for (name_key, ty, init) in context + .function + .local_variables + .iter() + .map(|(local_handle, local)| { + let name_key = NameKey::local(context.origin, local_handle); + (name_key, local.ty, local.init) + }) + .chain(oob_local_types.iter().map(|&ty| { + let name_key = NameKey::oob_local_for_type(context.origin, ty); + (name_key, ty, None) + })) + { + let ty_name = TypeContext { + handle: ty, + gctx: context.module.to_ctx(), + names: &self.names, + access: crate::StorageAccess::empty(), + first_time: false, + }; + write!( + self.out, + "{}{} {}", + back::INDENT, + ty_name, + self.names[&name_key] + )?; + match init { + Some(value) => { + write!(self.out, " = ")?; + self.put_expression(value, context, true)?; + } + None => { + write!(self.out, " = {{}}")?; + } + }; + writeln!(self.out, ";")?; + } + Ok(()) + } + fn put_level_of_detail( &mut self, level: LevelOfDetail, @@ -936,6 +1083,17 @@ impl Writer { kind: crate::ScalarKind, context: &ExpressionContext, ) -> BackendResult { + if let crate::TypeInner::Image { + class: crate::ImageClass::External, + .. + } = *context.resolve_type(image) + { + write!(self.out, "{IMAGE_SIZE_EXTERNAL_FUNCTION}(")?; + self.put_expression(image, context, true)?; + write!(self.out, ")")?; + return Ok(()); + } + //Note: MSL only has separate width/height/depth queries, // so compose the result of them. let dim = match *context.resolve_type(image) { @@ -1023,7 +1181,7 @@ impl Writer { //TODO: do we support Zero on `Sampled` image classes? } _ if !has_levels => { - log::warn!("1D image can't be sampled with level {:?}", level); + log::warn!("1D image can't be sampled with level {level:?}"); } crate::SampleLevel::Exact(h) => { write!(self.out, ", {NAMESPACE}::level(")?; @@ -1193,6 +1351,19 @@ impl Writer { mut address: TexelAddress, context: &ExpressionContext, ) -> BackendResult { + if let crate::TypeInner::Image { + class: crate::ImageClass::External, + .. + } = *context.resolve_type(image) + { + write!(self.out, "{IMAGE_LOAD_EXTERNAL_FUNCTION}(")?; + self.put_expression(image, context, true)?; + write!(self.out, ", ")?; + self.put_cast_to_uint_scalar_or_vector(address.coordinate, context)?; + write!(self.out, ")")?; + return Ok(()); + } + match context.policies.image_load { proc::BoundsCheckPolicy::Restrict => { // Use the cached restricted level of detail, if any. Omit the @@ -1270,7 +1441,7 @@ impl Writer { } else { fun.to_msl() }; - write!(self.out, ".atomic_{}(", op)?; + write!(self.out, ".atomic_{op}(")?; // coordinates in IR are int, but Metal expects uint self.put_cast_to_uint_scalar_or_vector(address.coordinate, &context.expression)?; write!(self.out, ", ")?; @@ -1375,12 +1546,14 @@ impl Writer { /// Emit code for the arithmetic expression of the dot product. /// - fn put_dot_product( + /// The argument `extractor` is a function that accepts a `Writer`, a vector, and + /// an index. It writes out the expression for the vector component at that index. + fn put_dot_product( &mut self, - arg: Handle, - arg1: Handle, + arg: T, + arg1: T, size: usize, - context: &ExpressionContext, + extractor: impl Fn(&mut Self, T, usize) -> BackendResult, ) -> BackendResult { // Write parentheses around the dot product expression to prevent operators // with different precedences from applying earlier. @@ -1388,28 +1561,70 @@ impl Writer { // Cycle through all the components of the vector for index in 0..size { - let component = back::COMPONENTS[index]; // Write the addition to the previous product // This will print an extra '+' at the beginning but that is fine in msl write!(self.out, " + ")?; - // Write the first vector expression, this expression is marked to be - // cached so unless it can't be cached (for example, it's a Constant) - // it shouldn't produce large expressions. - self.put_expression(arg, context, true)?; - // Access the current component on the first vector - write!(self.out, ".{component} * ")?; - // Write the second vector expression, this expression is marked to be - // cached so unless it can't be cached (for example, it's a Constant) - // it shouldn't produce large expressions. - self.put_expression(arg1, context, true)?; - // Access the current component on the second vector - write!(self.out, ".{component}")?; + extractor(self, arg, index)?; + write!(self.out, " * ")?; + extractor(self, arg1, index)?; } write!(self.out, ")")?; Ok(()) } + /// Emit code for the WGSL functions `pack4x{I, U}8[Clamp]`. + fn put_pack4x8( + &mut self, + arg: Handle, + context: &ExpressionContext<'_>, + was_signed: bool, + clamp_bounds: Option<(&str, &str)>, + ) -> Result<(), Error> { + let write_arg = |this: &mut Self| -> BackendResult { + if let Some((min, max)) = clamp_bounds { + // Clamping with scalar bounds works (component-wise) even for packed_[u]char4. + write!(this.out, "{NAMESPACE}::clamp(")?; + this.put_expression(arg, context, true)?; + write!(this.out, ", {min}, {max})")?; + } else { + this.put_expression(arg, context, true)?; + } + Ok(()) + }; + + if context.lang_version >= (2, 1) { + let packed_type = if was_signed { + "packed_char4" + } else { + "packed_uchar4" + }; + // Metal uses little endian byte order, which matches what WGSL expects here. + write!(self.out, "as_type({packed_type}(")?; + write_arg(self)?; + write!(self.out, "))")?; + } else { + // MSL < 2.1 doesn't support `as_type` casting between packed chars and scalars. + if was_signed { + write!(self.out, "uint(")?; + } + write!(self.out, "(")?; + write_arg(self)?; + write!(self.out, "[0] & 0xFF) | ((")?; + write_arg(self)?; + write!(self.out, "[1] & 0xFF) << 8) | ((")?; + write_arg(self)?; + write!(self.out, "[2] & 0xFF) << 16) | ((")?; + write_arg(self)?; + write!(self.out, "[3] & 0xFF) << 24)")?; + if was_signed { + write!(self.out, ")")?; + } + } + + Ok(()) + } + /// Emit code for the isign expression. /// fn put_isign( @@ -1493,13 +1708,31 @@ impl Writer { write!(self.out, "{value}u")?; } crate::Literal::I32(value) => { - write!(self.out, "{value}")?; + // `-2147483648` is parsed as unary negation of positive 2147483648. + // 2147483648 is too large for int32_t meaning the expression gets + // promoted to a int64_t which is not our intention. Avoid this by instead + // using `-2147483647 - 1`. + if value == i32::MIN { + write!(self.out, "({} - 1)", value + 1)?; + } else { + write!(self.out, "{value}")?; + } } crate::Literal::U64(value) => { write!(self.out, "{value}uL")?; } crate::Literal::I64(value) => { - write!(self.out, "{value}L")?; + // `-9223372036854775808` is parsed as unary negation of positive + // 9223372036854775808. 9223372036854775808 is too large for int64_t + // causing Metal to emit a `-Wconstant-conversion` warning, and change the + // value to `-9223372036854775808`. Which would then be negated, possibly + // causing undefined behaviour. Avoid this by instead using + // `-9223372036854775808L - 1L`. + if value == i64::MIN { + write!(self.out, "({}L - 1L)", value + 1)?; + } else { + write!(self.out, "{value}L")?; + } } crate::Literal::Bool(value) => { write!(self.out, "{value}")?; @@ -1641,7 +1874,6 @@ impl Writer { } let expression = &context.function.expressions[expr_handle]; - log::trace!("expression {:?} = {:?}", expr_handle, expression); match *expression { crate::Expression::Literal(_) | crate::Expression::Constant(_) @@ -1677,7 +1909,42 @@ impl Writer { { write!(self.out, " ? ")?; self.put_access_chain(expr_handle, policy, context)?; - write!(self.out, " : DefaultConstructible()")?; + write!(self.out, " : ")?; + + if context.resolve_type(base).pointer_space().is_some() { + // We can't just use `DefaultConstructible` if this is a pointer. + // Instead, we create a dummy local variable to serve as pointer + // target if the access is out of bounds. + let result_ty = context.info[expr_handle] + .ty + .inner_with(&context.module.types) + .pointer_base_type(); + let result_ty_handle = match result_ty { + Some(TypeResolution::Handle(handle)) => handle, + Some(TypeResolution::Value(_)) => { + // As long as the result of a pointer access expression is + // passed to a function or stored in a let binding, the + // type will be in the arena. If additional uses of + // pointers become valid, this assumption might no longer + // hold. Note that the LHS of a load or store doesn't + // take this path -- there is dedicated code in `put_load` + // and `put_store`. + unreachable!( + "Expected type {result_ty:?} of access through pointer type {base:?} to be in the arena", + ); + } + None => { + unreachable!( + "Expected access through pointer type {base:?} to return a pointer, but got {result_ty:?}", + ) + } + }; + let name_key = + NameKey::oob_local_for_type(context.origin, result_ty_handle); + self.out.write_str(&self.names[&name_key])?; + } else { + write!(self.out, "DefaultConstructible()")?; + } if !is_scoped { write!(self.out, ")")?; @@ -1717,18 +1984,30 @@ impl Writer { write!(self.out, "{name}")?; } crate::Expression::LocalVariable(handle) => { - let name_key = match context.origin { - FunctionOrigin::Handle(fun_handle) => { - NameKey::FunctionLocal(fun_handle, handle) - } - FunctionOrigin::EntryPoint(ep_index) => { - NameKey::EntryPointLocal(ep_index, handle) - } - }; + let name_key = NameKey::local(context.origin, handle); let name = &self.names[&name_key]; write!(self.out, "{name}")?; } crate::Expression::Load { pointer } => self.put_load(pointer, context, is_scoped)?, + crate::Expression::ImageSample { + coordinate, + image, + sampler, + clamp_to_edge: true, + gather: None, + array_index: None, + offset: None, + level: crate::SampleLevel::Zero, + depth_ref: None, + } => { + write!(self.out, "{IMAGE_SAMPLE_BASE_CLAMP_TO_EDGE_FUNCTION}(")?; + self.put_expression(image, context, true)?; + write!(self.out, ", ")?; + self.put_expression(sampler, context, true)?; + write!(self.out, ", ")?; + self.put_expression(coordinate, context, true)?; + write!(self.out, ")")?; + } crate::Expression::ImageSample { image, sampler, @@ -1738,7 +2017,14 @@ impl Writer { offset, level, depth_ref, + clamp_to_edge, } => { + if clamp_to_edge { + return Err(Error::GenericValidation( + "ImageSample::clamp_to_edge should have been validated out".to_string(), + )); + } + let main_op = match gather { Some(_) => "gather", None => "sample", @@ -2054,12 +2340,74 @@ impl Writer { .. } => "dot", crate::TypeInner::Vector { size, .. } => { - return self.put_dot_product(arg, arg1.unwrap(), size as usize, context) + return self.put_dot_product( + arg, + arg1.unwrap(), + size as usize, + |writer, arg, index| { + // Write the vector expression; this expression is marked to be + // cached so unless it can't be cached (for example, it's a Constant) + // it shouldn't produce large expressions. + writer.put_expression(arg, context, true)?; + // Access the current component on the vector. + write!(writer.out, ".{}", back::COMPONENTS[index])?; + Ok(()) + }, + ); } _ => unreachable!( "Correct TypeInner for dot product should be already validated" ), }, + fun @ (Mf::Dot4I8Packed | Mf::Dot4U8Packed) => { + if context.lang_version >= (2, 1) { + // Write potentially optimizable code using `packed_(u?)char4`. + // The two function arguments were already reinterpreted as packed (signed + // or unsigned) chars in `Self::put_block`. + let packed_type = match fun { + Mf::Dot4I8Packed => "packed_char4", + Mf::Dot4U8Packed => "packed_uchar4", + _ => unreachable!(), + }; + + return self.put_dot_product( + Reinterpreted::new(packed_type, arg), + Reinterpreted::new(packed_type, arg1.unwrap()), + 4, + |writer, arg, index| { + // MSL implicitly promotes these (signed or unsigned) chars to + // `int` or `uint` in the multiplication, so no overflow can occur. + write!(writer.out, "{arg}[{index}]")?; + Ok(()) + }, + ); + } else { + // Fall back to a polyfill since MSL < 2.1 doesn't seem to support + // bitcasting from uint to `packed_char4` or `packed_uchar4`. + // See . + let conversion = match fun { + Mf::Dot4I8Packed => "int", + Mf::Dot4U8Packed => "", + _ => unreachable!(), + }; + + return self.put_dot_product( + arg, + arg1.unwrap(), + 4, + |writer, arg, index| { + write!(writer.out, "({conversion}(")?; + writer.put_expression(arg, context, true)?; + if index == 3 { + write!(writer.out, ") >> 24)")?; + } else { + write!(writer.out, ") << {} >> 24)", (3 - index) * 8)?; + } + Ok(()) + }, + ); + } + } Mf::Outer => return Err(Error::UnsupportedCall(format!("{fun:?}"))), Mf::Cross => "cross", Mf::Distance => "distance", @@ -2103,6 +2451,8 @@ impl Writer { Mf::Pack2x16float => "", Mf::Pack4xI8 => "", Mf::Pack4xU8 => "", + Mf::Pack4xI8Clamp => "", + Mf::Pack4xU8Clamp => "", // data unpacking Mf::Unpack4x8snorm => "unpack_snorm4x8_to_float", Mf::Unpack4x8unorm => "unpack_unorm4x8_to_float", @@ -2267,38 +2617,41 @@ impl Writer { write!(self.out, "{fun_name}")?; self.put_call_parameters(iter::once(arg), context)?; } - fun @ (Mf::Pack4xI8 | Mf::Pack4xU8) => { - let was_signed = fun == Mf::Pack4xI8; - if was_signed { - write!(self.out, "uint(")?; - } - write!(self.out, "(")?; - self.put_expression(arg, context, true)?; - write!(self.out, "[0] & 0xFF) | ((")?; - self.put_expression(arg, context, true)?; - write!(self.out, "[1] & 0xFF) << 8) | ((")?; - self.put_expression(arg, context, true)?; - write!(self.out, "[2] & 0xFF) << 16) | ((")?; - self.put_expression(arg, context, true)?; - write!(self.out, "[3] & 0xFF) << 24)")?; - if was_signed { - write!(self.out, ")")?; - } + Mf::Pack4xI8 => self.put_pack4x8(arg, context, true, None)?, + Mf::Pack4xU8 => self.put_pack4x8(arg, context, false, None)?, + Mf::Pack4xI8Clamp => { + self.put_pack4x8(arg, context, true, Some(("-128", "127")))? + } + Mf::Pack4xU8Clamp => { + self.put_pack4x8(arg, context, false, Some(("0", "255")))? } fun @ (Mf::Unpack4xI8 | Mf::Unpack4xU8) => { - write!(self.out, "(")?; - if matches!(fun, Mf::Unpack4xU8) { - write!(self.out, "u")?; + let sign_prefix = if matches!(fun, Mf::Unpack4xU8) { + "u" + } else { + "" + }; + + if context.lang_version >= (2, 1) { + // Metal uses little endian byte order, which matches what WGSL expects here. + write!( + self.out, + "{sign_prefix}int4(as_type(" + )?; + self.put_expression(arg, context, true)?; + write!(self.out, "))")?; + } else { + // MSL < 2.1 doesn't support `as_type` casting between packed chars and scalars. + write!(self.out, "({sign_prefix}int4(")?; + self.put_expression(arg, context, true)?; + write!(self.out, ", ")?; + self.put_expression(arg, context, true)?; + write!(self.out, " >> 8, ")?; + self.put_expression(arg, context, true)?; + write!(self.out, " >> 16, ")?; + self.put_expression(arg, context, true)?; + write!(self.out, " >> 24) << 24 >> 24)")?; } - write!(self.out, "int4(")?; - self.put_expression(arg, context, true)?; - write!(self.out, ", ")?; - self.put_expression(arg, context, true)?; - write!(self.out, " >> 8, ")?; - self.put_expression(arg, context, true)?; - write!(self.out, " >> 16, ")?; - self.put_expression(arg, context, true)?; - write!(self.out, " >> 24) << 24 >> 24)")?; } Mf::QuantizeToF16 => { match *context.resolve_type(arg) { @@ -2628,68 +2981,44 @@ impl Writer { #[allow(unused_variables)] fn put_bounds_checks( &mut self, - mut chain: Handle, + chain: Handle, context: &ExpressionContext, level: back::Level, prefix: &'static str, ) -> Result { let mut check_written = false; - // Iterate over the access chain, handling each expression. - loop { - // Produce a `GuardedIndex`, so we can shared code between the - // `Access` and `AccessIndex` cases. - let (base, guarded_index) = match context.function.expressions[chain] { - crate::Expression::Access { base, index } => { - (base, Some(index::GuardedIndex::Expression(index))) - } - crate::Expression::AccessIndex { base, index } => { - // Don't try to check indices into structs. Validation already took - // care of them, and index::needs_guard doesn't handle that case. - let mut base_inner = context.resolve_type(base); - if let crate::TypeInner::Pointer { base, .. } = *base_inner { - base_inner = &context.module.types[base].inner; - } - match *base_inner { - crate::TypeInner::Struct { .. } => (base, None), - _ => (base, Some(index::GuardedIndex::Known(index))), - } - } - _ => break, - }; + // Iterate over the access chain, handling each required bounds check. + for item in context.bounds_check_iter(chain) { + let BoundsCheck { + base, + index, + length, + } = item; - if let Some(index) = guarded_index { - if let Some(length) = context.access_needs_check(base, index) { - if check_written { - write!(self.out, " && ")?; - } else { - write!(self.out, "{level}{prefix}")?; - check_written = true; - } - - // Check that the index falls within bounds. Do this with a single - // comparison, by casting the index to `uint` first, so that negative - // indices become large positive values. - write!(self.out, "uint(")?; - self.put_index(index, context, true)?; - self.out.write_str(") < ")?; - match length { - index::IndexableLength::Known(value) => write!(self.out, "{value}")?, - index::IndexableLength::Dynamic => { - let global = - context.function.originating_global(base).ok_or_else(|| { - Error::GenericValidation( - "Could not find originating global".into(), - ) - })?; - write!(self.out, "1 + ")?; - self.put_dynamic_array_max_index(global, context)? - } - } - } + if check_written { + write!(self.out, " && ")?; + } else { + write!(self.out, "{level}{prefix}")?; + check_written = true; } - chain = base + // Check that the index falls within bounds. Do this with a single + // comparison, by casting the index to `uint` first, so that negative + // indices become large positive values. + write!(self.out, "uint(")?; + self.put_index(index, context, true)?; + self.out.write_str(") < ")?; + match length { + index::IndexableLength::Known(value) => write!(self.out, "{value}")?, + index::IndexableLength::Dynamic => { + let global = context.function.originating_global(base).ok_or_else(|| { + Error::GenericValidation("Could not find originating global".into()) + })?; + write!(self.out, "1 + ")?; + self.put_dynamic_array_max_index(global, context)? + } + } } Ok(check_written) @@ -3061,12 +3390,24 @@ impl Writer { } } } - crate::MathFunction::FirstLeadingBit - | crate::MathFunction::Pack4xI8 + crate::MathFunction::Dot4U8Packed | crate::MathFunction::Dot4I8Packed => { + self.need_bake_expressions.insert(arg); + self.need_bake_expressions.insert(arg1.unwrap()); + } + crate::MathFunction::FirstLeadingBit => { + self.need_bake_expressions.insert(arg); + } + crate::MathFunction::Pack4xI8 | crate::MathFunction::Pack4xU8 + | crate::MathFunction::Pack4xI8Clamp + | crate::MathFunction::Pack4xU8Clamp | crate::MathFunction::Unpack4xI8 | crate::MathFunction::Unpack4xU8 => { - self.need_bake_expressions.insert(arg); + // On MSL < 2.1, we emit a polyfill for these functions that uses the + // argument multiple times. This is no longer necessary on MSL >= 2.1. + if context.lang_version < (2, 1) { + self.need_bake_expressions.insert(arg); + } } crate::MathFunction::ExtractBits => { // Only argument 1 is re-used. @@ -3123,7 +3464,7 @@ impl Writer { put_numeric_type(&mut self.out, scalar, &[rows, columns])?; } TypeResolution::Value(ref other) => { - log::warn!("Type {:?} isn't a known local", other); //TEMP! + log::warn!("Type {other:?} isn't a known local"); //TEMP! return Err(Error::FeatureNotImplemented("weird local type".to_string())); } } @@ -3179,6 +3520,38 @@ impl Writer { Ok(()) } + /// Convert the arguments of `Dot4{I, U}Packed` to `packed_(u?)char4`. + /// + /// Caches the results in temporary variables (whose names are derived from + /// the original variable names). This caching avoids the need to redo the + /// casting for each vector component when emitting the dot product. + fn put_casting_to_packed_chars( + &mut self, + fun: crate::MathFunction, + arg0: Handle, + arg1: Handle, + indent: back::Level, + context: &StatementContext<'_>, + ) -> Result<(), Error> { + let packed_type = match fun { + crate::MathFunction::Dot4I8Packed => "packed_char4", + crate::MathFunction::Dot4U8Packed => "packed_uchar4", + _ => unreachable!(), + }; + + for arg in [arg0, arg1] { + write!( + self.out, + "{indent}{packed_type} {0} = as_type<{packed_type}>(", + Reinterpreted::new(packed_type, arg) + )?; + self.put_expression(arg, &context.expression, true)?; + writeln!(self.out, ");")?; + } + + Ok(()) + } + fn put_block( &mut self, level: back::Level, @@ -3195,17 +3568,45 @@ impl Writer { match *statement { crate::Statement::Emit(ref range) => { for handle in range.clone() { - // `ImageLoad` expressions covered by the `Restrict` bounds check policy - // may need to cache a clamped version of their level-of-detail argument. - if let crate::Expression::ImageLoad { - image, - level: mip_level, - .. - } = context.expression.function.expressions[handle] - { - self.put_cache_restricted_level( - handle, image, mip_level, level, context, - )?; + use crate::MathFunction as Mf; + + match context.expression.function.expressions[handle] { + // `ImageLoad` expressions covered by the `Restrict` bounds check policy + // may need to cache a clamped version of their level-of-detail argument. + crate::Expression::ImageLoad { + image, + level: mip_level, + .. + } => { + self.put_cache_restricted_level( + handle, image, mip_level, level, context, + )?; + } + + // If we are going to write a `Dot4I8Packed` or `Dot4U8Packed` on Metal + // 2.1+ then we introduce two intermediate variables that recast the two + // arguments as packed (signed or unsigned) chars. The actual dot product + // is implemented in `Self::put_expression`, and it uses both of these + // intermediate variables multiple times. There's no danger that the + // original arguments get modified between the definition of these + // intermediate variables and the implementation of the actual dot + // product since we require the inputs of `Dot4{I, U}Packed` to be baked. + crate::Expression::Math { + fun: fun @ (Mf::Dot4I8Packed | Mf::Dot4U8Packed), + arg, + arg1, + .. + } if context.expression.lang_version >= (2, 1) => { + self.put_casting_to_packed_chars( + fun, + arg, + arg1.unwrap(), + level, + context, + )?; + } + + _ => (), } let ptr_class = context.expression.resolve_type(handle).pointer_space(); @@ -3374,7 +3775,8 @@ impl Writer { crate::Statement::Kill => { writeln!(self.out, "{level}{NAMESPACE}::discard_fragment();")?; } - crate::Statement::Barrier(flags) => { + crate::Statement::ControlBarrier(flags) + | crate::Statement::MemoryBarrier(flags) => { self.write_barrier(flags, level)?; } crate::Statement::Store { pointer, value } => { @@ -3661,6 +4063,14 @@ impl Writer { } } } + // TODO: write emitters for these + crate::Statement::MeshFunction(crate::MeshFunction::SetMeshOutputs { .. }) => { + unimplemented!() + } + crate::Statement::MeshFunction( + crate::MeshFunction::SetVertex { .. } + | crate::MeshFunction::SetPrimitive { .. }, + ) => unimplemented!(), crate::Statement::SubgroupBallot { result, predicate } => { write!(self.out, "{level}")?; let name = self.namer.call(""); @@ -3764,6 +4174,12 @@ impl Writer { crate::GatherMode::ShuffleXor(_) => { write!(self.out, "{NAMESPACE}::simd_shuffle_xor(")?; } + crate::GatherMode::QuadBroadcast(_) => { + write!(self.out, "{NAMESPACE}::quad_broadcast(")?; + } + crate::GatherMode::QuadSwap(_) => { + write!(self.out, "{NAMESPACE}::quad_shuffle_xor(")?; + } } self.put_expression(argument, &context.expression, true)?; match mode { @@ -3772,10 +4188,25 @@ impl Writer { | crate::GatherMode::Shuffle(index) | crate::GatherMode::ShuffleDown(index) | crate::GatherMode::ShuffleUp(index) - | crate::GatherMode::ShuffleXor(index) => { + | crate::GatherMode::ShuffleXor(index) + | crate::GatherMode::QuadBroadcast(index) => { write!(self.out, ", ")?; self.put_expression(index, &context.expression, true)?; } + crate::GatherMode::QuadSwap(direction) => { + write!(self.out, ", ")?; + match direction { + crate::Direction::X => { + write!(self.out, "1u")?; + } + crate::Direction::Y => { + write!(self.out, "2u")?; + } + crate::Direction::Diagonal => { + write!(self.out, "3u")?; + } + } + } } writeln!(self.out, ");")?; } @@ -3859,7 +4290,7 @@ impl Writer { self.namer.reset( module, &super::keywords::RESERVED_SET, - &[], + proc::CaseInsensitiveKeywordSet::empty(), &[CLAMPED_LOD_LOAD_PREFIX], &mut self.names, ); @@ -4007,15 +4438,43 @@ impl Writer { fn write_type_defs(&mut self, module: &crate::Module) -> BackendResult { let mut generated_argument_buffer_wrapper = false; + let mut generated_external_texture_wrapper = false; for (handle, ty) in module.types.iter() { - if let crate::TypeInner::BindingArray { .. } = ty.inner { - if !generated_argument_buffer_wrapper { + match ty.inner { + crate::TypeInner::BindingArray { .. } if !generated_argument_buffer_wrapper => { writeln!(self.out, "template ")?; writeln!(self.out, "struct {ARGUMENT_BUFFER_WRAPPER_STRUCT} {{")?; writeln!(self.out, "{}T {WRAPPED_ARRAY_FIELD};", back::INDENT)?; writeln!(self.out, "}};")?; generated_argument_buffer_wrapper = true; } + crate::TypeInner::Image { + class: crate::ImageClass::External, + .. + } if !generated_external_texture_wrapper => { + let params_ty_name = &self.names + [&NameKey::Type(module.special_types.external_texture_params.unwrap())]; + writeln!(self.out, "struct {EXTERNAL_TEXTURE_WRAPPER_STRUCT} {{")?; + writeln!( + self.out, + "{}{NAMESPACE}::texture2d plane0;", + back::INDENT + )?; + writeln!( + self.out, + "{}{NAMESPACE}::texture2d plane1;", + back::INDENT + )?; + writeln!( + self.out, + "{}{NAMESPACE}::texture2d plane2;", + back::INDENT + )?; + writeln!(self.out, "{}{params_ty_name} params;", back::INDENT)?; + writeln!(self.out, "}};")?; + generated_external_texture_wrapper = true; + } + _ => {} } if !ty.needs_alias() { @@ -4122,6 +4581,16 @@ impl Writer { } } } + if last_offset < span { + let pad = span - last_offset; + writeln!( + self.out, + "{}char _pad{}[{}];", + back::INDENT, + members.len(), + pad + )?; + } writeln!(self.out, "}};")?; } _ => { @@ -4686,14 +5155,14 @@ template let name = self.namer.call("unpackSnorm16x2"); writeln!( self.out, - "metal::float2 {name}(metal::ushort b0, \ - metal::ushort b1, \ - metal::ushort b2, \ - metal::ushort b3) {{" + "metal::float2 {name}(uint b0, \ + uint b1, \ + uint b2, \ + uint b3) {{" )?; writeln!( self.out, - "{}return metal::unpack_snorm2x16_to_float(b1 << 24 | b0 << 16 | b3 << 8 | b2);", + "{}return metal::unpack_snorm2x16_to_float(b3 << 24 | b2 << 16 | b1 << 8 | b0);", back::INDENT )?; writeln!(self.out, "}}")?; @@ -4703,19 +5172,19 @@ template let name = self.namer.call("unpackSnorm16x4"); writeln!( self.out, - "metal::float4 {name}(metal::ushort b0, \ - metal::ushort b1, \ - metal::ushort b2, \ - metal::ushort b3, \ - metal::ushort b4, \ - metal::ushort b5, \ - metal::ushort b6, \ - metal::ushort b7) {{" + "metal::float4 {name}(uint b0, \ + uint b1, \ + uint b2, \ + uint b3, \ + uint b4, \ + uint b5, \ + uint b6, \ + uint b7) {{" )?; writeln!( self.out, - "{}return metal::float4(metal::unpack_snorm2x16_to_float(b1 << 24 | b0 << 16 | b3 << 8 | b2), \ - metal::unpack_snorm2x16_to_float(b5 << 24 | b4 << 16 | b7 << 8 | b6));", + "{}return metal::float4(metal::unpack_snorm2x16_to_float(b3 << 24 | b2 << 16 | b1 << 8 | b0), \ + metal::unpack_snorm2x16_to_float(b7 << 24 | b6 << 16 | b5 << 8 | b4));", back::INDENT )?; writeln!(self.out, "}}")?; @@ -5123,6 +5592,680 @@ template } } + fn write_wrapped_unary_op( + &mut self, + module: &crate::Module, + func_ctx: &back::FunctionCtx, + op: crate::UnaryOperator, + operand: Handle, + ) -> BackendResult { + let operand_ty = func_ctx.resolve_type(operand, &module.types); + match op { + // Negating the TYPE_MIN of a two's complement signed integer + // type causes overflow, which is undefined behaviour in MSL. To + // avoid this we bitcast the value to unsigned and negate it, + // then bitcast back to signed. + // This adheres to the WGSL spec in that the negative of the + // type's minimum value should equal to the minimum value. + crate::UnaryOperator::Negate + if operand_ty.scalar_kind() == Some(crate::ScalarKind::Sint) => + { + let Some((vector_size, scalar)) = operand_ty.vector_size_and_scalar() else { + return Ok(()); + }; + let wrapped = WrappedFunction::UnaryOp { + op, + ty: (vector_size, scalar), + }; + if !self.wrapped_functions.insert(wrapped) { + return Ok(()); + } + + let unsigned_scalar = crate::Scalar { + kind: crate::ScalarKind::Uint, + ..scalar + }; + let mut type_name = String::new(); + let mut unsigned_type_name = String::new(); + match vector_size { + None => { + put_numeric_type(&mut type_name, scalar, &[])?; + put_numeric_type(&mut unsigned_type_name, unsigned_scalar, &[])? + } + Some(size) => { + put_numeric_type(&mut type_name, scalar, &[size])?; + put_numeric_type(&mut unsigned_type_name, unsigned_scalar, &[size])?; + } + }; + + writeln!(self.out, "{type_name} {NEG_FUNCTION}({type_name} val) {{")?; + let level = back::Level(1); + writeln!( + self.out, + "{level}return as_type<{type_name}>(-as_type<{unsigned_type_name}>(val));" + )?; + writeln!(self.out, "}}")?; + writeln!(self.out)?; + } + _ => {} + } + Ok(()) + } + + fn write_wrapped_binary_op( + &mut self, + module: &crate::Module, + func_ctx: &back::FunctionCtx, + expr: Handle, + op: crate::BinaryOperator, + left: Handle, + right: Handle, + ) -> BackendResult { + let expr_ty = func_ctx.resolve_type(expr, &module.types); + let left_ty = func_ctx.resolve_type(left, &module.types); + let right_ty = func_ctx.resolve_type(right, &module.types); + match (op, expr_ty.scalar_kind()) { + // Signed integer division of TYPE_MIN / -1, or signed or + // unsigned division by zero, gives an unspecified value in MSL. + // We override the divisor to 1 in these cases. + // This adheres to the WGSL spec in that: + // * TYPE_MIN / -1 == TYPE_MIN + // * x / 0 == x + ( + crate::BinaryOperator::Divide, + Some(crate::ScalarKind::Sint | crate::ScalarKind::Uint), + ) => { + let Some(left_wrapped_ty) = left_ty.vector_size_and_scalar() else { + return Ok(()); + }; + let Some(right_wrapped_ty) = right_ty.vector_size_and_scalar() else { + return Ok(()); + }; + let wrapped = WrappedFunction::BinaryOp { + op, + left_ty: left_wrapped_ty, + right_ty: right_wrapped_ty, + }; + if !self.wrapped_functions.insert(wrapped) { + return Ok(()); + } + + let Some((vector_size, scalar)) = expr_ty.vector_size_and_scalar() else { + return Ok(()); + }; + let mut type_name = String::new(); + match vector_size { + None => put_numeric_type(&mut type_name, scalar, &[])?, + Some(size) => put_numeric_type(&mut type_name, scalar, &[size])?, + }; + writeln!( + self.out, + "{type_name} {DIV_FUNCTION}({type_name} lhs, {type_name} rhs) {{" + )?; + let level = back::Level(1); + match scalar.kind { + crate::ScalarKind::Sint => { + let min_val = match scalar.width { + 4 => crate::Literal::I32(i32::MIN), + 8 => crate::Literal::I64(i64::MIN), + _ => { + return Err(Error::GenericValidation(format!( + "Unexpected width for scalar {scalar:?}" + ))); + } + }; + write!( + self.out, + "{level}return lhs / metal::select(rhs, 1, (lhs == " + )?; + self.put_literal(min_val)?; + writeln!(self.out, " & rhs == -1) | (rhs == 0));")? + } + crate::ScalarKind::Uint => writeln!( + self.out, + "{level}return lhs / metal::select(rhs, 1u, rhs == 0u);" + )?, + _ => unreachable!(), + } + writeln!(self.out, "}}")?; + writeln!(self.out)?; + } + // Integer modulo where one or both operands are negative, or the + // divisor is zero, is undefined behaviour in MSL. To avoid this + // we use the following equation: + // + // dividend - (dividend / divisor) * divisor + // + // overriding the divisor to 1 if either it is 0, or it is -1 + // and the dividend is TYPE_MIN. + // + // This adheres to the WGSL spec in that: + // * TYPE_MIN % -1 == 0 + // * x % 0 == 0 + ( + crate::BinaryOperator::Modulo, + Some(crate::ScalarKind::Sint | crate::ScalarKind::Uint), + ) => { + let Some(left_wrapped_ty) = left_ty.vector_size_and_scalar() else { + return Ok(()); + }; + let Some((right_vector_size, right_scalar)) = right_ty.vector_size_and_scalar() + else { + return Ok(()); + }; + let wrapped = WrappedFunction::BinaryOp { + op, + left_ty: left_wrapped_ty, + right_ty: (right_vector_size, right_scalar), + }; + if !self.wrapped_functions.insert(wrapped) { + return Ok(()); + } + + let Some((vector_size, scalar)) = expr_ty.vector_size_and_scalar() else { + return Ok(()); + }; + let mut type_name = String::new(); + match vector_size { + None => put_numeric_type(&mut type_name, scalar, &[])?, + Some(size) => put_numeric_type(&mut type_name, scalar, &[size])?, + }; + let mut rhs_type_name = String::new(); + match right_vector_size { + None => put_numeric_type(&mut rhs_type_name, right_scalar, &[])?, + Some(size) => put_numeric_type(&mut rhs_type_name, right_scalar, &[size])?, + }; + + writeln!( + self.out, + "{type_name} {MOD_FUNCTION}({type_name} lhs, {type_name} rhs) {{" + )?; + let level = back::Level(1); + match scalar.kind { + crate::ScalarKind::Sint => { + let min_val = match scalar.width { + 4 => crate::Literal::I32(i32::MIN), + 8 => crate::Literal::I64(i64::MIN), + _ => { + return Err(Error::GenericValidation(format!( + "Unexpected width for scalar {scalar:?}" + ))); + } + }; + write!( + self.out, + "{level}{rhs_type_name} divisor = metal::select(rhs, 1, (lhs == " + )?; + self.put_literal(min_val)?; + writeln!(self.out, " & rhs == -1) | (rhs == 0));")?; + writeln!(self.out, "{level}return lhs - (lhs / divisor) * divisor;")? + } + crate::ScalarKind::Uint => writeln!( + self.out, + "{level}return lhs % metal::select(rhs, 1u, rhs == 0u);" + )?, + _ => unreachable!(), + } + writeln!(self.out, "}}")?; + writeln!(self.out)?; + } + _ => {} + } + Ok(()) + } + + #[allow(clippy::too_many_arguments)] + fn write_wrapped_math_function( + &mut self, + module: &crate::Module, + func_ctx: &back::FunctionCtx, + fun: crate::MathFunction, + arg: Handle, + _arg1: Option>, + _arg2: Option>, + _arg3: Option>, + ) -> BackendResult { + let arg_ty = func_ctx.resolve_type(arg, &module.types); + match fun { + // Taking the absolute value of the TYPE_MIN of a two's + // complement signed integer type causes overflow, which is + // undefined behaviour in MSL. To avoid this, when the value is + // negative we bitcast the value to unsigned and negate it, then + // bitcast back to signed. + // This adheres to the WGSL spec in that the absolute of the + // type's minimum value should equal to the minimum value. + crate::MathFunction::Abs if arg_ty.scalar_kind() == Some(crate::ScalarKind::Sint) => { + let Some((vector_size, scalar)) = arg_ty.vector_size_and_scalar() else { + return Ok(()); + }; + let wrapped = WrappedFunction::Math { + fun, + arg_ty: (vector_size, scalar), + }; + if !self.wrapped_functions.insert(wrapped) { + return Ok(()); + } + + let unsigned_scalar = crate::Scalar { + kind: crate::ScalarKind::Uint, + ..scalar + }; + let mut type_name = String::new(); + let mut unsigned_type_name = String::new(); + match vector_size { + None => { + put_numeric_type(&mut type_name, scalar, &[])?; + put_numeric_type(&mut unsigned_type_name, unsigned_scalar, &[])? + } + Some(size) => { + put_numeric_type(&mut type_name, scalar, &[size])?; + put_numeric_type(&mut unsigned_type_name, unsigned_scalar, &[size])?; + } + }; + + writeln!(self.out, "{type_name} {ABS_FUNCTION}({type_name} val) {{")?; + let level = back::Level(1); + writeln!(self.out, "{level}return metal::select(as_type<{type_name}>(-as_type<{unsigned_type_name}>(val)), val, val >= 0);")?; + writeln!(self.out, "}}")?; + writeln!(self.out)?; + } + _ => {} + } + Ok(()) + } + + fn write_wrapped_cast( + &mut self, + module: &crate::Module, + func_ctx: &back::FunctionCtx, + expr: Handle, + kind: crate::ScalarKind, + convert: Option, + ) -> BackendResult { + // Avoid undefined behaviour when casting from a float to integer + // when the value is out of range for the target type. Additionally + // ensure we clamp to the correct value as per the WGSL spec. + // + // https://www.w3.org/TR/WGSL/#floating-point-conversion: + // * If X is exactly representable in the target type T, then the + // result is that value. + // * Otherwise, the result is the value in T closest to + // truncate(X) and also exactly representable in the original + // floating point type. + let src_ty = func_ctx.resolve_type(expr, &module.types); + let Some(width) = convert else { + return Ok(()); + }; + let Some((vector_size, src_scalar)) = src_ty.vector_size_and_scalar() else { + return Ok(()); + }; + let dst_scalar = crate::Scalar { kind, width }; + if src_scalar.kind != crate::ScalarKind::Float + || (dst_scalar.kind != crate::ScalarKind::Sint + && dst_scalar.kind != crate::ScalarKind::Uint) + { + return Ok(()); + } + let wrapped = WrappedFunction::Cast { + src_scalar, + vector_size, + dst_scalar, + }; + if !self.wrapped_functions.insert(wrapped) { + return Ok(()); + } + let (min, max) = proc::min_max_float_representable_by(src_scalar, dst_scalar); + + let mut src_type_name = String::new(); + match vector_size { + None => put_numeric_type(&mut src_type_name, src_scalar, &[])?, + Some(size) => put_numeric_type(&mut src_type_name, src_scalar, &[size])?, + }; + let mut dst_type_name = String::new(); + match vector_size { + None => put_numeric_type(&mut dst_type_name, dst_scalar, &[])?, + Some(size) => put_numeric_type(&mut dst_type_name, dst_scalar, &[size])?, + }; + let fun_name = match dst_scalar { + crate::Scalar::I32 => F2I32_FUNCTION, + crate::Scalar::U32 => F2U32_FUNCTION, + crate::Scalar::I64 => F2I64_FUNCTION, + crate::Scalar::U64 => F2U64_FUNCTION, + _ => unreachable!(), + }; + + writeln!( + self.out, + "{dst_type_name} {fun_name}({src_type_name} value) {{" + )?; + let level = back::Level(1); + write!( + self.out, + "{level}return static_cast<{dst_type_name}>({NAMESPACE}::clamp(value, " + )?; + self.put_literal(min)?; + write!(self.out, ", ")?; + self.put_literal(max)?; + writeln!(self.out, "));")?; + writeln!(self.out, "}}")?; + writeln!(self.out)?; + Ok(()) + } + + /// Helper function used by [`Self::write_wrapped_image_load`] and + /// [`Self::write_wrapped_image_sample`] to write the shared YUV to RGB + /// conversion code for external textures. Expects the preceding code to + /// declare the Y component as a `float` variable of name `y`, the UV + /// components as a `float2` variable of name `uv`, and the external + /// texture params as a variable of name `params`. The emitted code will + /// return the result. + fn write_convert_yuv_to_rgb_and_return( + &mut self, + level: back::Level, + y: &str, + uv: &str, + params: &str, + ) -> BackendResult { + let l1 = level; + let l2 = l1.next(); + + // Convert from YUV to non-linear RGB in the source color space. + writeln!( + self.out, + "{l1}float3 srcGammaRgb = ({params}.yuv_conversion_matrix * float4({y}, {uv}, 1.0)).rgb;" + )?; + + // Apply the inverse of the source transfer function to convert to + // linear RGB in the source color space. + writeln!(self.out, "{l1}float3 srcLinearRgb = {NAMESPACE}::select(")?; + writeln!(self.out, "{l2}{NAMESPACE}::pow((srcGammaRgb + {params}.src_tf.a - 1.0) / {params}.src_tf.a, {params}.src_tf.g),")?; + writeln!(self.out, "{l2}srcGammaRgb / {params}.src_tf.k,")?; + writeln!( + self.out, + "{l2}srcGammaRgb < {params}.src_tf.k * {params}.src_tf.b);" + )?; + + // Multiply by the gamut conversion matrix to convert to linear RGB in + // the destination color space. + writeln!( + self.out, + "{l1}float3 dstLinearRgb = {params}.gamut_conversion_matrix * srcLinearRgb;" + )?; + + // Finally, apply the dest transfer function to convert to non-linear + // RGB in the destination color space, and return the result. + writeln!(self.out, "{l1}float3 dstGammaRgb = {NAMESPACE}::select(")?; + writeln!(self.out, "{l2}{params}.dst_tf.a * {NAMESPACE}::pow(dstLinearRgb, 1.0 / {params}.dst_tf.g) - ({params}.dst_tf.a - 1),")?; + writeln!(self.out, "{l2}{params}.dst_tf.k * dstLinearRgb,")?; + writeln!(self.out, "{l2}dstLinearRgb < {params}.dst_tf.b);")?; + + writeln!(self.out, "{l1}return float4(dstGammaRgb, 1.0);")?; + Ok(()) + } + + #[allow(clippy::too_many_arguments)] + fn write_wrapped_image_load( + &mut self, + module: &crate::Module, + func_ctx: &back::FunctionCtx, + image: Handle, + _coordinate: Handle, + _array_index: Option>, + _sample: Option>, + _level: Option>, + ) -> BackendResult { + // We currently only need to wrap image loads for external textures + let class = match *func_ctx.resolve_type(image, &module.types) { + crate::TypeInner::Image { class, .. } => class, + _ => unreachable!(), + }; + if class != crate::ImageClass::External { + return Ok(()); + } + let wrapped = WrappedFunction::ImageLoad { class }; + if !self.wrapped_functions.insert(wrapped) { + return Ok(()); + } + + writeln!(self.out, "float4 {IMAGE_LOAD_EXTERNAL_FUNCTION}({EXTERNAL_TEXTURE_WRAPPER_STRUCT} tex, uint2 coords) {{")?; + let l1 = back::Level(1); + let l2 = l1.next(); + let l3 = l2.next(); + writeln!( + self.out, + "{l1}uint2 plane0_size = uint2(tex.plane0.get_width(), tex.plane0.get_height());" + )?; + // Clamp coords to provided size of external texture to prevent OOB + // read. If params.size is zero then clamp to the actual size of the + // texture. + writeln!( + self.out, + "{l1}uint2 cropped_size = {NAMESPACE}::any(tex.params.size != 0) ? tex.params.size : plane0_size;" + )?; + writeln!( + self.out, + "{l1}coords = {NAMESPACE}::min(coords, cropped_size - 1);" + )?; + + // Apply load transformation + writeln!(self.out, "{l1}uint2 plane0_coords = uint2({NAMESPACE}::round(tex.params.load_transform * float3(float2(coords), 1.0)));")?; + writeln!(self.out, "{l1}if (tex.params.num_planes == 1u) {{")?; + // For single plane, simply read from plane0 + writeln!(self.out, "{l2}return tex.plane0.read(plane0_coords);")?; + writeln!(self.out, "{l1}}} else {{")?; + + // Chroma planes may be subsampled so we must scale the coords accordingly. + writeln!( + self.out, + "{l2}uint2 plane1_size = uint2(tex.plane1.get_width(), tex.plane1.get_height());" + )?; + writeln!(self.out, "{l2}uint2 plane1_coords = uint2({NAMESPACE}::floor(float2(plane0_coords) * float2(plane1_size) / float2(plane0_size)));")?; + + // For multi-plane, read the Y value from plane 0 + writeln!(self.out, "{l2}float y = tex.plane0.read(plane0_coords).x;")?; + + writeln!(self.out, "{l2}float2 uv;")?; + writeln!(self.out, "{l2}if (tex.params.num_planes == 2u) {{")?; + // For 2 planes, read UV from interleaved plane 1 + writeln!(self.out, "{l3}uv = tex.plane1.read(plane1_coords).xy;")?; + writeln!(self.out, "{l2}}} else {{")?; + // For 3 planes, read U and V from planes 1 and 2 respectively + writeln!( + self.out, + "{l2}uint2 plane2_size = uint2(tex.plane2.get_width(), tex.plane2.get_height());" + )?; + writeln!(self.out, "{l2}uint2 plane2_coords = uint2({NAMESPACE}::floor(float2(plane0_coords) * float2(plane2_size) / float2(plane0_size)));")?; + writeln!( + self.out, + "{l3}uv = float2(tex.plane1.read(plane1_coords).x, tex.plane2.read(plane2_coords).x);" + )?; + writeln!(self.out, "{l2}}}")?; + + self.write_convert_yuv_to_rgb_and_return(l2, "y", "uv", "tex.params")?; + + writeln!(self.out, "{l1}}}")?; + writeln!(self.out, "}}")?; + writeln!(self.out)?; + Ok(()) + } + + #[allow(clippy::too_many_arguments)] + fn write_wrapped_image_sample( + &mut self, + module: &crate::Module, + func_ctx: &back::FunctionCtx, + image: Handle, + _sampler: Handle, + _gather: Option, + _coordinate: Handle, + _array_index: Option>, + _offset: Option>, + _level: crate::SampleLevel, + _depth_ref: Option>, + clamp_to_edge: bool, + ) -> BackendResult { + // We currently only need to wrap textureSampleBaseClampToEdge, for + // both sampled and external textures. + if !clamp_to_edge { + return Ok(()); + } + let class = match *func_ctx.resolve_type(image, &module.types) { + crate::TypeInner::Image { class, .. } => class, + _ => unreachable!(), + }; + let wrapped = WrappedFunction::ImageSample { + class, + clamp_to_edge: true, + }; + if !self.wrapped_functions.insert(wrapped) { + return Ok(()); + } + match class { + crate::ImageClass::External => { + writeln!(self.out, "float4 {IMAGE_SAMPLE_BASE_CLAMP_TO_EDGE_FUNCTION}({EXTERNAL_TEXTURE_WRAPPER_STRUCT} tex, {NAMESPACE}::sampler samp, float2 coords) {{")?; + let l1 = back::Level(1); + let l2 = l1.next(); + let l3 = l2.next(); + writeln!(self.out, "{l1}uint2 plane0_size = uint2(tex.plane0.get_width(), tex.plane0.get_height());")?; + writeln!( + self.out, + "{l1}coords = tex.params.sample_transform * float3(coords, 1.0);" + )?; + + // Calculate the sample bounds. The purported size of the texture + // (params.size) is irrelevant here as we are dealing with normalized + // coordinates. Usually we would clamp to (0,0)..(1,1). However, we must + // apply the sample transformation to that, also bearing in mind that it + // may contain a flip on either axis. We calculate and adjust for the + // half-texel separately for each plane as it depends on the actual + // texture size which may vary between planes. + writeln!( + self.out, + "{l1}float2 bounds_min = tex.params.sample_transform * float3(0.0, 0.0, 1.0);" + )?; + writeln!( + self.out, + "{l1}float2 bounds_max = tex.params.sample_transform * float3(1.0, 1.0, 1.0);" + )?; + writeln!(self.out, "{l1}float4 bounds = float4({NAMESPACE}::min(bounds_min, bounds_max), {NAMESPACE}::max(bounds_min, bounds_max));")?; + writeln!( + self.out, + "{l1}float2 plane0_half_texel = float2(0.5, 0.5) / float2(plane0_size);" + )?; + writeln!( + self.out, + "{l1}float2 plane0_coords = {NAMESPACE}::clamp(coords, bounds.xy + plane0_half_texel, bounds.zw - plane0_half_texel);" + )?; + writeln!(self.out, "{l1}if (tex.params.num_planes == 1u) {{")?; + // For single plane, simply sample from plane0 + writeln!( + self.out, + "{l2}return tex.plane0.sample(samp, plane0_coords, {NAMESPACE}::level(0.0f));" + )?; + writeln!(self.out, "{l1}}} else {{")?; + writeln!(self.out, "{l2}uint2 plane1_size = uint2(tex.plane1.get_width(), tex.plane1.get_height());")?; + writeln!( + self.out, + "{l2}float2 plane1_half_texel = float2(0.5, 0.5) / float2(plane1_size);" + )?; + writeln!( + self.out, + "{l2}float2 plane1_coords = {NAMESPACE}::clamp(coords, bounds.xy + plane1_half_texel, bounds.zw - plane1_half_texel);" + )?; + + // For multi-plane, sample the Y value from plane 0 + writeln!( + self.out, + "{l2}float y = tex.plane0.sample(samp, plane0_coords, {NAMESPACE}::level(0.0f)).r;" + )?; + writeln!(self.out, "{l2}float2 uv = float2(0.0, 0.0);")?; + writeln!(self.out, "{l2}if (tex.params.num_planes == 2u) {{")?; + // For 2 planes, sample UV from interleaved plane 1 + writeln!( + self.out, + "{l3}uv = tex.plane1.sample(samp, plane1_coords, {NAMESPACE}::level(0.0f)).xy;" + )?; + writeln!(self.out, "{l2}}} else {{")?; + // For 3 planes, sample U and V from planes 1 and 2 respectively + writeln!(self.out, "{l3}uint2 plane2_size = uint2(tex.plane2.get_width(), tex.plane2.get_height());")?; + writeln!( + self.out, + "{l3}float2 plane2_half_texel = float2(0.5, 0.5) / float2(plane2_size);" + )?; + writeln!( + self.out, + "{l3}float2 plane2_coords = {NAMESPACE}::clamp(coords, bounds.xy + plane2_half_texel, bounds.zw - plane1_half_texel);" + )?; + writeln!(self.out, "{l3}uv.x = tex.plane1.sample(samp, plane1_coords, {NAMESPACE}::level(0.0f)).x;")?; + writeln!(self.out, "{l3}uv.y = tex.plane2.sample(samp, plane2_coords, {NAMESPACE}::level(0.0f)).x;")?; + writeln!(self.out, "{l2}}}")?; + + self.write_convert_yuv_to_rgb_and_return(l2, "y", "uv", "tex.params")?; + + writeln!(self.out, "{l1}}}")?; + writeln!(self.out, "}}")?; + writeln!(self.out)?; + } + _ => { + writeln!(self.out, "{NAMESPACE}::float4 {IMAGE_SAMPLE_BASE_CLAMP_TO_EDGE_FUNCTION}({NAMESPACE}::texture2d tex, {NAMESPACE}::sampler samp, {NAMESPACE}::float2 coords) {{")?; + let l1 = back::Level(1); + writeln!(self.out, "{l1}{NAMESPACE}::float2 half_texel = 0.5 / {NAMESPACE}::float2(tex.get_width(0u), tex.get_height(0u));")?; + writeln!( + self.out, + "{l1}return tex.sample(samp, {NAMESPACE}::clamp(coords, half_texel, 1.0 - half_texel), {NAMESPACE}::level(0.0));" + )?; + writeln!(self.out, "}}")?; + writeln!(self.out)?; + } + } + Ok(()) + } + + fn write_wrapped_image_query( + &mut self, + module: &crate::Module, + func_ctx: &back::FunctionCtx, + image: Handle, + query: crate::ImageQuery, + ) -> BackendResult { + // We currently only need to wrap size image queries for external textures + if !matches!(query, crate::ImageQuery::Size { .. }) { + return Ok(()); + } + let class = match *func_ctx.resolve_type(image, &module.types) { + crate::TypeInner::Image { class, .. } => class, + _ => unreachable!(), + }; + if class != crate::ImageClass::External { + return Ok(()); + } + let wrapped = WrappedFunction::ImageQuerySize { class }; + if !self.wrapped_functions.insert(wrapped) { + return Ok(()); + } + writeln!( + self.out, + "uint2 {IMAGE_SIZE_EXTERNAL_FUNCTION}({EXTERNAL_TEXTURE_WRAPPER_STRUCT} tex) {{" + )?; + let l1 = back::Level(1); + let l2 = l1.next(); + writeln!( + self.out, + "{l1}if ({NAMESPACE}::any(tex.params.size != uint2(0u))) {{" + )?; + writeln!(self.out, "{l2}return tex.params.size;")?; + writeln!(self.out, "{l1}}} else {{")?; + // params.size == (0, 0) indicates to query and return plane 0's actual size + writeln!( + self.out, + "{l2}return uint2(tex.plane0.get_width(), tex.plane0.get_height());" + )?; + writeln!(self.out, "{l1}}}")?; + writeln!(self.out, "}}")?; + writeln!(self.out)?; + Ok(()) + } + pub(super) fn write_wrapped_functions( &mut self, module: &crate::Module, @@ -5131,323 +6274,71 @@ template for (expr_handle, expr) in func_ctx.expressions.iter() { match *expr { crate::Expression::Unary { op, expr: operand } => { - let operand_ty = func_ctx.resolve_type(operand, &module.types); - match op { - // Negating the TYPE_MIN of a two's complement signed integer - // type causes overflow, which is undefined behaviour in MSL. To - // avoid this we bitcast the value to unsigned and negate it, - // then bitcast back to signed. - // This adheres to the WGSL spec in that the negative of the - // type's minimum value should equal to the minimum value. - crate::UnaryOperator::Negate - if operand_ty.scalar_kind() == Some(crate::ScalarKind::Sint) => - { - let Some((vector_size, scalar)) = operand_ty.vector_size_and_scalar() - else { - continue; - }; - let wrapped = WrappedFunction::UnaryOp { - op, - ty: (vector_size, scalar), - }; - if !self.wrapped_functions.insert(wrapped) { - continue; - } - - let unsigned_scalar = crate::Scalar { - kind: crate::ScalarKind::Uint, - ..scalar - }; - let mut type_name = String::new(); - let mut unsigned_type_name = String::new(); - match vector_size { - None => { - put_numeric_type(&mut type_name, scalar, &[])?; - put_numeric_type(&mut unsigned_type_name, unsigned_scalar, &[])? - } - Some(size) => { - put_numeric_type(&mut type_name, scalar, &[size])?; - put_numeric_type( - &mut unsigned_type_name, - unsigned_scalar, - &[size], - )?; - } - }; - - writeln!(self.out, "{type_name} {NEG_FUNCTION}({type_name} val) {{")?; - let level = back::Level(1); - writeln!(self.out, "{level}return as_type<{type_name}>(-as_type<{unsigned_type_name}>(val));")?; - writeln!(self.out, "}}")?; - writeln!(self.out)?; - } - _ => {} - } + self.write_wrapped_unary_op(module, func_ctx, op, operand)?; } crate::Expression::Binary { op, left, right } => { - let expr_ty = func_ctx.resolve_type(expr_handle, &module.types); - let left_ty = func_ctx.resolve_type(left, &module.types); - let right_ty = func_ctx.resolve_type(right, &module.types); - match (op, expr_ty.scalar_kind()) { - // Signed integer division of TYPE_MIN / -1, or signed or - // unsigned division by zero, gives an unspecified value in MSL. - // We override the divisor to 1 in these cases. - // This adheres to the WGSL spec in that: - // * TYPE_MIN / -1 == TYPE_MIN - // * x / 0 == x - ( - crate::BinaryOperator::Divide, - Some(crate::ScalarKind::Sint | crate::ScalarKind::Uint), - ) => { - let Some(left_wrapped_ty) = left_ty.vector_size_and_scalar() else { - continue; - }; - let Some(right_wrapped_ty) = right_ty.vector_size_and_scalar() else { - continue; - }; - let wrapped = WrappedFunction::BinaryOp { - op, - left_ty: left_wrapped_ty, - right_ty: right_wrapped_ty, - }; - if !self.wrapped_functions.insert(wrapped) { - continue; - } - - let Some((vector_size, scalar)) = expr_ty.vector_size_and_scalar() - else { - continue; - }; - let mut type_name = String::new(); - match vector_size { - None => put_numeric_type(&mut type_name, scalar, &[])?, - Some(size) => put_numeric_type(&mut type_name, scalar, &[size])?, - }; - writeln!( - self.out, - "{type_name} {DIV_FUNCTION}({type_name} lhs, {type_name} rhs) {{" - )?; - let level = back::Level(1); - match scalar.kind { - crate::ScalarKind::Sint => { - let min = -1i64 << (scalar.width as u32 * 8 - 1); - writeln!(self.out, "{level}return lhs / metal::select(rhs, 1, (lhs == {min} & rhs == -1) | (rhs == 0));")? - } - crate::ScalarKind::Uint => writeln!( - self.out, - "{level}return lhs / metal::select(rhs, 1u, rhs == 0u);" - )?, - _ => unreachable!(), - } - writeln!(self.out, "}}")?; - writeln!(self.out)?; - } - // Integer modulo where one or both operands are negative, or the - // divisor is zero, is undefined behaviour in MSL. To avoid this - // we use the following equation: - // - // dividend - (dividend / divisor) * divisor - // - // overriding the divisor to 1 if either it is 0, or it is -1 - // and the dividend is TYPE_MIN. - // - // This adheres to the WGSL spec in that: - // * TYPE_MIN % -1 == 0 - // * x % 0 == 0 - ( - crate::BinaryOperator::Modulo, - Some(crate::ScalarKind::Sint | crate::ScalarKind::Uint), - ) => { - let Some(left_wrapped_ty) = left_ty.vector_size_and_scalar() else { - continue; - }; - let Some((right_vector_size, right_scalar)) = - right_ty.vector_size_and_scalar() - else { - continue; - }; - let wrapped = WrappedFunction::BinaryOp { - op, - left_ty: left_wrapped_ty, - right_ty: (right_vector_size, right_scalar), - }; - if !self.wrapped_functions.insert(wrapped) { - continue; - } - - let Some((vector_size, scalar)) = expr_ty.vector_size_and_scalar() - else { - continue; - }; - let mut type_name = String::new(); - match vector_size { - None => put_numeric_type(&mut type_name, scalar, &[])?, - Some(size) => put_numeric_type(&mut type_name, scalar, &[size])?, - }; - let mut rhs_type_name = String::new(); - match right_vector_size { - None => put_numeric_type(&mut rhs_type_name, right_scalar, &[])?, - Some(size) => { - put_numeric_type(&mut rhs_type_name, right_scalar, &[size])? - } - }; - - writeln!( - self.out, - "{type_name} {MOD_FUNCTION}({type_name} lhs, {type_name} rhs) {{" - )?; - let level = back::Level(1); - match scalar.kind { - crate::ScalarKind::Sint => { - let min = -1i64 << (scalar.width as u32 * 8 - 1); - writeln!(self.out, "{level}{rhs_type_name} divisor = metal::select(rhs, 1, (lhs == {min} & rhs == -1) | (rhs == 0));")?; - writeln!( - self.out, - "{level}return lhs - (lhs / divisor) * divisor;" - )? - } - crate::ScalarKind::Uint => writeln!( - self.out, - "{level}return lhs % metal::select(rhs, 1u, rhs == 0u);" - )?, - _ => unreachable!(), - } - writeln!(self.out, "}}")?; - writeln!(self.out)?; - } - _ => {} - } + self.write_wrapped_binary_op(module, func_ctx, expr_handle, op, left, right)?; } crate::Expression::Math { fun, arg, - arg1: _, - arg2: _, - arg3: _, + arg1, + arg2, + arg3, } => { - let arg_ty = func_ctx.resolve_type(arg, &module.types); - match fun { - // Taking the absolute value of the TYPE_MIN of a two's - // complement signed integer type causes overflow, which is - // undefined behaviour in MSL. To avoid this, when the value is - // negative we bitcast the value to unsigned and negate it, then - // bitcast back to signed. - // This adheres to the WGSL spec in that the absolute of the - // type's minimum value should equal to the minimum value. - crate::MathFunction::Abs - if arg_ty.scalar_kind() == Some(crate::ScalarKind::Sint) => - { - let Some((vector_size, scalar)) = arg_ty.vector_size_and_scalar() - else { - continue; - }; - let wrapped = WrappedFunction::Math { - fun, - arg_ty: (vector_size, scalar), - }; - if !self.wrapped_functions.insert(wrapped) { - continue; - } - - let unsigned_scalar = crate::Scalar { - kind: crate::ScalarKind::Uint, - ..scalar - }; - let mut type_name = String::new(); - let mut unsigned_type_name = String::new(); - match vector_size { - None => { - put_numeric_type(&mut type_name, scalar, &[])?; - put_numeric_type(&mut unsigned_type_name, unsigned_scalar, &[])? - } - Some(size) => { - put_numeric_type(&mut type_name, scalar, &[size])?; - put_numeric_type( - &mut unsigned_type_name, - unsigned_scalar, - &[size], - )?; - } - }; - - writeln!(self.out, "{type_name} {ABS_FUNCTION}({type_name} val) {{")?; - let level = back::Level(1); - writeln!(self.out, "{level}return metal::select(as_type<{type_name}>(-as_type<{unsigned_type_name}>(val)), val, val >= 0);")?; - writeln!(self.out, "}}")?; - writeln!(self.out)?; - } - _ => {} - } + self.write_wrapped_math_function(module, func_ctx, fun, arg, arg1, arg2, arg3)?; } crate::Expression::As { expr, kind, - convert: Some(width), + convert, } => { - // Avoid undefined behaviour when casting from a float to integer - // when the value is out of range for the target type. Additionally - // ensure we clamp to the correct value as per the WGSL spec. - // - // https://www.w3.org/TR/WGSL/#floating-point-conversion: - // * If X is exactly representable in the target type T, then the - // result is that value. - // * Otherwise, the result is the value in T closest to - // truncate(X) and also exactly representable in the original - // floating point type. - let src_ty = func_ctx.resolve_type(expr, &module.types); - let Some((vector_size, src_scalar)) = src_ty.vector_size_and_scalar() else { - continue; - }; - let dst_scalar = crate::Scalar { kind, width }; - if src_scalar.kind != crate::ScalarKind::Float - || (dst_scalar.kind != crate::ScalarKind::Sint - && dst_scalar.kind != crate::ScalarKind::Uint) - { - continue; - } - let wrapped = WrappedFunction::Cast { - src_scalar, - vector_size, - dst_scalar, - }; - if !self.wrapped_functions.insert(wrapped) { - continue; - } - let (min, max) = proc::min_max_float_representable_by(src_scalar, dst_scalar); - - let mut src_type_name = String::new(); - match vector_size { - None => put_numeric_type(&mut src_type_name, src_scalar, &[])?, - Some(size) => put_numeric_type(&mut src_type_name, src_scalar, &[size])?, - }; - let mut dst_type_name = String::new(); - match vector_size { - None => put_numeric_type(&mut dst_type_name, dst_scalar, &[])?, - Some(size) => put_numeric_type(&mut dst_type_name, dst_scalar, &[size])?, - }; - let fun_name = match dst_scalar { - crate::Scalar::I32 => F2I32_FUNCTION, - crate::Scalar::U32 => F2U32_FUNCTION, - crate::Scalar::I64 => F2I64_FUNCTION, - crate::Scalar::U64 => F2U64_FUNCTION, - _ => unreachable!(), - }; - - writeln!( - self.out, - "{dst_type_name} {fun_name}({src_type_name} value) {{" + self.write_wrapped_cast(module, func_ctx, expr, kind, convert)?; + } + crate::Expression::ImageLoad { + image, + coordinate, + array_index, + sample, + level, + } => { + self.write_wrapped_image_load( + module, + func_ctx, + image, + coordinate, + array_index, + sample, + level, )?; - let level = back::Level(1); - write!( - self.out, - "{level}return static_cast<{dst_type_name}>({NAMESPACE}::clamp(value, " + } + crate::Expression::ImageSample { + image, + sampler, + gather, + coordinate, + array_index, + offset, + level, + depth_ref, + clamp_to_edge, + } => { + self.write_wrapped_image_sample( + module, + func_ctx, + image, + sampler, + gather, + coordinate, + array_index, + offset, + level, + depth_ref, + clamp_to_edge, )?; - self.put_literal(min)?; - write!(self.out, ", ")?; - self.put_literal(max)?; - writeln!(self.out, "));")?; - writeln!(self.out, "}}")?; - writeln!(self.out)?; + } + crate::Expression::ImageQuery { image, query } => { + self.write_wrapped_image_query(module, func_ctx, image, query)?; } _ => {} } @@ -5479,7 +6370,7 @@ template struct VertexBufferMappingResolved<'a> { id: u32, stride: u32, - indexed_by_vertex: bool, + step_mode: back::msl::VertexBufferStepMode, ty_name: String, param_name: String, elem_name: String, @@ -5515,10 +6406,14 @@ template "Vertex pulling requires a non-zero buffer stride." ); - if vbm.indexed_by_vertex { - needs_vertex_id = true; - } else { - needs_instance_id = true; + match vbm.step_mode { + back::msl::VertexBufferStepMode::Constant => {} + back::msl::VertexBufferStepMode::ByVertex => { + needs_vertex_id = true; + } + back::msl::VertexBufferStepMode::ByInstance => { + needs_instance_id = true; + } } let buffer_ty = self.namer.call(format!("vb_{buffer_id}_type").as_str()); @@ -5528,7 +6423,7 @@ template vbm_resolved.push(VertexBufferMappingResolved { id: buffer_id, stride: buffer_stride, - indexed_by_vertex: vbm.indexed_by_vertex, + step_mode: vbm.step_mode, ty_name: buffer_ty, param_name: buffer_param, elem_name: buffer_elem, @@ -5572,7 +6467,6 @@ template info: &mod_info[fun_handle], expressions: &fun.expressions, named_expressions: &fun.named_expressions, - expr_kind_tracker: ExpressionKindTracker::from_arena(&fun.expressions), }; writeln!(self.out)?; @@ -5676,38 +6570,22 @@ template result_struct: None, }; - for (local_handle, local) in fun.local_variables.iter() { - let ty_name = TypeContext { - handle: local.ty, - gctx: module.to_ctx(), - names: &self.names, - access: crate::StorageAccess::empty(), - first_time: false, - }; - let local_name = &self.names[&NameKey::FunctionLocal(fun_handle, local_handle)]; - write!(self.out, "{}{} {}", back::INDENT, ty_name, local_name)?; - match local.init { - Some(value) => { - write!(self.out, " = ")?; - self.put_expression(value, &context.expression, true)?; - } - None => { - write!(self.out, " = {{}}")?; - } - }; - writeln!(self.out, ";")?; - } - + self.put_locals(&context.expression)?; self.update_expressions_to_bake(fun, fun_info, &context.expression); self.put_block(back::Level(1), &fun.body, &context)?; writeln!(self.out, "}}")?; self.named_expressions.clear(); } + let ep_range = get_entry_points(module, pipeline_options.entry_point.as_ref()) + .map_err(|(stage, name)| Error::EntryPointNotFound(stage, name))?; + let mut info = TranslationInfo { - entry_point_names: Vec::with_capacity(module.entry_points.len()), + entry_point_names: Vec::with_capacity(ep_range.len()), }; - for (ep_index, ep) in module.entry_points.iter().enumerate() { + + for ep_index in ep_range { + let ep = &module.entry_points[ep_index]; let fun = &ep.function; let fun_info = mod_info.get_entry_point(ep_index); let mut ep_error = None; @@ -5729,7 +6607,6 @@ template info: fun_info, expressions: &fun.expressions, named_expressions: &fun.named_expressions, - expr_kind_tracker: ExpressionKindTracker::from_arena(&fun.expressions), }; self.write_wrapped_functions(module, &ctx)?; @@ -5753,7 +6630,7 @@ template LocationMode::Uniform, false, ), - crate::ShaderStage::Task | crate::ShaderStage::Mesh => unreachable!(), + crate::ShaderStage::Task | crate::ShaderStage::Mesh => unimplemented!(), }; // Should this entry point be modified to do vertex pulling? @@ -5796,6 +6673,10 @@ template // so that binding arrays fall to the buffer location. match module.types[var.ty].inner { + crate::TypeInner::Image { + class: crate::ImageClass::External, + .. + } => target.external_texture.is_some(), crate::TypeInner::Image { .. } => target.texture.is_some(), crate::TypeInner::Sampler { .. } => { target.sampler.is_some() @@ -5816,6 +6697,9 @@ template break; } } + crate::AddressSpace::TaskPayload => { + unimplemented!() + } crate::AddressSpace::Function | crate::AddressSpace::Private | crate::AddressSpace::WorkGroup => {} @@ -6034,16 +6918,25 @@ template // Write the entry point function's name, and begin its argument list. writeln!(self.out, "{em_str} {result_type_name} {fun_name}(")?; + let mut is_first_argument = true; + let mut separator = || { + if is_first_argument { + is_first_argument = false; + ' ' + } else { + ',' + } + }; // If we have produced a struct holding the `EntryPoint`'s // `Function`'s arguments' varyings, pass that struct first. if has_varyings { writeln!( self.out, - " {stage_in_name} {varyings_member_name} [[stage_in]]" + "{} {stage_in_name} {varyings_member_name} [[stage_in]]", + separator() )?; - is_first_argument = false; } let mut local_invocation_id = None; @@ -6083,13 +6976,7 @@ template }; let resolved = options.resolve_local_binding(binding, in_mode)?; - let separator = if is_first_argument { - is_first_argument = false; - ' ' - } else { - ',' - }; - write!(self.out, "{separator} {ty_name} {name}")?; + write!(self.out, "{} {ty_name} {name}", separator())?; resolved.try_fmt(&mut self.out)?; writeln!(self.out)?; } @@ -6098,15 +6985,9 @@ template self.need_workgroup_variables_initialization(options, ep, module, fun_info); if need_workgroup_variables_initialization && local_invocation_id.is_none() { - let separator = if is_first_argument { - is_first_argument = false; - ' ' - } else { - ',' - }; writeln!( self.out, - "{separator} {NAMESPACE}::uint3 __local_invocation_id [[thread_position_in_threadgroup]]" + "{} {NAMESPACE}::uint3 __local_invocation_id [[thread_position_in_threadgroup]]", separator() )?; } @@ -6222,6 +7103,11 @@ template "read-write textures".to_string(), )); } + crate::ImageClass::External => { + return Err(Error::UnsupportedArrayOf( + "external textures".to_string(), + )); + } }, _ => { return Err(Error::UnsupportedArrayOfType(base)); @@ -6248,49 +7134,84 @@ template } } - let tyvar = TypedGlobalVariable { - module, - names: &self.names, - handle, - usage, - reference: true, - }; - let separator = if is_first_argument { - is_first_argument = false; - ' ' - } else { - ',' - }; - write!(self.out, "{separator} ")?; - tyvar.try_fmt(&mut self.out)?; - if let Some(resolved) = resolved { - resolved.try_fmt(&mut self.out)?; - } - if let Some(value) = var.init { - write!(self.out, " = ")?; - self.put_const_expression(value, module, mod_info, &module.global_expressions)?; + match module.types[var.ty].inner { + crate::TypeInner::Image { + class: crate::ImageClass::External, + .. + } => { + // External texture global variables get lowered to 3 textures + // and a constant buffer. We must emit a separate argument for + // each of these. + let target = match resolved { + Some(back::msl::ResolvedBinding::Resource(target)) => { + target.external_texture + } + _ => None, + }; + + for i in 0..3 { + write!(self.out, "{} ", separator())?; + + let plane_name = &self.names[&NameKey::ExternalTextureGlobalVariable( + handle, + ExternalTextureNameKey::Plane(i), + )]; + write!( + self.out, + "{NAMESPACE}::texture2d {plane_name}" + )?; + if let Some(ref target) = target { + write!(self.out, " [[texture({})]]", target.planes[i])?; + } + writeln!(self.out)?; + } + let params_ty_name = &self.names + [&NameKey::Type(module.special_types.external_texture_params.unwrap())]; + let params_name = &self.names[&NameKey::ExternalTextureGlobalVariable( + handle, + ExternalTextureNameKey::Params, + )]; + write!(self.out, "{} ", separator())?; + write!(self.out, "constant {params_ty_name}& {params_name}")?; + if let Some(ref target) = target { + write!(self.out, " [[buffer({})]]", target.params)?; + } + } + _ => { + let tyvar = TypedGlobalVariable { + module, + names: &self.names, + handle, + usage, + reference: true, + }; + write!(self.out, "{} ", separator())?; + tyvar.try_fmt(&mut self.out)?; + if let Some(resolved) = resolved { + resolved.try_fmt(&mut self.out)?; + } + if let Some(value) = var.init { + write!(self.out, " = ")?; + self.put_const_expression( + value, + module, + mod_info, + &module.global_expressions, + )?; + } + } } writeln!(self.out)?; } if do_vertex_pulling { - assert!(needs_vertex_id || needs_instance_id); - - let mut separator = if is_first_argument { - is_first_argument = false; - ' ' - } else { - ',' - }; - if needs_vertex_id && v_existing_id.is_none() { // Write the [[vertex_id]] argument. - writeln!(self.out, "{separator} uint {v_id} [[vertex_id]]")?; - separator = ','; + writeln!(self.out, "{} uint {v_id} [[vertex_id]]", separator())?; } if needs_instance_id && i_existing_id.is_none() { - writeln!(self.out, "{separator} uint {i_id} [[instance_id]]")?; + writeln!(self.out, "{} uint {i_id} [[instance_id]]", separator())?; } // Iterate vbm_resolved, output one argument for every vertex buffer, @@ -6301,7 +7222,8 @@ template let param_name = &vbm.param_name; writeln!( self.out, - ", const device {ty_name}* {param_name} [[buffer({id})]]" + "{} const device {ty_name}* {param_name} [[buffer({id})]]", + separator() )?; } } @@ -6311,10 +7233,10 @@ template if needs_buffer_sizes { // this is checked earlier let resolved = options.resolve_sizes_buffer(ep).unwrap(); - let separator = if is_first_argument { ' ' } else { ',' }; write!( self.out, - "{separator} constant _mslBufferSizes& _buffer_sizes", + "{} constant _mslBufferSizes& _buffer_sizes", + separator() )?; resolved.try_fmt(&mut self.out)?; writeln!(self.out)?; @@ -6353,16 +7275,22 @@ template let idx = &vbm.id; let stride = &vbm.stride; - let index_name = if vbm.indexed_by_vertex { - if let Some(ref name) = v_existing_id { - name - } else { - &v_id + let index_name = match vbm.step_mode { + back::msl::VertexBufferStepMode::Constant => "0", + back::msl::VertexBufferStepMode::ByVertex => { + if let Some(ref name) = v_existing_id { + name + } else { + &v_id + } + } + back::msl::VertexBufferStepMode::ByInstance => { + if let Some(ref name) = i_existing_id { + name + } else { + &i_id + } } - } else if let Some(ref name) = i_existing_id { - name - } else { - &i_id }; write!( self.out, @@ -6386,14 +7314,12 @@ template // from the buffer elements. for attribute in vbm.attributes { let location = attribute.shader_location; - let am_option = am_resolved.get(&location); - if am_option.is_none() { + let Some(am) = am_resolved.get(&location) else { // This bound attribute isn't used in this entry point, so // don't bother extracting the data. Too bad we emitted the // unpacking function earlier -- it might not get used. continue; - } - let am = am_option.unwrap(); + }; let attribute_name = &am.name; let attribute_ty_name = &am.ty_name; @@ -6403,36 +7329,62 @@ template .expect("Should have generated this unpacking function earlier."); let func_name = &func.name; + // Check dimensionality of the attribute compared to the unpacking + // function. If attribute dimension > unpack dimension, we have to + // pad out the unpack value from a vec4(0, 0, 0, 1) of matching + // scalar type. Otherwise, if attribute dimension is < unpack + // dimension, then we need to explicitly truncate the result. + + let needs_padding_or_truncation = am.dimension.cmp(&func.dimension); + + if needs_padding_or_truncation != Ordering::Equal { + // Emit a comment flagging that a conversion is happening, + // since the actual logic can be at the end of a long line. + writeln!( + self.out, + "{}// {attribute_ty_name} <- {:?}", + back::Level(2), + attribute.format + )?; + } + write!(self.out, "{}{attribute_name} = ", back::Level(2),)?; - // Check dimensionality of the attribute compared to the unpacking - // function. If attribute dimension is < unpack dimension, then - // we need to explicitly cast down the result. Otherwise, if attribute - // dimension > unpack dimension, we have to pad out the unpack value - // from a vec4(0, 0, 0, 1) of matching scalar type. - - let needs_truncate_or_padding = am.dimension != func.dimension; - if needs_truncate_or_padding { + if needs_padding_or_truncation == Ordering::Greater { + // Needs padding: emit constructor call for wider type write!(self.out, "{attribute_ty_name}(")?; } + // Emit call to unpacking function write!(self.out, "{func_name}({elem_name}.data[{offset}]",)?; for i in (offset + 1)..(offset + func.byte_count) { write!(self.out, ", {elem_name}.data[{i}]")?; } write!(self.out, ")")?; - if needs_truncate_or_padding { - let zero_value = if am.ty_is_int { "0" } else { "0.0" }; - let one_value = if am.ty_is_int { "1" } else { "1.0" }; - for i in func.dimension..am.dimension { + match needs_padding_or_truncation { + Ordering::Greater => { + // Padding + let zero_value = if am.ty_is_int { "0" } else { "0.0" }; + let one_value = if am.ty_is_int { "1" } else { "1.0" }; + for i in func.dimension..am.dimension { + write!( + self.out, + ", {}", + if i == 3 { one_value } else { zero_value } + )?; + } + write!(self.out, ")")?; + } + Ordering::Less => { + // Truncate to the first `am.dimension` components write!( self.out, - ", {}", - if i == 3 { one_value } else { zero_value } + ".{}", + &"xyzw"[0..usize::try_from(am.dimension).unwrap()] )?; } - write!(self.out, ")")?; + Ordering::Equal => {} } writeln!(self.out, ";")?; @@ -6486,9 +7438,9 @@ template } }; } else if let Some(ref binding) = var.binding { - // write an inline sampler let resolved = options.resolve_resource_binding(ep, binding).unwrap(); if let Some(sampler) = resolved.as_inline_sampler(options) { + // write an inline sampler let name = &self.names[&NameKey::GlobalVariable(handle)]; writeln!( self.out, @@ -6499,6 +7451,33 @@ template )?; self.put_inline_sampler_properties(back::Level(2), sampler)?; writeln!(self.out, "{});", back::INDENT)?; + } else if let crate::TypeInner::Image { + class: crate::ImageClass::External, + .. + } = module.types[var.ty].inner + { + // Wrap the individual arguments for each external texture global + // in a struct which can be easily passed around. + let wrapper_name = &self.names[&NameKey::GlobalVariable(handle)]; + let l1 = back::Level(1); + let l2 = l1.next(); + writeln!( + self.out, + "{l1}const {EXTERNAL_TEXTURE_WRAPPER_STRUCT} {wrapper_name} {{" + )?; + for i in 0..3 { + let plane_name = &self.names[&NameKey::ExternalTextureGlobalVariable( + handle, + ExternalTextureNameKey::Plane(i), + )]; + writeln!(self.out, "{l2}.plane{i} = {plane_name},")?; + } + let params_name = &self.names[&NameKey::ExternalTextureGlobalVariable( + handle, + ExternalTextureNameKey::Params, + )]; + writeln!(self.out, "{l2}.params = {params_name},")?; + writeln!(self.out, "{l1}}};")?; } } } @@ -6586,28 +7565,7 @@ template // Finally, declare all the local variables that we need //TODO: we can postpone this till the relevant expressions are emitted - for (local_handle, local) in fun.local_variables.iter() { - let name = &self.names[&NameKey::EntryPointLocal(ep_index as _, local_handle)]; - let ty_name = TypeContext { - handle: local.ty, - gctx: module.to_ctx(), - names: &self.names, - access: crate::StorageAccess::empty(), - first_time: false, - }; - write!(self.out, "{}{} {}", back::INDENT, ty_name, name)?; - match local.init { - Some(value) => { - write!(self.out, " = ")?; - self.put_expression(value, &context.expression, true)?; - } - None => { - write!(self.out, " = {{}}")?; - } - }; - writeln!(self.out, ";")?; - } - + self.put_locals(&context.expression)?; self.update_expressions_to_bake(fun, fun_info, &context.expression); self.put_block(back::Level(1), &fun.body, &context)?; writeln!(self.out, "}}")?; @@ -6739,7 +7697,7 @@ mod workgroup_mem_init { fun_info: &valid::FunctionInfo, ) -> bool { options.zero_initialize_workgroup_memory - && ep.stage == crate::ShaderStage::Compute + && ep.stage.compute_like() && module.global_variables.iter().any(|(handle, var)| { !fun_info[handle].is_empty() && var.space == crate::AddressSpace::WorkGroup }) @@ -6856,79 +7814,6 @@ mod workgroup_mem_init { } } -#[test] -fn test_stack_size() { - use crate::valid::{Capabilities, ValidationFlags}; - // create a module with at least one expression nested - let mut module = crate::Module::default(); - let mut fun = crate::Function::default(); - let const_expr = fun.expressions.append( - crate::Expression::Literal(crate::Literal::F32(1.0)), - Default::default(), - ); - let nested_expr = fun.expressions.append( - crate::Expression::Unary { - op: crate::UnaryOperator::Negate, - expr: const_expr, - }, - Default::default(), - ); - fun.body.push( - crate::Statement::Emit(fun.expressions.range_from(1)), - Default::default(), - ); - fun.body.push( - crate::Statement::If { - condition: nested_expr, - accept: crate::Block::new(), - reject: crate::Block::new(), - }, - Default::default(), - ); - let _ = module.functions.append(fun, Default::default()); - // analyse the module - let info = valid::Validator::new(ValidationFlags::empty(), Capabilities::empty()) - .validate(&module) - .unwrap(); - // process the module - let mut writer = Writer::new(String::new()); - writer - .write(&module, &info, &Default::default(), &Default::default()) - .unwrap(); - - { - // check expression stack - let mut addresses_start = usize::MAX; - let mut addresses_end = 0usize; - for pointer in writer.put_expression_stack_pointers { - addresses_start = addresses_start.min(pointer as usize); - addresses_end = addresses_end.max(pointer as usize); - } - let stack_size = addresses_end - addresses_start; - // check the size (in debug only) - // last observed macOS value: 20528 (CI) - if !(11000..=25000).contains(&stack_size) { - panic!("`put_expression` stack size {stack_size} has changed!"); - } - } - - { - // check block stack - let mut addresses_start = usize::MAX; - let mut addresses_end = 0usize; - for pointer in writer.put_block_stack_pointers { - addresses_start = addresses_start.min(pointer as usize); - addresses_end = addresses_end.max(pointer as usize); - } - let stack_size = addresses_end - addresses_start; - // check the size (in debug only) - // last observed macOS value: 22256 (CI) - if !(15000..=25000).contains(&stack_size) { - panic!("`put_block` stack size {stack_size} has changed!"); - } - } -} - impl crate::AtomicFunction { const fn to_msl(self) -> &'static str { match self { diff --git a/naga/src/back/pipeline_constants.rs b/naga/src/back/pipeline_constants.rs index 6c5be5852..109cc591e 100644 --- a/naga/src/back/pipeline_constants.rs +++ b/naga/src/back/pipeline_constants.rs @@ -10,12 +10,17 @@ use thiserror::Error; use super::PipelineConstants; use crate::{ arena::HandleVec, + compact::{compact, KeepUnused}, + ir, proc::{ConstantEvaluator, ConstantEvaluatorError, Emitter}, valid::{Capabilities, ModuleInfo, ValidationError, ValidationFlags, Validator}, Arena, Block, Constant, Expression, Function, Handle, Literal, Module, Override, Range, Scalar, Span, Statement, TypeInner, WithSpan, }; +#[cfg(no_std)] +use num_traits::float::FloatCore as _; + #[derive(Error, Debug, Clone)] #[cfg_attr(test, derive(PartialEq))] pub enum PipelineConstantError { @@ -34,31 +39,57 @@ pub enum PipelineConstantError { ValidationError(#[from] WithSpan), #[error("workgroup_size override isn't strictly positive")] NegativeWorkgroupSize, + #[error("max vertices or max primitives is negative")] + NegativeMeshOutputMax, } -/// Replace all overrides in `module` with constants. +/// Compact `module` and replace all overrides with constants. /// -/// If no changes are needed, this just returns `Cow::Borrowed` -/// references to `module` and `module_info`. Otherwise, it clones -/// `module`, edits its [`global_expressions`] arena to contain only -/// fully-evaluated expressions, and returns `Cow::Owned` values -/// holding the simplified module and its validation results. +/// If no changes are needed, this just returns `Cow::Borrowed` references to +/// `module` and `module_info`. Otherwise, it clones `module`, retains only the +/// selected entry point, compacts the module, edits its [`global_expressions`] +/// arena to contain only fully-evaluated expressions, and returns the +/// simplified module and its validation results. /// -/// In either case, the module returned has an empty `overrides` -/// arena, and the `global_expressions` arena contains only -/// fully-evaluated expressions. +/// The module returned has an empty `overrides` arena, and the +/// `global_expressions` arena contains only fully-evaluated expressions. /// /// [`global_expressions`]: Module::global_expressions pub fn process_overrides<'a>( module: &'a Module, module_info: &'a ModuleInfo, + entry_point: Option<(ir::ShaderStage, &str)>, pipeline_constants: &PipelineConstants, ) -> Result<(Cow<'a, Module>, Cow<'a, ModuleInfo>), PipelineConstantError> { - if module.overrides.is_empty() { + if (entry_point.is_none() || module.entry_points.len() <= 1) && module.overrides.is_empty() { + // We skip compacting the module here mostly to reduce the risk of + // hitting corner cases like https://github.com/gfx-rs/wgpu/issues/7793. + // Compaction doesn't cost very much [1], so it would also be reasonable + // to do it unconditionally. Even when there is a single entry point or + // when no entry point is specified, it is still possible that there + // are unreferenced items in the module that would be removed by this + // compaction. + // + // [1]: https://github.com/gfx-rs/wgpu/pull/7703#issuecomment-2902153760 return Ok((Cow::Borrowed(module), Cow::Borrowed(module_info))); } let mut module = module.clone(); + if let Some((ep_stage, ep_name)) = entry_point { + module + .entry_points + .retain(|ep| ep.stage == ep_stage && ep.name == ep_name); + } + + // Compact the module to remove anything not reachable from an entry point. + // This is necessary because we may not have values for overrides that are + // not reachable from the/an entry point. + compact(&mut module, KeepUnused::No); + + // If there are no overrides in the module, then we can skip the rest. + if module.overrides.is_empty() { + return revalidate(module); + } // A map from override handles to the handles of the constants // we've replaced them with. @@ -214,6 +245,7 @@ pub fn process_overrides<'a>( for ep in entry_points.iter_mut() { process_function(&mut module, &override_map, &mut layouter, &mut ep.function)?; process_workgroup_size_override(&mut module, &adjusted_global_expressions, ep)?; + process_mesh_shader_overrides(&mut module, &adjusted_global_expressions, ep)?; } module.entry_points = entry_points; module.overrides = overrides; @@ -221,9 +253,14 @@ pub fn process_overrides<'a>( // Now that we've rewritten all the expressions, we need to // recompute their types and other metadata. For the time being, // do a full re-validation. + revalidate(module) +} + +fn revalidate( + module: Module, +) -> Result<(Cow<'static, Module>, Cow<'static, ModuleInfo>), PipelineConstantError> { let mut validator = Validator::new(ValidationFlags::all(), Capabilities::all()); let module_info = validator.validate_resolved_overrides(&module)?; - Ok((Cow::Owned(module), Cow::Owned(module_info))) } @@ -262,6 +299,28 @@ fn process_workgroup_size_override( Ok(()) } +fn process_mesh_shader_overrides( + module: &mut Module, + adjusted_global_expressions: &HandleVec>, + ep: &mut crate::EntryPoint, +) -> Result<(), PipelineConstantError> { + if let Some(ref mut mesh_info) = ep.mesh_info { + if let Some(r#override) = mesh_info.max_vertices_override { + mesh_info.max_vertices = module + .to_ctx() + .eval_expr_to_u32(adjusted_global_expressions[r#override]) + .map_err(|_| PipelineConstantError::NegativeMeshOutputMax)?; + } + if let Some(r#override) = mesh_info.max_primitives_override { + mesh_info.max_primitives = module + .to_ctx() + .eval_expr_to_u32(adjusted_global_expressions[r#override]) + .map_err(|_| PipelineConstantError::NegativeMeshOutputMax)?; + } + } + Ok(()) +} + /// Add a [`Constant`] to `module` for the override `old_h`. /// /// Add the new `Constant` to `override_map` and `adjusted_constant_initializers`. @@ -443,6 +502,7 @@ fn adjust_expr(new_pos: &HandleVec>, expr: &mut E ref mut level, ref mut depth_ref, gather: _, + clamp_to_edge: _, } => { adjust(image); adjust(sampler); @@ -756,9 +816,11 @@ fn adjust_stmt(new_pos: &HandleVec>, stmt: &mut S | crate::GatherMode::Shuffle(ref mut index) | crate::GatherMode::ShuffleDown(ref mut index) | crate::GatherMode::ShuffleUp(ref mut index) - | crate::GatherMode::ShuffleXor(ref mut index) => { + | crate::GatherMode::ShuffleXor(ref mut index) + | crate::GatherMode::QuadBroadcast(ref mut index) => { adjust(index); } + crate::GatherMode::QuadSwap(_) => {} } adjust(argument); adjust(result) @@ -798,7 +860,31 @@ fn adjust_stmt(new_pos: &HandleVec>, stmt: &mut S crate::RayQueryFunction::Terminate => {} } } - Statement::Break | Statement::Continue | Statement::Kill | Statement::Barrier(_) => {} + Statement::MeshFunction(crate::MeshFunction::SetMeshOutputs { + ref mut vertex_count, + ref mut primitive_count, + }) => { + adjust(vertex_count); + adjust(primitive_count); + } + Statement::MeshFunction( + crate::MeshFunction::SetVertex { + ref mut index, + ref mut value, + } + | crate::MeshFunction::SetPrimitive { + ref mut index, + ref mut value, + }, + ) => { + adjust(index); + adjust(value); + } + Statement::Break + | Statement::Continue + | Statement::Kill + | Statement::ControlBarrier(_) + | Statement::MemoryBarrier(_) => {} } } @@ -927,6 +1013,19 @@ fn map_value_to_literal(value: f64, scalar: Scalar) -> Result { + // https://webidl.spec.whatwg.org/#js-float + if !value.is_finite() { + return Err(PipelineConstantError::SrcNeedsToBeFinite); + } + + let value = half::f16::from_f64(value); + if !value.is_finite() { + return Err(PipelineConstantError::DstRangeTooSmall); + } + + Ok(Literal::F16(value)) + } Scalar::F32 => { // https://webidl.spec.whatwg.org/#js-float if !value.is_finite() { @@ -948,7 +1047,10 @@ fn map_value_to_literal(value: f64, scalar: Scalar) -> Result unreachable!(), + Scalar::ABSTRACT_FLOAT | Scalar::ABSTRACT_INT => { + unreachable!("abstract values should not be validated out of override processing") + } + _ => unreachable!("unrecognized scalar type for override"), } } diff --git a/naga/src/back/spv/block.rs b/naga/src/back/spv/block.rs index f021dc6d8..d0556acdc 100644 --- a/naga/src/back/spv/block.rs +++ b/naga/src/back/spv/block.rs @@ -237,7 +237,7 @@ impl Writer { } }; - body.push(Instruction::store(res_member.id, member_value_id, None)); + self.store_io_with_f16_polyfill(body, res_member.id, member_value_id); match res_member.built_in { Some(crate::BuiltIn::Position { .. }) @@ -675,7 +675,7 @@ impl BlockContext<'_> { load_id } ref other => { - log::error!("Unable to access index of {:?}", other); + log::error!("Unable to access index of {other:?}"); return Err(Error::FeatureNotImplemented("access index for type")); } } @@ -1126,6 +1126,14 @@ impl BlockContext<'_> { arg1_id, size as u32, block, + |result_id, composite_id, index| { + Instruction::composite_extract( + result_type_id, + result_id, + composite_id, + &[index], + ) + }, ); self.cached[expr_handle] = id; return Ok(()); @@ -1134,6 +1142,97 @@ impl BlockContext<'_> { "Correct TypeInner for dot product should be already validated" ), }, + fun @ (Mf::Dot4I8Packed | Mf::Dot4U8Packed) => { + if self + .writer + .require_all(&[ + spirv::Capability::DotProduct, + spirv::Capability::DotProductInput4x8BitPacked, + ]) + .is_ok() + { + // Write optimized code using `PackedVectorFormat4x8Bit`. + if self.writer.lang_version() < (1, 6) { + // SPIR-V 1.6 supports the required capabilities natively, so the extension + // is only required for earlier versions. See right column of + // . + self.writer.use_extension("SPV_KHR_integer_dot_product"); + } + + let op = match fun { + Mf::Dot4I8Packed => spirv::Op::SDot, + Mf::Dot4U8Packed => spirv::Op::UDot, + _ => unreachable!(), + }; + + block.body.push(Instruction::ternary( + op, + result_type_id, + id, + arg0_id, + arg1_id, + spirv::PackedVectorFormat::PackedVectorFormat4x8Bit as Word, + )); + } else { + // Fall back to a polyfill since `PackedVectorFormat4x8Bit` is not available. + let (extract_op, arg0_id, arg1_id) = match fun { + Mf::Dot4U8Packed => (spirv::Op::BitFieldUExtract, arg0_id, arg1_id), + Mf::Dot4I8Packed => { + // Convert both packed arguments to signed integers so that we can apply the + // `BitFieldSExtract` operation on them in `write_dot_product` below. + let new_arg0_id = self.gen_id(); + block.body.push(Instruction::unary( + spirv::Op::Bitcast, + result_type_id, + new_arg0_id, + arg0_id, + )); + + let new_arg1_id = self.gen_id(); + block.body.push(Instruction::unary( + spirv::Op::Bitcast, + result_type_id, + new_arg1_id, + arg1_id, + )); + + (spirv::Op::BitFieldSExtract, new_arg0_id, new_arg1_id) + } + _ => unreachable!(), + }; + + let eight = self.writer.get_constant_scalar(crate::Literal::U32(8)); + + const VEC_LENGTH: u8 = 4; + let bit_shifts: [_; VEC_LENGTH as usize] = + core::array::from_fn(|index| { + self.writer + .get_constant_scalar(crate::Literal::U32(index as u32 * 8)) + }); + + self.write_dot_product( + id, + result_type_id, + arg0_id, + arg1_id, + VEC_LENGTH as Word, + block, + |result_id, composite_id, index| { + Instruction::ternary( + extract_op, + result_type_id, + result_id, + composite_id, + bit_shifts[index as usize], + eight, + ) + }, + ); + } + + self.cached[expr_handle] = id; + return Ok(()); + } Mf::Outer => MathOp::Custom(Instruction::binary( spirv::Op::OuterProduct, result_type_id, @@ -1452,77 +1551,30 @@ impl BlockContext<'_> { Mf::Pack2x16float => MathOp::Ext(spirv::GLOp::PackHalf2x16), Mf::Pack2x16unorm => MathOp::Ext(spirv::GLOp::PackUnorm2x16), Mf::Pack2x16snorm => MathOp::Ext(spirv::GLOp::PackSnorm2x16), - fun @ (Mf::Pack4xI8 | Mf::Pack4xU8) => { - let (int_type, is_signed) = match fun { - Mf::Pack4xI8 => (crate::ScalarKind::Sint, true), - Mf::Pack4xU8 => (crate::ScalarKind::Uint, false), - _ => unreachable!(), - }; - let uint_type_id = - self.get_numeric_type_id(NumericType::Scalar(crate::Scalar::U32)); + fun @ (Mf::Pack4xI8 | Mf::Pack4xU8 | Mf::Pack4xI8Clamp | Mf::Pack4xU8Clamp) => { + let is_signed = matches!(fun, Mf::Pack4xI8 | Mf::Pack4xI8Clamp); + let should_clamp = matches!(fun, Mf::Pack4xI8Clamp | Mf::Pack4xU8Clamp); - let int_type_id = - self.get_numeric_type_id(NumericType::Scalar(crate::Scalar { - kind: int_type, - width: 4, - })); - - let mut last_instruction = Instruction::new(spirv::Op::Nop); - - let zero = self.writer.get_constant_scalar(crate::Literal::U32(0)); - let mut preresult = zero; - block - .body - .reserve(usize::from(VEC_LENGTH) * (2 + usize::from(is_signed))); - - let eight = self.writer.get_constant_scalar(crate::Literal::U32(8)); - const VEC_LENGTH: u8 = 4; - for i in 0..u32::from(VEC_LENGTH) { - let offset = - self.writer.get_constant_scalar(crate::Literal::U32(i * 8)); - let mut extracted = self.gen_id(); - block.body.push(Instruction::binary( - spirv::Op::CompositeExtract, - int_type_id, - extracted, - arg0_id, - i, - )); - if is_signed { - let casted = self.gen_id(); - block.body.push(Instruction::unary( - spirv::Op::Bitcast, - uint_type_id, - casted, - extracted, - )); - extracted = casted; - } - let is_last = i == u32::from(VEC_LENGTH - 1); - if is_last { - last_instruction = Instruction::quaternary( - spirv::Op::BitFieldInsert, + let last_instruction = + if self.writer.require_all(&[spirv::Capability::Int8]).is_ok() { + self.write_pack4x8_optimized( + block, result_type_id, + arg0_id, id, - preresult, - extracted, - offset, - eight, + is_signed, + should_clamp, ) } else { - let new_preresult = self.gen_id(); - block.body.push(Instruction::quaternary( - spirv::Op::BitFieldInsert, + self.write_pack4x8_polyfill( + block, result_type_id, - new_preresult, - preresult, - extracted, - offset, - eight, - )); - preresult = new_preresult; - } - } + arg0_id, + id, + is_signed, + should_clamp, + ) + }; MathOp::Custom(last_instruction) } @@ -1532,59 +1584,28 @@ impl BlockContext<'_> { Mf::Unpack2x16unorm => MathOp::Ext(spirv::GLOp::UnpackUnorm2x16), Mf::Unpack2x16snorm => MathOp::Ext(spirv::GLOp::UnpackSnorm2x16), fun @ (Mf::Unpack4xI8 | Mf::Unpack4xU8) => { - let (int_type, extract_op, is_signed) = match fun { - Mf::Unpack4xI8 => { - (crate::ScalarKind::Sint, spirv::Op::BitFieldSExtract, true) - } - Mf::Unpack4xU8 => { - (crate::ScalarKind::Uint, spirv::Op::BitFieldUExtract, false) - } - _ => unreachable!(), - }; + let is_signed = matches!(fun, Mf::Unpack4xI8); - let sint_type_id = - self.get_numeric_type_id(NumericType::Scalar(crate::Scalar::I32)); + let last_instruction = + if self.writer.require_all(&[spirv::Capability::Int8]).is_ok() { + self.write_unpack4x8_optimized( + block, + result_type_id, + arg0_id, + id, + is_signed, + ) + } else { + self.write_unpack4x8_polyfill( + block, + result_type_id, + arg0_id, + id, + is_signed, + ) + }; - let eight = self.writer.get_constant_scalar(crate::Literal::U32(8)); - let int_type_id = - self.get_numeric_type_id(NumericType::Scalar(crate::Scalar { - kind: int_type, - width: 4, - })); - block - .body - .reserve(usize::from(VEC_LENGTH) * 2 + usize::from(is_signed)); - let arg_id = if is_signed { - let new_arg_id = self.gen_id(); - block.body.push(Instruction::unary( - spirv::Op::Bitcast, - sint_type_id, - new_arg_id, - arg0_id, - )); - new_arg_id - } else { - arg0_id - }; - - const VEC_LENGTH: u8 = 4; - let parts: [_; VEC_LENGTH as usize] = - core::array::from_fn(|_| self.gen_id()); - for (i, part_id) in parts.into_iter().enumerate() { - let index = self - .writer - .get_constant_scalar(crate::Literal::U32(i as u32 * 8)); - block.body.push(Instruction::ternary( - extract_op, - int_type_id, - part_id, - arg_id, - index, - eight, - )); - } - - MathOp::Custom(Instruction::composite_construct(result_type_id, id, &parts)) + MathOp::Custom(last_instruction) } }; @@ -1640,6 +1661,7 @@ impl BlockContext<'_> { offset, level, depth_ref, + clamp_to_edge, } => self.write_image_sample( result_type_id, image, @@ -1650,6 +1672,7 @@ impl BlockContext<'_> { offset, level, depth_ref, + clamp_to_edge, block, )?, crate::Expression::Select { @@ -1870,7 +1893,7 @@ impl BlockContext<'_> { crate::TypeInner::Scalar(scalar) => (scalar, None), crate::TypeInner::Vector { scalar, size } => (scalar, Some(size)), ref other => { - log::error!("As source {:?}", other); + log::error!("As source {other:?}"); return Err(Error::Validation("Unexpected Expression::As source")); } }; @@ -2540,6 +2563,12 @@ impl BlockContext<'_> { } /// Build the instructions for the arithmetic expression of a dot product + /// + /// The argument `extractor` is a function that maps `(result_id, + /// composite_id, index)` to an instruction that extracts the `index`th + /// entry of the value with ID `composite_id` and assigns it to the slot + /// with id `result_id` (which must have type `result_type_id`). + #[expect(clippy::too_many_arguments)] fn write_dot_product( &mut self, result_id: Word, @@ -2548,25 +2577,16 @@ impl BlockContext<'_> { arg1_id: Word, size: u32, block: &mut Block, + extractor: impl Fn(Word, Word, Word) -> Instruction, ) { let mut partial_sum = self.writer.get_constant_null(result_type_id); let last_component = size - 1; for index in 0..=last_component { // compute the product of the current components let a_id = self.gen_id(); - block.body.push(Instruction::composite_extract( - result_type_id, - a_id, - arg0_id, - &[index], - )); + block.body.push(extractor(a_id, arg0_id, index)); let b_id = self.gen_id(); - block.body.push(Instruction::composite_extract( - result_type_id, - b_id, - arg1_id, - &[index], - )); + block.body.push(extractor(b_id, arg1_id, index)); let prod_id = self.gen_id(); block.body.push(Instruction::binary( spirv::Op::IMul, @@ -2596,6 +2616,288 @@ impl BlockContext<'_> { } } + /// Emit code for `pack4x{I,U}8[Clamp]` if capability "Int8" is available. + fn write_pack4x8_optimized( + &mut self, + block: &mut Block, + result_type_id: u32, + arg0_id: u32, + id: u32, + is_signed: bool, + should_clamp: bool, + ) -> Instruction { + let int_type = if is_signed { + crate::ScalarKind::Sint + } else { + crate::ScalarKind::Uint + }; + let wide_vector_type = NumericType::Vector { + size: crate::VectorSize::Quad, + scalar: crate::Scalar { + kind: int_type, + width: 4, + }, + }; + let wide_vector_type_id = self.get_numeric_type_id(wide_vector_type); + let packed_vector_type_id = self.get_numeric_type_id(NumericType::Vector { + size: crate::VectorSize::Quad, + scalar: crate::Scalar { + kind: crate::ScalarKind::Uint, + width: 1, + }, + }); + + let mut wide_vector = arg0_id; + if should_clamp { + let (min, max, clamp_op) = if is_signed { + ( + crate::Literal::I32(-128), + crate::Literal::I32(127), + spirv::GLOp::SClamp, + ) + } else { + ( + crate::Literal::U32(0), + crate::Literal::U32(255), + spirv::GLOp::UClamp, + ) + }; + let [min, max] = [min, max].map(|lit| { + let scalar = self.writer.get_constant_scalar(lit); + self.writer.get_constant_composite( + LookupType::Local(LocalType::Numeric(wide_vector_type)), + &[scalar; 4], + ) + }); + + let clamp_id = self.gen_id(); + block.body.push(Instruction::ext_inst( + self.writer.gl450_ext_inst_id, + clamp_op, + wide_vector_type_id, + clamp_id, + &[wide_vector, min, max], + )); + + wide_vector = clamp_id; + } + + let packed_vector = self.gen_id(); + block.body.push(Instruction::unary( + spirv::Op::UConvert, // We truncate, so `UConvert` and `SConvert` behave identically. + packed_vector_type_id, + packed_vector, + wide_vector, + )); + + // The SPIR-V spec [1] defines the bit order for bit casting between a vector + // and a scalar precisely as required by the WGSL spec [2]. + // [1]: https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#OpBitcast + // [2]: https://www.w3.org/TR/WGSL/#pack4xI8-builtin + Instruction::unary(spirv::Op::Bitcast, result_type_id, id, packed_vector) + } + + /// Emit code for `pack4x{I,U}8[Clamp]` if capability "Int8" is not available. + fn write_pack4x8_polyfill( + &mut self, + block: &mut Block, + result_type_id: u32, + arg0_id: u32, + id: u32, + is_signed: bool, + should_clamp: bool, + ) -> Instruction { + let int_type = if is_signed { + crate::ScalarKind::Sint + } else { + crate::ScalarKind::Uint + }; + let uint_type_id = self.get_numeric_type_id(NumericType::Scalar(crate::Scalar::U32)); + let int_type_id = self.get_numeric_type_id(NumericType::Scalar(crate::Scalar { + kind: int_type, + width: 4, + })); + + let mut last_instruction = Instruction::new(spirv::Op::Nop); + + let zero = self.writer.get_constant_scalar(crate::Literal::U32(0)); + let mut preresult = zero; + block + .body + .reserve(usize::from(VEC_LENGTH) * (2 + usize::from(is_signed))); + + let eight = self.writer.get_constant_scalar(crate::Literal::U32(8)); + const VEC_LENGTH: u8 = 4; + for i in 0..u32::from(VEC_LENGTH) { + let offset = self.writer.get_constant_scalar(crate::Literal::U32(i * 8)); + let mut extracted = self.gen_id(); + block.body.push(Instruction::binary( + spirv::Op::CompositeExtract, + int_type_id, + extracted, + arg0_id, + i, + )); + if is_signed { + let casted = self.gen_id(); + block.body.push(Instruction::unary( + spirv::Op::Bitcast, + uint_type_id, + casted, + extracted, + )); + extracted = casted; + } + if should_clamp { + let (min, max, clamp_op) = if is_signed { + ( + crate::Literal::I32(-128), + crate::Literal::I32(127), + spirv::GLOp::SClamp, + ) + } else { + ( + crate::Literal::U32(0), + crate::Literal::U32(255), + spirv::GLOp::UClamp, + ) + }; + let [min, max] = [min, max].map(|lit| self.writer.get_constant_scalar(lit)); + + let clamp_id = self.gen_id(); + block.body.push(Instruction::ext_inst( + self.writer.gl450_ext_inst_id, + clamp_op, + result_type_id, + clamp_id, + &[extracted, min, max], + )); + + extracted = clamp_id; + } + let is_last = i == u32::from(VEC_LENGTH - 1); + if is_last { + last_instruction = Instruction::quaternary( + spirv::Op::BitFieldInsert, + result_type_id, + id, + preresult, + extracted, + offset, + eight, + ) + } else { + let new_preresult = self.gen_id(); + block.body.push(Instruction::quaternary( + spirv::Op::BitFieldInsert, + result_type_id, + new_preresult, + preresult, + extracted, + offset, + eight, + )); + preresult = new_preresult; + } + } + last_instruction + } + + /// Emit code for `unpack4x{I,U}8` if capability "Int8" is available. + fn write_unpack4x8_optimized( + &mut self, + block: &mut Block, + result_type_id: u32, + arg0_id: u32, + id: u32, + is_signed: bool, + ) -> Instruction { + let (int_type, convert_op) = if is_signed { + (crate::ScalarKind::Sint, spirv::Op::SConvert) + } else { + (crate::ScalarKind::Uint, spirv::Op::UConvert) + }; + + let packed_vector_type_id = self.get_numeric_type_id(NumericType::Vector { + size: crate::VectorSize::Quad, + scalar: crate::Scalar { + kind: int_type, + width: 1, + }, + }); + + // The SPIR-V spec [1] defines the bit order for bit casting between a vector + // and a scalar precisely as required by the WGSL spec [2]. + // [1]: https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#OpBitcast + // [2]: https://www.w3.org/TR/WGSL/#pack4xI8-builtin + let packed_vector = self.gen_id(); + block.body.push(Instruction::unary( + spirv::Op::Bitcast, + packed_vector_type_id, + packed_vector, + arg0_id, + )); + + Instruction::unary(convert_op, result_type_id, id, packed_vector) + } + + /// Emit code for `unpack4x{I,U}8` if capability "Int8" is not available. + fn write_unpack4x8_polyfill( + &mut self, + block: &mut Block, + result_type_id: u32, + arg0_id: u32, + id: u32, + is_signed: bool, + ) -> Instruction { + let (int_type, extract_op) = if is_signed { + (crate::ScalarKind::Sint, spirv::Op::BitFieldSExtract) + } else { + (crate::ScalarKind::Uint, spirv::Op::BitFieldUExtract) + }; + + let sint_type_id = self.get_numeric_type_id(NumericType::Scalar(crate::Scalar::I32)); + + let eight = self.writer.get_constant_scalar(crate::Literal::U32(8)); + let int_type_id = self.get_numeric_type_id(NumericType::Scalar(crate::Scalar { + kind: int_type, + width: 4, + })); + block + .body + .reserve(usize::from(VEC_LENGTH) * 2 + usize::from(is_signed)); + let arg_id = if is_signed { + let new_arg_id = self.gen_id(); + block.body.push(Instruction::unary( + spirv::Op::Bitcast, + sint_type_id, + new_arg_id, + arg0_id, + )); + new_arg_id + } else { + arg0_id + }; + + const VEC_LENGTH: u8 = 4; + let parts: [_; VEC_LENGTH as usize] = core::array::from_fn(|_| self.gen_id()); + for (i, part_id) in parts.into_iter().enumerate() { + let index = self + .writer + .get_constant_scalar(crate::Literal::U32(i as u32 * 8)); + block.body.push(Instruction::ternary( + extract_op, + int_type_id, + part_id, + arg_id, + index, + eight, + )); + } + + Instruction::composite_construct(result_type_id, id, &parts) + } + /// Generate one or more SPIR-V blocks for `naga_block`. /// /// Use `label_id` as the label for the SPIR-V entry point block. @@ -2677,62 +2979,69 @@ impl BlockContext<'_> { ref accept, ref reject, } => { - let condition_id = self.cached[condition]; + // In spirv 1.6, in a conditional branch the two block ids + // of the branches can't have the same label. If `accept` + // and `reject` are both empty (e.g. in `if (condition) {}`) + // merge id will be both labels. Because both branches are + // empty, we can skip the if statement. + if !(accept.is_empty() && reject.is_empty()) { + let condition_id = self.cached[condition]; - let merge_id = self.gen_id(); - block.body.push(Instruction::selection_merge( - merge_id, - spirv::SelectionControl::NONE, - )); + let merge_id = self.gen_id(); + block.body.push(Instruction::selection_merge( + merge_id, + spirv::SelectionControl::NONE, + )); - let accept_id = if accept.is_empty() { - None - } else { - Some(self.gen_id()) - }; - let reject_id = if reject.is_empty() { - None - } else { - Some(self.gen_id()) - }; + let accept_id = if accept.is_empty() { + None + } else { + Some(self.gen_id()) + }; + let reject_id = if reject.is_empty() { + None + } else { + Some(self.gen_id()) + }; - self.function.consume( - block, - Instruction::branch_conditional( - condition_id, - accept_id.unwrap_or(merge_id), - reject_id.unwrap_or(merge_id), - ), - ); + self.function.consume( + block, + Instruction::branch_conditional( + condition_id, + accept_id.unwrap_or(merge_id), + reject_id.unwrap_or(merge_id), + ), + ); - if let Some(block_id) = accept_id { - // We can ignore the `BlockExitDisposition` returned here because, - // even if `merge_id` is not actually reachable, it is always - // referred to by the `OpSelectionMerge` instruction we emitted - // earlier. - let _ = self.write_block( - block_id, - accept, - BlockExit::Branch { target: merge_id }, - loop_context, - debug_info, - )?; + if let Some(block_id) = accept_id { + // We can ignore the `BlockExitDisposition` returned here because, + // even if `merge_id` is not actually reachable, it is always + // referred to by the `OpSelectionMerge` instruction we emitted + // earlier. + let _ = self.write_block( + block_id, + accept, + BlockExit::Branch { target: merge_id }, + loop_context, + debug_info, + )?; + } + if let Some(block_id) = reject_id { + // We can ignore the `BlockExitDisposition` returned here because, + // even if `merge_id` is not actually reachable, it is always + // referred to by the `OpSelectionMerge` instruction we emitted + // earlier. + let _ = self.write_block( + block_id, + reject, + BlockExit::Branch { target: merge_id }, + loop_context, + debug_info, + )?; + } + + block = Block::new(merge_id); } - if let Some(block_id) = reject_id { - // We can ignore the `BlockExitDisposition` returned here because, - // even if `merge_id` is not actually reachable, it is always - // referred to by the `OpSelectionMerge` instruction we emitted - // earlier. - let _ = self.write_block( - block_id, - reject, - BlockExit::Branch { target: merge_id }, - loop_context, - debug_info, - )?; - } - - block = Block::new(merge_id); } Statement::Switch { selector, @@ -2940,8 +3249,11 @@ impl BlockContext<'_> { self.function.consume(block, Instruction::kill()); return Ok(BlockExitDisposition::Discarded); } - Statement::Barrier(flags) => { - self.writer.write_barrier(flags, &mut block); + Statement::ControlBarrier(flags) => { + self.writer.write_control_barrier(flags, &mut block); + } + Statement::MemoryBarrier(flags) => { + self.writer.write_memory_barrier(flags, &mut block); } Statement::Store { pointer, value } => { let value_id = self.cached[value]; @@ -3231,6 +3543,7 @@ impl BlockContext<'_> { } _ => unimplemented!(), }; + let mut cas_instr = Instruction::new(spirv::Op::AtomicCompareExchange); cas_instr.set_type(scalar_type_id); cas_instr.set_result(cas_result_id); @@ -3276,7 +3589,7 @@ impl BlockContext<'_> { } Statement::WorkGroupUniformLoad { pointer, result } => { self.writer - .write_barrier(crate::Barrier::WORK_GROUP, &mut block); + .write_control_barrier(crate::Barrier::WORK_GROUP, &mut block); let result_type_id = self.get_expression_type_id(&self.fun_info[result].ty); // Embed the body of match self.write_access_chain( @@ -3316,7 +3629,7 @@ impl BlockContext<'_> { } } self.writer - .write_barrier(crate::Barrier::WORK_GROUP, &mut block); + .write_control_barrier(crate::Barrier::WORK_GROUP, &mut block); } Statement::RayQuery { query, ref fun } => { self.write_ray_query_function(query, fun, &mut block); @@ -3342,6 +3655,7 @@ impl BlockContext<'_> { } => { self.write_subgroup_gather(mode, argument, result, &mut block)?; } + Statement::MeshFunction(_) => unreachable!(), } } diff --git a/naga/src/back/spv/f16_polyfill.rs b/naga/src/back/spv/f16_polyfill.rs new file mode 100644 index 000000000..824490265 --- /dev/null +++ b/naga/src/back/spv/f16_polyfill.rs @@ -0,0 +1,104 @@ +/*! +This module provides functionality for polyfilling `f16` input/output variables +when the `StorageInputOutput16` capability is not available or disabled. + +It works by: + +1. Declaring `f16` I/O variables as `f32` in SPIR-V +2. Converting between `f16` and `f32` at runtime using `OpFConvert` +3. Maintaining mappings to track which variables need conversion +*/ + +use crate::back::spv::{Instruction, LocalType, NumericType, Word}; +use alloc::vec::Vec; + +/// Manages `f16` I/O polyfill state and operations. +#[derive(Default)] +pub(in crate::back::spv) struct F16IoPolyfill { + use_native: bool, + io_var_to_f32_type: crate::FastHashMap, +} + +impl F16IoPolyfill { + pub fn new(use_storage_input_output_16: bool) -> Self { + Self { + use_native: use_storage_input_output_16, + io_var_to_f32_type: crate::FastHashMap::default(), + } + } + + pub fn needs_polyfill(&self, ty_inner: &crate::TypeInner) -> bool { + use crate::{ScalarKind as Sk, TypeInner}; + + !self.use_native + && match *ty_inner { + TypeInner::Scalar(ref s) if s.kind == Sk::Float && s.width == 2 => true, + TypeInner::Vector { scalar, .. } + if scalar.kind == Sk::Float && scalar.width == 2 => + { + true + } + _ => false, + } + } + + pub fn register_io_var(&mut self, variable_id: Word, f32_type_id: Word) { + self.io_var_to_f32_type.insert(variable_id, f32_type_id); + } + + pub fn get_f32_io_type(&self, variable_id: Word) -> Option { + self.io_var_to_f32_type.get(&variable_id).copied() + } + + pub fn emit_f16_to_f32_conversion( + f16_value_id: Word, + f32_type_id: Word, + converted_id: Word, + body: &mut Vec, + ) { + body.push(Instruction::unary( + spirv::Op::FConvert, + f32_type_id, + converted_id, + f16_value_id, + )); + } + + pub fn emit_f32_to_f16_conversion( + f32_value_id: Word, + f16_type_id: Word, + converted_id: Word, + body: &mut Vec, + ) { + body.push(Instruction::unary( + spirv::Op::FConvert, + f16_type_id, + converted_id, + f32_value_id, + )); + } + + pub fn create_polyfill_type(ty_inner: &crate::TypeInner) -> Option { + use crate::{ScalarKind as Sk, TypeInner}; + + match *ty_inner { + TypeInner::Scalar(ref s) if s.kind == Sk::Float && s.width == 2 => { + Some(LocalType::Numeric(NumericType::Scalar(crate::Scalar::F32))) + } + TypeInner::Vector { size, scalar } if scalar.kind == Sk::Float && scalar.width == 2 => { + Some(LocalType::Numeric(NumericType::Vector { + size, + scalar: crate::Scalar::F32, + })) + } + _ => None, + } + } +} + +impl crate::back::spv::recyclable::Recyclable for F16IoPolyfill { + fn recycle(mut self) -> Self { + self.io_var_to_f32_type = self.io_var_to_f32_type.recycle(); + self + } +} diff --git a/naga/src/back/spv/helpers.rs b/naga/src/back/spv/helpers.rs index 7938791ba..6522a0970 100644 --- a/naga/src/back/spv/helpers.rs +++ b/naga/src/back/spv/helpers.rs @@ -35,6 +35,9 @@ pub(super) fn string_to_byte_chunks(input: &str, limit: usize) -> Vec<&[u8]> { let mut words = vec![]; while offset < input.len() { offset = input.floor_char_boundary(offset + limit); + // Clippy wants us to call as_bytes() first to avoid the UTF-8 check, + // but we want to assert the output is valid UTF-8. + #[allow(clippy::sliced_string_as_bytes)] words.push(input[start..offset].as_bytes()); start = offset; } @@ -51,6 +54,7 @@ pub(super) const fn map_storage_class(space: crate::AddressSpace) -> spirv::Stor crate::AddressSpace::Uniform => spirv::StorageClass::Uniform, crate::AddressSpace::WorkGroup => spirv::StorageClass::Workgroup, crate::AddressSpace::PushConstant => spirv::StorageClass::PushConstant, + crate::AddressSpace::TaskPayload => unreachable!(), } } @@ -76,11 +80,10 @@ impl crate::AddressSpace { self, ) -> (spirv::MemorySemantics, spirv::Scope) { match self { - Self::Storage { .. } => (spirv::MemorySemantics::UNIFORM_MEMORY, spirv::Scope::Device), - Self::WorkGroup => ( - spirv::MemorySemantics::WORKGROUP_MEMORY, - spirv::Scope::Workgroup, - ), + Self::Storage { .. } => (spirv::MemorySemantics::empty(), spirv::Scope::Device), + Self::WorkGroup => (spirv::MemorySemantics::empty(), spirv::Scope::Workgroup), + Self::Uniform => (spirv::MemorySemantics::empty(), spirv::Scope::Device), + Self::Handle => (spirv::MemorySemantics::empty(), spirv::Scope::Device), _ => (spirv::MemorySemantics::empty(), spirv::Scope::Invocation), } } diff --git a/naga/src/back/spv/image.rs b/naga/src/back/spv/image.rs index c554be423..3aec1333f 100644 --- a/naga/src/back/spv/image.rs +++ b/naga/src/back/spv/image.rs @@ -118,6 +118,7 @@ impl Load { crate::ImageClass::Depth { .. } | crate::ImageClass::Sampled { .. } => { spirv::Op::ImageFetch } + crate::ImageClass::External => unimplemented!(), }; // `OpImageRead` and `OpImageFetch` instructions produce vec4 @@ -303,7 +304,7 @@ impl BlockContext<'_> { return Err(Error::Validation("extending vec4 coordinate")); } ref other => { - log::error!("wrong coordinate type {:?}", other); + log::error!("wrong coordinate type {other:?}"); return Err(Error::Validation("coordinate type")); } }; @@ -810,6 +811,7 @@ impl BlockContext<'_> { offset: Option>, level: crate::SampleLevel, depth_ref: Option>, + clamp_to_edge: bool, block: &mut Block, ) -> Result { use super::instructions::SampleLod; @@ -840,9 +842,99 @@ impl BlockContext<'_> { self.get_type_id(LookupType::Local(LocalType::SampledImage { image_type_id })); let sampler_id = self.get_handle_id(sampler); - let coordinates_id = self - .write_image_coordinates(coordinate, array_index, block)? - .value_id; + + let coordinates = self.write_image_coordinates(coordinate, array_index, block)?; + let coordinates_id = if clamp_to_edge { + self.writer.require_any( + "clamp sample coordinates to edge", + &[spirv::Capability::ImageQuery], + )?; + + // clamp_to_edge can only be used with Level 0, and no array offset, offset, + // depth_ref or gather. This should have been caught by validation. Rather + // than entirely duplicate validation code here just ensure the level is + // zero, as we rely on that to query the texture size in order to calculate + // the clamped coordinates. + if level != crate::SampleLevel::Zero { + return Err(Error::Validation( + "ImageSample::clamp_to_edge requires SampleLevel::Zero", + )); + } + + // Query the size of level 0 of the texture. + let image_size_id = self.gen_id(); + let vec2u_type_id = self.writer.get_vec2u_type_id(); + let const_zero_uint_id = self.writer.get_constant_scalar(crate::Literal::U32(0)); + let mut query_inst = Instruction::image_query( + spirv::Op::ImageQuerySizeLod, + vec2u_type_id, + image_size_id, + image_id, + ); + query_inst.add_operand(const_zero_uint_id); + block.body.push(query_inst); + + let image_size_f_id = self.gen_id(); + let vec2f_type_id = self.writer.get_vec2f_type_id(); + block.body.push(Instruction::unary( + spirv::Op::ConvertUToF, + vec2f_type_id, + image_size_f_id, + image_size_id, + )); + + // Calculate the top-left and bottom-right margin for clamping to. I.e. a + // half-texel from each side. + let const_0_5_f32_id = self.writer.get_constant_scalar(crate::Literal::F32(0.5)); + let const_0_5_vec2f_id = self.writer.get_constant_composite( + LookupType::Local(LocalType::Numeric(NumericType::Vector { + size: crate::VectorSize::Bi, + scalar: crate::Scalar::F32, + })), + &[const_0_5_f32_id, const_0_5_f32_id], + ); + + let margin_left_id = self.gen_id(); + block.body.push(Instruction::binary( + spirv::Op::FDiv, + vec2f_type_id, + margin_left_id, + const_0_5_vec2f_id, + image_size_f_id, + )); + + let const_1_f32_id = self.writer.get_constant_scalar(crate::Literal::F32(1.0)); + let const_1_vec2f_id = self.writer.get_constant_composite( + LookupType::Local(LocalType::Numeric(NumericType::Vector { + size: crate::VectorSize::Bi, + scalar: crate::Scalar::F32, + })), + &[const_1_f32_id, const_1_f32_id], + ); + + let margin_right_id = self.gen_id(); + block.body.push(Instruction::binary( + spirv::Op::FSub, + vec2f_type_id, + margin_right_id, + const_1_vec2f_id, + margin_left_id, + )); + + // Clamp the coords to the calculated margins + let clamped_coords_id = self.gen_id(); + block.body.push(Instruction::ext_inst( + self.writer.gl450_ext_inst_id, + spirv::GLOp::NClamp, + vec2f_type_id, + clamped_coords_id, + &[coordinates.value_id, margin_left_id, margin_right_id], + )); + + clamped_coords_id + } else { + coordinates.value_id + }; let sampled_image_id = self.gen_id(); block.body.push(Instruction::sampled_image( diff --git a/naga/src/back/spv/index.rs b/naga/src/back/spv/index.rs index 45d628e0f..3a15ee880 100644 --- a/naga/src/back/spv/index.rs +++ b/naga/src/back/spv/index.rs @@ -277,7 +277,7 @@ impl BlockContext<'_> { Ok(MaybeKnown::Computed(length_id)) } Err(err) => { - log::error!("Sequence length for {:?} failed: {}", sequence, err); + log::error!("Sequence length for {sequence:?} failed: {err}"); Err(Error::Validation("indexable length")) } } diff --git a/naga/src/back/spv/instructions.rs b/naga/src/back/spv/instructions.rs index a34790614..788c3bc11 100644 --- a/naga/src/back/spv/instructions.rs +++ b/naga/src/back/spv/instructions.rs @@ -1138,6 +1138,12 @@ impl super::Instruction { instruction.add_operand(semantics_id); instruction } + pub(super) fn memory_barrier(mem_scope_id: Word, semantics_id: Word) -> Self { + let mut instruction = Self::new(Op::MemoryBarrier); + instruction.add_operand(mem_scope_id); + instruction.add_operand(semantics_id); + instruction + } // Group Instructions @@ -1203,6 +1209,22 @@ impl super::Instruction { } instruction.add_operand(value); + instruction + } + pub(super) fn group_non_uniform_quad_swap( + result_type_id: Word, + id: Word, + exec_scope_id: Word, + value: Word, + direction: Word, + ) -> Self { + let mut instruction = Self::new(Op::GroupNonUniformQuadSwap); + instruction.set_type(result_type_id); + instruction.set_result(id); + instruction.add_operand(exec_scope_id); + instruction.add_operand(value); + instruction.add_operand(direction); + instruction } } diff --git a/naga/src/back/spv/layout.rs b/naga/src/back/spv/layout.rs index 177996741..6652b3350 100644 --- a/naga/src/back/spv/layout.rs +++ b/naga/src/back/spv/layout.rs @@ -12,7 +12,8 @@ use alloc::format; const GENERATOR: Word = 28; impl PhysicalLayout { - pub(super) const fn new(version: Word) -> Self { + pub(super) const fn new(major_version: u8, minor_version: u8) -> Self { + let version = ((major_version as u32) << 16) | ((minor_version as u32) << 8); PhysicalLayout { magic_number: MAGIC_NUMBER, version, @@ -29,6 +30,13 @@ impl PhysicalLayout { sink.extend(iter::once(self.bound)); sink.extend(iter::once(self.instruction_schema)); } + + /// Returns `(major, minor)`. + pub(super) const fn lang_version(&self) -> (u8, u8) { + let major = (self.version >> 16) as u8; + let minor = (self.version >> 8) as u8; + (major, minor) + } } impl super::recyclable::Recyclable for PhysicalLayout { @@ -150,10 +158,13 @@ impl Instruction { #[test] fn test_physical_layout_in_words() { let bound = 5; - let version = 0x10203; + + // The least and most significant bytes of `version` must both be zero + // according to the SPIR-V spec. + let version = 0x0001_0200; let mut output = vec![]; - let mut layout = PhysicalLayout::new(version); + let mut layout = PhysicalLayout::new(1, 2); layout.bound = bound; layout.in_words(&mut output); diff --git a/naga/src/back/spv/mod.rs b/naga/src/back/spv/mod.rs index 3f9fcc98e..4690dc719 100644 --- a/naga/src/back/spv/mod.rs +++ b/naga/src/back/spv/mod.rs @@ -5,6 +5,7 @@ Backend for [SPIR-V][spv] (Standard Portable Intermediate Representation). */ mod block; +mod f16_polyfill; mod helpers; mod image; mod index; @@ -77,6 +78,8 @@ pub enum Error { Override, #[error(transparent)] ResolveArraySizeError(#[from] crate::proc::ResolveArraySizeError), + #[error("mapping of {0:?} is missing")] + MissingBinding(crate::ResourceBinding), } #[derive(Default)] @@ -92,7 +95,7 @@ impl IdGenerator { #[derive(Debug, Clone)] pub struct DebugInfo<'a> { pub source_code: &'a str, - pub file_name: &'a std::path::Path, + pub file_name: &'a str, pub language: SourceLanguage, } @@ -275,6 +278,7 @@ impl LocalImageType { flags: make_flags(false, ImageTypeFlags::empty()), image_format: format.into(), }, + crate::ImageClass::External => unimplemented!(), } } } @@ -743,6 +747,7 @@ pub struct Writer { bounds_check_policies: BoundsCheckPolicies, zero_initialize_workgroup_memory: ZeroInitializeWorkgroupMemoryMode, force_loop_bounding: bool, + use_storage_input_output_16: bool, void_type: Word, //TODO: convert most of these into vectors, addressable by handle indices lookup_type: crate::FastHashMap, @@ -756,6 +761,7 @@ pub struct Writer { constant_ids: HandleVec, cached_constants: crate::FastHashMap, global_variables: HandleVec, + fake_missing_bindings: bool, binding_map: BindingMap, // Cached expressions are only meaningful within a BlockContext, but we @@ -767,7 +773,12 @@ pub struct Writer { // Just a temporary list of SPIR-V ids temp_list: Vec, - ray_get_intersection_function: Option, + ray_get_committed_intersection_function: Option, + ray_get_candidate_intersection_function: Option, + + /// F16 I/O polyfill manager for handling `f16` input/output variables + /// when `StorageInputOutput16` capability is not available. + io_f16_polyfills: f16_polyfill::F16IoPolyfill, } bitflags::bitflags! { @@ -802,10 +813,12 @@ bitflags::bitflags! { } } -#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] pub struct BindingInfo { + pub descriptor_set: u32, + pub binding: u32, /// If the binding is an unsized binding array, this overrides the size. pub binding_array_size: Option, } @@ -830,6 +843,10 @@ pub struct Options<'a> { /// Configuration flags for the writer. pub flags: WriterFlags, + /// Don't panic on missing bindings. Instead use fake values for `Binding` + /// and `DescriptorSet` decorations. This may result in invalid SPIR-V. + pub fake_missing_bindings: bool, + /// Map of resources to information about the binding. pub binding_map: BindingMap, @@ -850,6 +867,10 @@ pub struct Options<'a> { /// to think the number of iterations is bounded. pub force_loop_bounding: bool, + /// Whether to use the `StorageInputOutput16` capability for `f16` shader I/O. + /// When false, `f16` I/O is polyfilled using `f32` types with conversions. + pub use_storage_input_output_16: bool, + pub debug_info: Option>, } @@ -864,11 +885,13 @@ impl Default for Options<'_> { Options { lang_version: (1, 0), flags, + fake_missing_bindings: true, binding_map: BindingMap::default(), capabilities: None, bounds_check_policies: BoundsCheckPolicies::default(), zero_initialize_workgroup_memory: ZeroInitializeWorkgroupMemoryMode::Polyfill, force_loop_bounding: true, + use_storage_input_output_16: true, debug_info: None, } } diff --git a/naga/src/back/spv/ray.rs b/naga/src/back/spv/ray.rs index 3f6c06627..05a55c78d 100644 --- a/naga/src/back/spv/ray.rs +++ b/naga/src/back/spv/ray.rs @@ -16,9 +16,13 @@ impl Writer { is_committed: bool, ir_module: &crate::Module, ) -> spirv::Word { - if let Some(func_id) = self.ray_get_intersection_function { + if is_committed { + if let Some(func_id) = self.ray_get_committed_intersection_function { + return func_id; + } + } else if let Some(func_id) = self.ray_get_candidate_intersection_function { return func_id; - } + }; let ray_intersection = ir_module.special_types.ray_intersection.unwrap(); let intersection_type_id = self.get_handle_type_id(ray_intersection); let intersection_pointer_type_id = @@ -50,7 +54,7 @@ impl Writer { let scalar_type_id = self.get_f32_type_id(); let float_pointer_type_id = self.get_f32_pointer_type_id(spirv::StorageClass::Function); - let argument_type_id = self.get_ray_query_pointer_id(ir_module); + let argument_type_id = self.get_ray_query_pointer_id(); let func_ty = self.get_function_type(LookupFunctionType { parameter_type_ids: vec![argument_type_id], @@ -437,7 +441,11 @@ impl Writer { ); function.to_words(&mut self.logical_layout.function_definitions); - self.ray_get_intersection_function = Some(func_id); + if is_committed { + self.ray_get_committed_intersection_function = Some(func_id); + } else { + self.ray_get_candidate_intersection_function = Some(func_id); + } func_id } } diff --git a/naga/src/back/spv/subgroup.rs b/naga/src/back/spv/subgroup.rs index 6f4dc9aba..a0c35f1d6 100644 --- a/naga/src/back/spv/subgroup.rs +++ b/naga/src/back/spv/subgroup.rs @@ -125,10 +125,6 @@ impl BlockContext<'_> { result: Handle, block: &mut Block, ) -> Result<(), Error> { - self.writer.require_any( - "GroupNonUniformBallot", - &[spirv::Capability::GroupNonUniformBallot], - )?; match *mode { crate::GatherMode::BroadcastFirst => { self.writer.require_any( @@ -150,6 +146,12 @@ impl BlockContext<'_> { &[spirv::Capability::GroupNonUniformShuffleRelative], )?; } + crate::GatherMode::QuadBroadcast(_) | crate::GatherMode::QuadSwap(_) => { + self.writer.require_any( + "GroupNonUniformQuad", + &[spirv::Capability::GroupNonUniformQuad], + )?; + } } let id = self.gen_id(); @@ -174,7 +176,8 @@ impl BlockContext<'_> { | crate::GatherMode::Shuffle(index) | crate::GatherMode::ShuffleDown(index) | crate::GatherMode::ShuffleUp(index) - | crate::GatherMode::ShuffleXor(index) => { + | crate::GatherMode::ShuffleXor(index) + | crate::GatherMode::QuadBroadcast(index) => { let index_id = self.cached[index]; let op = match *mode { crate::GatherMode::BroadcastFirst => unreachable!(), @@ -187,6 +190,8 @@ impl BlockContext<'_> { crate::GatherMode::ShuffleDown(_) => spirv::Op::GroupNonUniformShuffleDown, crate::GatherMode::ShuffleUp(_) => spirv::Op::GroupNonUniformShuffleUp, crate::GatherMode::ShuffleXor(_) => spirv::Op::GroupNonUniformShuffleXor, + crate::GatherMode::QuadBroadcast(_) => spirv::Op::GroupNonUniformQuadBroadcast, + crate::GatherMode::QuadSwap(_) => unreachable!(), }; block.body.push(Instruction::group_non_uniform_gather( op, @@ -197,6 +202,20 @@ impl BlockContext<'_> { index_id, )); } + crate::GatherMode::QuadSwap(direction) => { + let direction = self.get_index_constant(match direction { + crate::Direction::X => 0, + crate::Direction::Y => 1, + crate::Direction::Diagonal => 2, + }); + block.body.push(Instruction::group_non_uniform_quad_swap( + result_type_id, + id, + exec_scope_id, + arg_id, + direction, + )); + } } self.cached[result] = id; Ok(()) diff --git a/naga/src/back/spv/writer.rs b/naga/src/back/spv/writer.rs index 7b2f15c36..1beb86577 100644 --- a/naga/src/back/spv/writer.rs +++ b/naga/src/back/spv/writer.rs @@ -1,8 +1,4 @@ -use alloc::{ - string::{String, ToString}, - vec, - vec::Vec, -}; +use alloc::{string::String, vec, vec::Vec}; use hashbrown::hash_map::Entry; use spirv::Word; @@ -60,7 +56,6 @@ impl Writer { if major != 1 { return Err(Error::UnsupportedVersion(major, minor)); } - let raw_version = ((major as u32) << 16) | ((minor as u32) << 8); let mut capabilities_used = crate::FastIndexSet::default(); capabilities_used.insert(spirv::Capability::Shader); @@ -70,7 +65,7 @@ impl Writer { let void_type = id_gen.next(); Ok(Writer { - physical_layout: PhysicalLayout::new(raw_version), + physical_layout: PhysicalLayout::new(major, minor), logical_layout: LogicalLayout::default(), id_gen, capabilities_available: options.capabilities.clone(), @@ -82,6 +77,7 @@ impl Writer { bounds_check_policies: options.bounds_check_policies, zero_initialize_workgroup_memory: options.zero_initialize_workgroup_memory, force_loop_bounding: options.force_loop_bounding, + use_storage_input_output_16: options.use_storage_input_output_16, void_type, lookup_type: crate::FastHashMap::default(), lookup_function: crate::FastHashMap::default(), @@ -90,14 +86,42 @@ impl Writer { constant_ids: HandleVec::new(), cached_constants: crate::FastHashMap::default(), global_variables: HandleVec::new(), + fake_missing_bindings: options.fake_missing_bindings, binding_map: options.binding_map.clone(), saved_cached: CachedExpressions::default(), gl450_ext_inst_id, temp_list: Vec::new(), - ray_get_intersection_function: None, + ray_get_committed_intersection_function: None, + ray_get_candidate_intersection_function: None, + io_f16_polyfills: super::f16_polyfill::F16IoPolyfill::new( + options.use_storage_input_output_16, + ), }) } + pub fn set_options(&mut self, options: &Options) -> Result<(), Error> { + let (major, minor) = options.lang_version; + if major != 1 { + return Err(Error::UnsupportedVersion(major, minor)); + } + self.physical_layout = PhysicalLayout::new(major, minor); + self.capabilities_available = options.capabilities.clone(); + self.flags = options.flags; + self.bounds_check_policies = options.bounds_check_policies; + self.zero_initialize_workgroup_memory = options.zero_initialize_workgroup_memory; + self.force_loop_bounding = options.force_loop_bounding; + self.use_storage_input_output_16 = options.use_storage_input_output_16; + self.binding_map = options.binding_map.clone(); + self.io_f16_polyfills = + super::f16_polyfill::F16IoPolyfill::new(options.use_storage_input_output_16); + Ok(()) + } + + /// Returns `(major, minor)` of the SPIR-V language version. + pub const fn lang_version(&self) -> (u8, u8) { + self.physical_layout.lang_version() + } + /// Reset `Writer` to its initial state, retaining any allocations. /// /// Why not just implement `Recyclable` for `Writer`? By design, @@ -123,7 +147,9 @@ impl Writer { bounds_check_policies: self.bounds_check_policies, zero_initialize_workgroup_memory: self.zero_initialize_workgroup_memory, force_loop_bounding: self.force_loop_bounding, + use_storage_input_output_16: self.use_storage_input_output_16, capabilities_available: take(&mut self.capabilities_available), + fake_missing_bindings: self.fake_missing_bindings, binding_map: take(&mut self.binding_map), // Initialized afresh: @@ -147,7 +173,9 @@ impl Writer { global_variables: take(&mut self.global_variables).recycle(), saved_cached: take(&mut self.saved_cached).recycle(), temp_list: take(&mut self.temp_list).recycle(), - ray_get_intersection_function: None, + ray_get_candidate_intersection_function: None, + ray_get_committed_intersection_function: None, + io_f16_polyfills: take(&mut self.io_f16_polyfills).recycle(), }; *self = fresh; @@ -200,6 +228,43 @@ impl Writer { } } + /// Indicate that the code requires all of the listed capabilities. + /// + /// If all entries of `capabilities` appear in the available capabilities + /// specified in the [`Options`] from which this `Writer` was created + /// (including the case where [`Options::capabilities`] is `None`), add + /// them all to this `Writer`'s [`capabilities_used`] table, and return + /// `Ok(())`. If at least one of the listed capabilities is not available, + /// do not add anything to the `capabilities_used` table, and return the + /// first unavailable requested capability, wrapped in `Err()`. + /// + /// This method is does not return an [`enum@Error`] in case of failure + /// because it may be used in cases where the caller can recover (e.g., + /// with a polyfill) if the requested capabilities are not available. In + /// this case, it would be unnecessary work to find *all* the unavailable + /// requested capabilities, and to allocate a `Vec` for them, just so we + /// could return an [`Error::MissingCapabilities`]). + /// + /// [`capabilities_used`]: Writer::capabilities_used + pub(super) fn require_all( + &mut self, + capabilities: &[spirv::Capability], + ) -> Result<(), spirv::Capability> { + if let Some(ref available) = self.capabilities_available { + for requested in capabilities { + if !available.contains(requested) { + return Err(*requested); + } + } + } + + for requested in capabilities { + self.capabilities_used.insert(*requested); + } + + Ok(()) + } + /// Indicate that the code uses the given extension. pub(super) fn use_extension(&mut self, extension: &'static str) { self.extensions_used.insert(extension); @@ -258,25 +323,9 @@ impl Writer { self.get_pointer_type_id(base_id, class) } - pub(super) fn get_ray_query_pointer_id(&mut self, module: &crate::Module) -> Word { - let rq_ty = module - .types - .get(&crate::Type { - name: None, - inner: crate::TypeInner::RayQuery { - vertex_return: false, - }, - }) - .or_else(|| { - module.types.get(&crate::Type { - name: None, - inner: crate::TypeInner::RayQuery { - vertex_return: true, - }, - }) - }) - .expect("ray_query type should have been populated by the variable passed into this!"); - self.get_handle_pointer_type_id(rq_ty, spirv::StorageClass::Function) + pub(super) fn get_ray_query_pointer_id(&mut self) -> Word { + let rq_id = self.get_type_id(LookupType::Local(LocalType::RayQuery)); + self.get_pointer_type_id(rq_id, spirv::StorageClass::Function) } /// Return a SPIR-V type for a pointer to `resolution`. @@ -311,6 +360,13 @@ impl Writer { }) } + pub(super) fn get_vec2f_type_id(&mut self) -> Word { + self.get_numeric_type_id(NumericType::Vector { + size: crate::VectorSize::Bi, + scalar: crate::Scalar::F32, + }) + } + pub(super) fn get_vec3u_type_id(&mut self) -> Word { self.get_numeric_type_id(NumericType::Vector { size: crate::VectorSize::Tri, @@ -414,6 +470,26 @@ impl Writer { }) } + /// Resolve the [`BindingInfo`] for a [`crate::ResourceBinding`] from the + /// provided [`Writer::binding_map`]. + /// + /// If the specified resource is not present in the binding map this will + /// return an error, unless [`Writer::fake_missing_bindings`] is set. + fn resolve_resource_binding( + &self, + res_binding: &crate::ResourceBinding, + ) -> Result { + match self.binding_map.get(res_binding) { + Some(target) => Ok(*target), + None if self.fake_missing_bindings => Ok(BindingInfo { + descriptor_set: res_binding.group, + binding: res_binding.binding, + binding_array_size: None, + }), + None => Err(Error::MissingBinding(*res_binding)), + } + } + /// Emits code for any wrapper functions required by the expressions in ir_function. /// The IDs of any emitted functions will be stored in [`Self::wrapped_functions`]. fn write_wrapped_functions( @@ -695,10 +771,11 @@ impl Writer { binding, )?; iface.varying_ids.push(varying_id); - let id = self.id_gen.next(); - prelude - .body - .push(Instruction::load(argument_type_id, id, varying_id, None)); + let id = self.load_io_with_f16_polyfill( + &mut prelude.body, + varying_id, + argument_type_id, + ); if binding == &crate::Binding::BuiltIn(crate::BuiltIn::LocalInvocationId) { local_invocation_id = Some(id); @@ -723,13 +800,11 @@ impl Writer { binding, )?; iface.varying_ids.push(varying_id); - let id = self.id_gen.next(); - prelude - .body - .push(Instruction::load(type_id, id, varying_id, None)); + let id = + self.load_io_with_f16_polyfill(&mut prelude.body, varying_id, type_id); constituent_ids.push(id); - if binding == &crate::Binding::BuiltIn(crate::BuiltIn::GlobalInvocationId) { + if binding == &crate::Binding::BuiltIn(crate::BuiltIn::LocalInvocationId) { local_invocation_id = Some(id); } } @@ -1019,7 +1094,10 @@ impl Writer { super::ZeroInitializeWorkgroupMemoryMode::Polyfill, Some( ref mut interface @ FunctionInterface { - stage: crate::ShaderStage::Compute, + stage: + crate::ShaderStage::Compute + | crate::ShaderStage::Mesh + | crate::ShaderStage::Task, .. }, ), @@ -1090,6 +1168,35 @@ impl Writer { crate::ShaderStage::Vertex => spirv::ExecutionModel::Vertex, crate::ShaderStage::Fragment => { self.write_execution_mode(function_id, spirv::ExecutionMode::OriginUpperLeft)?; + match entry_point.early_depth_test { + Some(crate::EarlyDepthTest::Force) => { + self.write_execution_mode( + function_id, + spirv::ExecutionMode::EarlyFragmentTests, + )?; + } + Some(crate::EarlyDepthTest::Allow { conservative }) => { + // TODO: Consider emitting EarlyAndLateFragmentTestsAMD here, if available. + // https://github.khronos.org/SPIRV-Registry/extensions/AMD/SPV_AMD_shader_early_and_late_fragment_tests.html + // This permits early depth tests even if the shader writes to a storage + // binding + match conservative { + crate::ConservativeDepth::GreaterEqual => self.write_execution_mode( + function_id, + spirv::ExecutionMode::DepthGreater, + )?, + crate::ConservativeDepth::LessEqual => self.write_execution_mode( + function_id, + spirv::ExecutionMode::DepthLess, + )?, + crate::ConservativeDepth::Unchanged => self.write_execution_mode( + function_id, + spirv::ExecutionMode::DepthUnchanged, + )?, + } + } + None => {} + } if let Some(ref result) = entry_point.function.result { if contains_builtin( result.binding.as_ref(), @@ -1160,8 +1267,10 @@ impl Writer { .insert(spirv::Capability::StorageBuffer16BitAccess); self.capabilities_used .insert(spirv::Capability::UniformAndStorageBuffer16BitAccess); - self.capabilities_used - .insert(spirv::Capability::StorageInputOutput16); + if self.use_storage_input_output_16 { + self.capabilities_used + .insert(spirv::Capability::StorageInputOutput16); + } } Instruction::type_float(id, bits) } @@ -1186,6 +1295,7 @@ impl Writer { self.request_image_format_capabilities(format.into())?; false } + crate::ImageClass::External => unimplemented!(), }; match dim { @@ -1639,9 +1749,11 @@ impl Writer { Ok(id) } - pub(super) fn write_barrier(&mut self, flags: crate::Barrier, block: &mut Block) { + pub(super) fn write_control_barrier(&mut self, flags: crate::Barrier, block: &mut Block) { let memory_scope = if flags.contains(crate::Barrier::STORAGE) { spirv::Scope::Device + } else if flags.contains(crate::Barrier::SUB_GROUP) { + spirv::Scope::Subgroup } else { spirv::Scope::Workgroup }; @@ -1654,6 +1766,10 @@ impl Writer { spirv::MemorySemantics::WORKGROUP_MEMORY, flags.contains(crate::Barrier::WORK_GROUP), ); + semantics.set( + spirv::MemorySemantics::SUBGROUP_MEMORY, + flags.contains(crate::Barrier::SUB_GROUP), + ); semantics.set( spirv::MemorySemantics::IMAGE_MEMORY, flags.contains(crate::Barrier::TEXTURE), @@ -1672,6 +1788,37 @@ impl Writer { )); } + pub(super) fn write_memory_barrier(&mut self, flags: crate::Barrier, block: &mut Block) { + let mut semantics = spirv::MemorySemantics::ACQUIRE_RELEASE; + semantics.set( + spirv::MemorySemantics::UNIFORM_MEMORY, + flags.contains(crate::Barrier::STORAGE), + ); + semantics.set( + spirv::MemorySemantics::WORKGROUP_MEMORY, + flags.contains(crate::Barrier::WORK_GROUP), + ); + semantics.set( + spirv::MemorySemantics::SUBGROUP_MEMORY, + flags.contains(crate::Barrier::SUB_GROUP), + ); + semantics.set( + spirv::MemorySemantics::IMAGE_MEMORY, + flags.contains(crate::Barrier::TEXTURE), + ); + let mem_scope_id = if flags.contains(crate::Barrier::STORAGE) { + self.get_index_constant(spirv::Scope::Device as u32) + } else if flags.contains(crate::Barrier::SUB_GROUP) { + self.get_index_constant(spirv::Scope::Subgroup as u32) + } else { + self.get_index_constant(spirv::Scope::Workgroup as u32) + }; + let semantics_id = self.get_index_constant(semantics.bits()); + block + .body + .push(Instruction::memory_barrier(mem_scope_id, semantics_id)); + } + fn generate_workgroup_vars_init_block( &mut self, entry_id: Word, @@ -1772,7 +1919,7 @@ impl Writer { let mut post_if_block = Block::new(merge_id); - self.write_barrier(crate::Barrier::WORK_GROUP, &mut post_if_block); + self.write_control_barrier(crate::Barrier::WORK_GROUP, &mut post_if_block); let next_id = self.id_gen.next(); function.consume(post_if_block, Instruction::branch(next_id)); @@ -1807,8 +1954,26 @@ impl Writer { ty: Handle, binding: &crate::Binding, ) -> Result { + use crate::TypeInner; + let id = self.id_gen.next(); - let pointer_type_id = self.get_handle_pointer_type_id(ty, class); + let ty_inner = &ir_module.types[ty].inner; + let needs_polyfill = self.needs_f16_polyfill(ty_inner); + + let pointer_type_id = if needs_polyfill { + let f32_value_local = + super::f16_polyfill::F16IoPolyfill::create_polyfill_type(ty_inner) + .expect("needs_polyfill returned true but create_polyfill_type returned None"); + + let f32_type_id = self.get_localtype_id(f32_value_local); + let ptr_id = self.get_pointer_type_id(f32_type_id, class); + self.io_f16_polyfills.register_io_var(id, f32_type_id); + + ptr_id + } else { + self.get_handle_pointer_type_id(ty, class) + }; + Instruction::variable(pointer_type_id, id, class, None) .to_words(&mut self.logical_layout.declarations); @@ -1829,6 +1994,7 @@ impl Writer { interpolation, sampling, blend_src, + per_primitive: _, } => { self.decorate(id, Decoration::Location, &[location]); @@ -1927,6 +2093,14 @@ impl Writer { )?; BuiltIn::PrimitiveId } + Bi::Barycentric => { + self.require_any( + "`barycentric` built-in", + &[spirv::Capability::FragmentBarycentricKHR], + )?; + self.use_extension("SPV_KHR_fragment_shader_barycentric"); + BuiltIn::BaryCoordKHR + } Bi::SampleIndex => { self.require_any( "`sample_index` built-in", @@ -1978,6 +2152,11 @@ impl Writer { )?; BuiltIn::SubgroupLocalInvocationId } + Bi::MeshTaskSize + | Bi::CullPrimitive + | Bi::PointIndex + | Bi::LineIndices + | Bi::TriangleIndices => unreachable!(), }; self.decorate(id, Decoration::BuiltIn, &[built_in as u32]); @@ -1991,8 +2170,9 @@ impl Writer { // > shader, must be decorated Flat if class == spirv::StorageClass::Input && stage == crate::ShaderStage::Fragment { let is_flat = match ir_module.types[ty].inner { - crate::TypeInner::Scalar(scalar) - | crate::TypeInner::Vector { scalar, .. } => match scalar.kind { + TypeInner::Scalar(scalar) | TypeInner::Vector { scalar, .. } => match scalar + .kind + { Sk::Uint | Sk::Sint | Sk::Bool => true, Sk::Float => false, Sk::AbstractInt | Sk::AbstractFloat => { @@ -2014,6 +2194,49 @@ impl Writer { Ok(id) } + /// Load an IO variable, converting from `f32` to `f16` if polyfill is active. + /// Returns the id of the loaded value matching `target_type_id`. + pub(super) fn load_io_with_f16_polyfill( + &mut self, + body: &mut Vec, + varying_id: Word, + target_type_id: Word, + ) -> Word { + let tmp = self.id_gen.next(); + if let Some(f32_ty) = self.io_f16_polyfills.get_f32_io_type(varying_id) { + body.push(Instruction::load(f32_ty, tmp, varying_id, None)); + let converted = self.id_gen.next(); + super::f16_polyfill::F16IoPolyfill::emit_f32_to_f16_conversion( + tmp, + target_type_id, + converted, + body, + ); + converted + } else { + body.push(Instruction::load(target_type_id, tmp, varying_id, None)); + tmp + } + } + + /// Store an IO variable, converting from `f16` to `f32` if polyfill is active. + pub(super) fn store_io_with_f16_polyfill( + &mut self, + body: &mut Vec, + varying_id: Word, + value_id: Word, + ) { + if let Some(f32_ty) = self.io_f16_polyfills.get_f32_io_type(varying_id) { + let converted = self.id_gen.next(); + super::f16_polyfill::F16IoPolyfill::emit_f16_to_f32_conversion( + value_id, f32_ty, converted, body, + ); + body.push(Instruction::store(varying_id, converted, None)); + } else { + body.push(Instruction::store(varying_id, value_id, None)); + } + } + fn write_global_variable( &mut self, ir_module: &crate::Module, @@ -2056,13 +2279,11 @@ impl Writer { // and it is failing on 0. let mut substitute_inner_type_lookup = None; if let Some(ref res_binding) = global_variable.binding { - self.decorate(id, Decoration::DescriptorSet, &[res_binding.group]); - self.decorate(id, Decoration::Binding, &[res_binding.binding]); + let bind_target = self.resolve_resource_binding(res_binding)?; + self.decorate(id, Decoration::DescriptorSet, &[bind_target.descriptor_set]); + self.decorate(id, Decoration::Binding, &[bind_target.binding]); - if let Some(&BindingInfo { - binding_array_size: Some(remapped_binding_array_size), - }) = self.binding_map.get(res_binding) - { + if let Some(remapped_binding_array_size) = bind_target.binding_array_size { if let crate::TypeInner::BindingArray { base, .. } = ir_module.types[global_variable.ty].inner { @@ -2314,10 +2535,8 @@ impl Writer { if self.flags.contains(WriterFlags::DEBUG) { if let Some(debug_info) = debug_info.as_ref() { let source_file_id = self.id_gen.next(); - self.debugs.push(Instruction::string( - &debug_info.file_name.display().to_string(), - source_file_id, - )); + self.debugs + .push(Instruction::string(debug_info.file_name, source_file_id)); debug_info_inner = Some(DebugInfoInner { source_code: debug_info.source_code, @@ -2487,6 +2706,10 @@ impl Writer { self.decorate(id, spirv::Decoration::NonUniform, &[]); Ok(()) } + + pub(super) fn needs_f16_polyfill(&self, ty_inner: &crate::TypeInner) -> bool { + self.io_f16_polyfills.needs_polyfill(ty_inner) + } } #[test] diff --git a/naga/src/back/wgsl/writer.rs b/naga/src/back/wgsl/writer.rs index 9ca746e64..d1ebf62e6 100644 --- a/naga/src/back/wgsl/writer.rs +++ b/naga/src/back/wgsl/writer.rs @@ -5,7 +5,6 @@ use alloc::{ vec::Vec, }; use core::fmt::Write; -use hashbrown::HashSet; use super::Error; use super::ToWgslIfImplemented as _; @@ -16,7 +15,7 @@ use crate::{ self, wgsl::{address_space_str, ToWgsl, TryToWgsl}, }, - proc::{self, ExpressionKindTracker, NameKey}, + proc::{self, NameKey}, valid, Handle, Module, ShaderStage, TypeInner, }; @@ -102,7 +101,7 @@ impl Writer { module, &crate::keywords::wgsl::RESERVED_SET, // an identifier must not start with two underscore - &[], + proc::CaseInsensitiveKeywordSet::empty(), &["__", "_naga"], &mut self.names, ); @@ -110,12 +109,29 @@ impl Writer { self.required_polyfills.clear(); } - fn is_builtin_wgsl_struct(&self, module: &Module, handle: Handle) -> bool { + /// Determine if `ty` is the Naga IR presentation of a WGSL builtin type. + /// + /// Return true if `ty` refers to the Naga IR form of a WGSL builtin type + /// like `__atomic_compare_exchange_result`. + /// + /// Even though the module may use the type, the WGSL backend should avoid + /// emitting a definition for it, since it is [predeclared] in WGSL. + /// + /// This also covers types like [`NagaExternalTextureParams`], which other + /// backends use to lower WGSL constructs like external textures to their + /// implementations. WGSL can express these directly, so the types need not + /// be emitted. + /// + /// [predeclared]: https://www.w3.org/TR/WGSL/#predeclared + /// [`NagaExternalTextureParams`]: crate::ir::SpecialTypes::external_texture_params + fn is_builtin_wgsl_struct(&self, module: &Module, ty: Handle) -> bool { module .special_types .predeclared_types .values() - .any(|t| *t == handle) + .any(|t| *t == ty) + || Some(ty) == module.special_types.external_texture_params + || Some(ty) == module.special_types.external_texture_transfer_function } pub fn write(&mut self, module: &Module, info: &valid::ModuleInfo) -> BackendResult { @@ -127,9 +143,6 @@ impl Writer { self.reset(module); - // Write all needed directives. - self.write_enable_dual_source_blending_if_needed(module)?; - // Write all `enable` declarations self.write_enable_declarations(module)?; @@ -178,7 +191,6 @@ impl Writer { info: fun_info, expressions: &function.expressions, named_expressions: &function.named_expressions, - expr_kind_tracker: ExpressionKindTracker::from_arena(&function.expressions), }; // Write the function @@ -195,7 +207,7 @@ impl Writer { Attribute::Stage(ShaderStage::Compute), Attribute::WorkGroupSize(ep.workgroup_size), ], - ShaderStage::Task | ShaderStage::Mesh => unreachable!(), + ShaderStage::Mesh | ShaderStage::Task => unreachable!(), }; self.write_attributes(&attributes)?; @@ -207,7 +219,6 @@ impl Writer { info: info.get_entry_point(index), expressions: &ep.function.expressions, named_expressions: &ep.function.named_expressions, - expr_kind_tracker: ExpressionKindTracker::from_arena(&ep.function.expressions), }; self.write_function(module, &ep.function, &func_ctx)?; @@ -229,31 +240,52 @@ impl Writer { /// Helper method which writes all the `enable` declarations /// needed for a module. fn write_enable_declarations(&mut self, module: &Module) -> BackendResult { - #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] - enum WrittenDeclarations { - F16, - } + let mut needs_f16 = false; + let mut needs_dual_source_blending = false; + let mut needs_clip_distances = false; - let mut written_declarations = HashSet::new(); - - // Write all the `enable` declarations + // Determine which `enable` declarations are needed for (_, ty) in module.types.iter() { match ty.inner { TypeInner::Scalar(scalar) | TypeInner::Vector { scalar, .. } | TypeInner::Matrix { scalar, .. } => { - if scalar == crate::Scalar::F16 - && !written_declarations.contains(&WrittenDeclarations::F16) - { - writeln!(self.out, "enable f16;")?; - written_declarations.insert(WrittenDeclarations::F16); + needs_f16 |= scalar == crate::Scalar::F16; + } + TypeInner::Struct { ref members, .. } => { + for binding in members.iter().filter_map(|m| m.binding.as_ref()) { + match *binding { + crate::Binding::Location { + blend_src: Some(_), .. + } => { + needs_dual_source_blending = true; + } + crate::Binding::BuiltIn(crate::BuiltIn::ClipDistance) => { + needs_clip_distances = true; + } + _ => {} + } } } _ => {} } } - if !written_declarations.is_empty() { + // Write required declarations + let mut any_written = false; + if needs_f16 { + writeln!(self.out, "enable f16;")?; + any_written = true; + } + if needs_dual_source_blending { + writeln!(self.out, "enable dual_source_blending;")?; + any_written = true; + } + if needs_clip_distances { + writeln!(self.out, "enable clip_distances;")?; + any_written = true; + } + if any_written { // Empty line for readability writeln!(self.out)?; } @@ -406,32 +438,6 @@ impl Writer { Ok(()) } - /// Writes all the necessary directives out - fn write_enable_dual_source_blending_if_needed(&mut self, module: &Module) -> BackendResult { - // Check for dual source blending. - if module.types.iter().any(|(_handle, ty)| { - if let TypeInner::Struct { ref members, .. } = ty.inner { - members.iter().any(|member| { - member.binding.as_ref().is_some_and(|binding| { - matches!( - binding, - &crate::Binding::Location { - blend_src: Some(_), - .. - } - ) - }) - }) - } else { - false - } - }) { - writeln!(self.out, "enable dual_source_blending;")?; - } - - Ok(()) - } - /// Helper method used to write structs /// Write the full declaration of a struct type. /// @@ -483,7 +489,11 @@ impl Writer { Ok(()) } - fn write_type_inner(&mut self, module: &Module, inner: &TypeInner) -> BackendResult { + fn write_type_resolution( + &mut self, + module: &Module, + resolution: &proc::TypeResolution, + ) -> BackendResult { // This actually can't be factored out into a nice constructor method, // because the borrow checker needs to be able to see that the borrows // of `self.names` and `self.out` are disjoint. @@ -491,7 +501,7 @@ impl Writer { module, names: &self.names, }; - type_context.write_type_inner(inner, &mut self.out)?; + type_context.write_type_resolution(resolution, &mut self.out)?; Ok(()) } @@ -828,7 +838,7 @@ impl Writer { Statement::Continue => { writeln!(self.out, "{level}continue;")?; } - Statement::Barrier(barrier) => { + Statement::ControlBarrier(barrier) | Statement::MemoryBarrier(barrier) => { if barrier.contains(crate::Barrier::STORAGE) { writeln!(self.out, "{level}storageBarrier();")?; } @@ -846,6 +856,7 @@ impl Writer { } } Statement::RayQuery { .. } => unreachable!(), + Statement::MeshFunction(..) => unreachable!(), Statement::SubgroupBallot { result, predicate } => { write!(self.out, "{level}")?; let res_name = Baked(result).to_string(); @@ -943,6 +954,20 @@ impl Writer { crate::GatherMode::ShuffleXor(_) => { write!(self.out, "subgroupShuffleXor(")?; } + crate::GatherMode::QuadBroadcast(_) => { + write!(self.out, "quadBroadcast(")?; + } + crate::GatherMode::QuadSwap(direction) => match direction { + crate::Direction::X => { + write!(self.out, "quadSwapX(")?; + } + crate::Direction::Y => { + write!(self.out, "quadSwapY(")?; + } + crate::Direction::Diagonal => { + write!(self.out, "quadSwapDiagonal(")?; + } + }, } self.write_expr(module, argument, func_ctx)?; match mode { @@ -951,10 +976,12 @@ impl Writer { | crate::GatherMode::Shuffle(index) | crate::GatherMode::ShuffleDown(index) | crate::GatherMode::ShuffleUp(index) - | crate::GatherMode::ShuffleXor(index) => { + | crate::GatherMode::ShuffleXor(index) + | crate::GatherMode::QuadBroadcast(index) => { write!(self.out, ", ")?; self.write_expr(module, index, func_ctx)?; } + crate::GatherMode::QuadSwap(_) => {} } writeln!(self.out, ");")?; } @@ -1029,26 +1056,12 @@ impl Writer { func_ctx: &back::FunctionCtx, name: &str, ) -> BackendResult { - // Some functions are marked as const, but are not yet implemented as constant expression - let quantifier = if func_ctx.expr_kind_tracker.is_impl_const(handle) { - "const" - } else { - "let" - }; // Write variable name - write!(self.out, "{quantifier} {name}")?; + write!(self.out, "let {name}")?; if self.flags.contains(WriterFlags::EXPLICIT_TYPES) { write!(self.out, ": ")?; - let ty = &func_ctx.info[handle].ty; // Write variable type - match *ty { - proc::TypeResolution::Handle(handle) => { - self.write_type(module, handle)?; - } - proc::TypeResolution::Value(ref inner) => { - self.write_type_inner(module, inner)?; - } - } + self.write_type_resolution(module, &func_ctx.info[handle].ty)?; } write!(self.out, " = ")?; @@ -1147,12 +1160,12 @@ impl Writer { crate::Literal::Bool(value) => write!(self.out, "{value}")?, crate::Literal::F64(value) => write!(self.out, "{value:?}lf")?, crate::Literal::I64(value) => { - // `-9223372036854775808li` is not valid WGSL. Nor can we use the AbstractInt - // trick above, as AbstractInt also cannot represent `9223372036854775808`. - // The most negative `i64` value can only be expressed in WGSL using - // subtracting 1 from the second most negative value. + // `-9223372036854775808li` is not valid WGSL. Nor can we simply use the + // AbstractInt trick above, as AbstractInt also cannot represent + // `9223372036854775808`. Instead construct the second most negative + // AbstractInt, subtract one from it, then cast to i64. if value == i64::MIN { - write!(self.out, "{}li - 1li", value + 1)?; + write!(self.out, "i64({} - 1)", value + 1)?; } else { write!(self.out, "{value}li")?; } @@ -1308,6 +1321,7 @@ impl Writer { offset, level, depth_ref, + clamp_to_edge, } => { use crate::SampleLevel as Sl; @@ -1317,6 +1331,7 @@ impl Writer { }; let suffix_level = match level { Sl::Auto => "", + Sl::Zero if clamp_to_edge => "BaseClampToEdge", Sl::Zero | Sl::Exact(_) => "Level", Sl::Bias(_) => "Bias", Sl::Gradient { .. } => "Grad", @@ -1342,8 +1357,8 @@ impl Writer { match level { Sl::Auto => {} Sl::Zero => { - // Level 0 is implied for depth comparison - if depth_ref.is_none() { + // Level 0 is implied for depth comparison and BaseClampToEdge + if depth_ref.is_none() && !clamp_to_edge { write!(self.out, ", 0.0")?; } } @@ -1380,6 +1395,7 @@ impl Writer { offset, level: _, depth_ref, + clamp_to_edge: _, } => { let suffix_cmp = match depth_ref { Some(_) => "Compare", @@ -1776,6 +1792,10 @@ impl TypeContext for WriterTypeContext<'_> { self.names[&NameKey::Type(handle)].as_str() } + fn write_unnamed_struct(&self, _: &TypeInner, _: &mut W) -> core::fmt::Result { + unreachable!("the WGSL back end should always provide type handles"); + } + fn write_override(&self, _: Handle, _: &mut W) -> core::fmt::Result { unreachable!("overrides should be validated out"); } @@ -1803,6 +1823,7 @@ fn map_binding_to_attribute(binding: &crate::Binding) -> Vec { interpolation, sampling, blend_src: None, + per_primitive: _, } => vec![ Attribute::Location(location), Attribute::Interpolate(interpolation, sampling), @@ -1812,6 +1833,7 @@ fn map_binding_to_attribute(binding: &crate::Binding) -> Vec { interpolation, sampling, blend_src: Some(blend_src), + per_primitive: _, } => vec![ Attribute::Location(location), Attribute::BlendSrc(blend_src), diff --git a/naga/src/common/diagnostic_debug.rs b/naga/src/common/diagnostic_debug.rs new file mode 100644 index 000000000..efa3ec548 --- /dev/null +++ b/naga/src/common/diagnostic_debug.rs @@ -0,0 +1,126 @@ +//! Displaying Naga IR terms in debugging output. + +#[cfg(any(feature = "wgsl-in", feature = "wgsl-out"))] +use crate::common::wgsl::TypeContext; + +use crate::proc::TypeResolution; +use crate::{Handle, Scalar, Type, TypeInner, UniqueArena}; + +use core::fmt; + +/// A wrapper for displaying Naga IR terms in debugging output. +/// +/// This is like [`DiagnosticDisplay`], but requires weaker context +/// and produces correspondingly lower-fidelity output. For example, +/// this cannot show the override names for override-sized array +/// lengths. +/// +/// [`DiagnosticDisplay`]: super::DiagnosticDisplay +pub struct DiagnosticDebug(pub T); + +impl fmt::Debug for DiagnosticDebug<(Handle, &UniqueArena)> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (handle, ctx) = self.0; + + #[cfg(any(feature = "wgsl-in", feature = "wgsl-out"))] + ctx.write_type(handle, f)?; + + #[cfg(not(any(feature = "wgsl-in", feature = "wgsl-out")))] + { + let _ = ctx; + write!(f, "{handle:?}")?; + } + + Ok(()) + } +} + +impl fmt::Debug for DiagnosticDebug<(&TypeInner, &UniqueArena)> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (inner, ctx) = self.0; + + #[cfg(any(feature = "wgsl-in", feature = "wgsl-out"))] + ctx.write_type_inner(inner, f)?; + + #[cfg(not(any(feature = "wgsl-in", feature = "wgsl-out")))] + { + let _ = ctx; + write!(f, "{inner:?}")?; + } + + Ok(()) + } +} + +impl fmt::Debug for DiagnosticDebug<(&TypeResolution, &UniqueArena)> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (resolution, ctx) = self.0; + + #[cfg(any(feature = "wgsl-in", feature = "wgsl-out"))] + ctx.write_type_resolution(resolution, f)?; + + #[cfg(not(any(feature = "wgsl-in", feature = "wgsl-out")))] + { + let _ = ctx; + write!(f, "{resolution:?}")?; + } + + Ok(()) + } +} + +impl fmt::Debug for DiagnosticDebug { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let scalar = self.0; + + #[cfg(any(feature = "wgsl-in", feature = "wgsl-out"))] + f.write_str(&crate::common::wgsl::TryToWgsl::to_wgsl_for_diagnostics( + scalar, + ))?; + + #[cfg(not(any(feature = "wgsl-in", feature = "wgsl-out")))] + write!(f, "{scalar:?}")?; + + Ok(()) + } +} + +pub trait ForDebug: Sized { + /// Format this type using [`core::fmt::Debug`]. + /// + /// Return a value that implements the [`core::fmt::Debug`] trait + /// by displaying `self` in a language-appropriate way. For + /// example: + /// + /// # use naga::common::ForDebug; + /// # let scalar: naga::Scalar = naga::Scalar::F32; + /// log::debug!("My scalar: {:?}", scalar.for_debug()); + fn for_debug(self) -> DiagnosticDebug { + DiagnosticDebug(self) + } +} + +impl ForDebug for Scalar {} + +pub trait ForDebugWithTypes: Sized { + /// Format this type using [`core::fmt::Debug`]. + /// + /// Given an arena to look up type handles in, return a value that + /// implements the [`core::fmt::Debug`] trait by displaying `self` + /// in a language-appropriate way. For example: + /// + /// # use naga::{Span, Type, TypeInner, Scalar, UniqueArena}; + /// # use naga::common::ForDebugWithTypes; + /// # let mut types = UniqueArena::::default(); + /// # let inner = TypeInner::Scalar(Scalar::F32); + /// # let span = Span::UNDEFINED; + /// # let handle = types.insert(Type { name: None, inner }, span); + /// log::debug!("My type: {:?}", handle.for_debug(&types)); + fn for_debug(self, types: &UniqueArena) -> DiagnosticDebug<(Self, &UniqueArena)> { + DiagnosticDebug((self, types)) + } +} + +impl ForDebugWithTypes for Handle {} +impl ForDebugWithTypes for &TypeInner {} +impl ForDebugWithTypes for &TypeResolution {} diff --git a/naga/src/common/diagnostic_display.rs b/naga/src/common/diagnostic_display.rs new file mode 100644 index 000000000..2713d5a0e --- /dev/null +++ b/naga/src/common/diagnostic_display.rs @@ -0,0 +1,120 @@ +//! Displaying Naga IR terms in diagnostic output. + +use crate::proc::{GlobalCtx, Rule, TypeResolution}; +use crate::{Handle, Scalar, Type}; + +#[cfg(any(feature = "wgsl-in", feature = "wgsl-out"))] +use crate::common::wgsl::TypeContext; + +use core::fmt; + +/// A wrapper for displaying Naga IR terms in diagnostic output. +/// +/// For some Naga IR type `T`, `DiagnosticDisplay` implements +/// [`core::fmt::Display`] in a way that displays values of type `T` +/// appropriately for diagnostic messages presented to human readers. +/// +/// For example, the implementation of [`Display`] for +/// `DiagnosticDisplay` formats the type represented by the +/// given [`Scalar`] appropriately for users. +/// +/// Some types like `Handle` require contextual information like +/// a type arena to be displayed. In such cases, we implement [`Display`] +/// for a type like `DiagnosticDisplay<(Handle, GlobalCtx)>`, where +/// the [`GlobalCtx`] type provides the necessary context. +/// +/// Do not implement this type for [`TypeInner`], as that does not +/// have enough information to display struct types correctly. +/// +/// If you only need debugging output, [`DiagnosticDebug`] uses +/// easier-to-obtain context types but still does a good enough job +/// for logging or debugging. +/// +/// [`Display`]: core::fmt::Display +/// [`GlobalCtx`]: crate::proc::GlobalCtx +/// [`TypeInner`]: crate::ir::TypeInner +/// [`DiagnosticDebug`]: super::DiagnosticDebug +/// +/// ## Language-sensitive diagnostics +/// +/// Diagnostic output ought to depend on the source language from +/// which the IR was produced: diagnostics resulting from processing +/// GLSL code should use GLSL type syntax, for example. That means +/// that `DiagnosticDisplay` ought to include some indication of which +/// notation to use. +/// +/// For the moment, only WGSL output is implemented, so +/// `DiagnosticDisplay` lacks any support for this (#7268). However, +/// the plan is that all language-independent code in Naga should use +/// `DiagnosticDisplay` wherever appropriate, such that when its +/// definition is expanded to include some indication of the right +/// source language to use, any use site that does not supply this +/// indication will provoke a compile-time error. +pub struct DiagnosticDisplay(pub T); + +impl fmt::Display for DiagnosticDisplay<(&TypeResolution, GlobalCtx<'_>)> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (resolution, ctx) = self.0; + + #[cfg(any(feature = "wgsl-in", feature = "wgsl-out"))] + ctx.write_type_resolution(resolution, f)?; + + #[cfg(not(any(feature = "wgsl-in", feature = "wgsl-out")))] + { + let _ = ctx; + write!(f, "{resolution:?}")?; + } + + Ok(()) + } +} + +impl fmt::Display for DiagnosticDisplay<(Handle, GlobalCtx<'_>)> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (handle, ref ctx) = self.0; + + #[cfg(any(feature = "wgsl-in", feature = "wgsl-out"))] + ctx.write_type(handle, f)?; + + #[cfg(not(any(feature = "wgsl-in", feature = "wgsl-out")))] + { + let _ = ctx; + write!(f, "{handle:?}")?; + } + + Ok(()) + } +} + +impl fmt::Display for DiagnosticDisplay<(&str, &Rule, GlobalCtx<'_>)> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (name, rule, ref ctx) = self.0; + + #[cfg(any(feature = "wgsl-in", feature = "wgsl-out"))] + ctx.write_type_rule(name, rule, f)?; + + #[cfg(not(any(feature = "wgsl-in", feature = "wgsl-out")))] + { + let _ = ctx; + write!(f, "{name}({:?}) -> {:?}", rule.arguments, rule.conclusion)?; + } + + Ok(()) + } +} + +impl fmt::Display for DiagnosticDisplay { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let scalar = self.0; + + #[cfg(any(feature = "wgsl-in", feature = "wgsl-out"))] + f.write_str(&crate::common::wgsl::TryToWgsl::to_wgsl_for_diagnostics( + scalar, + ))?; + + #[cfg(not(any(feature = "wgsl-in", feature = "wgsl-out")))] + write!(f, "{scalar:?}")?; + + Ok(()) + } +} diff --git a/naga/src/common/mod.rs b/naga/src/common/mod.rs index 8ed039695..34de0185b 100644 --- a/naga/src/common/mod.rs +++ b/naga/src/common/mod.rs @@ -1,7 +1,13 @@ //! Code common to the front and backends for specific languages. +mod diagnostic_debug; +mod diagnostic_display; +pub mod predeclared; pub mod wgsl; +pub use diagnostic_debug::{DiagnosticDebug, ForDebug, ForDebugWithTypes}; +pub use diagnostic_display::DiagnosticDisplay; + /// Helper function that returns the string corresponding to the [`VectorSize`](crate::VectorSize) pub const fn vector_size_str(size: crate::VectorSize) -> &'static str { match size { diff --git a/naga/src/common/predeclared.rs b/naga/src/common/predeclared.rs new file mode 100644 index 000000000..0c2004f7f --- /dev/null +++ b/naga/src/common/predeclared.rs @@ -0,0 +1,33 @@ +//! Generating names for predeclared types. + +use crate::ir; + +use alloc::format; +use alloc::string::String; + +impl ir::PredeclaredType { + pub fn struct_name(&self) -> String { + use crate::PredeclaredType as Pt; + match *self { + Pt::AtomicCompareExchangeWeakResult(scalar) => { + format!( + "__atomic_compare_exchange_result<{:?},{}>", + scalar.kind, scalar.width, + ) + } + Pt::ModfResult { size, scalar } => frexp_mod_name("modf", size, scalar), + Pt::FrexpResult { size, scalar } => frexp_mod_name("frexp", size, scalar), + } + } +} + +fn frexp_mod_name(function: &str, size: Option, scalar: ir::Scalar) -> String { + let bits = 8 * scalar.width; + match size { + Some(size) => { + let size = size as u8; + format!("__{function}_result_vec{size}_f{bits}") + } + None => format!("__{function}_result_f{bits}"), + } +} diff --git a/naga/src/common/wgsl/to_wgsl.rs b/naga/src/common/wgsl/to_wgsl.rs index 82fe7c592..25847a5df 100644 --- a/naga/src/common/wgsl/to_wgsl.rs +++ b/naga/src/common/wgsl/to_wgsl.rs @@ -14,7 +14,7 @@ use alloc::string::{String, ToString}; /// /// - If a type's WGSL form requires dynamic formatting, so that /// returning a `&'static str` isn't feasible, consider implementing -/// [`std::fmt::Display`] on some wrapper type instead. +/// [`core::fmt::Display`] on some wrapper type instead. pub trait ToWgsl: Sized { /// Return WGSL source code representation of `self`. fn to_wgsl(self) -> &'static str; @@ -32,7 +32,7 @@ pub trait ToWgsl: Sized { /// /// - If a type's WGSL form requires dynamic formatting, so that /// returning a `&'static str` isn't feasible, consider implementing -/// [`std::fmt::Display`] on some wrapper type instead. +/// [`core::fmt::Display`] on some wrapper type instead. pub trait TryToWgsl: Sized { /// Return the WGSL form of `self` as a `'static` string. /// @@ -105,6 +105,8 @@ impl TryToWgsl for crate::MathFunction { Mf::Log2 => "log2", Mf::Pow => "pow", Mf::Dot => "dot", + Mf::Dot4I8Packed => "dot4I8Packed", + Mf::Dot4U8Packed => "dot4U8Packed", Mf::Cross => "cross", Mf::Distance => "distance", Mf::Length => "length", @@ -137,6 +139,8 @@ impl TryToWgsl for crate::MathFunction { Mf::Pack2x16float => "pack2x16float", Mf::Pack4xI8 => "pack4xI8", Mf::Pack4xU8 => "pack4xU8", + Mf::Pack4xI8Clamp => "pack4xI8Clamp", + Mf::Pack4xU8Clamp => "pack4xU8Clamp", Mf::Unpack4x8snorm => "unpack4x8snorm", Mf::Unpack4x8unorm => "unpack4x8unorm", Mf::Unpack2x16snorm => "unpack2x16snorm", @@ -161,9 +165,11 @@ impl TryToWgsl for crate::BuiltIn { Bi::ViewIndex => "view_index", Bi::InstanceIndex => "instance_index", Bi::VertexIndex => "vertex_index", + Bi::ClipDistance => "clip_distances", Bi::FragDepth => "frag_depth", Bi::FrontFacing => "front_facing", Bi::PrimitiveIndex => "primitive_index", + Bi::Barycentric => "barycentric", Bi::SampleIndex => "sample_index", Bi::SampleMask => "sample_mask", Bi::GlobalInvocationId => "global_invocation_id", @@ -179,12 +185,16 @@ impl TryToWgsl for crate::BuiltIn { // Non-standard built-ins. Bi::BaseInstance | Bi::BaseVertex - | Bi::ClipDistance | Bi::CullDistance | Bi::PointSize | Bi::DrawID | Bi::PointCoord - | Bi::WorkGroupSize => return None, + | Bi::WorkGroupSize + | Bi::CullPrimitive + | Bi::TriangleIndices + | Bi::LineIndices + | Bi::MeshTaskSize + | Bi::PointIndex => return None, }) } } @@ -240,7 +250,7 @@ impl ToWgsl for crate::StorageFormat { Sf::Bgra8Unorm => "bgra8unorm", Sf::Rgb10a2Uint => "rgb10a2uint", Sf::Rgb10a2Unorm => "rgb10a2unorm", - Sf::Rg11b10Ufloat => "rg11b10float", + Sf::Rg11b10Ufloat => "rg11b10ufloat", Sf::R64Uint => "r64uint", Sf::Rg32Uint => "rg32uint", Sf::Rg32Sint => "rg32sint", @@ -268,9 +278,9 @@ impl TryToWgsl for crate::Scalar { use crate::Scalar; Some(match self { - Scalar::F64 => "f64", - Scalar::F32 => "f32", Scalar::F16 => "f16", + Scalar::F32 => "f32", + Scalar::F64 => "f64", Scalar::I32 => "i32", Scalar::U32 => "u32", Scalar::I64 => "i64", @@ -348,6 +358,7 @@ pub const fn address_space_str( As::WorkGroup => "workgroup", As::Handle => return (None, None), As::Function => "function", + As::TaskPayload => return (None, None), }), None, ) diff --git a/naga/src/common/wgsl/types.rs b/naga/src/common/wgsl/types.rs index 8c3e83159..82b8eeaa6 100644 --- a/naga/src/common/wgsl/types.rs +++ b/naga/src/common/wgsl/types.rs @@ -39,6 +39,14 @@ pub trait TypeContext { out: &mut W, ) -> core::fmt::Result; + /// Write a [`TypeInner::Struct`] for which we are unable to find a name. + /// + /// The names of struct types are only available if we have `Handle`, + /// not from [`TypeInner`]. For logging and debugging, it's fine to just + /// write something helpful to the developer, but for generating WGSL, + /// this should be unreachable. + fn write_unnamed_struct(&self, inner: &TypeInner, out: &mut W) -> core::fmt::Result; + /// Write a [`TypeInner`] that has no representation as WGSL source, /// even including Naga extensions. /// @@ -133,23 +141,54 @@ pub trait TypeContext { } } + fn write_type_conclusion( + &self, + conclusion: &crate::proc::Conclusion, + out: &mut W, + ) -> core::fmt::Result { + use crate::proc::Conclusion as Co; + + match *conclusion { + Co::Value(ref inner) => self.write_type_inner(inner, out), + Co::Predeclared(ref predeclared) => out.write_str(&predeclared.struct_name()), + } + } + + fn write_type_rule( + &self, + name: &str, + rule: &crate::proc::Rule, + out: &mut W, + ) -> core::fmt::Result { + write!(out, "fn {name}(")?; + for (i, arg) in rule.arguments.iter().enumerate() { + if i > 0 { + out.write_str(", ")?; + } + self.write_type_resolution(arg, out)? + } + out.write_str(") -> ")?; + self.write_type_conclusion(&rule.conclusion, out)?; + Ok(()) + } + fn type_to_string(&self, handle: Handle) -> String { let mut buf = String::new(); self.write_type(handle, &mut buf).unwrap(); buf } - fn type_inner_to_string(&self, inner: &TypeInner) -> String { - let mut buf = String::new(); - self.write_type_inner(inner, &mut buf).unwrap(); - buf - } - fn type_resolution_to_string(&self, resolution: &TypeResolution) -> String { let mut buf = String::new(); self.write_type_resolution(resolution, &mut buf).unwrap(); buf } + + fn type_rule_to_string(&self, name: &str, rule: &crate::proc::Rule) -> String { + let mut buf = String::new(); + self.write_type_rule(name, rule, &mut buf).unwrap(); + buf + } } fn try_write_type_inner(ctx: &C, inner: &TypeInner, out: &mut W) -> Result<(), WriteTypeError> @@ -211,6 +250,9 @@ where "texture_storage_{dim_str}{arrayed_str}<{format_str}{access_str}>" )?; } + Ic::External => { + write!(out, "texture_external")?; + } } } TypeInner::Scalar(scalar) => { @@ -298,7 +340,7 @@ where } => { let (address, maybe_access) = address_space_str(space); if let Some(space) = address { - write!(out, "ptr<{}, ", space)?; + write!(out, "ptr<{space}, ")?; ctx.write_scalar(scalar, out)?; if let Some(access) = maybe_access { write!(out, ", {access}")?; @@ -329,14 +371,14 @@ where } TypeInner::AccelerationStructure { vertex_return } => { let caps = if vertex_return { "" } else { "" }; - write!(out, "acceleration_structure{}", caps)? + write!(out, "acceleration_structure{caps}")? } TypeInner::Struct { .. } => { - unreachable!("structs can only be referenced by name in WGSL"); + ctx.write_unnamed_struct(inner, out)?; } TypeInner::RayQuery { vertex_return } => { let caps = if vertex_return { "" } else { "" }; - write!(out, "ray_query{}", caps)? + write!(out, "ray_query{caps}")? } } @@ -356,3 +398,78 @@ impl From for WriteTypeError { Self::Format(err) } } + +/// Format types as WGSL based on a [`GlobalCtx`]. +/// +/// This is probably good enough for diagnostic output, but it has some +/// limitations: +/// +/// - It does not apply [`Namer`] renamings, to avoid collisions. +/// +/// - It generates invalid WGSL for anonymous struct types. +/// +/// - It doesn't write the lengths of override-expression-sized arrays +/// correctly, unless the expression is just the override identifier. +/// +/// [`GlobalCtx`]: crate::proc::GlobalCtx +/// [`Namer`]: crate::proc::Namer +impl TypeContext for crate::proc::GlobalCtx<'_> { + fn lookup_type(&self, handle: Handle) -> &crate::Type { + &self.types[handle] + } + + fn type_name(&self, handle: Handle) -> &str { + self.types[handle] + .name + .as_deref() + .unwrap_or("{anonymous type}") + } + + fn write_unnamed_struct(&self, _: &TypeInner, out: &mut W) -> core::fmt::Result { + write!(out, "{{unnamed struct}}") + } + + fn write_override( + &self, + handle: Handle, + out: &mut W, + ) -> core::fmt::Result { + match self.overrides[handle].name { + Some(ref name) => out.write_str(name), + None => write!(out, "{{anonymous override {handle:?}}}"), + } + } +} + +/// Format types as WGSL based on a `UniqueArena`. +/// +/// This is probably only good enough for logging: +/// +/// - It does not apply any kind of [`Namer`] renamings. +/// +/// - It generates invalid WGSL for anonymous struct types. +/// +/// - It doesn't write override-sized arrays properly. +/// +/// [`Namer`]: crate::proc::Namer +impl TypeContext for crate::UniqueArena { + fn lookup_type(&self, handle: Handle) -> &crate::Type { + &self[handle] + } + + fn type_name(&self, handle: Handle) -> &str { + self[handle].name.as_deref().unwrap_or("{anonymous type}") + } + + fn write_unnamed_struct(&self, inner: &TypeInner, out: &mut W) -> core::fmt::Result { + write!(out, "{{unnamed struct {inner:?}}}") + } + + fn write_override( + &self, + handle: Handle, + out: &mut W, + ) -> core::fmt::Result { + write!(out, "{{override {handle:?}}}") + } +} diff --git a/naga/src/compact/expressions.rs b/naga/src/compact/expressions.rs index b0a858786..f36d747a9 100644 --- a/naga/src/compact/expressions.rs +++ b/naga/src/compact/expressions.rs @@ -11,6 +11,9 @@ pub struct ExpressionTracer<'tracer> { /// The used map for `types`. pub types_used: &'tracer mut HandleSet, + /// The used map for global variables. + pub global_variables_used: &'tracer mut HandleSet, + /// The used map for `constants`. pub constants_used: &'tracer mut HandleSet, @@ -65,7 +68,7 @@ impl ExpressionTracer<'_> { continue; } - log::trace!("tracing new expression {:?}", expr); + log::trace!("tracing new expression {expr:?}"); self.trace_expression(expr); } } @@ -76,9 +79,7 @@ impl ExpressionTracer<'_> { // Expressions that do not contain handles that need to be traced. Ex::Literal(_) | Ex::FunctionArgument(_) - | Ex::GlobalVariable(_) | Ex::LocalVariable(_) - | Ex::CallResult(_) | Ex::SubgroupBallotResult | Ex::RayQueryProceedResult => {} @@ -134,6 +135,9 @@ impl ExpressionTracer<'_> { } => { self.expressions_used.insert(vector); } + Ex::GlobalVariable(handle) => { + self.global_variables_used.insert(handle); + } Ex::Load { pointer } => { self.expressions_used.insert(pointer); } @@ -146,6 +150,7 @@ impl ExpressionTracer<'_> { offset, ref level, depth_ref, + clamp_to_edge: _, } => { self.expressions_used .insert_iter([image, sampler, coordinate]); @@ -233,6 +238,10 @@ impl ExpressionTracer<'_> { Ex::ArrayLength(expr) => { self.expressions_used.insert(expr); } + // `CallResult` expressions do contain a function handle, but any used + // `CallResult` expression should have an associated `ir::Statement::Call` + // that we will trace. + Ex::CallResult(_) => {} Ex::AtomicResult { ty, comparison: _ } | Ex::WorkGroupUniformLoadResult { ty } | Ex::SubgroupOperationResult { ty } => { @@ -267,9 +276,7 @@ impl ModuleMap { // Expressions that do not contain handles that need to be adjusted. Ex::Literal(_) | Ex::FunctionArgument(_) - | Ex::GlobalVariable(_) | Ex::LocalVariable(_) - | Ex::CallResult(_) | Ex::SubgroupBallotResult | Ex::RayQueryProceedResult => {} @@ -306,6 +313,7 @@ impl ModuleMap { ref mut vector, pattern: _, } => adjust(vector), + Ex::GlobalVariable(ref mut handle) => self.globals.adjust(handle), Ex::Load { ref mut pointer } => adjust(pointer), Ex::ImageSample { ref mut image, @@ -316,6 +324,7 @@ impl ModuleMap { ref mut offset, ref mut level, ref mut depth_ref, + clamp_to_edge: _, } => { adjust(image); adjust(sampler); @@ -392,6 +401,9 @@ impl ModuleMap { kind: _, convert: _, } => adjust(expr), + Ex::CallResult(ref mut function) => { + self.functions.adjust(function); + } Ex::AtomicResult { ref mut ty, comparison: _, diff --git a/naga/src/compact/functions.rs b/naga/src/compact/functions.rs index 57f6f104f..dc91cade3 100644 --- a/naga/src/compact/functions.rs +++ b/naga/src/compact/functions.rs @@ -6,7 +6,10 @@ pub struct FunctionTracer<'a> { pub constants: &'a crate::Arena, pub overrides: &'a crate::Arena, + pub functions_pending: &'a mut HandleSet, + pub functions_used: &'a mut HandleSet, pub types_used: &'a mut HandleSet, + pub global_variables_used: &'a mut HandleSet, pub constants_used: &'a mut HandleSet, pub overrides_used: &'a mut HandleSet, pub global_expressions_used: &'a mut HandleSet, @@ -16,6 +19,13 @@ pub struct FunctionTracer<'a> { } impl FunctionTracer<'_> { + pub fn trace_call(&mut self, function: crate::Handle) { + if !self.functions_used.contains(function) { + self.functions_used.insert(function); + self.functions_pending.insert(function); + } + } + pub fn trace(&mut self) { for argument in self.function.arguments.iter() { self.types_used.insert(argument.ty); @@ -46,13 +56,14 @@ impl FunctionTracer<'_> { self.as_expression().trace_expressions(); } - fn as_expression(&mut self) -> super::expressions::ExpressionTracer { + fn as_expression(&mut self) -> super::expressions::ExpressionTracer<'_> { super::expressions::ExpressionTracer { constants: self.constants, overrides: self.overrides, expressions: &self.function.expressions, types_used: self.types_used, + global_variables_used: self.global_variables_used, constants_used: self.constants_used, overrides_used: self.overrides_used, expressions_used: &mut self.expressions_used, @@ -105,6 +116,6 @@ impl FunctionMap { assert!(reuse.is_empty()); // Adjust statements. - self.adjust_body(function); + self.adjust_body(function, &module_map.functions); } } diff --git a/naga/src/compact/handle_set_map.rs b/naga/src/compact/handle_set_map.rs index 5e80b954f..b3cbb909e 100644 --- a/naga/src/compact/handle_set_map.rs +++ b/naga/src/compact/handle_set_map.rs @@ -4,19 +4,43 @@ use crate::arena::{Arena, Handle, HandleSet, Range}; type Index = crate::non_max_u32::NonMaxU32; -/// A map from old handle indices to new, compressed handle indices. -pub struct HandleMap { +/// A map keyed by handles. +/// +/// In most cases, this is used to map from old handle indices to new, +/// compressed handle indices. +#[derive(Debug)] +pub struct HandleMap { /// The indices assigned to handles in the compacted module. /// /// If `new_index[i]` is `Some(n)`, then `n` is the `Index` of the /// compacted `Handle` corresponding to the pre-compacted `Handle` /// whose index is `i`. - new_index: Vec>, + new_index: Vec>, /// This type is indexed by values of type `T`. as_keys: core::marker::PhantomData, } +impl HandleMap { + pub fn with_capacity(capacity: usize) -> Self { + Self { + new_index: Vec::with_capacity(capacity), + as_keys: core::marker::PhantomData, + } + } + + pub fn get(&self, handle: Handle) -> Option<&U> { + self.new_index.get(handle.index()).unwrap_or(&None).as_ref() + } + + pub fn insert(&mut self, handle: Handle, value: U) -> Option { + if self.new_index.len() <= handle.index() { + self.new_index.resize_with(handle.index() + 1, || None); + } + self.new_index[handle.index()].replace(value) + } +} + impl HandleMap { pub fn from_set(set: HandleSet) -> Self { let mut next_index = Index::new(0).unwrap(); diff --git a/naga/src/compact/mod.rs b/naga/src/compact/mod.rs index 97cc9a7b4..a7d3d463f 100644 --- a/naga/src/compact/mod.rs +++ b/naga/src/compact/mod.rs @@ -6,56 +6,75 @@ mod types; use alloc::vec::Vec; -use crate::arena::HandleSet; -use crate::{arena, compact::functions::FunctionTracer}; +use crate::{ + arena::{self, HandleSet}, + compact::functions::FunctionTracer, + ir, +}; use handle_set_map::HandleMap; #[cfg(test)] use alloc::{format, string::ToString}; -/// Remove unused types, expressions, and constants from `module`. +/// Configuration option for [`compact`]. See [`compact`] for details. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum KeepUnused { + No, + Yes, +} + +impl From for bool { + fn from(keep_unused: KeepUnused) -> Self { + match keep_unused { + KeepUnused::No => false, + KeepUnused::Yes => true, + } + } +} + +/// Remove most unused objects from `module`, which must be valid. /// -/// Assume that the following are used by definition: +/// Always removes the following unused objects: +/// - anonymous types, overrides, and constants +/// - abstract-typed constants +/// - expressions +/// +/// If `keep_unused` is `Yes`, the following are never considered unused, +/// otherwise, they will also be removed if unused: +/// - functions /// - global variables -/// - named constants and overrides +/// - named types and overrides +/// +/// The following are never removed: +/// - named constants with a concrete type /// - special types -/// - functions and entry points, and within those: +/// - entry points +/// - within an entry point or a used function: /// - arguments /// - local variables /// - named expressions /// -/// Given those assumptions, determine which types, constants, -/// overrides, and expressions (both function-local and global -/// constant expressions) are actually used, and remove the rest, -/// adjusting all handles as necessary. The result should always be a -/// module functionally identical to the original. -/// -/// This may be useful to apply to modules generated in the snapshot -/// tests. Our backends often generate temporary names based on handle -/// indices, which means that adding or removing unused arena entries -/// can affect the output even though they have no semantic effect. -/// Such meaningless changes add noise to snapshot diffs, making -/// accurate patch review difficult. Compacting the modules before -/// generating snapshots makes the output independent of unused arena -/// entries. +/// After removing items according to the rules above, all handles in the +/// remaining objects are adjusted as necessary. When `KeepUnused` is `Yes`, the +/// resulting module should have all the named objects (except abstract-typed +/// constants) present in the original, and those objects should be functionally +/// identical. When `KeepUnused` is `No`, the resulting module should have the +/// entry points present in the original, and those entry points should be +/// functionally identical. /// /// # Panics /// /// If `module` would not pass validation, this may panic. -pub fn compact(module: &mut crate::Module) { +pub fn compact(module: &mut crate::Module, keep_unused: KeepUnused) { // The trickiest part of compaction is determining what is used and what is // not. Once we have computed that correctly, it's easy enough to call // `retain_mut` on each arena, drop unused elements, and fix up the handles // in what's left. // - // Some arenas' contents are considered used by definition, like - // `Module::global_variables` and `Module::functions`, so those are never - // compacted. - // - // But for every compactable arena in a `Module`, whether global to the - // `Module` or local to a function or entry point, the `ModuleTracer` type - // holds a bitmap indicating which elements of that arena are used. Our task - // is to populate those bitmaps correctly. + // For every compactable arena in a `Module`, whether global to the `Module` + // or local to a function or entry point, the `ModuleTracer` type holds a + // bitmap indicating which elements of that arena are used. Our task is to + // populate those bitmaps correctly. // // First, we mark everything that is considered used by definition, as // described in this function's documentation. @@ -99,70 +118,9 @@ pub fn compact(module: &mut crate::Module) { // anything it refers to could be compacted away. let mut module_tracer = ModuleTracer::new(module); - // We treat all globals as used by definition. - log::trace!("tracing global variables"); - { - for (_, global) in module.global_variables.iter() { - log::trace!("tracing global {:?}", global.name); - module_tracer.types_used.insert(global.ty); - if let Some(init) = global.init { - module_tracer.global_expressions_used.insert(init); - } - } - } - - // We treat all special types as used by definition. - log::trace!("tracing special types"); - module_tracer.trace_special_types(&module.special_types); - - // We treat all named constants as used by definition, unless they have an - // abstract type as we do not want those reaching the validator. - log::trace!("tracing named constants"); - for (handle, constant) in module.constants.iter() { - if constant.name.is_none() || module.types[constant.ty].inner.is_abstract(&module.types) { - continue; - } - - log::trace!("tracing constant {:?}", constant.name.as_ref().unwrap()); - module_tracer.constants_used.insert(handle); - module_tracer.types_used.insert(constant.ty); - module_tracer.global_expressions_used.insert(constant.init); - } - - // We treat all named overrides as used by definition. - log::trace!("tracing named overrides"); - for (handle, r#override) in module.overrides.iter() { - if r#override.name.is_some() { - log::trace!("tracing override {:?}", r#override.name.as_ref().unwrap()); - module_tracer.overrides_used.insert(handle); - module_tracer.types_used.insert(r#override.ty); - if let Some(init) = r#override.init { - module_tracer.global_expressions_used.insert(init); - } - } - } - - // We assume that all functions are used. - // - // Observe which types, constant expressions, constants, and - // expressions each function uses, and produce maps for each - // function from pre-compaction to post-compaction expression - // handles. - log::trace!("tracing functions"); - let function_maps: Vec = module - .functions - .iter() - .map(|(_, f)| { - log::trace!("tracing function {:?}", f.name); - let mut function_tracer = module_tracer.as_function(f); - function_tracer.trace(); - FunctionMap::from(function_tracer) - }) - .collect(); - - // Similarly, observe what each entry point actually uses. + // Observe what each entry point actually uses. log::trace!("tracing entry points"); - let entry_point_maps: Vec = module + let entry_point_maps = module .entry_points .iter() .map(|e| { @@ -178,13 +136,127 @@ pub fn compact(module: &mut crate::Module) { used.trace(); FunctionMap::from(used) }) - .collect(); + .collect::>(); - // Treat all named types as used. - for (handle, ty) in module.types.iter() { - log::trace!("tracing type {:?}, name {:?}", handle, ty.name); - if ty.name.is_some() { - module_tracer.types_used.insert(handle); + // Observe which types, constant expressions, constants, and expressions + // each function uses, and produce maps for each function from + // pre-compaction to post-compaction expression handles. + // + // The function tracing logic here works in conjunction with + // `FunctionTracer::trace_call`, which, when tracing a `Statement::Call` + // to a function not already identified as used, adds the called function + // to both `functions_used` and `functions_pending`. + // + // Called functions are required to appear before their callers in the + // functions arena (recursion is disallowed). We have already traced the + // entry point(s) and added any functions called directly by the entry + // point(s) to `functions_pending`. We proceed by repeatedly tracing the + // last function in `functions_pending`. By an inductive argument, any + // functions after the last function in `functions_pending` must be unused. + // + // When `KeepUnused` is active, we simply mark all functions as pending, + // and then trace all of them. + log::trace!("tracing functions"); + let mut function_maps = HandleMap::with_capacity(module.functions.len()); + if keep_unused.into() { + module_tracer.functions_used.add_all(); + module_tracer.functions_pending.add_all(); + } + while let Some(handle) = module_tracer.functions_pending.pop() { + let function = &module.functions[handle]; + log::trace!("tracing function {function:?}"); + let mut function_tracer = module_tracer.as_function(function); + function_tracer.trace(); + function_maps.insert(handle, FunctionMap::from(function_tracer)); + } + + // We treat all special types as used by definition. + log::trace!("tracing special types"); + module_tracer.trace_special_types(&module.special_types); + + log::trace!("tracing global variables"); + if keep_unused.into() { + module_tracer.global_variables_used.add_all(); + } + for global in module_tracer.global_variables_used.iter() { + log::trace!("tracing global {:?}", module.global_variables[global].name); + module_tracer + .types_used + .insert(module.global_variables[global].ty); + if let Some(init) = module.global_variables[global].init { + module_tracer.global_expressions_used.insert(init); + } + } + + // We treat all named constants as used by definition, unless they have an + // abstract type as we do not want those reaching the validator. + log::trace!("tracing named constants"); + for (handle, constant) in module.constants.iter() { + if constant.name.is_none() || module.types[constant.ty].inner.is_abstract(&module.types) { + continue; + } + + log::trace!("tracing constant {:?}", constant.name.as_ref().unwrap()); + module_tracer.constants_used.insert(handle); + module_tracer.types_used.insert(constant.ty); + module_tracer.global_expressions_used.insert(constant.init); + } + + if keep_unused.into() { + // Treat all named overrides as used. + for (handle, r#override) in module.overrides.iter() { + if r#override.name.is_some() && module_tracer.overrides_used.insert(handle) { + module_tracer.types_used.insert(r#override.ty); + if let Some(init) = r#override.init { + module_tracer.global_expressions_used.insert(init); + } + } + } + + // Treat all named types as used. + for (handle, ty) in module.types.iter() { + if ty.name.is_some() { + module_tracer.types_used.insert(handle); + } + } + } + + for entry in &module.entry_points { + if let Some(task_payload) = entry.task_payload { + module_tracer.global_variables_used.insert(task_payload); + } + if let Some(ref mesh_info) = entry.mesh_info { + module_tracer + .types_used + .insert(mesh_info.vertex_output_type); + module_tracer + .types_used + .insert(mesh_info.primitive_output_type); + if let Some(max_vertices_override) = mesh_info.max_vertices_override { + module_tracer + .global_expressions_used + .insert(max_vertices_override); + } + if let Some(max_primitives_override) = mesh_info.max_primitives_override { + module_tracer + .global_expressions_used + .insert(max_primitives_override); + } + } + if entry.stage == crate::ShaderStage::Task || entry.stage == crate::ShaderStage::Mesh { + // u32 should always be there if the module is valid, as it is e.g. the type of some expressions + let u32_type = module + .types + .iter() + .find_map(|tuple| { + if tuple.1.inner == crate::TypeInner::Scalar(crate::Scalar::U32) { + Some(tuple.0) + } else { + None + } + }) + .unwrap(); + module_tracer.types_used.insert(u32_type); } } @@ -263,25 +335,43 @@ pub fn compact(module: &mut crate::Module) { } } - // Adjust global variables' types and initializers. + // Drop unused global variables, reusing existing storage. + // Adjust used global variables' types and initializers. log::trace!("adjusting global variables"); - for (_, global) in module.global_variables.iter_mut() { - log::trace!("adjusting global {:?}", global.name); - module_map.types.adjust(&mut global.ty); - if let Some(ref mut init) = global.init { - module_map.global_expressions.adjust(init); + module.global_variables.retain_mut(|handle, global| { + if module_map.globals.used(handle) { + log::trace!("retaining global variable {:?}", global.name); + module_map.types.adjust(&mut global.ty); + if let Some(ref mut init) = global.init { + module_map.global_expressions.adjust(init); + } + true + } else { + log::trace!("dropping global variable {:?}", global.name); + false } + }); + + // Adjust doc comments + if let Some(ref mut doc_comments) = module.doc_comments { + module_map.adjust_doc_comments(doc_comments.as_mut()); } // Temporary storage to help us reuse allocations of existing // named expression tables. let mut reused_named_expressions = crate::NamedExpressions::default(); - // Compact each function. - for ((_, function), map) in module.functions.iter_mut().zip(function_maps.iter()) { - log::trace!("compacting function {:?}", function.name); - map.compact(function, &module_map, &mut reused_named_expressions); - } + // Drop unused functions. Compact and adjust used functions. + module.functions.retain_mut(|handle, function| { + if let Some(map) = function_maps.get(handle) { + log::trace!("retaining and compacting function {:?}", function.name); + map.compact(function, &module_map, &mut reused_named_expressions); + true + } else { + log::trace!("dropping function {:?}", function.name); + false + } + }); // Compact each entry point. for (entry, map) in module.entry_points.iter_mut().zip(entry_point_maps.iter()) { @@ -291,12 +381,36 @@ pub fn compact(module: &mut crate::Module) { &module_map, &mut reused_named_expressions, ); + if let Some(ref mut task_payload) = entry.task_payload { + module_map.globals.adjust(task_payload); + } + if let Some(ref mut mesh_info) = entry.mesh_info { + module_map.types.adjust(&mut mesh_info.vertex_output_type); + module_map + .types + .adjust(&mut mesh_info.primitive_output_type); + if let Some(ref mut max_vertices_override) = mesh_info.max_vertices_override { + module_map.global_expressions.adjust(max_vertices_override); + } + if let Some(ref mut max_primitives_override) = mesh_info.max_primitives_override { + module_map + .global_expressions + .adjust(max_primitives_override); + } + } } } struct ModuleTracer<'module> { module: &'module crate::Module, + + /// The subset of functions in `functions_used` that have not yet been + /// traced. + functions_pending: HandleSet, + + functions_used: HandleSet, types_used: HandleSet, + global_variables_used: HandleSet, constants_used: HandleSet, overrides_used: HandleSet, global_expressions_used: HandleSet, @@ -306,7 +420,10 @@ impl<'module> ModuleTracer<'module> { fn new(module: &'module crate::Module) -> Self { Self { module, + functions_pending: HandleSet::for_arena(&module.functions), + functions_used: HandleSet::for_arena(&module.functions), types_used: HandleSet::for_arena(&module.types), + global_variables_used: HandleSet::for_arena(&module.global_variables), constants_used: HandleSet::for_arena(&module.constants), overrides_used: HandleSet::for_arena(&module.overrides), global_expressions_used: HandleSet::for_arena(&module.global_expressions), @@ -319,6 +436,8 @@ impl<'module> ModuleTracer<'module> { ref ray_intersection, ref ray_vertex_return, ref predeclared_types, + ref external_texture_params, + ref external_texture_transfer_function, } = *special_types; if let Some(ray_desc) = *ray_desc { @@ -330,6 +449,15 @@ impl<'module> ModuleTracer<'module> { if let Some(ray_vertex_return) = *ray_vertex_return { self.types_used.insert(ray_vertex_return); } + // The `external_texture_params` type is generated purely as a + // convenience to the backends. While it will never actually be used in + // the IR, it must be marked as used so that it survives compaction. + if let Some(external_texture_params) = *external_texture_params { + self.types_used.insert(external_texture_params); + } + if let Some(external_texture_transfer_function) = *external_texture_transfer_function { + self.types_used.insert(external_texture_transfer_function); + } for (_, &handle) in predeclared_types { self.types_used.insert(handle); } @@ -399,7 +527,7 @@ impl<'module> ModuleTracer<'module> { } } - fn as_type(&mut self) -> types::TypeTracer { + fn as_type(&mut self) -> types::TypeTracer<'_> { types::TypeTracer { overrides: &self.module.overrides, types_used: &mut self.types_used, @@ -408,12 +536,13 @@ impl<'module> ModuleTracer<'module> { } } - fn as_const_expression(&mut self) -> expressions::ExpressionTracer { + fn as_const_expression(&mut self) -> expressions::ExpressionTracer<'_> { expressions::ExpressionTracer { constants: &self.module.constants, overrides: &self.module.overrides, expressions: &self.module.global_expressions, types_used: &mut self.types_used, + global_variables_used: &mut self.global_variables_used, constants_used: &mut self.constants_used, expressions_used: &mut self.global_expressions_used, overrides_used: &mut self.overrides_used, @@ -429,7 +558,10 @@ impl<'module> ModuleTracer<'module> { function, constants: &self.module.constants, overrides: &self.module.overrides, + functions_pending: &mut self.functions_pending, + functions_used: &mut self.functions_used, types_used: &mut self.types_used, + global_variables_used: &mut self.global_variables_used, constants_used: &mut self.constants_used, overrides_used: &mut self.overrides_used, global_expressions_used: &mut self.global_expressions_used, @@ -439,7 +571,9 @@ impl<'module> ModuleTracer<'module> { } struct ModuleMap { + functions: HandleMap, types: HandleMap, + globals: HandleMap, constants: HandleMap, overrides: HandleMap, global_expressions: HandleMap, @@ -448,7 +582,9 @@ struct ModuleMap { impl From> for ModuleMap { fn from(used: ModuleTracer) -> Self { ModuleMap { + functions: HandleMap::from_set(used.functions_used), types: HandleMap::from_set(used.types_used), + globals: HandleMap::from_set(used.global_variables_used), constants: HandleMap::from_set(used.constants_used), overrides: HandleMap::from_set(used.overrides_used), global_expressions: HandleMap::from_set(used.global_expressions_used), @@ -463,6 +599,8 @@ impl ModuleMap { ref mut ray_intersection, ref mut ray_vertex_return, ref mut predeclared_types, + ref mut external_texture_params, + ref mut external_texture_transfer_function, } = *special; if let Some(ref mut ray_desc) = *ray_desc { @@ -476,10 +614,72 @@ impl ModuleMap { self.types.adjust(ray_vertex_return); } + if let Some(ref mut external_texture_params) = *external_texture_params { + self.types.adjust(external_texture_params); + } + + if let Some(ref mut external_texture_transfer_function) = + *external_texture_transfer_function + { + self.types.adjust(external_texture_transfer_function); + } + for handle in predeclared_types.values_mut() { self.types.adjust(handle); } } + + fn adjust_doc_comments(&self, doc_comments: &mut ir::DocComments) { + let crate::DocComments { + module: _, + types: ref mut doc_types, + struct_members: ref mut doc_struct_members, + entry_points: _, + functions: ref mut doc_functions, + constants: ref mut doc_constants, + global_variables: ref mut doc_globals, + } = *doc_comments; + log::trace!("adjusting doc comments for types"); + for (mut ty, doc_comment) in core::mem::take(doc_types) { + if !self.types.used(ty) { + continue; + } + self.types.adjust(&mut ty); + doc_types.insert(ty, doc_comment); + } + log::trace!("adjusting doc comments for struct members"); + for ((mut ty, index), doc_comment) in core::mem::take(doc_struct_members) { + if !self.types.used(ty) { + continue; + } + self.types.adjust(&mut ty); + doc_struct_members.insert((ty, index), doc_comment); + } + log::trace!("adjusting doc comments for functions"); + for (mut handle, doc_comment) in core::mem::take(doc_functions) { + if !self.functions.used(handle) { + continue; + } + self.functions.adjust(&mut handle); + doc_functions.insert(handle, doc_comment); + } + log::trace!("adjusting doc comments for constants"); + for (mut constant, doc_comment) in core::mem::take(doc_constants) { + if !self.constants.used(constant) { + continue; + } + self.constants.adjust(&mut constant); + doc_constants.insert(constant, doc_comment); + } + log::trace!("adjusting doc comments for globals"); + for (mut handle, doc_comment) in core::mem::take(doc_globals) { + if !self.globals.used(handle) { + continue; + } + self.globals.adjust(&mut handle); + doc_globals.insert(handle, doc_comment); + } + } } struct FunctionMap { @@ -559,7 +759,7 @@ fn type_expression_interdependence() { }; let mut type_name_counter = 0; let mut type_needed = |module: &mut crate::Module, handle| { - let name = Some(format!("type{}", type_name_counter)); + let name = Some(format!("type{type_name_counter}")); type_name_counter += 1; module.types.insert( crate::Type { @@ -575,7 +775,7 @@ fn type_expression_interdependence() { }; let mut override_name_counter = 0; let mut expression_needed = |module: &mut crate::Module, handle| { - let name = Some(format!("override{}", override_name_counter)); + let name = Some(format!("override{override_name_counter}")); override_name_counter += 1; module.overrides.append( crate::Override { @@ -602,7 +802,7 @@ fn type_expression_interdependence() { let ty_init = type_needs_expression(&mut module, expr_trace); type_needed(&mut module, ty_init); let untouched = module.clone(); - compact(&mut module); + compact(&mut module, KeepUnused::Yes); assert!(cmp_modules(&module, &untouched)); let unused_expr = module.global_expressions.append( crate::Expression::Literal(crate::Literal::U32(1)), @@ -610,7 +810,7 @@ fn type_expression_interdependence() { ); type_needs_expression(&mut module, unused_expr); assert!(!cmp_modules(&module, &untouched)); - compact(&mut module); + compact(&mut module, KeepUnused::Yes); assert!(cmp_modules(&module, &untouched)); } @@ -671,7 +871,7 @@ fn array_length_override() { ); assert!(validator.validate(&module).is_ok()); - compact(&mut module); + compact(&mut module, KeepUnused::Yes); assert!(validator.validate(&module).is_ok()); } @@ -777,7 +977,7 @@ fn array_length_override_mutual() { ); assert!(validator.validate(&module).is_ok()); - compact(&mut module); + compact(&mut module, KeepUnused::Yes); assert!(validator.validate(&module).is_ok()); } @@ -826,7 +1026,7 @@ fn array_length_expression() { ); assert!(validator.validate(&module).is_ok()); - compact(&mut module); + compact(&mut module, KeepUnused::Yes); assert!(validator.validate(&module).is_ok()); } @@ -882,7 +1082,7 @@ fn global_expression_override() { ); assert!(validator.validate(&module).is_ok()); - compact(&mut module); + compact(&mut module, KeepUnused::Yes); assert!(validator.validate(&module).is_ok()); } @@ -953,7 +1153,7 @@ fn local_expression_override() { ); assert!(validator.validate(&module).is_ok()); - compact(&mut module); + compact(&mut module, KeepUnused::Yes); assert!(validator.validate(&module).is_ok()); } @@ -1025,7 +1225,7 @@ fn unnamed_constant_type() { ); assert!(validator.validate(&module).is_ok()); - compact(&mut module); + compact(&mut module, KeepUnused::Yes); assert!(validator.validate(&module).is_ok()); } @@ -1097,6 +1297,6 @@ fn unnamed_override_type() { ); assert!(validator.validate(&module).is_ok()); - compact(&mut module); + compact(&mut module, KeepUnused::Yes); assert!(validator.validate(&module).is_ok()); } diff --git a/naga/src/compact/statements.rs b/naga/src/compact/statements.rs index 32a8130fd..b370501ba 100644 --- a/naga/src/compact/statements.rs +++ b/naga/src/compact/statements.rs @@ -3,6 +3,7 @@ use alloc::{vec, vec::Vec}; use super::functions::FunctionTracer; use super::FunctionMap; use crate::arena::Handle; +use crate::compact::handle_set_map::HandleMap; impl FunctionTracer<'_> { pub fn trace_block(&mut self, block: &[crate::Statement]) { @@ -100,10 +101,11 @@ impl FunctionTracer<'_> { self.expressions_used.insert(result); } St::Call { - function: _, + function, ref arguments, result, } => { + self.trace_call(function); for expr in arguments { self.expressions_used.insert(*expr); } @@ -115,6 +117,20 @@ impl FunctionTracer<'_> { self.expressions_used.insert(query); self.trace_ray_query_function(fun); } + St::MeshFunction(crate::MeshFunction::SetMeshOutputs { + vertex_count, + primitive_count, + }) => { + self.expressions_used.insert(vertex_count); + self.expressions_used.insert(primitive_count); + } + St::MeshFunction( + crate::MeshFunction::SetPrimitive { index, value } + | crate::MeshFunction::SetVertex { index, value }, + ) => { + self.expressions_used.insert(index); + self.expressions_used.insert(value); + } St::SubgroupBallot { result, predicate } => { if let Some(predicate) = predicate { self.expressions_used.insert(predicate); @@ -141,9 +157,11 @@ impl FunctionTracer<'_> { | crate::GatherMode::Shuffle(index) | crate::GatherMode::ShuffleDown(index) | crate::GatherMode::ShuffleUp(index) - | crate::GatherMode::ShuffleXor(index) => { + | crate::GatherMode::ShuffleXor(index) + | crate::GatherMode::QuadBroadcast(index) => { self.expressions_used.insert(index); } + crate::GatherMode::QuadSwap(_) => {} } self.expressions_used.insert(argument); self.expressions_used.insert(result); @@ -153,7 +171,8 @@ impl FunctionTracer<'_> { St::Break | St::Continue | St::Kill - | St::Barrier(_) + | St::ControlBarrier(_) + | St::MemoryBarrier(_) | St::Return { value: None } => {} } } @@ -202,7 +221,15 @@ impl FunctionTracer<'_> { } impl FunctionMap { - pub fn adjust_body(&self, function: &mut crate::Function) { + /// Adjust statements in the body of `function`. + /// + /// Adjusts expressions using `self.expressions`, and adjusts calls to other + /// functions using `function_map`. + pub fn adjust_body( + &self, + function: &mut crate::Function, + function_map: &HandleMap, + ) { let block = &mut function.body; let mut worklist: Vec<&mut [crate::Statement]> = vec![block]; let adjust = |handle: &mut Handle| { @@ -303,10 +330,11 @@ impl FunctionMap { adjust(result); } St::Call { - function: _, + ref mut function, ref mut arguments, ref mut result, } => { + function_map.adjust(function); for expr in arguments { adjust(expr); } @@ -321,6 +349,26 @@ impl FunctionMap { adjust(query); self.adjust_ray_query_function(fun); } + St::MeshFunction(crate::MeshFunction::SetMeshOutputs { + ref mut vertex_count, + ref mut primitive_count, + }) => { + adjust(vertex_count); + adjust(primitive_count); + } + St::MeshFunction( + crate::MeshFunction::SetVertex { + ref mut index, + ref mut value, + } + | crate::MeshFunction::SetPrimitive { + ref mut index, + ref mut value, + }, + ) => { + adjust(index); + adjust(value); + } St::SubgroupBallot { ref mut result, ref mut predicate, @@ -350,7 +398,9 @@ impl FunctionMap { | crate::GatherMode::Shuffle(ref mut index) | crate::GatherMode::ShuffleDown(ref mut index) | crate::GatherMode::ShuffleUp(ref mut index) - | crate::GatherMode::ShuffleXor(ref mut index) => adjust(index), + | crate::GatherMode::ShuffleXor(ref mut index) + | crate::GatherMode::QuadBroadcast(ref mut index) => adjust(index), + crate::GatherMode::QuadSwap(_) => {} } adjust(argument); adjust(result); @@ -360,7 +410,8 @@ impl FunctionMap { St::Break | St::Continue | St::Kill - | St::Barrier(_) + | St::ControlBarrier(_) + | St::MemoryBarrier(_) | St::Return { value: None } => {} } } diff --git a/naga/src/diagnostic_filter.rs b/naga/src/diagnostic_filter.rs index 37fb92612..16b8de669 100644 --- a/naga/src/diagnostic_filter.rs +++ b/naga/src/diagnostic_filter.rs @@ -4,12 +4,12 @@ use alloc::boxed::Box; use crate::{Arena, Handle}; +#[cfg(feature = "wgsl-in")] +use crate::FastIndexMap; #[cfg(feature = "wgsl-in")] use crate::Span; #[cfg(feature = "arbitrary")] use arbitrary::Arbitrary; -#[cfg(feature = "wgsl-in")] -use indexmap::IndexMap; #[cfg(feature = "deserialize")] use serde::Deserialize; #[cfg(feature = "serialize")] @@ -133,7 +133,7 @@ pub(crate) enum ShouldConflictOnFullDuplicate { /// [`add`]: DiagnosticFilterMap::add #[derive(Clone, Debug, Default)] #[cfg(feature = "wgsl-in")] -pub(crate) struct DiagnosticFilterMap(IndexMap); +pub(crate) struct DiagnosticFilterMap(FastIndexMap); #[cfg(feature = "wgsl-in")] impl DiagnosticFilterMap { diff --git a/naga/src/error.rs b/naga/src/error.rs index 81aa99d9d..282cb6c88 100644 --- a/naga/src/error.rs +++ b/naga/src/error.rs @@ -1,4 +1,4 @@ -use alloc::{boxed::Box, string::String, vec::Vec}; +use alloc::{borrow::Cow, boxed::Box, string::String}; use core::{error::Error, fmt}; #[derive(Clone, Debug)] @@ -17,6 +17,7 @@ impl fmt::Display for ShaderError { write!(f, "\nShader '{label}' parsing {string}") } } + #[cfg(feature = "glsl-in")] impl fmt::Display for ShaderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -25,6 +26,7 @@ impl fmt::Display for ShaderError { write!(f, "\nShader '{label}' parsing {string}") } } + #[cfg(feature = "spv-in")] impl fmt::Display for ShaderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -33,29 +35,134 @@ impl fmt::Display for ShaderError { write!(f, "\nShader '{label}' parsing {string}") } } + impl fmt::Display for ShaderError> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use codespan_reporting::{files::SimpleFile, term}; let label = self.label.as_deref().unwrap_or_default(); - let files = SimpleFile::new(label, &self.source); + let files = SimpleFile::new(label, replace_control_chars(&self.source)); let config = term::Config::default(); - let mut writer = term::termcolor::NoColor::new(Vec::new()); - term::emit(&mut writer, &config, &files, &self.inner.diagnostic()) + + let writer = { + let mut writer = DiagnosticBuffer::new(); + term::emit( + writer.inner_mut(), + &config, + &files, + &self.inner.diagnostic(), + ) .expect("cannot write error"); - write!( - f, - "\nShader validation {}", - String::from_utf8_lossy(&writer.into_inner()) - ) + writer.into_string() + }; + + write!(f, "\nShader validation {writer}") } } + +cfg_if::cfg_if! { + if #[cfg(feature = "termcolor")] { + type DiagnosticBufferInner = codespan_reporting::term::termcolor::NoColor>; + pub(crate) use codespan_reporting::term::termcolor::WriteColor as _ErrorWrite; + } else if #[cfg(feature = "stderr")] { + type DiagnosticBufferInner = alloc::vec::Vec; + pub(crate) use std::io::Write as _ErrorWrite; + } else { + type DiagnosticBufferInner = String; + pub(crate) use core::fmt::Write as _ErrorWrite; + } +} + +// Using this indirect export to avoid duplicating the expect(...) for all three cases above. +#[cfg_attr( + not(any(feature = "spv-in", feature = "glsl-in")), + expect( + unused_imports, + reason = "only need `ErrorWrite` with an appropriate front-end." + ) +)] +pub(crate) use _ErrorWrite as ErrorWrite; + +pub(crate) struct DiagnosticBuffer { + inner: DiagnosticBufferInner, +} + +impl DiagnosticBuffer { + #[cfg_attr( + not(feature = "termcolor"), + expect( + clippy::missing_const_for_fn, + reason = "`NoColor::new` isn't `const`, but other `inner`s are." + ) + )] + pub fn new() -> Self { + cfg_if::cfg_if! { + if #[cfg(feature = "termcolor")] { + let inner = codespan_reporting::term::termcolor::NoColor::new(alloc::vec::Vec::new()); + } else if #[cfg(feature = "stderr")] { + let inner = alloc::vec::Vec::new(); + } else { + let inner = String::new(); + } + }; + + Self { inner } + } + + pub fn inner_mut(&mut self) -> &mut DiagnosticBufferInner { + &mut self.inner + } + + pub fn into_string(self) -> String { + let Self { inner } = self; + + cfg_if::cfg_if! { + if #[cfg(feature = "termcolor")] { + String::from_utf8(inner.into_inner()).unwrap() + } else if #[cfg(feature = "stderr")] { + String::from_utf8(inner).unwrap() + } else { + inner + } + } + } +} + impl Error for ShaderError where ShaderError: fmt::Display, E: Error + 'static, { fn source(&self) -> Option<&(dyn Error + 'static)> { - Some(&self.inner) + self.inner.source() } } + +pub(crate) fn replace_control_chars(s: &str) -> Cow<'_, str> { + const REPLACEMENT_CHAR: &str = "\u{FFFD}"; + debug_assert_eq!( + REPLACEMENT_CHAR.chars().next().unwrap(), + char::REPLACEMENT_CHARACTER + ); + + let mut res = Cow::Borrowed(s); + let mut offset = 0; + + while let Some(found_pos) = res[offset..].find(|c: char| c.is_control() && !c.is_whitespace()) { + offset += found_pos; + let found_len = res[offset..].chars().next().unwrap().len_utf8(); + res.to_mut() + .replace_range(offset..offset + found_len, REPLACEMENT_CHAR); + offset += REPLACEMENT_CHAR.len(); + } + + res +} + +#[test] +fn test_replace_control_chars() { + // The UTF-8 encoding of \u{0080} is multiple bytes. + let input = "Foo\u{0080}Bar\u{0001}Baz\n"; + let expected = "Foo\u{FFFD}Bar\u{FFFD}Baz\n"; + assert_eq!(replace_control_chars(input), expected); +} diff --git a/naga/src/front/glsl/builtins.rs b/naga/src/front/glsl/builtins.rs index f73004aa9..3d7588d27 100644 --- a/naga/src/front/glsl/builtins.rs +++ b/naga/src/front/glsl/builtins.rs @@ -2035,8 +2035,10 @@ impl MacroCall { )?, MacroCall::Barrier => { ctx.emit_restart(); - ctx.body - .push(crate::Statement::Barrier(crate::Barrier::all()), meta); + ctx.body.push( + crate::Statement::ControlBarrier(crate::Barrier::all()), + meta, + ); return Ok(None); } MacroCall::SmoothStep { splatted } => { @@ -2083,6 +2085,7 @@ fn texture_call( offset, level, depth_ref: comps.depth_ref, + clamp_to_edge: false, }, meta, )?) @@ -2135,6 +2138,7 @@ impl Frontend { ImageClass::Depth { .. } => (true, false), ImageClass::Storage { .. } => (false, true), ImageClass::Sampled { .. } => (false, false), + ImageClass::External => unreachable!(), }; let coordinate = match (image_size, coord_size) { @@ -2256,6 +2260,7 @@ pub fn sampled_to_depth( kind: ErrorKind::SemanticError("Not a texture".into()), meta, }), + ImageClass::External => unreachable!(), }, _ => errors.push(Error { kind: ErrorKind::SemanticError("Not a texture".into()), diff --git a/naga/src/front/glsl/context.rs b/naga/src/front/glsl/context.rs index e6c5546fb..d65004499 100644 --- a/naga/src/front/glsl/context.rs +++ b/naga/src/front/glsl/context.rs @@ -541,7 +541,7 @@ impl<'a> Context<'a> { ) -> Result<(Option>, Span)> { let HirExpr { ref kind, meta } = stmt.hir_exprs[expr]; - log::debug!("Lowering {:?} (kind {:?}, pos {:?})", expr, kind, pos); + log::debug!("Lowering {expr:?} (kind {kind:?}, pos {pos:?})"); let handle = match *kind { HirExprKind::Access { base, index } => { @@ -636,8 +636,7 @@ impl<'a> Context<'a> { frontend.errors.push(Error { kind: ErrorKind::SemanticError( format!( - "Cannot apply operation to {:?} and {:?}", - left_inner, right_inner + "Cannot apply operation to {left_inner:?} and {right_inner:?}" ) .into(), ), @@ -835,8 +834,7 @@ impl<'a> Context<'a> { frontend.errors.push(Error { kind: ErrorKind::SemanticError( format!( - "Cannot apply operation to {:?} and {:?}", - left_inner, right_inner + "Cannot apply operation to {left_inner:?} and {right_inner:?}" ) .into(), ), @@ -916,8 +914,7 @@ impl<'a> Context<'a> { frontend.errors.push(Error { kind: ErrorKind::SemanticError( format!( - "Cannot apply operation to {:?} and {:?}", - left_inner, right_inner + "Cannot apply operation to {left_inner:?} and {right_inner:?}" ) .into(), ), @@ -1339,13 +1336,7 @@ impl<'a> Context<'a> { } }; - log::trace!( - "Lowered {:?}\n\tKind = {:?}\n\tPos = {:?}\n\tResult = {:?}", - expr, - kind, - pos, - handle - ); + log::trace!("Lowered {expr:?}\n\tKind = {kind:?}\n\tPos = {pos:?}\n\tResult = {handle:?}"); Ok((Some(handle), meta)) } diff --git a/naga/src/front/glsl/error.rs b/naga/src/front/glsl/error.rs index 13c679019..9c9e58549 100644 --- a/naga/src/front/glsl/error.rs +++ b/naga/src/front/glsl/error.rs @@ -8,13 +8,12 @@ use alloc::{ use codespan_reporting::diagnostic::{Diagnostic, Label}; use codespan_reporting::files::SimpleFile; use codespan_reporting::term; -use codespan_reporting::term::termcolor::{NoColor, WriteColor}; use pp_rs::token::PreprocessorError; use thiserror::Error; use super::token::TokenValue; -use crate::SourceLocation; -use crate::{proc::ConstantEvaluatorError, Span}; +use crate::{error::replace_control_chars, SourceLocation}; +use crate::{error::ErrorWrite, proc::ConstantEvaluatorError, Span}; fn join_with_comma(list: &[ExpectedToken]) -> String { let mut string = "".to_string(); @@ -166,13 +165,13 @@ pub struct ParseErrors { } impl ParseErrors { - pub fn emit_to_writer(&self, writer: &mut impl WriteColor, source: &str) { + pub fn emit_to_writer(&self, writer: &mut impl ErrorWrite, source: &str) { self.emit_to_writer_with_path(writer, source, "glsl"); } - pub fn emit_to_writer_with_path(&self, writer: &mut impl WriteColor, source: &str, path: &str) { + pub fn emit_to_writer_with_path(&self, writer: &mut impl ErrorWrite, source: &str, path: &str) { let path = path.to_string(); - let files = SimpleFile::new(path, source); + let files = SimpleFile::new(path, replace_control_chars(source)); let config = term::Config::default(); for err in &self.errors { @@ -187,9 +186,9 @@ impl ParseErrors { } pub fn emit_to_string(&self, source: &str) -> String { - let mut writer = NoColor::new(Vec::new()); - self.emit_to_writer(&mut writer, source); - String::from_utf8(writer.into_inner()).unwrap() + let mut writer = crate::error::DiagnosticBuffer::new(); + self.emit_to_writer(writer.inner_mut(), source); + writer.into_string() } } @@ -199,11 +198,7 @@ impl core::fmt::Display for ParseErrors { } } -impl core::error::Error for ParseErrors { - fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { - None - } -} +impl core::error::Error for ParseErrors {} impl From> for ParseErrors { fn from(errors: Vec) -> Self { diff --git a/naga/src/front/glsl/functions.rs b/naga/src/front/glsl/functions.rs index 4d6e64162..ba096a82b 100644 --- a/naga/src/front/glsl/functions.rs +++ b/naga/src/front/glsl/functions.rs @@ -560,7 +560,7 @@ impl Frontend { continue; } - log::trace!("Testing overload {}", overload_idx); + log::trace!("Testing overload {overload_idx}"); // Stores whether the current overload matches exactly the function call let mut exact = true; @@ -592,10 +592,7 @@ impl Frontend { let call_arg_ty = ctx.get_type(call_argument.0); log::trace!( - "Testing parameter {}\n\tOverload = {:?}\n\tCall = {:?}", - i, - overload_param_ty, - call_arg_ty + "Testing parameter {i}\n\tOverload = {overload_param_ty:?}\n\tCall = {call_arg_ty:?}" ); // Storage images cannot be directly compared since while the access is part of the @@ -641,8 +638,7 @@ impl Frontend { self.errors.push(Error { kind: ErrorKind::SemanticError( format!( - "'{}': image needs {:?} access but only {:?} was provided", - name, overload_access, call_access + "'{name}': image needs {overload_access:?} access but only {call_access:?} was provided" ) .into(), ), @@ -1370,7 +1366,7 @@ impl Frontend { ctx.module.entry_points.push(EntryPoint { name: "main".to_string(), stage: self.meta.stage, - early_depth_test: Some(crate::EarlyDepthTest { conservative: None }) + early_depth_test: Some(crate::EarlyDepthTest::Force) .filter(|_| self.meta.early_fragment_tests), workgroup_size: self.meta.workgroup_size, workgroup_size_overrides: None, @@ -1381,6 +1377,8 @@ impl Frontend { result: ty.map(|ty| FunctionResult { ty, binding: None }), ..Default::default() }, + mesh_info: None, + task_payload: None, }); Ok(()) @@ -1450,6 +1448,7 @@ impl Context<'_> { interpolation, sampling: None, blend_src: None, + per_primitive: false, }; location += 1; @@ -1486,6 +1485,7 @@ impl Context<'_> { interpolation, sampling: None, blend_src: None, + per_primitive: false, }; location += 1; binding diff --git a/naga/src/front/glsl/mod.rs b/naga/src/front/glsl/mod.rs index 876add46a..e5eda6b3a 100644 --- a/naga/src/front/glsl/mod.rs +++ b/naga/src/front/glsl/mod.rs @@ -107,7 +107,7 @@ impl ShaderMetadata { self.version = 0; self.profile = Profile::Core; self.stage = stage; - self.workgroup_size = [u32::from(stage == ShaderStage::Compute); 3]; + self.workgroup_size = [u32::from(stage.compute_like()); 3]; self.early_fragment_tests = false; self.extensions.clear(); } diff --git a/naga/src/front/glsl/variables.rs b/naga/src/front/glsl/variables.rs index ef98143b7..0b21cde2f 100644 --- a/naga/src/front/glsl/variables.rs +++ b/naga/src/front/glsl/variables.rs @@ -200,6 +200,7 @@ impl Frontend { "gl_BaseVertex" => BuiltIn::BaseVertex, "gl_BaseInstance" => BuiltIn::BaseInstance, "gl_PrimitiveID" => BuiltIn::PrimitiveIndex, + "gl_BaryCoordEXT" => BuiltIn::Barycentric, "gl_InstanceIndex" => BuiltIn::InstanceIndex, "gl_VertexIndex" => BuiltIn::VertexIndex, "gl_SampleID" => BuiltIn::SampleIndex, @@ -465,6 +466,7 @@ impl Frontend { interpolation, sampling, blend_src, + per_primitive: false, }, handle, storage, diff --git a/naga/src/front/interpolator.rs b/naga/src/front/interpolator.rs index e23cae0e7..126e86042 100644 --- a/naga/src/front/interpolator.rs +++ b/naga/src/front/interpolator.rs @@ -44,6 +44,7 @@ impl crate::Binding { interpolation: ref mut interpolation @ None, ref mut sampling, blend_src: _, + per_primitive: _, } = *self { match ty.scalar_kind() { diff --git a/naga/src/front/mod.rs b/naga/src/front/mod.rs index 9480e69aa..826100e87 100644 --- a/naga/src/front/mod.rs +++ b/naga/src/front/mod.rs @@ -14,7 +14,7 @@ pub mod spv; #[cfg(feature = "wgsl-in")] pub mod wgsl; -use alloc::{vec, vec::Vec}; +use alloc::{boxed::Box, vec, vec::Vec}; use core::ops; use crate::{ @@ -114,7 +114,7 @@ impl Typifier { for (eh, expr) in expressions.iter().skip(self.resolutions.len()) { //Note: the closure can't `Err` by construction let resolution = ctx.resolve(expr, |h| Ok(&self.resolutions[h]))?; - log::debug!("Resolving {:?} = {:?} : {:?}", eh, expr, resolution); + log::debug!("Resolving {eh:?} = {expr:?} : {resolution:?}"); self.resolutions.insert(eh, resolution); } } @@ -330,3 +330,10 @@ impl fmt::Debug for SymbolTable { .finish() } } + +impl crate::Module { + pub fn get_or_insert_default_doc_comments(&mut self) -> &mut Box { + self.doc_comments + .get_or_insert_with(|| Box::new(crate::DocComments::default())) + } +} diff --git a/naga/src/front/spv/convert.rs b/naga/src/front/spv/convert.rs index 3e68c7bee..7befa5f29 100644 --- a/naga/src/front/spv/convert.rs +++ b/naga/src/front/spv/convert.rs @@ -147,6 +147,7 @@ pub(super) fn map_builtin(word: spirv::Word, invariant: bool) -> Result crate::BuiltIn::PointCoord, Some(Bi::FrontFacing) => crate::BuiltIn::FrontFacing, Some(Bi::PrimitiveId) => crate::BuiltIn::PrimitiveIndex, + Some(Bi::BaryCoordKHR) => crate::BuiltIn::Barycentric, Some(Bi::SampleId) => crate::BuiltIn::SampleIndex, Some(Bi::SampleMask) => crate::BuiltIn::SampleMask, // compute diff --git a/naga/src/front/spv/error.rs b/naga/src/front/spv/error.rs index 016c690c4..3e18e4034 100644 --- a/naga/src/front/spv/error.rs +++ b/naga/src/front/spv/error.rs @@ -1,16 +1,18 @@ use alloc::{ format, string::{String, ToString}, - vec::Vec, }; use codespan_reporting::diagnostic::Diagnostic; use codespan_reporting::files::SimpleFile; use codespan_reporting::term; -use codespan_reporting::term::termcolor::{NoColor, WriteColor}; use super::ModuleState; -use crate::{arena::Handle, front::atomic_upgrade}; +use crate::{ + arena::Handle, + error::{replace_control_chars, ErrorWrite}, + front::atomic_upgrade, +}; #[derive(Clone, Debug, thiserror::Error)] pub enum Error { @@ -105,6 +107,8 @@ pub enum Error { InvalidGlobalVar(crate::Expression), #[error("invalid image/sampler expression {0:?}")] InvalidImageExpression(crate::Expression), + #[error("image write without format is not currently supported. See https://github.com/gfx-rs/wgpu/issues/6797")] + InvalidImageWriteType, #[error("invalid image base type {0:?}")] InvalidImageBaseType(Handle), #[error("invalid image {0:?}")] @@ -153,13 +157,13 @@ pub enum Error { } impl Error { - pub fn emit_to_writer(&self, writer: &mut impl WriteColor, source: &str) { + pub fn emit_to_writer(&self, writer: &mut impl ErrorWrite, source: &str) { self.emit_to_writer_with_path(writer, source, "glsl"); } - pub fn emit_to_writer_with_path(&self, writer: &mut impl WriteColor, source: &str, path: &str) { + pub fn emit_to_writer_with_path(&self, writer: &mut impl ErrorWrite, source: &str, path: &str) { let path = path.to_string(); - let files = SimpleFile::new(path, source); + let files = SimpleFile::new(path, replace_control_chars(source)); let config = term::Config::default(); let diagnostic = Diagnostic::error().with_message(format!("{self:?}")); @@ -167,9 +171,9 @@ impl Error { } pub fn emit_to_string(&self, source: &str) -> String { - let mut writer = NoColor::new(Vec::new()); - self.emit_to_writer(&mut writer, source); - String::from_utf8(writer.into_inner()).unwrap() + let mut writer = crate::error::DiagnosticBuffer::new(); + self.emit_to_writer(writer.inner_mut(), source); + writer.into_string() } } diff --git a/naga/src/front/spv/function.rs b/naga/src/front/spv/function.rs index fe56ba833..48b23e7c4 100644 --- a/naga/src/front/spv/function.rs +++ b/naga/src/front/spv/function.rs @@ -167,12 +167,20 @@ impl> super::Frontend { if let Some(ref prefix) = self.options.block_ctx_dump_prefix { let dump_suffix = match self.lookup_entry_point.get(&fun_id) { Some(ep) => format!("block_ctx.{:?}-{}.txt", ep.stage, ep.name), - None => format!("block_ctx.Fun-{}.txt", function_index), + None => format!("block_ctx.Fun-{function_index}.txt"), }; - let dest = prefix.join(dump_suffix); - let dump = format!("{block_ctx:#?}"); - if let Err(e) = std::fs::write(&dest, dump) { - log::error!("Unable to dump the block context into {:?}: {}", dest, e); + + cfg_if::cfg_if! { + if #[cfg(feature = "fs")] { + let prefix: &std::path::Path = prefix.as_ref(); + let dest = prefix.join(dump_suffix); + let dump = format!("{block_ctx:#?}"); + if let Err(e) = std::fs::write(&dest, dump) { + log::error!("Unable to dump the block context into {dest:?}: {e}"); + } + } else { + log::error!("Unable to dump the block context into {prefix:?}/{dump_suffix}: file system integration was not enabled with the `fs` feature"); + } } } @@ -183,7 +191,7 @@ impl> super::Frontend { // to get the spill. for phi in block_ctx.phis.iter() { // Get a pointer to the local variable for the phi's value. - let phi_pointer = block_ctx.expressions.append( + let phi_pointer: Handle = block_ctx.expressions.append( crate::Expression::LocalVariable(phi.local), crate::Span::default(), ); @@ -374,7 +382,15 @@ impl> super::Frontend { ); // 3. copy the outputs from privates to the result + // + // It would be nice to share struct layout code here with `parse_type_struct`, + // but that case needs to take into account offset decorations, which makes an + // abstraction harder to follow than just writing out what we mean. `Layouter` + // and `Alignment` cover the worst parts already. let mut members = Vec::new(); + self.layouter.update(module.to_ctx()).unwrap(); + let mut next_member_offset = 0; + let mut struct_alignment = crate::proc::Alignment::ONE; let mut components = Vec::new(); for &v_id in ep.variable_ids.iter() { let lvar = self.lookup_variable.lookup(v_id)?; @@ -435,6 +451,11 @@ impl> super::Frontend { } } + let member_alignment = self.layouter[sm.ty].alignment; + next_member_offset = member_alignment.round_up(next_member_offset); + sm.offset = next_member_offset; + struct_alignment = struct_alignment.max(member_alignment); + next_member_offset += self.layouter[sm.ty].size; members.push(sm); components.push(function.expressions.append( @@ -454,12 +475,16 @@ impl> super::Frontend { } } + let member_alignment = self.layouter[result.ty].alignment; + next_member_offset = member_alignment.round_up(next_member_offset); members.push(crate::StructMember { name: None, ty: result.ty, binding, - offset: 0, + offset: next_member_offset, }); + struct_alignment = struct_alignment.max(member_alignment); + next_member_offset += self.layouter[result.ty].size; // populate just the globals first, then do `Load` in a // separate step, so that we can get a range. components.push(expr_handle); @@ -545,7 +570,7 @@ impl> super::Frontend { name: None, inner: crate::TypeInner::Struct { members, - span: 0xFFFF, // shouldn't matter + span: struct_alignment.round_up(next_member_offset), }, }, span, @@ -571,6 +596,8 @@ impl> super::Frontend { workgroup_size: ep.workgroup_size, workgroup_size_overrides: None, function, + mesh_info: None, + task_payload: None, }); Ok(()) @@ -578,7 +605,7 @@ impl> super::Frontend { } impl BlockContext<'_> { - pub(super) fn gctx(&self) -> crate::proc::GlobalCtx { + pub(super) fn gctx(&self) -> crate::proc::GlobalCtx<'_> { crate::proc::GlobalCtx { types: &self.module.types, constants: &self.module.constants, diff --git a/naga/src/front/spv/image.rs b/naga/src/front/spv/image.rs index df0578f3b..591590be0 100644 --- a/naga/src/front/spv/image.rs +++ b/naga/src/front/spv/image.rs @@ -48,6 +48,8 @@ pub struct SamplingOptions { pub project: bool, /// Depth comparison sampling with a reference value. pub compare: bool, + /// Gather sampling: Operates on four samples of one channel. + pub gather: bool, } enum ExtraCoordinate { @@ -202,7 +204,7 @@ pub(super) fn patch_comparison_type( return false; } - log::debug!("Flipping comparison for {:?}", var); + log::debug!("Flipping comparison for {var:?}"); let original_ty = &arena[var.ty]; let original_ty_span = arena.get_span(var.ty); let ty_inner = match original_ty.inner { @@ -279,7 +281,7 @@ impl> super::Frontend { if image_ops != 0 { let other = spirv::ImageOperands::from_bits_truncate(image_ops); - log::warn!("Unknown image write ops {:?}", other); + log::warn!("Unknown image write ops {other:?}"); for _ in 1..words_left { self.next()?; } @@ -403,7 +405,7 @@ impl> super::Frontend { words_left -= 1; } other => { - log::warn!("Unknown image load op {:?}", other); + log::warn!("Unknown image load op {other:?}"); for _ in 0..words_left { self.next()?; } @@ -500,10 +502,10 @@ impl> super::Frontend { let result_id = self.next()?; let sampled_image_id = self.next()?; let coordinate_id = self.next()?; - let dref_id = if options.compare { - Some(self.next()?) - } else { - None + let (component_id, dref_id) = match (options.gather, options.compare) { + (true, false) => (Some(self.next()?), None), + (_, true) => (None, Some(self.next()?)), + (_, _) => (None, None), }; let span = self.span_from_with_op(start); @@ -546,12 +548,11 @@ impl> super::Frontend { }; level = if options.compare { - log::debug!("Assuming {:?} is zero", lod_handle); + log::debug!("Assuming {lod_handle:?} is zero"); crate::SampleLevel::Zero } else if is_depth_image { log::debug!( - "Assuming level {:?} converts losslessly to an integer", - lod_handle + "Assuming level {lod_handle:?} converts losslessly to an integer" ); let expr = crate::Expression::As { expr: lod_handle, @@ -588,9 +589,7 @@ impl> super::Frontend { ); level = if options.compare { log::debug!( - "Assuming gradients {:?} and {:?} are not greater than 1", - grad_x_handle, - grad_y_handle + "Assuming gradients {grad_x_handle:?} and {grad_y_handle:?} are not greater than 1" ); crate::SampleLevel::Zero } else { @@ -616,7 +615,7 @@ impl> super::Frontend { words_left -= 1; } other => { - log::warn!("Unknown image sample operand {:?}", other); + log::warn!("Unknown image sample operand {other:?}"); for _ in 0..words_left { self.next()?; } @@ -632,6 +631,58 @@ impl> super::Frontend { self.get_expr_handle(coordinate_id, coord_lexp, ctx, emitter, block, body_idx); let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle; + let gather = match (options.gather, component_id) { + (true, Some(component_id)) => { + let component_lexp = self.lookup_expression.lookup(component_id)?; + + let component_value = match ctx.expressions[component_lexp.handle] { + // VUID-StandaloneSpirv-OpImageGather-04664: + // The “Component” operand of OpImageGather, and OpImageSparseGather must be the + // of a constant instruction. + crate::Expression::Constant(const_handle) => { + let constant = &ctx.module.constants[const_handle]; + match ctx.module.global_expressions[constant.init] { + // SPIR-V specification: "It must be a 32-bit integer type scalar." + crate::Expression::Literal(crate::Literal::U32(value)) => value, + crate::Expression::Literal(crate::Literal::I32(value)) => value as u32, + _ => { + log::error!( + "Image gather component constant must be a 32-bit integer literal" + ); + return Err(Error::InvalidOperand); + } + } + } + _ => { + log::error!("Image gather component must be a constant"); + return Err(Error::InvalidOperand); + } + }; + + debug_assert_eq!(level, crate::SampleLevel::Auto); + level = crate::SampleLevel::Zero; + + // SPIR-V specification: "Behavior is undefined if its value is not 0, 1, 2 or 3." + match component_value { + 0 => Some(crate::SwizzleComponent::X), + 1 => Some(crate::SwizzleComponent::Y), + 2 => Some(crate::SwizzleComponent::Z), + 3 => Some(crate::SwizzleComponent::W), + other => { + log::error!("Invalid gather component operand: {other}"); + return Err(Error::InvalidOperand); + } + } + } + (true, None) => { + debug_assert_eq!(level, crate::SampleLevel::Auto); + level = crate::SampleLevel::Zero; + + Some(crate::SwizzleComponent::X) + } + (_, _) => None, + }; + let sampling_bit = if options.compare { SamplingFlags::COMPARISON } else { @@ -748,12 +799,13 @@ impl> super::Frontend { let expr = crate::Expression::ImageSample { image: si_lexp.image, sampler: si_lexp.sampler, - gather: None, //TODO + gather, coordinate, array_index, offset, level, depth_ref, + clamp_to_edge: false, }; let image_sample_handle = ctx.expressions.append(expr, self.span_from_with_op(start)); let handle = if is_depth && depth_ref.is_none() { diff --git a/naga/src/front/spv/mod.rs b/naga/src/front/spv/mod.rs index b62f00d28..2a3a971a8 100644 --- a/naga/src/front/spv/mod.rs +++ b/naga/src/front/spv/mod.rs @@ -37,7 +37,6 @@ pub use error::Error; use alloc::{borrow::ToOwned, format, string::String, vec, vec::Vec}; use core::{convert::TryInto, mem, num::NonZeroU32}; -use std::path::PathBuf; use half::f16; use petgraph::graphmap::GraphMap; @@ -74,6 +73,17 @@ pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ spirv::Capability::Float64, spirv::Capability::Geometry, spirv::Capability::MultiView, + spirv::Capability::StorageBuffer16BitAccess, + spirv::Capability::UniformAndStorageBuffer16BitAccess, + spirv::Capability::GroupNonUniform, + spirv::Capability::GroupNonUniformVote, + spirv::Capability::GroupNonUniformArithmetic, + spirv::Capability::GroupNonUniformBallot, + spirv::Capability::GroupNonUniformShuffle, + spirv::Capability::GroupNonUniformShuffleRelative, + spirv::Capability::RuntimeDescriptorArray, + spirv::Capability::StorageImageMultisample, + spirv::Capability::FragmentBarycentricKHR, // tricky ones spirv::Capability::UniformBufferArrayDynamicIndexing, spirv::Capability::StorageBufferArrayDynamicIndexing, @@ -82,6 +92,7 @@ pub const SUPPORTED_EXTENSIONS: &[&str] = &[ "SPV_KHR_storage_buffer_storage_class", "SPV_KHR_vulkan_memory_model", "SPV_KHR_multiview", + "SPV_EXT_descriptor_indexing", "SPV_EXT_shader_atomic_float_add", "SPV_KHR_16bit_storage", ]; @@ -255,6 +266,7 @@ impl Decoration { interpolation, sampling, blend_src: None, + per_primitive: false, }), _ => Err(Error::MissingDecoration(spirv::Decoration::Location)), } @@ -373,14 +385,14 @@ pub struct Options { pub adjust_coordinate_space: bool, /// Only allow shaders with the known set of capabilities. pub strict_capabilities: bool, - pub block_ctx_dump_prefix: Option, + pub block_ctx_dump_prefix: Option, } impl Default for Options { fn default() -> Self { Options { adjust_coordinate_space: true, - strict_capabilities: false, + strict_capabilities: true, block_ctx_dump_prefix: None, } } @@ -507,7 +519,6 @@ enum MergeBlockInformation { /// [`blocks`]: BlockContext::blocks /// [`bodies`]: BlockContext::bodies /// [`phis`]: BlockContext::phis -/// [`lower`]: function::lower #[derive(Debug)] struct BlockContext<'function> { /// Phi nodes encountered when parsing the function, used to generate spills @@ -609,7 +620,12 @@ pub struct Frontend { // Graph of all function calls through the module. // It's used to sort the functions (as nodes) topologically, // so that in the IR any called function is already known. - function_call_graph: GraphMap, + function_call_graph: GraphMap< + spirv::Word, + (), + petgraph::Directed, + core::hash::BuildHasherDefault, + >, options: Options, /// Maps for a switch from a case target to the respective body and associated literals that @@ -783,7 +799,7 @@ impl> Frontend { dec.specialization_constant_id = Some(self.next()?); } other => { - log::warn!("Unknown decoration {:?}", other); + log::warn!("Unknown decoration {other:?}"); for _ in base_words + 1..inst.wc { let _var = self.next()?; } @@ -1374,7 +1390,7 @@ impl> Frontend { block: &mut crate::Block, body_idx: usize, ) -> Result<(Handle, Handle), Error> { - log::trace!("\t\t\tlooking up pointer expr {:?}", pointer_id); + log::trace!("\t\t\tlooking up pointer expr {pointer_id:?}"); let p_lexp_handle; let p_lexp_ty_id; { @@ -1587,7 +1603,7 @@ impl> Frontend { .remove(&result_id) .and_then(|decor| decor.name); if let Some(ref name) = name { - log::debug!("\t\t\tid={} name={}", result_id, name); + log::debug!("\t\t\tid={result_id} name={name}"); } let lookup_ty = self.lookup_type.lookup(result_type_id)?; let var_handle = ctx.local_arena.append( @@ -1673,7 +1689,7 @@ impl> Frontend { let result_type_id = self.next()?; let result_id = self.next()?; let base_id = self.next()?; - log::trace!("\t\t\tlooking up expr {:?}", base_id); + log::trace!("\t\t\tlooking up expr {base_id:?}"); let mut acex = { let lexp = self.lookup_expression.lookup(base_id)?; @@ -1708,7 +1724,7 @@ impl> Frontend { for _ in 4..inst.wc { let access_id = self.next()?; - log::trace!("\t\t\tlooking up index expr {:?}", access_id); + log::trace!("\t\t\tlooking up index expr {access_id:?}"); let index_expr = self.lookup_expression.lookup(access_id)?.clone(); let index_expr_handle = get_expr_handle!(access_id, &index_expr); let index_expr_data = &ctx.expressions[index_expr.handle]; @@ -2051,7 +2067,7 @@ impl> Frontend { let result_type_id = self.next()?; let result_id = self.next()?; let base_id = self.next()?; - log::trace!("\t\t\tlooking up expr {:?}", base_id); + log::trace!("\t\t\tlooking up expr {base_id:?}"); let mut lexp = self.lookup_expression.lookup(base_id)?.clone(); lexp.handle = get_expr_handle!(base_id, &lexp); for _ in 4..inst.wc { @@ -2071,7 +2087,7 @@ impl> Frontend { .base_id .ok_or(Error::InvalidAccessType(lexp.type_id))?, ref other => { - log::warn!("composite type {:?}", other); + log::warn!("composite type {other:?}"); return Err(Error::UnsupportedType(type_lookup.handle)); } }; @@ -2140,7 +2156,7 @@ impl> Frontend { let mut components = Vec::with_capacity(inst.wc as usize - 2); for _ in 3..inst.wc { let comp_id = self.next()?; - log::trace!("\t\t\tlooking up expr {:?}", comp_id); + log::trace!("\t\t\tlooking up expr {comp_id:?}"); let lexp = self.lookup_expression.lookup(comp_id)?; let handle = get_expr_handle!(comp_id, lexp); components.push(handle); @@ -2787,6 +2803,7 @@ impl> Frontend { let options = image::SamplingOptions { compare: false, project: false, + gather: false, }; self.parse_image_sample( extra, @@ -2803,6 +2820,7 @@ impl> Frontend { let options = image::SamplingOptions { compare: false, project: true, + gather: false, }; self.parse_image_sample( extra, @@ -2819,6 +2837,7 @@ impl> Frontend { let options = image::SamplingOptions { compare: true, project: false, + gather: false, }; self.parse_image_sample( extra, @@ -2835,6 +2854,41 @@ impl> Frontend { let options = image::SamplingOptions { compare: true, project: true, + gather: false, + }; + self.parse_image_sample( + extra, + options, + ctx, + &mut emitter, + &mut block, + block_id, + body_idx, + )?; + } + Op::ImageGather => { + let extra = inst.expect_at_least(6)?; + let options = image::SamplingOptions { + compare: false, + project: false, + gather: true, + }; + self.parse_image_sample( + extra, + options, + ctx, + &mut emitter, + &mut block, + block_id, + body_idx, + )?; + } + Op::ImageDrefGather => { + let extra = inst.expect_at_least(6)?; + let options = image::SamplingOptions { + compare: true, + project: false, + gather: true, }; self.parse_image_sample( extra, @@ -3837,7 +3891,9 @@ impl> Frontend { let semantics = resolve_constant(ctx.gctx(), &semantics_const.inner) .ok_or(Error::InvalidBarrierMemorySemantics(semantics_id))?; - if exec_scope == spirv::Scope::Workgroup as u32 { + if exec_scope == spirv::Scope::Workgroup as u32 + || exec_scope == spirv::Scope::Subgroup as u32 + { let mut flags = crate::Barrier::empty(); flags.set( crate::Barrier::STORAGE, @@ -3845,21 +3901,66 @@ impl> Frontend { ); flags.set( crate::Barrier::WORK_GROUP, - semantics - & (spirv::MemorySemantics::SUBGROUP_MEMORY - | spirv::MemorySemantics::WORKGROUP_MEMORY) - .bits() - != 0, + semantics & (spirv::MemorySemantics::WORKGROUP_MEMORY).bits() != 0, + ); + flags.set( + crate::Barrier::SUB_GROUP, + semantics & spirv::MemorySemantics::SUBGROUP_MEMORY.bits() != 0, ); flags.set( crate::Barrier::TEXTURE, semantics & spirv::MemorySemantics::IMAGE_MEMORY.bits() != 0, ); - block.push(crate::Statement::Barrier(flags), span); + + block.extend(emitter.finish(ctx.expressions)); + block.push(crate::Statement::ControlBarrier(flags), span); + emitter.start(ctx.expressions); } else { - log::warn!("Unsupported barrier execution scope: {}", exec_scope); + log::warn!("Unsupported barrier execution scope: {exec_scope}"); } } + Op::MemoryBarrier => { + inst.expect(3)?; + let mem_scope_id = self.next()?; + let semantics_id = self.next()?; + let mem_scope_const = self.lookup_constant.lookup(mem_scope_id)?; + let semantics_const = self.lookup_constant.lookup(semantics_id)?; + + let mem_scope = resolve_constant(ctx.gctx(), &mem_scope_const.inner) + .ok_or(Error::InvalidBarrierScope(mem_scope_id))?; + let semantics = resolve_constant(ctx.gctx(), &semantics_const.inner) + .ok_or(Error::InvalidBarrierMemorySemantics(semantics_id))?; + + let mut flags = if mem_scope == spirv::Scope::Device as u32 { + crate::Barrier::STORAGE + } else if mem_scope == spirv::Scope::Workgroup as u32 { + crate::Barrier::WORK_GROUP + } else if mem_scope == spirv::Scope::Subgroup as u32 { + crate::Barrier::SUB_GROUP + } else { + crate::Barrier::empty() + }; + flags.set( + crate::Barrier::STORAGE, + semantics & spirv::MemorySemantics::UNIFORM_MEMORY.bits() != 0, + ); + flags.set( + crate::Barrier::WORK_GROUP, + semantics & (spirv::MemorySemantics::WORKGROUP_MEMORY).bits() != 0, + ); + flags.set( + crate::Barrier::SUB_GROUP, + semantics & spirv::MemorySemantics::SUBGROUP_MEMORY.bits() != 0, + ); + flags.set( + crate::Barrier::TEXTURE, + semantics & spirv::MemorySemantics::IMAGE_MEMORY.bits() != 0, + ); + + block.extend(emitter.finish(ctx.expressions)); + block.push(crate::Statement::MemoryBarrier(flags), span); + emitter.start(ctx.expressions); + } Op::CopyObject => { inst.expect(4)?; let result_type_id = self.next()?; @@ -4051,7 +4152,8 @@ impl> Frontend { | Op::GroupNonUniformShuffle | Op::GroupNonUniformShuffleDown | Op::GroupNonUniformShuffleUp - | Op::GroupNonUniformShuffleXor => { + | Op::GroupNonUniformShuffleXor + | Op::GroupNonUniformQuadBroadcast => { inst.expect(if matches!(inst.op, Op::GroupNonUniformBroadcastFirst) { 5 } else { @@ -4091,6 +4193,9 @@ impl> Frontend { Op::GroupNonUniformShuffleXor => { crate::GatherMode::ShuffleXor(index_handle) } + Op::GroupNonUniformQuadBroadcast => { + crate::GatherMode::QuadBroadcast(index_handle) + } _ => unreachable!(), } }; @@ -4122,6 +4227,60 @@ impl> Frontend { ); emitter.start(ctx.expressions); } + Op::GroupNonUniformQuadSwap => { + inst.expect(6)?; + block.extend(emitter.finish(ctx.expressions)); + let result_type_id = self.next()?; + let result_id = self.next()?; + let exec_scope_id = self.next()?; + let argument_id = self.next()?; + let direction_id = self.next()?; + + let argument_lookup = self.lookup_expression.lookup(argument_id)?; + let argument_handle = get_expr_handle!(argument_id, argument_lookup); + + let exec_scope_const = self.lookup_constant.lookup(exec_scope_id)?; + let _exec_scope = resolve_constant(ctx.gctx(), &exec_scope_const.inner) + .filter(|exec_scope| *exec_scope == spirv::Scope::Subgroup as u32) + .ok_or(Error::InvalidBarrierScope(exec_scope_id))?; + + let direction_const = self.lookup_constant.lookup(direction_id)?; + let direction_const = resolve_constant(ctx.gctx(), &direction_const.inner) + .ok_or(Error::InvalidOperand)?; + let direction = match direction_const { + 0 => crate::Direction::X, + 1 => crate::Direction::Y, + 2 => crate::Direction::Diagonal, + _ => unreachable!(), + }; + + let result_type = self.lookup_type.lookup(result_type_id)?; + + let result_handle = ctx.expressions.append( + crate::Expression::SubgroupOperationResult { + ty: result_type.handle, + }, + span, + ); + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: result_handle, + type_id: result_type_id, + block_id, + }, + ); + + block.push( + crate::Statement::SubgroupGather { + mode: crate::GatherMode::QuadSwap(direction), + result: result_handle, + argument: argument_handle, + }, + span, + ); + emitter.start(ctx.expressions); + } Op::AtomicLoad => { inst.expect(6)?; let start = self.data_offset; @@ -4132,7 +4291,7 @@ impl> Frontend { let _memory_semantics_id = self.next()?; let span = self.span_from_with_op(start); - log::trace!("\t\t\tlooking up expr {:?}", pointer_id); + log::trace!("\t\t\tlooking up expr {pointer_id:?}"); let p_lexp_handle = get_expr_handle!(pointer_id, self.lookup_expression.lookup(pointer_id)?); @@ -4162,11 +4321,11 @@ impl> Frontend { let value_id = self.next()?; let span = self.span_from_with_op(start); - log::trace!("\t\t\tlooking up pointer expr {:?}", pointer_id); + log::trace!("\t\t\tlooking up pointer expr {pointer_id:?}"); let p_lexp_handle = get_expr_handle!(pointer_id, self.lookup_expression.lookup(pointer_id)?); - log::trace!("\t\t\tlooking up value expr {:?}", pointer_id); + log::trace!("\t\t\tlooking up value expr {pointer_id:?}"); let v_lexp_handle = get_expr_handle!(value_id, self.lookup_expression.lookup(value_id)?); @@ -4268,11 +4427,11 @@ impl> Frontend { body_idx, )?; - log::trace!("\t\t\tlooking up value expr {:?}", value_id); + log::trace!("\t\t\tlooking up value expr {value_id:?}"); let v_lexp_handle = get_expr_handle!(value_id, self.lookup_expression.lookup(value_id)?); - log::trace!("\t\t\tlooking up comparator expr {:?}", value_id); + log::trace!("\t\t\tlooking up comparator expr {value_id:?}"); let c_lexp_handle = get_expr_handle!( comparator_id, self.lookup_expression.lookup(comparator_id)? @@ -4495,12 +4654,14 @@ impl> Frontend { | S::Continue | S::Return { .. } | S::Kill - | S::Barrier(_) + | S::ControlBarrier(_) + | S::MemoryBarrier(_) | S::Store { .. } | S::ImageStore { .. } | S::Atomic { .. } | S::ImageAtomic { .. } | S::RayQuery { .. } + | S::MeshFunction(..) | S::SubgroupBallot { .. } | S::SubgroupCollectiveOperation { .. } | S::SubgroupGather { .. } => {} @@ -4586,7 +4747,7 @@ impl> Frontend { let generator = self.next()?; let _bound = self.next()?; let _schema = self.next()?; - log::info!("Generated by {} version {:x}", generator, version_raw); + log::info!("Generated by {generator} version {version_raw:x}"); crate::Module::default() }; @@ -4727,7 +4888,7 @@ impl> Frontend { if self.options.strict_capabilities { return Err(Error::UnsupportedCapability(cap)); } else { - log::warn!("Unknown capability {:?}", cap); + log::warn!("Unknown capability {cap:?}"); } } Ok(()) @@ -4782,6 +4943,8 @@ impl> Frontend { spirv::ExecutionModel::Vertex => crate::ShaderStage::Vertex, spirv::ExecutionModel::Fragment => crate::ShaderStage::Fragment, spirv::ExecutionModel::GLCompute => crate::ShaderStage::Compute, + spirv::ExecutionModel::TaskEXT => crate::ShaderStage::Task, + spirv::ExecutionModel::MeshEXT => crate::ShaderStage::Mesh, _ => return Err(Error::UnsupportedExecutionModel(exec_model as u32)), }, name, @@ -4812,24 +4975,49 @@ impl> Frontend { match mode { ExecutionMode::EarlyFragmentTests => { - if ep.early_depth_test.is_none() { - ep.early_depth_test = Some(crate::EarlyDepthTest { conservative: None }); - } + ep.early_depth_test = Some(crate::EarlyDepthTest::Force); } ExecutionMode::DepthUnchanged => { - ep.early_depth_test = Some(crate::EarlyDepthTest { - conservative: Some(crate::ConservativeDepth::Unchanged), - }); + if let &mut Some(ref mut early_depth_test) = &mut ep.early_depth_test { + if let &mut crate::EarlyDepthTest::Allow { + ref mut conservative, + } = early_depth_test + { + *conservative = crate::ConservativeDepth::Unchanged; + } + } else { + ep.early_depth_test = Some(crate::EarlyDepthTest::Allow { + conservative: crate::ConservativeDepth::Unchanged, + }); + } } ExecutionMode::DepthGreater => { - ep.early_depth_test = Some(crate::EarlyDepthTest { - conservative: Some(crate::ConservativeDepth::GreaterEqual), - }); + if let &mut Some(ref mut early_depth_test) = &mut ep.early_depth_test { + if let &mut crate::EarlyDepthTest::Allow { + ref mut conservative, + } = early_depth_test + { + *conservative = crate::ConservativeDepth::GreaterEqual; + } + } else { + ep.early_depth_test = Some(crate::EarlyDepthTest::Allow { + conservative: crate::ConservativeDepth::GreaterEqual, + }); + } } ExecutionMode::DepthLess => { - ep.early_depth_test = Some(crate::EarlyDepthTest { - conservative: Some(crate::ConservativeDepth::LessEqual), - }); + if let &mut Some(ref mut early_depth_test) = &mut ep.early_depth_test { + if let &mut crate::EarlyDepthTest::Allow { + ref mut conservative, + } = early_depth_test + { + *conservative = crate::ConservativeDepth::LessEqual; + } + } else { + ep.early_depth_test = Some(crate::EarlyDepthTest::Allow { + conservative: crate::ConservativeDepth::LessEqual, + }); + } } ExecutionMode::DepthReplacing => { // Ignored because it can be deduced from the IR. @@ -5452,7 +5640,7 @@ impl> Frontend { let is_depth = self.next()?; let is_array = self.next()? != 0; let is_msaa = self.next()? != 0; - let _is_sampled = self.next()?; + let is_sampled = self.next()?; let format = self.next()?; let dim = map_image_dim(dim)?; @@ -5487,6 +5675,8 @@ impl> Frontend { format: map_image_format(format)?, access: crate::StorageAccess::default(), } + } else if is_sampled == 2 { + return Err(Error::InvalidImageWriteType); } else { crate::ImageClass::Sampled { kind, @@ -5853,6 +6043,10 @@ impl> Frontend { size: crate::VectorSize::Tri, scalar: crate::Scalar::U32, }), + crate::BuiltIn::Barycentric => Some(crate::TypeInner::Vector { + size: crate::VectorSize::Tri, + scalar: crate::Scalar::F32, + }), _ => None, }; if let (Some(inner), Some(crate::ScalarKind::Sint)) = @@ -5892,7 +6086,7 @@ impl> Frontend { ) { Ok(handle) => Some(handle), Err(e) => { - log::warn!("Failed to initialize output built-in: {}", e); + log::warn!("Failed to initialize output built-in: {e}"); None } } @@ -5939,7 +6133,7 @@ impl> Frontend { let handle = module.global_variables.append(var, span); if module.types[ty].inner.can_comparison_sample(module) { - log::debug!("\t\ttracking {:?} for sampling properties", handle); + log::debug!("\t\ttracking {handle:?} for sampling properties"); self.handle_sampling .insert(handle, image::SamplingFlags::empty()); diff --git a/naga/src/front/type_gen.rs b/naga/src/front/type_gen.rs index 687d245b1..4165f051d 100644 --- a/naga/src/front/type_gen.rs +++ b/naga/src/front/type_gen.rs @@ -2,7 +2,7 @@ Type generators. */ -use alloc::{format, string::ToString, vec}; +use alloc::{string::ToString, vec}; use crate::{arena::Handle, span::Span}; @@ -276,6 +276,179 @@ impl crate::Module { handle } + /// Generate [`SpecialTypes::external_texture_params`] and + /// [`SpecialTypes::external_texture_transfer_function`]. + /// + /// Other than the WGSL backend, every backend that supports external + /// textures does so by lowering them to a set of ordinary textures and + /// some parameters saying how to sample from them. These types are used + /// for said parameters. Note that they are not used by the IR, but + /// generated purely as a convenience for the backends. + /// + /// [`SpecialTypes::external_texture_params`]: crate::ir::SpecialTypes::external_texture_params + /// [`SpecialTypes::external_texture_transfer_function`]: crate::ir::SpecialTypes::external_texture_transfer_function + pub fn generate_external_texture_types(&mut self) { + if self.special_types.external_texture_params.is_some() { + return; + } + + let ty_f32 = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar(crate::Scalar::F32), + }, + Span::UNDEFINED, + ); + let ty_u32 = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar(crate::Scalar::U32), + }, + Span::UNDEFINED, + ); + let ty_vec2u = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Vector { + size: crate::VectorSize::Bi, + scalar: crate::Scalar::U32, + }, + }, + Span::UNDEFINED, + ); + let ty_mat3x2f = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Matrix { + columns: crate::VectorSize::Tri, + rows: crate::VectorSize::Bi, + scalar: crate::Scalar::F32, + }, + }, + Span::UNDEFINED, + ); + let ty_mat3x3f = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Matrix { + columns: crate::VectorSize::Tri, + rows: crate::VectorSize::Tri, + scalar: crate::Scalar::F32, + }, + }, + Span::UNDEFINED, + ); + let ty_mat4x4f = self.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Matrix { + columns: crate::VectorSize::Quad, + rows: crate::VectorSize::Quad, + scalar: crate::Scalar::F32, + }, + }, + Span::UNDEFINED, + ); + + let transfer_fn_handle = self.types.insert( + crate::Type { + name: Some("NagaExternalTextureTransferFn".to_string()), + inner: crate::TypeInner::Struct { + members: vec![ + crate::StructMember { + name: Some("a".to_string()), + ty: ty_f32, + binding: None, + offset: 0, + }, + crate::StructMember { + name: Some("b".to_string()), + ty: ty_f32, + binding: None, + offset: 4, + }, + crate::StructMember { + name: Some("g".to_string()), + ty: ty_f32, + binding: None, + offset: 8, + }, + crate::StructMember { + name: Some("k".to_string()), + ty: ty_f32, + binding: None, + offset: 12, + }, + ], + span: 16, + }, + }, + Span::UNDEFINED, + ); + self.special_types.external_texture_transfer_function = Some(transfer_fn_handle); + + let params_handle = self.types.insert( + crate::Type { + name: Some("NagaExternalTextureParams".to_string()), + inner: crate::TypeInner::Struct { + members: vec![ + crate::StructMember { + name: Some("yuv_conversion_matrix".to_string()), + ty: ty_mat4x4f, + binding: None, + offset: 0, + }, + crate::StructMember { + name: Some("gamut_conversion_matrix".to_string()), + ty: ty_mat3x3f, + binding: None, + offset: 64, + }, + crate::StructMember { + name: Some("src_tf".to_string()), + ty: transfer_fn_handle, + binding: None, + offset: 112, + }, + crate::StructMember { + name: Some("dst_tf".to_string()), + ty: transfer_fn_handle, + binding: None, + offset: 128, + }, + crate::StructMember { + name: Some("sample_transform".to_string()), + ty: ty_mat3x2f, + binding: None, + offset: 144, + }, + crate::StructMember { + name: Some("load_transform".to_string()), + ty: ty_mat3x2f, + binding: None, + offset: 168, + }, + crate::StructMember { + name: Some("size".to_string()), + ty: ty_vec2u, + binding: None, + offset: 192, + }, + crate::StructMember { + name: Some("num_planes".to_string()), + ty: ty_u32, + binding: None, + offset: 200, + }, + ], + span: 208, + }, + }, + Span::UNDEFINED, + ); + self.special_types.external_texture_params = Some(params_handle); + } + /// Populate this module's [`SpecialTypes::predeclared_types`] type and return the handle. /// /// [`SpecialTypes::predeclared_types`]: crate::SpecialTypes::predeclared_types @@ -283,12 +456,11 @@ impl crate::Module { &mut self, special_type: crate::PredeclaredType, ) -> Handle { - use core::fmt::Write; - if let Some(value) = self.special_types.predeclared_types.get(&special_type) { return *value; } + let name = special_type.struct_name(); let ty = match special_type { crate::PredeclaredType::AtomicCompareExchangeWeakResult(scalar) => { let bool_ty = self.types.insert( @@ -307,10 +479,7 @@ impl crate::Module { ); crate::Type { - name: Some(format!( - "__atomic_compare_exchange_result<{:?},{}>", - scalar.kind, scalar.width, - )), + name: Some(name), inner: crate::TypeInner::Struct { members: vec![ crate::StructMember { @@ -352,14 +521,8 @@ impl crate::Module { (float_ty, scalar.width as u32) }; - let mut type_name = "__modf_result_".to_string(); - if let Some(size) = size { - let _ = write!(type_name, "vec{}_", size as u8); - } - let _ = write!(type_name, "f{}", scalar.width * 8); - crate::Type { - name: Some(type_name), + name: Some(name), inner: crate::TypeInner::Struct { members: vec![ crate::StructMember { @@ -425,14 +588,8 @@ impl crate::Module { (float_ty, int_ty, scalar.width as u32) }; - let mut type_name = "__frexp_result_".to_string(); - if let Some(size) = size { - let _ = write!(type_name, "vec{}_", size as u8); - } - let _ = write!(type_name, "f{}", scalar.width * 8); - crate::Type { - name: Some(type_name), + name: Some(name), inner: crate::TypeInner::Struct { members: vec![ crate::StructMember { diff --git a/naga/src/front/wgsl/error.rs b/naga/src/front/wgsl/error.rs index 4a1f3a30a..17dab5cb0 100644 --- a/naga/src/front/wgsl/error.rs +++ b/naga/src/front/wgsl/error.rs @@ -2,6 +2,7 @@ use crate::common::wgsl::TryToWgsl; use crate::diagnostic_filter::ConflictingDiagnosticRuleError; +use crate::error::replace_control_chars; use crate::proc::{Alignment, ConstantEvaluatorError, ResolveError}; use crate::{Scalar, SourceLocation, Span}; @@ -14,7 +15,6 @@ use super::parse::lexer::Token; use codespan_reporting::diagnostic::{Diagnostic, Label}; use codespan_reporting::files::SimpleFile; use codespan_reporting::term; -use codespan_reporting::term::termcolor::{ColorChoice, NoColor, StandardStream}; use thiserror::Error; use alloc::{ @@ -68,19 +68,29 @@ impl ParseError { } /// Emits a summary of the error to standard error stream. + #[cfg(feature = "stderr")] pub fn emit_to_stderr(&self, source: &str) { self.emit_to_stderr_with_path(source, "wgsl") } /// Emits a summary of the error to standard error stream. + #[cfg(feature = "stderr")] pub fn emit_to_stderr_with_path

(&self, source: &str, path: P) where P: AsRef, { let path = path.as_ref().display().to_string(); - let files = SimpleFile::new(path, source); + let files = SimpleFile::new(path, replace_control_chars(source)); let config = term::Config::default(); - let writer = StandardStream::stderr(ColorChoice::Auto); + + cfg_if::cfg_if! { + if #[cfg(feature = "termcolor")] { + let writer = term::termcolor::StandardStream::stderr(term::termcolor::ColorChoice::Auto); + } else { + let writer = std::io::stderr(); + } + } + term::emit(&mut writer.lock(), &config, &files, &self.diagnostic()) .expect("cannot write error"); } @@ -96,11 +106,13 @@ impl ParseError { P: AsRef, { let path = path.as_ref().display().to_string(); - let files = SimpleFile::new(path, source); + let files = SimpleFile::new(path, replace_control_chars(source)); let config = term::Config::default(); - let mut writer = NoColor::new(Vec::new()); - term::emit(&mut writer, &config, &files, &self.diagnostic()).expect("cannot write error"); - String::from_utf8(writer.into_inner()).unwrap() + + let mut writer = crate::error::DiagnosticBuffer::new(); + term::emit(writer.inner_mut(), &config, &files, &self.diagnostic()) + .expect("cannot write error"); + writer.into_string() } /// Returns a [`SourceLocation`] for the first label in the error message. @@ -115,11 +127,7 @@ impl core::fmt::Display for ParseError { } } -impl core::error::Error for ParseError { - fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { - None - } -} +impl core::error::Error for ParseError {} #[derive(Copy, Clone, Debug, PartialEq)] pub enum ExpectedToken<'a> { @@ -176,6 +184,7 @@ pub(crate) enum Error<'a> { from_type: String, to_type: String, }, + NotStorageTexture(Span), BadTextureSampleType { span: Span, scalar: Scalar, @@ -271,6 +280,75 @@ pub(crate) enum Error<'a> { expected: Range, found: u32, }, + /// No overload of this function accepts this many arguments. + TooManyArguments { + /// The name of the function being called. + function: String, + + /// The function name in the call expression. + call_span: Span, + + /// The first argument that is unacceptable. + arg_span: Span, + + /// Maximum number of arguments accepted by any overload of + /// this function. + max_arguments: u32, + }, + /// A value passed to a builtin function has a type that is not + /// accepted by any overload of the function. + WrongArgumentType { + /// The name of the function being called. + function: String, + + /// The function name in the call expression. + call_span: Span, + + /// The first argument whose type is unacceptable. + arg_span: Span, + + /// The index of the first argument whose type is unacceptable. + arg_index: u32, + + /// That argument's actual type. + arg_ty: String, + + /// The set of argument types that would have been accepted for + /// this argument, given the prior arguments. + allowed: Vec, + }, + /// A value passed to a builtin function has a type that is not + /// accepted, given the earlier arguments' types. + InconsistentArgumentType { + /// The name of the function being called. + function: String, + + /// The function name in the call expression. + call_span: Span, + + /// The first unacceptable argument. + arg_span: Span, + + /// The index of the first unacceptable argument. + arg_index: u32, + + /// The actual type of the first unacceptable argument. + arg_ty: String, + + /// The prior argument whose type made the `arg_span` argument + /// unacceptable. + inconsistent_span: Span, + + /// The index of the `inconsistent_span` argument. + inconsistent_index: u32, + + /// The type of the `inconsistent_span` argument. + inconsistent_ty: String, + + /// The types that would have been accepted instead of the + /// first unacceptable argument. + allowed: Vec, + }, FunctionReturnsVoid(Span), FunctionMustUseUnused(Span), FunctionMustUseReturnsVoid(Span, Span), @@ -318,6 +396,22 @@ pub(crate) enum Error<'a> { on_what: DiagnosticAttributeNotSupportedPosition, spans: Vec, }, + SelectUnexpectedArgumentType { + arg_span: Span, + arg_type: String, + }, + SelectRejectAndAcceptHaveNoCommonType { + reject_span: Span, + reject_type: String, + accept_span: Span, + accept_type: String, + }, + StructMemberTooLarge { + member_name_span: Span, + }, + TypeTooLarge { + span: Span, + }, } impl From for Error<'_> { @@ -388,6 +482,8 @@ impl<'a> Error<'a> { Token::Arrow => "->".to_string(), Token::Unknown(c) => format!("unknown (`{c}`)"), Token::Trivia => "trivia".to_string(), + Token::DocComment(s) => format!("doc comment ('{s}')"), + Token::ModuleDocComment(s) => format!("module doc comment ('{s}')"), Token::End => "end".to_string(), }, ExpectedToken::Identifier => "identifier".to_string(), @@ -402,7 +498,8 @@ impl<'a> Error<'a> { "workgroup size separator (`,`) or a closing parenthesis".to_string() } ExpectedToken::GlobalItem => concat!( - "global item (`struct`, `const`, `var`, `alias`, `fn`, `diagnostic`, `enable`, `requires`, `;`) ", + "global item (`struct`, `const`, `var`, `alias`, ", + "`fn`, `diagnostic`, `enable`, `requires`, `;`) ", "or the end of the file" ) .to_string(), @@ -466,6 +563,11 @@ impl<'a> Error<'a> { labels: vec![(bad_span, "unknown scalar type".into())], notes: vec!["Valid scalar types are f32, f64, i32, u32, bool".into()], }, + Error::NotStorageTexture(bad_span) => ParseError { + message: "textureStore can only be applied to storage textures".to_string(), + labels: vec![(bad_span, "not a storage texture".into())], + notes: vec![], + }, Error::BadTextureSampleType { span, scalar } => ParseError { message: format!( "texture sample type must be one of f32, i32 or u32, but found {}", @@ -591,7 +693,7 @@ impl<'a> Error<'a> { notes: vec![], }, Error::UnknownEnableExtension(span, word) => ParseError { - message: format!("unknown enable-extension `{}`", word), + message: format!("unknown enable-extension `{word}`"), labels: vec![(span, "".into())], notes: vec![ "See available extensions at ." @@ -831,6 +933,74 @@ impl<'a> Error<'a> { labels: vec![(span, "wrong number of arguments".into())], notes: vec![], }, + Error::TooManyArguments { + ref function, + call_span, + arg_span, + max_arguments, + } => ParseError { + message: format!("too many arguments passed to `{function}`"), + labels: vec![ + (call_span, "".into()), + (arg_span, format!("unexpected argument #{}", max_arguments + 1).into()) + ], + notes: vec![ + format!("The `{function}` function accepts at most {max_arguments} argument(s)") + ], + }, + Error::WrongArgumentType { + ref function, + call_span, + arg_span, + arg_index, + ref arg_ty, + ref allowed, + } => { + let message = format!( + "wrong type passed as argument #{} to `{function}`", + arg_index + 1, + ); + let labels = vec![ + (call_span, "".into()), + (arg_span, format!("argument #{} has type `{arg_ty}`", arg_index + 1).into()) + ]; + + let mut notes = vec![]; + notes.push(format!("`{function}` accepts the following types for argument #{}:", arg_index + 1)); + notes.extend(allowed.iter().map(|ty| format!("allowed type: {ty}"))); + + ParseError { message, labels, notes } + }, + Error::InconsistentArgumentType { + ref function, + call_span, + arg_span, + arg_index, + ref arg_ty, + inconsistent_span, + inconsistent_index, + ref inconsistent_ty, + ref allowed + } => { + let message = format!( + "inconsistent type passed as argument #{} to `{function}`", + arg_index + 1, + ); + let labels = vec![ + (call_span, "".into()), + (arg_span, format!("argument #{} has type {arg_ty}", arg_index + 1).into()), + (inconsistent_span, format!( + "this argument has type {inconsistent_ty}, which constrains subsequent arguments" + ).into()), + ]; + let mut notes = vec![ + format!("Because argument #{} has type {inconsistent_ty}, only the following types", inconsistent_index + 1), + format!("(or types that automatically convert to them) are accepted for argument #{}:", arg_index + 1), + ]; + notes.extend(allowed.iter().map(|ty| format!("allowed type: {ty}"))); + + ParseError { message, labels, notes } + } Error::FunctionReturnsVoid(span) => ParseError { message: "function does not return any value".to_string(), labels: vec![(span, "".into())], @@ -911,8 +1081,7 @@ impl<'a> Error<'a> { } = **error; ParseError { message: format!( - "automatic conversions cannot convert `{}` to `{}`", - source_type, dest_type + "automatic conversions cannot convert `{source_type}` to `{dest_type}`" ), labels: vec![ ( @@ -936,15 +1105,13 @@ impl<'a> Error<'a> { } = **error; ParseError { message: format!( - "automatic conversions cannot convert elements of `{}` to `{}`", - source_type, dest_scalar + "automatic conversions cannot convert elements of `{source_type}` to `{dest_scalar}`" ), labels: vec![ ( dest_span, format!( - "a value with elements of type {} is required here", - dest_scalar + "a value with elements of type {dest_scalar} is required here" ) .into(), ), @@ -1185,6 +1352,40 @@ impl<'a> Error<'a> { ], } } + Error::SelectUnexpectedArgumentType { arg_span, ref arg_type } => ParseError { + message: "unexpected argument type for `select` call".into(), + labels: vec![(arg_span, format!("this value of type {arg_type}").into())], + notes: vec!["expected a scalar or a `vecN` of scalars".into()], + }, + Error::SelectRejectAndAcceptHaveNoCommonType { + reject_span, + ref reject_type, + accept_span, + ref accept_type, + } => ParseError { + message: "type mismatch for reject and accept values in `select` call".into(), + labels: vec![ + (reject_span, format!("reject value of type {reject_type}").into()), + (accept_span, format!("accept value of type {accept_type}").into()), + ], + notes: vec![], + }, + Error::StructMemberTooLarge { member_name_span } => ParseError { + message: "struct member is too large".into(), + labels: vec![(member_name_span, "this member exceeds the maximum size".into())], + notes: vec![format!( + "the maximum size is {} bytes", + crate::valid::MAX_TYPE_SIZE + )], + }, + Error::TypeTooLarge { span } => ParseError { + message: "type is too large".into(), + labels: vec![(span, "this type exceeds the maximum size".into())], + notes: vec![format!( + "the maximum size is {} bytes", + crate::valid::MAX_TYPE_SIZE + )], + }, } } } diff --git a/naga/src/front/wgsl/index.rs b/naga/src/front/wgsl/index.rs index 923cc7547..b9e5cf375 100644 --- a/naga/src/front/wgsl/index.rs +++ b/naga/src/front/wgsl/index.rs @@ -183,7 +183,7 @@ impl<'a> DependencySolver<'a, '_> { self.temp_visited[id_usize] = false; // Now everything this declaration uses has been visited, and is already - // present in `out`. That means we we can append this one to the + // present in `out`. That means we can append this one to the // ordering, and mark it as visited. self.out.push(id); self.visited[id_usize] = true; diff --git a/naga/src/front/wgsl/lower/construction.rs b/naga/src/front/wgsl/lower/construction.rs index fe5f4655e..997d5a312 100644 --- a/naga/src/front/wgsl/lower/construction.rs +++ b/naga/src/front/wgsl/lower/construction.rs @@ -167,11 +167,25 @@ impl<'source> Lowerer<'source, '_> { // Empty constructor (Components::None, dst_ty) => match dst_ty { Constructor::Type((result_ty, _)) => { - return ctx.append_expression(crate::Expression::ZeroValue(result_ty), span) + expr = crate::Expression::ZeroValue(result_ty); } - Constructor::PartialVector { .. } - | Constructor::PartialMatrix { .. } - | Constructor::PartialArray => { + Constructor::PartialVector { size } => { + // vec2(), vec3(), vec4() return vectors of abstractInts; the same + // is not true of the similar constructors for matrices or arrays. + // See https://www.w3.org/TR/WGSL/#vec2-builtin et seq. + let result_ty = ctx.module.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Vector { + size, + scalar: crate::Scalar::ABSTRACT_INT, + }, + }, + span, + ); + expr = crate::Expression::ZeroValue(result_ty); + } + Constructor::PartialMatrix { .. } | Constructor::PartialArray => { // We have no arguments from which to infer the result type, so // partial constructors aren't acceptable here. return Err(Box::new(Error::TypeNotInferable(ty_span))); @@ -536,8 +550,14 @@ impl<'source> Lowerer<'source, '_> { // ERRORS // Bad conversion (type cast) - (Components::One { span, ty_inner, .. }, constructor) => { - let from_type = ctx.type_inner_to_string(ty_inner); + ( + Components::One { + span, component, .. + }, + constructor, + ) => { + let component_ty = &ctx.typifier()[component]; + let from_type = ctx.type_resolution_to_string(component_ty); return Err(Box::new(Error::BadTypeCast { span, from_type, diff --git a/naga/src/front/wgsl/lower/conversion.rs b/naga/src/front/wgsl/lower/conversion.rs index d750f20b1..b22692a3c 100644 --- a/naga/src/front/wgsl/lower/conversion.rs +++ b/naga/src/front/wgsl/lower/conversion.rs @@ -46,7 +46,7 @@ impl<'source> super::ExpressionContext<'source, '_, '_> { } // If `expr` already has the requested type, we're done. - if expr_inner.equivalent(goal_inner, types) { + if self.module.compare_types(expr_resolution, goal_ty) { return Ok(expr); } @@ -71,7 +71,7 @@ impl<'source> super::ExpressionContext<'source, '_, '_> { self.convert_leaf_scalar(expr, expr_span, goal_scalar) } - /// Try to convert `expr`'s leaf scalar to `goal` using automatic conversions. + /// Try to convert `expr`'s leaf scalar to `goal_scalar` using automatic conversions. /// /// If no conversions are necessary, return `expr` unchanged. /// @@ -311,17 +311,19 @@ impl<'source> super::ExpressionContext<'source, '_, '_> { I::IntoIter: Clone, // for debugging { let types = &self.module.types; - let mut inners = components - .into_iter() - .map(|&c| self.typifier()[c].inner_with(types)); + let components_iter = components.into_iter(); log::debug!( "wgsl automatic_conversion_consensus: {}", - inners + components_iter .clone() - .map(|inner| self.type_inner_to_string(inner)) + .map(|&expr| { + let res = &self.typifier()[expr]; + self.type_resolution_to_string(res) + }) .collect::>() .join(", ") ); + let mut inners = components_iter.map(|&c| self.typifier()[c].inner_with(types)); let mut best = inners.next().unwrap().scalar().ok_or(0_usize)?; for (inner, i) in inners.zip(1..) { let scalar = inner.scalar().ok_or(i)?; @@ -339,96 +341,6 @@ impl<'source> super::ExpressionContext<'source, '_, '_> { } impl crate::TypeInner { - /// Determine whether `self` automatically converts to `goal`. - /// - /// If WGSL's automatic conversions (excluding the Load Rule) will - /// convert `self` to `goal`, then return a pair `(from, to)`, - /// where `from` and `to` are the scalar types of the leaf values - /// of `self` and `goal`. - /// - /// This function assumes that `self` and `goal` are different - /// types. Callers should first check whether any conversion is - /// needed at all. - /// - /// If the automatic conversions cannot convert `self` to `goal`, - /// return `None`. - fn automatically_converts_to( - &self, - goal: &Self, - types: &crate::UniqueArena, - ) -> Option<(crate::Scalar, crate::Scalar)> { - use crate::ScalarKind as Sk; - use crate::TypeInner as Ti; - - // Automatic conversions only change the scalar type of a value's leaves - // (e.g., `vec4` to `vec4`), never the type - // constructors applied to those scalar types (e.g., never scalar to - // `vec4`, or `vec2` to `vec3`). So first we check that the type - // constructors match, extracting the leaf scalar types in the process. - let expr_scalar; - let goal_scalar; - match (self, goal) { - (&Ti::Scalar(expr), &Ti::Scalar(goal)) => { - expr_scalar = expr; - goal_scalar = goal; - } - ( - &Ti::Vector { - size: expr_size, - scalar: expr, - }, - &Ti::Vector { - size: goal_size, - scalar: goal, - }, - ) if expr_size == goal_size => { - expr_scalar = expr; - goal_scalar = goal; - } - ( - &Ti::Matrix { - rows: expr_rows, - columns: expr_columns, - scalar: expr, - }, - &Ti::Matrix { - rows: goal_rows, - columns: goal_columns, - scalar: goal, - }, - ) if expr_rows == goal_rows && expr_columns == goal_columns => { - expr_scalar = expr; - goal_scalar = goal; - } - ( - &Ti::Array { - base: expr_base, - size: expr_size, - stride: _, - }, - &Ti::Array { - base: goal_base, - size: goal_size, - stride: _, - }, - ) if expr_size == goal_size => { - return types[expr_base] - .inner - .automatically_converts_to(&types[goal_base].inner, types); - } - _ => return None, - } - - match (expr_scalar.kind, goal_scalar.kind) { - (Sk::AbstractFloat, Sk::Float) => {} - (Sk::AbstractInt, Sk::Sint | Sk::Uint | Sk::AbstractFloat | Sk::Float) => {} - _ => return None, - } - - log::trace!(" okay: expr {expr_scalar:?}, goal {goal_scalar:?}"); - Some((expr_scalar, goal_scalar)) - } - fn automatically_convertible_scalar( &self, types: &crate::UniqueArena, @@ -537,7 +449,7 @@ impl crate::Scalar { self.automatic_conversion_combine(goal) == Some(goal) } - const fn concretize(self) -> Self { + pub(in crate::front::wgsl) const fn concretize(self) -> Self { use crate::ScalarKind as Sk; match self.kind { Sk::Sint | Sk::Uint | Sk::Float | Sk::Bool => self, diff --git a/naga/src/front/wgsl/lower/mod.rs b/naga/src/front/wgsl/lower/mod.rs index 1fa3ecc83..2066d7cf2 100644 --- a/naga/src/front/wgsl/lower/mod.rs +++ b/naga/src/front/wgsl/lower/mod.rs @@ -1,21 +1,24 @@ use alloc::{ borrow::ToOwned, boxed::Box, + format, string::{String, ToString}, vec::Vec, }; use core::num::NonZeroU32; -use crate::common::wgsl::TypeContext; use crate::front::wgsl::error::{Error, ExpectedToken, InvalidAssignmentType}; use crate::front::wgsl::index::Index; use crate::front::wgsl::parse::number::Number; use crate::front::wgsl::parse::{ast, conv}; use crate::front::wgsl::Result; use crate::front::Typifier; -use crate::proc::{ - ensure_block_returns, Alignment, ConstantEvaluator, Emitter, Layouter, ResolveContext, +use crate::{ + common::wgsl::{TryToWgsl, TypeContext}, + compact::KeepUnused, }; +use crate::{common::ForDebugWithTypes, proc::LayoutErrorInner}; +use crate::{ir, proc}; use crate::{Arena, FastHashMap, FastIndexMap, Handle, Span}; mod construction; @@ -25,7 +28,7 @@ mod conversion; /// /// Expects a &mut [`ExpressionContext`] and a [`Handle`]. /// -/// Returns a &[`crate::TypeInner`]. +/// Returns a &[`ir::TypeInner`]. /// /// Ideally, we would simply have a function that takes a `&mut ExpressionContext` /// and returns a `&TypeResolution`. Unfortunately, this leads the borrow checker @@ -46,7 +49,7 @@ pub(super) use resolve_inner; /// /// Expects a &mut [`ExpressionContext`] and two [`Handle`]s. /// -/// Returns a tuple containing two &[`crate::TypeInner`]. +/// Returns a tuple containing two &[`ir::TypeInner`]. /// /// See the documentation of [`resolve_inner!`] for why this macro is necessary. macro_rules! resolve_inner_binary { @@ -68,16 +71,17 @@ macro_rules! resolve_inner_binary { /// /// See the documentation of [`resolve_inner!`] for why this macro is necessary. /// -/// [`TypeResolution`]: crate::proc::TypeResolution +/// [`TypeResolution`]: proc::TypeResolution macro_rules! resolve { ($ctx:ident, $expr:expr) => {{ - $ctx.grow_types($expr)?; - &$ctx.typifier()[$expr] + let expr = $expr; + $ctx.grow_types(expr)?; + &$ctx.typifier()[expr] }}; } pub(super) use resolve; -/// State for constructing a `crate::Module`. +/// State for constructing a `ir::Module`. pub struct GlobalContext<'source, 'temp, 'out> { /// The `TranslationUnit`'s expressions arena. ast_expressions: &'temp Arena>, @@ -91,13 +95,13 @@ pub struct GlobalContext<'source, 'temp, 'out> { globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, /// The module we're constructing. - module: &'out mut crate::Module, + module: &'out mut ir::Module, const_typifier: &'temp mut Typifier, - layouter: &'temp mut Layouter, + layouter: &'temp mut proc::Layouter, - global_expression_kind_tracker: &'temp mut crate::proc::ExpressionKindTracker, + global_expression_kind_tracker: &'temp mut proc::ExpressionKindTracker, } impl<'source> GlobalContext<'source, '_, '_> { @@ -130,11 +134,11 @@ impl<'source> GlobalContext<'source, '_, '_> { fn ensure_type_exists( &mut self, name: Option, - inner: crate::TypeInner, - ) -> Handle { + inner: ir::TypeInner, + ) -> Handle { self.module .types - .insert(crate::Type { inner, name }, Span::UNDEFINED) + .insert(ir::Type { inner, name }, Span::UNDEFINED) } } @@ -170,19 +174,19 @@ pub struct StatementContext<'source, 'temp, 'out> { /// This always borrows the `local_table` local variable in /// [`Lowerer::function`]. /// - /// [`LocalVariable`]: crate::Expression::LocalVariable - /// [`FunctionArgument`]: crate::Expression::FunctionArgument + /// [`LocalVariable`]: ir::Expression::LocalVariable + /// [`FunctionArgument`]: ir::Expression::FunctionArgument local_table: - &'temp mut FastHashMap, Declared>>>, + &'temp mut FastHashMap, Declared>>>, const_typifier: &'temp mut Typifier, typifier: &'temp mut Typifier, - layouter: &'temp mut Layouter, - function: &'out mut crate::Function, + layouter: &'temp mut proc::Layouter, + function: &'out mut ir::Function, /// Stores the names of expressions that are assigned in `let` statement /// Also stores the spans of the names, for use in errors. - named_expressions: &'out mut FastIndexMap, (String, Span)>, - module: &'out mut crate::Module, + named_expressions: &'out mut FastIndexMap, (String, Span)>, + module: &'out mut ir::Module, /// Which `Expression`s in `self.naga_expressions` are const expressions, in /// the WGSL sense. @@ -193,15 +197,15 @@ pub struct StatementContext<'source, 'temp, 'out> { /// with the form of the expressions; it is also tracking whether WGSL says /// we should consider them to be const. See the use of `force_non_const` in /// the code for lowering `let` bindings. - local_expression_kind_tracker: &'temp mut crate::proc::ExpressionKindTracker, - global_expression_kind_tracker: &'temp mut crate::proc::ExpressionKindTracker, + local_expression_kind_tracker: &'temp mut proc::ExpressionKindTracker, + global_expression_kind_tracker: &'temp mut proc::ExpressionKindTracker, } impl<'a, 'temp> StatementContext<'a, 'temp, '_> { fn as_const<'t>( &'t mut self, - block: &'t mut crate::Block, - emitter: &'t mut Emitter, + block: &'t mut ir::Block, + emitter: &'t mut proc::Emitter, ) -> ExpressionContext<'a, 't, 't> where 'temp: 't, @@ -227,8 +231,8 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> { fn as_expression<'t>( &'t mut self, - block: &'t mut crate::Block, - emitter: &'t mut Emitter, + block: &'t mut ir::Block, + emitter: &'t mut proc::Emitter, ) -> ExpressionContext<'a, 't, 't> where 'temp: 't, @@ -265,14 +269,14 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> { } } - fn invalid_assignment_type(&self, expr: Handle) -> InvalidAssignmentType { + fn invalid_assignment_type(&self, expr: Handle) -> InvalidAssignmentType { if let Some(&(_, span)) = self.named_expressions.get(&expr) { InvalidAssignmentType::ImmutableBinding(span) } else { match self.function.expressions[expr] { - crate::Expression::Swizzle { .. } => InvalidAssignmentType::Swizzle, - crate::Expression::Access { base, .. } => self.invalid_assignment_type(base), - crate::Expression::AccessIndex { base, .. } => self.invalid_assignment_type(base), + ir::Expression::Swizzle { .. } => InvalidAssignmentType::Swizzle, + ir::Expression::Access { base, .. } => self.invalid_assignment_type(base), + ir::Expression::AccessIndex { base, .. } => self.invalid_assignment_type(base), _ => InvalidAssignmentType::Other, } } @@ -284,18 +288,18 @@ pub struct LocalExpressionContext<'temp, 'out> { /// /// This is always [`StatementContext::local_table`] for the /// enclosing statement; see that documentation for details. - local_table: &'temp FastHashMap, Declared>>>, + local_table: &'temp FastHashMap, Declared>>>, - function: &'out mut crate::Function, - block: &'temp mut crate::Block, - emitter: &'temp mut Emitter, + function: &'out mut ir::Function, + block: &'temp mut ir::Block, + emitter: &'temp mut proc::Emitter, typifier: &'temp mut Typifier, /// Which `Expression`s in `self.naga_expressions` are const expressions, in /// the WGSL sense. /// /// See [`StatementContext::local_expression_kind_tracker`] for details. - local_expression_kind_tracker: &'temp mut crate::proc::ExpressionKindTracker, + local_expression_kind_tracker: &'temp mut proc::ExpressionKindTracker, } /// The type of Naga IR expression we are lowering an [`ast::Expression`] to. @@ -356,12 +360,12 @@ pub enum ExpressionContextType<'temp, 'out> { /// /// [`expr_type`]: ExpressionContext::expr_type /// [`Runtime`]: ExpressionContextType::Runtime -/// [`naga::Expression`]: crate::Expression -/// [`naga::Function`]: crate::Function +/// [`naga::Expression`]: ir::Expression +/// [`naga::Function`]: ir::Function /// [`Constant`]: ExpressionContextType::Constant -/// [`naga::Module`]: crate::Module +/// [`naga::Module`]: ir::Module /// [`as_const`]: ExpressionContext::as_const -/// [`Expression::Constant`]: crate::Expression::Constant +/// [`Expression::Constant`]: ir::Expression::Constant pub struct ExpressionContext<'source, 'temp, 'out> { // WGSL AST values. ast_expressions: &'temp Arena>, @@ -374,15 +378,15 @@ pub struct ExpressionContext<'source, 'temp, 'out> { /// The IR [`Module`] we're constructing. /// - /// [`Module`]: crate::Module - module: &'out mut crate::Module, + /// [`Module`]: ir::Module + module: &'out mut ir::Module, /// Type judgments for [`module::global_expressions`]. /// - /// [`module::global_expressions`]: crate::Module::global_expressions + /// [`module::global_expressions`]: ir::Module::global_expressions const_typifier: &'temp mut Typifier, - layouter: &'temp mut Layouter, - global_expression_kind_tracker: &'temp mut crate::proc::ExpressionKindTracker, + layouter: &'temp mut proc::Layouter, + global_expression_kind_tracker: &'temp mut proc::ExpressionKindTracker, /// Whether we are lowering a constant expression or a general /// runtime expression, and the data needed in each case. @@ -390,11 +394,11 @@ pub struct ExpressionContext<'source, 'temp, 'out> { } impl TypeContext for ExpressionContext<'_, '_, '_> { - fn lookup_type(&self, handle: Handle) -> &crate::Type { + fn lookup_type(&self, handle: Handle) -> &ir::Type { &self.module.types[handle] } - fn type_name(&self, handle: Handle) -> &str { + fn type_name(&self, handle: Handle) -> &str { self.module.types[handle] .name .as_deref() @@ -403,7 +407,7 @@ impl TypeContext for ExpressionContext<'_, '_, '_> { fn write_override( &self, - handle: Handle, + handle: Handle, out: &mut W, ) -> core::fmt::Result { match self.module.overrides[handle].name { @@ -411,6 +415,14 @@ impl TypeContext for ExpressionContext<'_, '_, '_> { None => write!(out, "{{anonymous override {handle:?}}}"), } } + + fn write_unnamed_struct( + &self, + _: &ir::TypeInner, + _: &mut W, + ) -> core::fmt::Result { + unreachable!("the WGSL front end should always know the type name"); + } } impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { @@ -454,19 +466,21 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { } } - fn as_const_evaluator(&mut self) -> ConstantEvaluator { + fn as_const_evaluator(&mut self) -> proc::ConstantEvaluator<'_> { match self.expr_type { - ExpressionContextType::Runtime(ref mut rctx) => ConstantEvaluator::for_wgsl_function( - self.module, - &mut rctx.function.expressions, - rctx.local_expression_kind_tracker, - self.layouter, - rctx.emitter, - rctx.block, - false, - ), + ExpressionContextType::Runtime(ref mut rctx) => { + proc::ConstantEvaluator::for_wgsl_function( + self.module, + &mut rctx.function.expressions, + rctx.local_expression_kind_tracker, + self.layouter, + rctx.emitter, + rctx.block, + false, + ) + } ExpressionContextType::Constant(Some(ref mut rctx)) => { - ConstantEvaluator::for_wgsl_function( + proc::ConstantEvaluator::for_wgsl_function( self.module, &mut rctx.function.expressions, rctx.local_expression_kind_tracker, @@ -476,13 +490,13 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { true, ) } - ExpressionContextType::Constant(None) => ConstantEvaluator::for_wgsl_module( + ExpressionContextType::Constant(None) => proc::ConstantEvaluator::for_wgsl_module( self.module, self.global_expression_kind_tracker, self.layouter, false, ), - ExpressionContextType::Override => ConstantEvaluator::for_wgsl_module( + ExpressionContextType::Override => proc::ConstantEvaluator::for_wgsl_module( self.module, self.global_expression_kind_tracker, self.layouter, @@ -491,11 +505,24 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { } } + /// Return a wrapper around `value` suitable for formatting. + /// + /// Return a wrapper around `value` that implements + /// [`core::fmt::Display`] in a form suitable for use in + /// diagnostic messages. + fn as_diagnostic_display( + &self, + value: T, + ) -> crate::common::DiagnosticDisplay<(T, proc::GlobalCtx<'_>)> { + let ctx = self.module.to_ctx(); + crate::common::DiagnosticDisplay((value, ctx)) + } + fn append_expression( &mut self, - expr: crate::Expression, + expr: ir::Expression, span: Span, - ) -> Result<'source, Handle> { + ) -> Result<'source, Handle> { let mut eval = self.as_const_evaluator(); eval.try_eval_and_append(expr, span) .map_err(|e| Box::new(Error::ConstantEvaluatorError(e.into(), span))) @@ -503,12 +530,12 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { fn const_eval_expr_to_u32( &self, - handle: Handle, - ) -> core::result::Result { + handle: Handle, + ) -> core::result::Result { match self.expr_type { ExpressionContextType::Runtime(ref ctx) => { if !ctx.local_expression_kind_tracker.is_const(handle) { - return Err(crate::proc::U32EvalError::NonConst); + return Err(proc::U32EvalError::NonConst); } self.module @@ -522,11 +549,24 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { .eval_expr_to_u32_from(handle, &ctx.function.expressions) } ExpressionContextType::Constant(None) => self.module.to_ctx().eval_expr_to_u32(handle), - ExpressionContextType::Override => Err(crate::proc::U32EvalError::NonConst), + ExpressionContextType::Override => Err(proc::U32EvalError::NonConst), } } - fn get_expression_span(&self, handle: Handle) -> Span { + /// Return `true` if `handle` is a constant expression. + fn is_const(&self, handle: Handle) -> bool { + use ExpressionContextType as Ect; + match self.expr_type { + Ect::Runtime(ref ctx) | Ect::Constant(Some(ref ctx)) => { + ctx.local_expression_kind_tracker.is_const(handle) + } + Ect::Constant(None) | Ect::Override => { + self.global_expression_kind_tracker.is_const(handle) + } + } + } + + fn get_expression_span(&self, handle: Handle) -> Span { match self.expr_type { ExpressionContextType::Runtime(ref ctx) | ExpressionContextType::Constant(Some(ref ctx)) => { @@ -552,7 +592,7 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { &mut self, local: &Handle, span: Span, - ) -> Result<'source, Typed>> { + ) -> Result<'source, Typed>> { match self.expr_type { ExpressionContextType::Runtime(ref ctx) => Ok(ctx.local_table[local].runtime()), ExpressionContextType::Constant(Some(ref ctx)) => ctx.local_table[local] @@ -576,10 +616,10 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { fn gather_component( &mut self, - expr: Handle, + expr: Handle, component_span: Span, gather_span: Span, - ) -> Result<'source, crate::SwizzleComponent> { + ) -> Result<'source, ir::SwizzleComponent> { match self.expr_type { ExpressionContextType::Runtime(ref rctx) => { if !rctx.local_expression_kind_tracker.is_const(expr) { @@ -593,14 +633,12 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { .to_ctx() .eval_expr_to_u32_from(expr, &rctx.function.expressions) .map_err(|err| match err { - crate::proc::U32EvalError::NonConst => { + proc::U32EvalError::NonConst => { Error::ExpectedConstExprConcreteIntegerScalar(component_span) } - crate::proc::U32EvalError::Negative => { - Error::ExpectedNonNegative(component_span) - } + proc::U32EvalError::Negative => Error::ExpectedNonNegative(component_span), })?; - crate::SwizzleComponent::XYZW + ir::SwizzleComponent::XYZW .get(index as usize) .copied() .ok_or(Box::new(Error::InvalidGatherComponent(component_span))) @@ -622,11 +660,11 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { /// creating a [`LocalVariable`] whose type is inferred from its /// initializer. /// - /// [`LocalVariable`]: crate::LocalVariable + /// [`LocalVariable`]: ir::LocalVariable fn register_type( &mut self, - handle: Handle, - ) -> Result<'source, Handle> { + handle: Handle, + ) -> Result<'source, Handle> { self.grow_types(handle)?; // This is equivalent to calling ExpressionContext::typifier(), // except that this lets the borrow checker see that it's okay @@ -658,10 +696,10 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { /// [`resolve_inner!`] or [`resolve_inner_binary!`]. /// /// [`self.typifier`]: ExpressionContext::typifier - /// [`TypeResolution`]: crate::proc::TypeResolution + /// [`TypeResolution`]: proc::TypeResolution /// [`register_type`]: Self::register_type /// [`Typifier`]: Typifier - fn grow_types(&mut self, handle: Handle) -> Result<'source, &mut Self> { + fn grow_types(&mut self, handle: Handle) -> Result<'source, &mut Self> { let empty_arena = Arena::new(); let resolve_ctx; let typifier; @@ -669,7 +707,7 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { match self.expr_type { ExpressionContextType::Runtime(ref mut ctx) | ExpressionContextType::Constant(Some(ref mut ctx)) => { - resolve_ctx = ResolveContext::with_locals( + resolve_ctx = proc::ResolveContext::with_locals( self.module, &ctx.function.local_variables, &ctx.function.arguments, @@ -678,7 +716,7 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { expressions = &ctx.function.expressions; } ExpressionContextType::Constant(None) | ExpressionContextType::Override => { - resolve_ctx = ResolveContext::with_locals(self.module, &empty_arena, &[]); + resolve_ctx = proc::ResolveContext::with_locals(self.module, &empty_arena, &[]); typifier = self.const_typifier; expressions = &self.module.global_expressions; } @@ -692,11 +730,11 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { fn image_data( &mut self, - image: Handle, + image: Handle, span: Span, - ) -> Result<'source, (crate::ImageClass, bool)> { + ) -> Result<'source, (ir::ImageClass, bool)> { match *resolve_inner!(self, image) { - crate::TypeInner::Image { class, arrayed, .. } => Ok((class, arrayed)), + ir::TypeInner::Image { class, arrayed, .. } => Ok((class, arrayed)), _ => Err(Box::new(Error::BadTexture(span))), } } @@ -725,30 +763,30 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { /// operations, so inserting splats into the IR increases size needlessly. fn binary_op_splat( &mut self, - op: crate::BinaryOperator, - left: &mut Handle, - right: &mut Handle, + op: ir::BinaryOperator, + left: &mut Handle, + right: &mut Handle, ) -> Result<'source, ()> { if matches!( op, - crate::BinaryOperator::Add - | crate::BinaryOperator::Subtract - | crate::BinaryOperator::Divide - | crate::BinaryOperator::Modulo + ir::BinaryOperator::Add + | ir::BinaryOperator::Subtract + | ir::BinaryOperator::Divide + | ir::BinaryOperator::Modulo ) { match resolve_inner_binary!(self, *left, *right) { - (&crate::TypeInner::Vector { size, .. }, &crate::TypeInner::Scalar { .. }) => { + (&ir::TypeInner::Vector { size, .. }, &ir::TypeInner::Scalar { .. }) => { *right = self.append_expression( - crate::Expression::Splat { + ir::Expression::Splat { size, value: *right, }, self.get_expression_span(*right), )?; } - (&crate::TypeInner::Scalar { .. }, &crate::TypeInner::Vector { size, .. }) => { + (&ir::TypeInner::Scalar { .. }, &ir::TypeInner::Vector { size, .. }) => { *left = self.append_expression( - crate::Expression::Splat { size, value: *left }, + ir::Expression::Splat { size, value: *left }, self.get_expression_span(*left), )?; } @@ -765,9 +803,9 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { /// `Emit` statements. fn interrupt_emitter( &mut self, - expression: crate::Expression, + expression: ir::Expression, span: Span, - ) -> Result<'source, Handle> { + ) -> Result<'source, Handle> { match self.expr_type { ExpressionContextType::Runtime(ref mut rctx) | ExpressionContextType::Constant(Some(ref mut rctx)) => { @@ -793,11 +831,11 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { /// `T`. Otherwise, return `expr` unchanged. fn apply_load_rule( &mut self, - expr: Typed>, - ) -> Result<'source, Handle> { + expr: Typed>, + ) -> Result<'source, Handle> { match expr { Typed::Reference(pointer) => { - let load = crate::Expression::Load { pointer }; + let load = ir::Expression::Load { pointer }; let span = self.get_expression_span(pointer); self.append_expression(load, span) } @@ -805,7 +843,7 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> { } } - fn ensure_type_exists(&mut self, inner: crate::TypeInner) -> Handle { + fn ensure_type_exists(&mut self, inner: ir::TypeInner) -> Handle { self.as_global().ensure_type_exists(None, inner) } } @@ -879,18 +917,18 @@ impl Declared { /// /// The `T` type parameter can be any expression-like thing: /// -/// - `Typed>` can represent a full WGSL type. For example, +/// - `Typed>` can represent a full WGSL type. For example, /// given some Naga `Pointer` type `ptr`, a WGSL reference type is a /// `Typed::Reference(ptr)` whereas a WGSL pointer type is a /// `Typed::Plain(ptr)`. /// -/// - `Typed` or `Typed>` can +/// - `Typed` or `Typed>` can /// represent references similarly. /// /// Use the `map` and `try_map` methods to convert from one expression /// representation to another. /// -/// [`Expression`]: crate::Expression +/// [`Expression`]: ir::Expression #[derive(Debug, Copy, Clone)] enum Typed { /// A WGSL reference. @@ -927,14 +965,14 @@ impl Typed { enum Components { Single(u32), Swizzle { - size: crate::VectorSize, - pattern: [crate::SwizzleComponent; 4], + size: ir::VectorSize, + pattern: [ir::SwizzleComponent; 4], }, } impl Components { - const fn letter_component(letter: char) -> Option { - use crate::SwizzleComponent as Sc; + const fn letter_component(letter: char) -> Option { + use ir::SwizzleComponent as Sc; match letter { 'x' | 'r' => Some(Sc::X), 'y' | 'g' => Some(Sc::Y), @@ -944,7 +982,7 @@ impl Components { } } - fn single_component(name: &str, name_span: Span) -> Result { + fn single_component(name: &str, name_span: Span) -> Result<'_, u32> { let ch = name.chars().next().ok_or(Error::BadAccessor(name_span))?; match Self::letter_component(ch) { Some(sc) => Ok(sc as u32), @@ -955,16 +993,16 @@ impl Components { /// Construct a `Components` value from a 'member' name, like `"wzy"` or `"x"`. /// /// Use `name_span` for reporting errors in parsing the component string. - fn new(name: &str, name_span: Span) -> Result { + fn new(name: &str, name_span: Span) -> Result<'_, Self> { let size = match name.len() { 1 => return Ok(Components::Single(Self::single_component(name, name_span)?)), - 2 => crate::VectorSize::Bi, - 3 => crate::VectorSize::Tri, - 4 => crate::VectorSize::Quad, + 2 => ir::VectorSize::Bi, + 3 => ir::VectorSize::Tri, + 4 => ir::VectorSize::Quad, _ => return Err(Box::new(Error::BadAccessor(name_span))), }; - let mut pattern = [crate::SwizzleComponent::X; 4]; + let mut pattern = [ir::SwizzleComponent::X; 4]; for (comp, ch) in pattern.iter_mut().zip(name.chars()) { *comp = Self::letter_component(ch).ok_or(Error::BadAccessor(name_span))?; } @@ -982,14 +1020,14 @@ impl Components { /// An `ast::GlobalDecl` for which we have built the Naga IR equivalent. enum LoweredGlobalDecl { Function { - handle: Handle, + handle: Handle, must_use: bool, }, - Var(Handle), - Const(Handle), - Override(Handle), - Type(Handle), - EntryPoint, + Var(Handle), + Const(Handle), + Override(Handle), + Type(Handle), + EntryPoint(usize), } enum Texture { @@ -1002,7 +1040,7 @@ enum Texture { SampleCompareLevel, SampleGrad, SampleLevel, - // SampleBaseClampToEdge, + SampleBaseClampToEdge, } impl Texture { @@ -1017,7 +1055,7 @@ impl Texture { "textureSampleCompareLevel" => Self::SampleCompareLevel, "textureSampleGrad" => Self::SampleGrad, "textureSampleLevel" => Self::SampleLevel, - // "textureSampleBaseClampToEdge" => Some(Self::SampleBaseClampToEdge), + "textureSampleBaseClampToEdge" => Self::SampleBaseClampToEdge, _ => return None, }) } @@ -1033,7 +1071,7 @@ impl Texture { Self::SampleCompareLevel => 5, Self::SampleGrad => 6, Self::SampleLevel => 5, - // Self::SampleBaseClampToEdge => 3, + Self::SampleBaseClampToEdge => 3, } } } @@ -1045,6 +1083,7 @@ enum SubgroupGather { ShuffleDown, ShuffleUp, ShuffleXor, + QuadBroadcast, } impl SubgroupGather { @@ -1056,6 +1095,7 @@ impl SubgroupGather { "subgroupShuffleDown" => Self::ShuffleDown, "subgroupShuffleUp" => Self::ShuffleUp, "subgroupShuffleXor" => Self::ShuffleXor, + "quadBroadcast" => Self::QuadBroadcast, _ => return None, }) } @@ -1079,8 +1119,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { Self { index } } - pub fn lower(&mut self, tu: ast::TranslationUnit<'source>) -> Result<'source, crate::Module> { - let mut module = crate::Module { + pub fn lower(&mut self, tu: ast::TranslationUnit<'source>) -> Result<'source, ir::Module> { + let mut module = ir::Module { diagnostic_filters: tu.diagnostic_filters, diagnostic_filter_leaf: tu.diagnostic_filter_leaf, ..Default::default() @@ -1092,9 +1132,13 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { types: &tu.types, module: &mut module, const_typifier: &mut Typifier::new(), - layouter: &mut Layouter::default(), - global_expression_kind_tracker: &mut crate::proc::ExpressionKindTracker::new(), + layouter: &mut proc::Layouter::default(), + global_expression_kind_tracker: &mut proc::ExpressionKindTracker::new(), }; + if !tu.doc_comments.is_empty() { + ctx.module.get_or_insert_default_doc_comments().module = + tu.doc_comments.iter().map(|s| s.to_string()).collect(); + } for decl_handle in self.index.visit_ordered() { let span = tu.decls.get_span(decl_handle); @@ -1103,6 +1147,29 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { match decl.kind { ast::GlobalDeclKind::Fn(ref f) => { let lowered_decl = self.function(f, span, &mut ctx)?; + if !f.doc_comments.is_empty() { + match lowered_decl { + LoweredGlobalDecl::Function { handle, .. } => { + ctx.module + .get_or_insert_default_doc_comments() + .functions + .insert( + handle, + f.doc_comments.iter().map(|s| s.to_string()).collect(), + ); + } + LoweredGlobalDecl::EntryPoint(index) => { + ctx.module + .get_or_insert_default_doc_comments() + .entry_points + .insert( + index, + f.doc_comments.iter().map(|s| s.to_string()).collect(), + ); + } + _ => {} + } + } ctx.globals.insert(f.name.name, lowered_decl); } ast::GlobalDeclKind::Var(ref v) => { @@ -1119,7 +1186,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { )?; let binding = if let Some(ref binding) = v.binding { - Some(crate::ResourceBinding { + Some(ir::ResourceBinding { group: self.const_u32(binding.group, &mut ctx.as_const())?.0, binding: self.const_u32(binding.binding, &mut ctx.as_const())?.0, }) @@ -1128,7 +1195,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }; let handle = ctx.module.global_variables.append( - crate::GlobalVariable { + ir::GlobalVariable { name: Some(v.name.name.to_string()), space: v.space, binding, @@ -1138,6 +1205,15 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { span, ); + if !v.doc_comments.is_empty() { + ctx.module + .get_or_insert_default_doc_comments() + .global_variables + .insert( + handle, + v.doc_comments.iter().map(|s| s.to_string()).collect(), + ); + } ctx.globals .insert(v.name.name, LoweredGlobalDecl::Var(handle)); } @@ -1158,7 +1234,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let init = init.expect("Global const must have init"); let handle = ctx.module.constants.append( - crate::Constant { + ir::Constant { name: Some(c.name.name.to_string()), ty, init, @@ -1168,6 +1244,15 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ctx.globals .insert(c.name.name, LoweredGlobalDecl::Const(handle)); + if !c.doc_comments.is_empty() { + ctx.module + .get_or_insert_default_doc_comments() + .constants + .insert( + handle, + c.doc_comments.iter().map(|s| s.to_string()).collect(), + ); + } } ast::GlobalDeclKind::Override(ref o) => { let explicit_ty = @@ -1198,7 +1283,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }; let handle = ctx.module.overrides.append( - crate::Override { + ir::Override { name: Some(o.name.name.to_string()), id, ty, @@ -1214,6 +1299,15 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let handle = self.r#struct(s, span, &mut ctx)?; ctx.globals .insert(s.name.name, LoweredGlobalDecl::Type(handle)); + if !s.doc_comments.is_empty() { + ctx.module + .get_or_insert_default_doc_comments() + .types + .insert( + handle, + s.doc_comments.iter().map(|s| s.to_string()).collect(), + ); + } } ast::GlobalDeclKind::Type(ref alias) => { let ty = self.resolve_named_ast_type( @@ -1244,7 +1338,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { // Constant evaluation may leave abstract-typed literals and // compositions in expression arenas, so we need to compact the module // to remove unused expressions and types. - crate::compact::compact(&mut module); + crate::compact::compact(&mut module, KeepUnused::Yes); Ok(module) } @@ -1254,16 +1348,16 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { &mut self, name: ast::Ident<'source>, init: Option>>, - explicit_ty: Option>, + explicit_ty: Option>, abstract_rule: AbstractRule, ectx: &mut ExpressionContext<'source, '_, '_>, - ) -> Result<'source, (Handle, Option>)> { + ) -> Result<'source, (Handle, Option>)> { let ty; let initializer; match (init, explicit_ty) { (Some(init), Some(explicit_ty)) => { let init = self.expression_for_abstract(init, ectx)?; - let ty_res = crate::proc::TypeResolution::Handle(explicit_ty); + let ty_res = proc::TypeResolution::Handle(explicit_ty); let init = ectx .try_automatic_conversions(init, &ty_res, name.span) .map_err(|error| match *error { @@ -1276,13 +1370,14 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { })?; let init_ty = ectx.register_type(init)?; - let explicit_inner = &ectx.module.types[explicit_ty].inner; - let init_inner = &ectx.module.types[init_ty].inner; - if !explicit_inner.equivalent(init_inner, &ectx.module.types) { + if !ectx.module.compare_types( + &proc::TypeResolution::Handle(explicit_ty), + &proc::TypeResolution::Handle(init_ty), + ) { return Err(Box::new(Error::InitializationTypeMismatch { name: name.span, - expected: ectx.type_inner_to_string(explicit_inner), - got: ectx.type_inner_to_string(init_inner), + expected: ectx.type_to_string(explicit_ty), + got: ectx.type_to_string(init_ty), })); } ty = explicit_ty; @@ -1314,7 +1409,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let mut local_table = FastHashMap::default(); let mut expressions = Arena::new(); let mut named_expressions = FastIndexMap::default(); - let mut local_expression_kind_tracker = crate::proc::ExpressionKindTracker::new(); + let mut local_expression_kind_tracker = proc::ExpressionKindTracker::new(); let arguments = f .arguments @@ -1322,13 +1417,13 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .enumerate() .map(|(i, arg)| -> Result<'_, _> { let ty = self.resolve_ast_type(arg.ty, &mut ctx.as_const())?; - let expr = expressions - .append(crate::Expression::FunctionArgument(i as u32), arg.name.span); + let expr = + expressions.append(ir::Expression::FunctionArgument(i as u32), arg.name.span); local_table.insert(arg.handle, Declared::Runtime(Typed::Plain(expr))); named_expressions.insert(expr, (arg.name.name.to_string(), arg.name.span)); - local_expression_kind_tracker.insert(expr, crate::proc::ExpressionKind::Runtime); + local_expression_kind_tracker.insert(expr, proc::ExpressionKind::Runtime); - Ok(crate::FunctionArgument { + Ok(ir::FunctionArgument { name: Some(arg.name.name.to_string()), ty, binding: self.binding(&arg.binding, ty, ctx)?, @@ -1341,21 +1436,21 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .as_ref() .map(|res| -> Result<'_, _> { let ty = self.resolve_ast_type(res.ty, &mut ctx.as_const())?; - Ok(crate::FunctionResult { + Ok(ir::FunctionResult { ty, binding: self.binding(&res.binding, ty, ctx)?, }) }) .transpose()?; - let mut function = crate::Function { + let mut function = ir::Function { name: Some(f.name.name.to_string()), arguments, result, local_variables: Arena::new(), expressions, named_expressions: crate::NamedExpressions::default(), - body: crate::Block::default(), + body: ir::Block::default(), diagnostic_filter_leaf: f.diagnostic_filter_leaf, }; @@ -1375,7 +1470,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { global_expression_kind_tracker: ctx.global_expression_kind_tracker, }; let mut body = self.block(&f.body, false, &mut stmt_ctx)?; - ensure_block_returns(&mut body); + proc::ensure_block_returns(&mut body); function.body = body; function.named_expressions = named_expressions @@ -1397,7 +1492,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { Err(err) => { if let Error::ConstantEvaluatorError(ref ty, _) = *err { match **ty { - crate::proc::ConstantEvaluatorError::OverrideExpr => { + proc::ConstantEvaluatorError::OverrideExpr => { workgroup_size_overrides_out[i] = Some(self.workgroup_size_override( size_expr, @@ -1425,15 +1520,19 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }; let (workgroup_size, workgroup_size_overrides) = workgroup_size_info; - ctx.module.entry_points.push(crate::EntryPoint { + ctx.module.entry_points.push(ir::EntryPoint { name: f.name.name.to_string(), stage: entry.stage, early_depth_test: entry.early_depth_test, workgroup_size, workgroup_size_overrides, function, + mesh_info: None, + task_payload: None, }); - Ok(LoweredGlobalDecl::EntryPoint) + Ok(LoweredGlobalDecl::EntryPoint( + ctx.module.entry_points.len() - 1, + )) } else { let handle = ctx.module.functions.append(function, span); Ok(LoweredGlobalDecl::Function { @@ -1447,11 +1546,11 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { &mut self, size_expr: Handle>, ctx: &mut ExpressionContext<'source, '_, '_>, - ) -> Result<'source, Handle> { + ) -> Result<'source, Handle> { let span = ctx.ast_expressions.get_span(size_expr); let expr = self.expression(size_expr, ctx)?; match resolve_inner!(ctx, expr).scalar_kind().ok_or(0) { - Ok(crate::ScalarKind::Sint) | Ok(crate::ScalarKind::Uint) => Ok(expr), + Ok(ir::ScalarKind::Sint) | Ok(ir::ScalarKind::Uint) => Ok(expr), _ => Err(Box::new(Error::ExpectedConstExprConcreteIntegerScalar( span, ))), @@ -1463,8 +1562,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { b: &ast::Block<'source>, is_inside_loop: bool, ctx: &mut StatementContext<'source, '_, '_>, - ) -> Result<'source, crate::Block> { - let mut block = crate::Block::default(); + ) -> Result<'source, ir::Block> { + let mut block = ir::Block::default(); for stmt in b.stmts.iter() { self.statement(stmt, &mut block, is_inside_loop, ctx)?; @@ -1476,60 +1575,58 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { fn statement( &mut self, stmt: &ast::Statement<'source>, - block: &mut crate::Block, + block: &mut ir::Block, is_inside_loop: bool, ctx: &mut StatementContext<'source, '_, '_>, ) -> Result<'source, ()> { let out = match stmt.kind { ast::StatementKind::Block(ref block) => { let block = self.block(block, is_inside_loop, ctx)?; - crate::Statement::Block(block) + ir::Statement::Block(block) } ast::StatementKind::LocalDecl(ref decl) => match *decl { ast::LocalDecl::Let(ref l) => { - let mut emitter = Emitter::default(); + let mut emitter = proc::Emitter::default(); emitter.start(&ctx.function.expressions); - let value = - self.expression(l.init, &mut ctx.as_expression(block, &mut emitter))?; - - // The WGSL spec says that any expression that refers to a - // `let`-bound variable is not a const expression. This - // affects when errors must be reported, so we can't even - // treat suitable `let` bindings as constant as an - // optimization. - ctx.local_expression_kind_tracker.force_non_const(value); - let explicit_ty = l .ty .map(|ty| self.resolve_ast_type(ty, &mut ctx.as_const(block, &mut emitter))) .transpose()?; - if let Some(ty) = explicit_ty { - let mut ctx = ctx.as_expression(block, &mut emitter); - let init_ty = ctx.register_type(value)?; - if !ctx.module.types[ty] - .inner - .equivalent(&ctx.module.types[init_ty].inner, &ctx.module.types) - { - return Err(Box::new(Error::InitializationTypeMismatch { - name: l.name.span, - expected: ctx.type_to_string(ty), - got: ctx.type_to_string(init_ty), - })); - } - } + let mut ectx = ctx.as_expression(block, &mut emitter); + + let (_ty, initializer) = self.type_and_init( + l.name, + Some(l.init), + explicit_ty, + AbstractRule::Concretize, + &mut ectx, + )?; + + // We passed `Some()` to `type_and_init`, so we + // will get a lowered initializer expression back. + let initializer = + initializer.expect("type_and_init did not return an initializer"); + + // The WGSL spec says that any expression that refers to a + // `let`-bound variable is not a const expression. This + // affects when errors must be reported, so we can't even + // treat suitable `let` bindings as constant as an + // optimization. + ctx.local_expression_kind_tracker + .force_non_const(initializer); block.extend(emitter.finish(&ctx.function.expressions)); ctx.local_table - .insert(l.handle, Declared::Runtime(Typed::Plain(value))); + .insert(l.handle, Declared::Runtime(Typed::Plain(initializer))); ctx.named_expressions - .insert(value, (l.name.name.to_string(), l.name.span)); + .insert(initializer, (l.name.name.to_string(), l.name.span)); return Ok(()); } ast::LocalDecl::Var(ref v) => { - let mut emitter = Emitter::default(); + let mut emitter = proc::Emitter::default(); emitter.start(&ctx.function.expressions); let explicit_ty = @@ -1570,7 +1667,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }; let var = ctx.function.local_variables.append( - crate::LocalVariable { + ir::LocalVariable { name: Some(v.name.name.to_string()), ty, init: const_initializer, @@ -1578,16 +1675,15 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { stmt.span, ); - let handle = ctx.as_expression(block, &mut emitter).interrupt_emitter( - crate::Expression::LocalVariable(var), - Span::UNDEFINED, - )?; + let handle = ctx + .as_expression(block, &mut emitter) + .interrupt_emitter(ir::Expression::LocalVariable(var), Span::UNDEFINED)?; block.extend(emitter.finish(&ctx.function.expressions)); ctx.local_table .insert(v.handle, Declared::Runtime(Typed::Reference(handle))); match initializer { - Some(initializer) => crate::Statement::Store { + Some(initializer) => ir::Statement::Store { pointer: handle, value: initializer, }, @@ -1595,7 +1691,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } } ast::LocalDecl::Const(ref c) => { - let mut emitter = Emitter::default(); + let mut emitter = proc::Emitter::default(); emitter.start(&ctx.function.expressions); let ectx = &mut ctx.as_const(block, &mut emitter); @@ -1604,7 +1700,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { c.ty.map(|ast| self.resolve_ast_type(ast, &mut ectx.as_const())) .transpose()?; - let (ty, init) = self.type_and_init( + let (_ty, init) = self.type_and_init( c.name, Some(c.init), explicit_ty, @@ -1616,13 +1712,6 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { block.extend(emitter.finish(&ctx.function.expressions)); ctx.local_table .insert(c.handle, Declared::Const(Typed::Plain(init))); - // Only add constants of non-abstract types to the named expressions - // to prevent abstract types ending up in the IR. - let is_abstract = ctx.module.types[ty].inner.is_abstract(&ctx.module.types); - if !is_abstract { - ctx.named_expressions - .insert(init, (c.name.name.to_string(), c.name.span)); - } return Ok(()); } }, @@ -1631,7 +1720,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ref accept, ref reject, } => { - let mut emitter = Emitter::default(); + let mut emitter = proc::Emitter::default(); emitter.start(&ctx.function.expressions); let condition = @@ -1641,7 +1730,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let accept = self.block(accept, is_inside_loop, ctx)?; let reject = self.block(reject, is_inside_loop, ctx)?; - crate::Statement::If { + ir::Statement::If { condition, accept, reject, @@ -1651,7 +1740,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { selector, ref cases, } => { - let mut emitter = Emitter::default(); + let mut emitter = proc::Emitter::default(); emitter.start(&ctx.function.expressions); let mut ectx = ctx.as_expression(block, &mut emitter); @@ -1669,10 +1758,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let expr = self.expression_for_abstract(expr, &mut ectx)?; let ty = resolve_inner!(ectx, expr); match *ty { - crate::TypeInner::Scalar( - crate::Scalar::I32 - | crate::Scalar::U32 - | crate::Scalar::ABSTRACT_INT, + ir::TypeInner::Scalar( + ir::Scalar::I32 | ir::Scalar::U32 | ir::Scalar::ABSTRACT_INT, ) => Ok((expr, span)), _ => match i { 0 => Err(Box::new(Error::InvalidSwitchSelector { span })), @@ -1688,8 +1775,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { span: spans[span_idx], })?; // Concretize to I32 if the selector and all cases were abstract - if consensus == crate::Scalar::ABSTRACT_INT { - consensus = crate::Scalar::I32; + if consensus == ir::Scalar::ABSTRACT_INT { + consensus = ir::Scalar::I32; } for expr in &mut exprs { ectx.convert_to_leaf_scalar(expr, consensus)?; @@ -1705,7 +1792,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let cases = cases .iter() .map(|case| { - Ok(crate::SwitchCase { + Ok(ir::SwitchCase { value: match case.value { ast::SwitchValue::Expr(expr) => { let span = ctx.ast_expressions.get_span(expr); @@ -1717,11 +1804,11 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .to_ctx() .eval_expr_to_literal_from(expr, &ctx.function.expressions) { - Some(crate::Literal::I32(value)) => { - crate::SwitchValue::I32(value) + Some(ir::Literal::I32(value)) => { + ir::SwitchValue::I32(value) } - Some(crate::Literal::U32(value)) => { - crate::SwitchValue::U32(value) + Some(ir::Literal::U32(value)) => { + ir::SwitchValue::U32(value) } _ => { return Err(Box::new(Error::InvalidSwitchCase { @@ -1730,7 +1817,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } } } - ast::SwitchValue::Default => crate::SwitchValue::Default, + ast::SwitchValue::Default => ir::SwitchValue::Default, }, body: self.block(&case.body, is_inside_loop, ctx)?, fall_through: case.fall_through, @@ -1738,7 +1825,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }) .collect::>()?; - crate::Statement::Switch { selector, cases } + ir::Statement::Switch { selector, cases } } ast::StatementKind::Loop { ref body, @@ -1748,7 +1835,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let body = self.block(body, true, ctx)?; let mut continuing = self.block(continuing, true, ctx)?; - let mut emitter = Emitter::default(); + let mut emitter = proc::Emitter::default(); emitter.start(&ctx.function.expressions); let break_if = break_if .map(|expr| { @@ -1757,16 +1844,16 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .transpose()?; continuing.extend(emitter.finish(&ctx.function.expressions)); - crate::Statement::Loop { + ir::Statement::Loop { body, continuing, break_if, } } - ast::StatementKind::Break => crate::Statement::Break, - ast::StatementKind::Continue => crate::Statement::Continue, + ast::StatementKind::Break => ir::Statement::Break, + ast::StatementKind::Continue => ir::Statement::Continue, ast::StatementKind::Return { value: ast_value } => { - let mut emitter = Emitter::default(); + let mut emitter = proc::Emitter::default(); emitter.start(&ctx.function.expressions); let value; @@ -1777,7 +1864,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { if let Some(result_ty) = result_ty { let mut ectx = ctx.as_expression(block, &mut emitter); - let resolution = crate::proc::TypeResolution::Handle(result_ty); + let resolution = proc::TypeResolution::Handle(result_ty); let converted = ectx.try_automatic_conversions(expr, &resolution, Span::default())?; value = Some(converted); @@ -1789,14 +1876,14 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } block.extend(emitter.finish(&ctx.function.expressions)); - crate::Statement::Return { value } + ir::Statement::Return { value } } - ast::StatementKind::Kill => crate::Statement::Kill, + ast::StatementKind::Kill => ir::Statement::Kill, ast::StatementKind::Call { ref function, ref arguments, } => { - let mut emitter = Emitter::default(); + let mut emitter = proc::Emitter::default(); emitter.start(&ctx.function.expressions); let _ = self.call( @@ -1814,7 +1901,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { op, value, } => { - let mut emitter = Emitter::default(); + let mut emitter = proc::Emitter::default(); emitter.start(&ctx.function.expressions); let target_span = ctx.ast_expressions.get_span(ast_target); @@ -1836,8 +1923,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { // operators are exceptions, in that the right operand is always // a `u32` or `vecN`. let target_scalar = match op { - Some(crate::BinaryOperator::ShiftLeft | crate::BinaryOperator::ShiftRight) => { - Some(crate::Scalar::U32) + Some(ir::BinaryOperator::ShiftLeft | ir::BinaryOperator::ShiftRight) => { + Some(ir::Scalar::U32) } _ => resolve_inner!(ectx, target_handle) .pointer_automatically_convertible_scalar(&ectx.module.types), @@ -1858,7 +1945,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let mut left = ectx.apply_load_rule(target)?; ectx.binary_op_splat(op, &mut left, &mut value)?; ectx.append_expression( - crate::Expression::Binary { + ir::Expression::Binary { op, left, right: value, @@ -1870,18 +1957,18 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }; block.extend(emitter.finish(&ctx.function.expressions)); - crate::Statement::Store { + ir::Statement::Store { pointer: target_handle, value, } } ast::StatementKind::Increment(value) | ast::StatementKind::Decrement(value) => { - let mut emitter = Emitter::default(); + let mut emitter = proc::Emitter::default(); emitter.start(&ctx.function.expressions); let op = match stmt.kind { - ast::StatementKind::Increment(_) => crate::BinaryOperator::Add, - ast::StatementKind::Decrement(_) => crate::BinaryOperator::Subtract, + ast::StatementKind::Increment(_) => ir::BinaryOperator::Add, + ast::StatementKind::Decrement(_) => ir::BinaryOperator::Subtract, _ => unreachable!(), }; @@ -1897,28 +1984,26 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let mut ectx = ctx.as_expression(block, &mut emitter); let scalar = match *resolve_inner!(ectx, target_handle) { - crate::TypeInner::ValuePointer { + ir::TypeInner::ValuePointer { size: None, scalar, .. } => scalar, - crate::TypeInner::Pointer { base, .. } => match ectx.module.types[base].inner { - crate::TypeInner::Scalar(scalar) => scalar, + ir::TypeInner::Pointer { base, .. } => match ectx.module.types[base].inner { + ir::TypeInner::Scalar(scalar) => scalar, _ => return Err(Box::new(Error::BadIncrDecrReferenceType(value_span))), }, _ => return Err(Box::new(Error::BadIncrDecrReferenceType(value_span))), }; let literal = match scalar.kind { - crate::ScalarKind::Sint | crate::ScalarKind::Uint => { - crate::Literal::one(scalar) - .ok_or(Error::BadIncrDecrReferenceType(value_span))? - } + ir::ScalarKind::Sint | ir::ScalarKind::Uint => ir::Literal::one(scalar) + .ok_or(Error::BadIncrDecrReferenceType(value_span))?, _ => return Err(Box::new(Error::BadIncrDecrReferenceType(value_span))), }; let right = - ectx.interrupt_emitter(crate::Expression::Literal(literal), Span::UNDEFINED)?; + ectx.interrupt_emitter(ir::Expression::Literal(literal), Span::UNDEFINED)?; let rctx = ectx.runtime_expression_ctx(stmt.span)?; let left = rctx.function.expressions.append( - crate::Expression::Load { + ir::Expression::Load { pointer: target_handle, }, value_span, @@ -1926,20 +2011,20 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let value = rctx .function .expressions - .append(crate::Expression::Binary { op, left, right }, stmt.span); + .append(ir::Expression::Binary { op, left, right }, stmt.span); rctx.local_expression_kind_tracker - .insert(left, crate::proc::ExpressionKind::Runtime); + .insert(left, proc::ExpressionKind::Runtime); rctx.local_expression_kind_tracker - .insert(value, crate::proc::ExpressionKind::Runtime); + .insert(value, proc::ExpressionKind::Runtime); block.extend(emitter.finish(&ctx.function.expressions)); - crate::Statement::Store { + ir::Statement::Store { pointer: target_handle, value, } } ast::StatementKind::ConstAssert(condition) => { - let mut emitter = Emitter::default(); + let mut emitter = proc::Emitter::default(); emitter.start(&ctx.function.expressions); let condition = @@ -1961,7 +2046,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { return Ok(()); } ast::StatementKind::Phony(expr) => { - let mut emitter = Emitter::default(); + // Remembered the RHS of the phony assignment as a named expression. This + // is important (1) to preserve the RHS for validation, (2) to track any + // referenced globals. + let mut emitter = proc::Emitter::default(); emitter.start(&ctx.function.expressions); let value = self.expression(expr, &mut ctx.as_expression(block, &mut emitter))?; @@ -1988,7 +2076,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { &mut self, expr: Handle>, ctx: &mut ExpressionContext<'source, '_, '_>, - ) -> Result<'source, Handle> { + ) -> Result<'source, Handle> { let expr = self.expression_for_abstract(expr, ctx)?; ctx.concretize(expr) } @@ -1997,36 +2085,44 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { &mut self, expr: Handle>, ctx: &mut ExpressionContext<'source, '_, '_>, - ) -> Result<'source, Handle> { + ) -> Result<'source, Handle> { let expr = self.expression_for_reference(expr, ctx)?; ctx.apply_load_rule(expr) } + fn expression_with_leaf_scalar( + &mut self, + expr: Handle>, + scalar: ir::Scalar, + ctx: &mut ExpressionContext<'source, '_, '_>, + ) -> Result<'source, Handle> { + let unconverted = self.expression_for_abstract(expr, ctx)?; + ctx.try_automatic_conversion_for_leaf_scalar(unconverted, scalar, Span::default()) + } + fn expression_for_reference( &mut self, expr: Handle>, ctx: &mut ExpressionContext<'source, '_, '_>, - ) -> Result<'source, Typed>> { + ) -> Result<'source, Typed>> { let span = ctx.ast_expressions.get_span(expr); let expr = &ctx.ast_expressions[expr]; - let expr: Typed = match *expr { + let expr: Typed = match *expr { ast::Expression::Literal(literal) => { let literal = match literal { - ast::Literal::Number(Number::F16(f)) => crate::Literal::F16(f), - ast::Literal::Number(Number::F32(f)) => crate::Literal::F32(f), - ast::Literal::Number(Number::I32(i)) => crate::Literal::I32(i), - ast::Literal::Number(Number::U32(u)) => crate::Literal::U32(u), - ast::Literal::Number(Number::I64(i)) => crate::Literal::I64(i), - ast::Literal::Number(Number::U64(u)) => crate::Literal::U64(u), - ast::Literal::Number(Number::F64(f)) => crate::Literal::F64(f), - ast::Literal::Number(Number::AbstractInt(i)) => crate::Literal::AbstractInt(i), - ast::Literal::Number(Number::AbstractFloat(f)) => { - crate::Literal::AbstractFloat(f) - } - ast::Literal::Bool(b) => crate::Literal::Bool(b), + ast::Literal::Number(Number::F16(f)) => ir::Literal::F16(f), + ast::Literal::Number(Number::F32(f)) => ir::Literal::F32(f), + ast::Literal::Number(Number::I32(i)) => ir::Literal::I32(i), + ast::Literal::Number(Number::U32(u)) => ir::Literal::U32(u), + ast::Literal::Number(Number::I64(i)) => ir::Literal::I64(i), + ast::Literal::Number(Number::U64(u)) => ir::Literal::U64(u), + ast::Literal::Number(Number::F64(f)) => ir::Literal::F64(f), + ast::Literal::Number(Number::AbstractInt(i)) => ir::Literal::AbstractInt(i), + ast::Literal::Number(Number::AbstractFloat(f)) => ir::Literal::AbstractFloat(f), + ast::Literal::Bool(b) => ir::Literal::Bool(b), }; - let handle = ctx.interrupt_emitter(crate::Expression::Literal(literal), span)?; + let handle = ctx.interrupt_emitter(ir::Expression::Literal(literal), span)?; return Ok(Typed::Plain(handle)); } ast::Expression::Ident(ast::IdentExpr::Local(local)) => { @@ -2039,21 +2135,21 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .ok_or(Error::UnknownIdent(span, name))?; let expr = match *global { LoweredGlobalDecl::Var(handle) => { - let expr = crate::Expression::GlobalVariable(handle); + let expr = ir::Expression::GlobalVariable(handle); match ctx.module.global_variables[handle].space { - crate::AddressSpace::Handle => Typed::Plain(expr), + ir::AddressSpace::Handle => Typed::Plain(expr), _ => Typed::Reference(expr), } } LoweredGlobalDecl::Const(handle) => { - Typed::Plain(crate::Expression::Constant(handle)) + Typed::Plain(ir::Expression::Constant(handle)) } LoweredGlobalDecl::Override(handle) => { - Typed::Plain(crate::Expression::Override(handle)) + Typed::Plain(ir::Expression::Override(handle)) } LoweredGlobalDecl::Function { .. } | LoweredGlobalDecl::Type(_) - | LoweredGlobalDecl::EntryPoint => { + | LoweredGlobalDecl::EntryPoint(_) => { return Err(Box::new(Error::Unexpected(span, ExpectedToken::Variable))); } }; @@ -2070,7 +2166,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } ast::Expression::Unary { op, expr } => { let expr = self.expression_for_abstract(expr, ctx)?; - Typed::Plain(crate::Expression::Unary { op, expr }) + Typed::Plain(ir::Expression::Unary { op, expr }) } ast::Expression::AddrOf(expr) => { // The `&` operator simply converts a reference to a pointer. And since a @@ -2078,13 +2174,13 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { match self.expression_for_reference(expr, ctx)? { Typed::Reference(handle) => { let expr = &ctx.runtime_expression_ctx(span)?.function.expressions[handle]; - if let &crate::Expression::Access { base, .. } - | &crate::Expression::AccessIndex { base, .. } = expr + if let &ir::Expression::Access { base, .. } + | &ir::Expression::AccessIndex { base, .. } = expr { if let Some(ty) = resolve_inner!(ctx, base).pointer_base_type() { if matches!( *ty.inner_with(&ctx.module.types), - crate::TypeInner::Vector { .. }, + ir::TypeInner::Vector { .. }, ) { return Err(Box::new(Error::InvalidAddrOfOperand( ctx.get_expression_span(handle), @@ -2139,9 +2235,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } lowered_base.try_map(|base| match ctx.const_eval_expr_to_u32(index).ok() { - Some(index) => { - Ok::<_, Box>(crate::Expression::AccessIndex { base, index }) - } + Some(index) => Ok::<_, Box>(ir::Expression::AccessIndex { base, index }), None => { // When an abstract array value e is indexed by an expression // that is not a const-expression, then the array is concretized @@ -2149,7 +2243,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { // https://www.w3.org/TR/WGSL/#array-access-expr // Also applies to vectors and matrices. let base = ctx.concretize(base)?; - Ok(crate::Expression::Access { base, index }) + Ok(ir::Expression::Access { base, index }) } })? } @@ -2165,7 +2259,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } let temp_ty; - let composite_type: &crate::TypeInner = match lowered_base { + let composite_type: &ir::TypeInner = match lowered_base { Typed::Reference(handle) => { temp_ty = resolve_inner!(ctx, handle) .pointer_base_type() @@ -2179,26 +2273,27 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }; let access = match *composite_type { - crate::TypeInner::Struct { ref members, .. } => { + ir::TypeInner::Struct { ref members, .. } => { let index = members .iter() .position(|m| m.name.as_deref() == Some(field.name)) .ok_or(Error::BadAccessor(field.span))? as u32; - lowered_base.map(|base| crate::Expression::AccessIndex { base, index }) + lowered_base.map(|base| ir::Expression::AccessIndex { base, index }) } - crate::TypeInner::Vector { .. } => { + ir::TypeInner::Vector { .. } => { match Components::new(field.name, field.span)? { Components::Swizzle { size, pattern } => { - Typed::Plain(crate::Expression::Swizzle { + Typed::Plain(ir::Expression::Swizzle { size, vector: ctx.apply_load_rule(lowered_base)?, pattern, }) } - Components::Single(index) => lowered_base - .map(|base| crate::Expression::AccessIndex { base, index }), + Components::Single(index) => { + lowered_base.map(|base| ir::Expression::AccessIndex { base, index }) + } } } _ => return Err(Box::new(Error::BadAccessor(field.span))), @@ -2211,8 +2306,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let to_resolved = self.resolve_ast_type(to, &mut ctx.as_const())?; let element_scalar = match ctx.module.types[to_resolved].inner { - crate::TypeInner::Scalar(scalar) => scalar, - crate::TypeInner::Vector { scalar, .. } => scalar, + ir::TypeInner::Scalar(scalar) => scalar, + ir::TypeInner::Vector { scalar, .. } => scalar, _ => { let ty = resolve!(ctx, expr); return Err(Box::new(Error::BadTypeCast { @@ -2223,7 +2318,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } }; - Typed::Plain(crate::Expression::As { + Typed::Plain(ir::Expression::As { expr, kind: element_scalar.kind, convert: None, @@ -2236,12 +2331,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { fn binary( &mut self, - op: crate::BinaryOperator, + op: ir::BinaryOperator, left: Handle>, right: Handle>, span: Span, ctx: &mut ExpressionContext<'source, '_, '_>, - ) -> Result<'source, Typed> { + ) -> Result<'source, Typed> { // Load both operands. let mut left = self.expression_for_abstract(left, ctx)?; let mut right = self.expression_for_abstract(right, ctx)?; @@ -2252,13 +2347,13 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { // Apply automatic conversions. match op { - crate::BinaryOperator::ShiftLeft | crate::BinaryOperator::ShiftRight => { + ir::BinaryOperator::ShiftLeft | ir::BinaryOperator::ShiftRight => { // Shift operators require the right operand to be `u32` or // `vecN`. We can let the validator sort out vector length // issues, but the right operand must be, or convert to, a u32 leaf // scalar. right = - ctx.try_automatic_conversion_for_leaf_scalar(right, crate::Scalar::U32, span)?; + ctx.try_automatic_conversion_for_leaf_scalar(right, ir::Scalar::U32, span)?; // Additionally, we must concretize the left operand if the right operand // is not a const-expression. @@ -2271,16 +2366,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { // We only have to explicitly do so for shifts as their operands may be // of different types - for other binary ops this is achieved by finding // the conversion consensus for both operands. - let expr_kind_tracker = match ctx.expr_type { - ExpressionContextType::Runtime(ref ctx) - | ExpressionContextType::Constant(Some(ref ctx)) => { - &ctx.local_expression_kind_tracker - } - ExpressionContextType::Constant(None) | ExpressionContextType::Override => { - &ctx.global_expression_kind_tracker - } - }; - if !expr_kind_tracker.is_const(right) { + if !ctx.is_const(right) { left = ctx.concretize(left)?; } } @@ -2301,7 +2387,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } } - Ok(Typed::Plain(crate::Expression::Binary { op, left, right })) + Ok(Typed::Plain(ir::Expression::Binary { op, left, right })) } /// Generate Naga IR for call expressions and statements, and type @@ -2321,7 +2407,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { /// `Call` statement to the current block, and then resume generating /// expressions. /// - /// [`Call`]: crate::Statement::Call + /// [`Call`]: ir::Statement::Call fn call( &mut self, span: Span, @@ -2329,7 +2415,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { arguments: &[Handle>], ctx: &mut ExpressionContext<'source, '_, '_>, is_statement: bool, - ) -> Result<'source, Option>> { + ) -> Result<'source, Option>> { let function_span = function.span; match ctx.globals.get(function.name) { Some(&LoweredGlobalDecl::Type(ty)) => { @@ -2350,7 +2436,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { function_span, ExpectedToken::Function, ))), - Some(&LoweredGlobalDecl::EntryPoint) => { + Some(&LoweredGlobalDecl::EntryPoint(_)) => { Err(Box::new(Error::CalledEntryPoint(function_span))) } Some(&LoweredGlobalDecl::Function { @@ -2362,7 +2448,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .enumerate() .map(|(i, &arg)| { // Try to convert abstract values to the known argument types - let Some(&crate::FunctionArgument { + let Some(&ir::FunctionArgument { ty: parameter_ty, .. }) = ctx.module.functions[function].arguments.get(i) else { @@ -2374,7 +2460,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let expr = self.expression_for_abstract(arg, ctx)?; ctx.try_automatic_conversions( expr, - &crate::proc::TypeResolution::Handle(parameter_ty), + &proc::TypeResolution::Handle(parameter_ty), ctx.ast_expressions.get_span(arg), ) }) @@ -2394,14 +2480,14 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let result = rctx .function .expressions - .append(crate::Expression::CallResult(function), span); + .append(ir::Expression::CallResult(function), span); rctx.local_expression_kind_tracker - .insert(result, crate::proc::ExpressionKind::Runtime); + .insert(result, proc::ExpressionKind::Runtime); result }); rctx.emitter.start(&rctx.function.expressions); rctx.block.push( - crate::Statement::Call { + ir::Statement::Call { function, arguments, result, @@ -2421,12 +2507,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { // Check for no-op all(bool) and any(bool): let argument_unmodified = matches!( fun, - crate::RelationalFunction::All | crate::RelationalFunction::Any + ir::RelationalFunction::All | ir::RelationalFunction::Any ) && { matches!( resolve_inner!(ctx, argument), - &crate::TypeInner::Scalar(crate::Scalar { - kind: crate::ScalarKind::Bool, + &ir::TypeInner::Scalar(ir::Scalar { + kind: ir::ScalarKind::Bool, .. }) ) @@ -2435,62 +2521,16 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { if argument_unmodified { return Ok(Some(argument)); } else { - crate::Expression::Relational { fun, argument } + ir::Expression::Relational { fun, argument } } } else if let Some((axis, ctrl)) = conv::map_derivative(function.name) { let mut args = ctx.prepare_args(arguments, 1, span); let expr = self.expression(args.next()?, ctx)?; args.finish()?; - crate::Expression::Derivative { axis, ctrl, expr } + ir::Expression::Derivative { axis, ctrl, expr } } else if let Some(fun) = conv::map_standard_fun(function.name) { - let expected = fun.argument_count() as _; - let mut args = ctx.prepare_args(arguments, expected, span); - - let arg = self.expression(args.next()?, ctx)?; - let arg1 = args - .next() - .map(|x| self.expression(x, ctx)) - .ok() - .transpose()?; - let arg2 = args - .next() - .map(|x| self.expression(x, ctx)) - .ok() - .transpose()?; - let arg3 = args - .next() - .map(|x| self.expression(x, ctx)) - .ok() - .transpose()?; - - args.finish()?; - - if fun == crate::MathFunction::Modf || fun == crate::MathFunction::Frexp { - if let Some((size, scalar)) = match *resolve_inner!(ctx, arg) { - crate::TypeInner::Scalar(scalar) => Some((None, scalar)), - crate::TypeInner::Vector { size, scalar, .. } => { - Some((Some(size), scalar)) - } - _ => None, - } { - ctx.module.generate_predeclared_type( - if fun == crate::MathFunction::Modf { - crate::PredeclaredType::ModfResult { size, scalar } - } else { - crate::PredeclaredType::FrexpResult { size, scalar } - }, - ); - } - } - - crate::Expression::Math { - fun, - arg, - arg1, - arg2, - arg3, - } + self.math_function_helper(span, fun, arguments, ctx)? } else if let Some(fun) = Texture::map(function.name) { self.texture_sample_helper(fun, arguments, span, ctx)? } else if let Some((op, cop)) = conv::map_subgroup_operation(function.name) { @@ -2501,20 +2541,76 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { return Ok(Some( self.subgroup_gather_helper(span, mode, arguments, ctx)?, )); - } else if let Some(fun) = crate::AtomicFunction::map(function.name) { + } else if let Some(fun) = ir::AtomicFunction::map(function.name) { return self.atomic_helper(span, fun, arguments, is_statement, ctx); } else { match function.name { "select" => { let mut args = ctx.prepare_args(arguments, 3, span); - let reject = self.expression(args.next()?, ctx)?; - let accept = self.expression(args.next()?, ctx)?; + let reject_orig = args.next()?; + let accept_orig = args.next()?; + let mut values = [ + self.expression_for_abstract(reject_orig, ctx)?, + self.expression_for_abstract(accept_orig, ctx)?, + ]; let condition = self.expression(args.next()?, ctx)?; args.finish()?; - crate::Expression::Select { + let diagnostic_details = + |ctx: &ExpressionContext<'_, '_, '_>, + ty_res: &proc::TypeResolution, + orig_expr| { + ( + ctx.ast_expressions.get_span(orig_expr), + format!("`{}`", ctx.as_diagnostic_display(ty_res)), + ) + }; + for (&value, orig_value) in + values.iter().zip([reject_orig, accept_orig]) + { + let value_ty_res = resolve!(ctx, value); + if value_ty_res + .inner_with(&ctx.module.types) + .vector_size_and_scalar() + .is_none() + { + let (arg_span, arg_type) = + diagnostic_details(ctx, value_ty_res, orig_value); + return Err(Box::new(Error::SelectUnexpectedArgumentType { + arg_span, + arg_type, + })); + } + } + let mut consensus_scalar = ctx + .automatic_conversion_consensus(&values) + .map_err(|_idx| { + let [reject, accept] = values; + let [(reject_span, reject_type), (accept_span, accept_type)] = + [(reject_orig, reject), (accept_orig, accept)].map( + |(orig_expr, expr)| { + let ty_res = &ctx.typifier()[expr]; + diagnostic_details(ctx, ty_res, orig_expr) + }, + ); + Error::SelectRejectAndAcceptHaveNoCommonType { + reject_span, + reject_type, + accept_span, + accept_type, + } + })?; + if !ctx.is_const(condition) { + consensus_scalar = consensus_scalar.concretize(); + } + + ctx.convert_slice_to_common_leaf_scalar(&mut values, consensus_scalar)?; + + let [reject, accept] = values; + + ir::Expression::Select { reject, accept, condition, @@ -2525,19 +2621,20 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let expr = self.expression(args.next()?, ctx)?; args.finish()?; - crate::Expression::ArrayLength(expr) + ir::Expression::ArrayLength(expr) } "atomicLoad" => { let mut args = ctx.prepare_args(arguments, 1, span); - let pointer = self.atomic_pointer(args.next()?, ctx)?; + let (pointer, _scalar) = self.atomic_pointer(args.next()?, ctx)?; args.finish()?; - crate::Expression::Load { pointer } + ir::Expression::Load { pointer } } "atomicStore" => { let mut args = ctx.prepare_args(arguments, 2, span); - let pointer = self.atomic_pointer(args.next()?, ctx)?; - let value = self.expression(args.next()?, ctx)?; + let (pointer, scalar) = self.atomic_pointer(args.next()?, ctx)?; + let value = + self.expression_with_leaf_scalar(args.next()?, scalar, ctx)?; args.finish()?; let rctx = ctx.runtime_expression_ctx(span)?; @@ -2545,33 +2642,32 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .extend(rctx.emitter.finish(&rctx.function.expressions)); rctx.emitter.start(&rctx.function.expressions); rctx.block - .push(crate::Statement::Store { pointer, value }, span); + .push(ir::Statement::Store { pointer, value }, span); return Ok(None); } "atomicCompareExchangeWeak" => { let mut args = ctx.prepare_args(arguments, 3, span); - let pointer = self.atomic_pointer(args.next()?, ctx)?; + let (pointer, scalar) = self.atomic_pointer(args.next()?, ctx)?; - let compare = self.expression(args.next()?, ctx)?; + let compare = + self.expression_with_leaf_scalar(args.next()?, scalar, ctx)?; let value = args.next()?; let value_span = ctx.ast_expressions.get_span(value); - let value = self.expression(value, ctx)?; + let value = self.expression_with_leaf_scalar(value, scalar, ctx)?; args.finish()?; let expression = match *resolve_inner!(ctx, value) { - crate::TypeInner::Scalar(scalar) => { - crate::Expression::AtomicResult { - ty: ctx.module.generate_predeclared_type( - crate::PredeclaredType::AtomicCompareExchangeWeakResult( - scalar, - ), + ir::TypeInner::Scalar(scalar) => ir::Expression::AtomicResult { + ty: ctx.module.generate_predeclared_type( + ir::PredeclaredType::AtomicCompareExchangeWeakResult( + scalar, ), - comparison: true, - } - } + ), + comparison: true, + }, _ => { return Err(Box::new(Error::InvalidAtomicOperandType( value_span, @@ -2582,9 +2678,9 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let result = ctx.interrupt_emitter(expression, span)?; let rctx = ctx.runtime_expression_ctx(span)?; rctx.block.push( - crate::Statement::Atomic { + ir::Statement::Atomic { pointer, - fun: crate::AtomicFunction::Exchange { + fun: ir::AtomicFunction::Exchange { compare: Some(compare), }, value, @@ -2620,17 +2716,17 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { rctx.block .extend(rctx.emitter.finish(&rctx.function.expressions)); rctx.emitter.start(&rctx.function.expressions); - let stmt = crate::Statement::ImageAtomic { + let stmt = ir::Statement::ImageAtomic { image, coordinate, array_index, fun: match function.name { - "textureAtomicMin" => crate::AtomicFunction::Min, - "textureAtomicMax" => crate::AtomicFunction::Max, - "textureAtomicAdd" => crate::AtomicFunction::Add, - "textureAtomicAnd" => crate::AtomicFunction::And, - "textureAtomicOr" => crate::AtomicFunction::InclusiveOr, - "textureAtomicXor" => crate::AtomicFunction::ExclusiveOr, + "textureAtomicMin" => ir::AtomicFunction::Min, + "textureAtomicMax" => ir::AtomicFunction::Max, + "textureAtomicAdd" => ir::AtomicFunction::Add, + "textureAtomicAnd" => ir::AtomicFunction::And, + "textureAtomicOr" => ir::AtomicFunction::InclusiveOr, + "textureAtomicXor" => ir::AtomicFunction::ExclusiveOr, _ => unreachable!(), }, value, @@ -2643,7 +2739,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let rctx = ctx.runtime_expression_ctx(span)?; rctx.block - .push(crate::Statement::Barrier(crate::Barrier::STORAGE), span); + .push(ir::Statement::ControlBarrier(ir::Barrier::STORAGE), span); return Ok(None); } "workgroupBarrier" => { @@ -2651,7 +2747,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let rctx = ctx.runtime_expression_ctx(span)?; rctx.block - .push(crate::Statement::Barrier(crate::Barrier::WORK_GROUP), span); + .push(ir::Statement::ControlBarrier(ir::Barrier::WORK_GROUP), span); return Ok(None); } "subgroupBarrier" => { @@ -2659,7 +2755,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let rctx = ctx.runtime_expression_ctx(span)?; rctx.block - .push(crate::Statement::Barrier(crate::Barrier::SUB_GROUP), span); + .push(ir::Statement::ControlBarrier(ir::Barrier::SUB_GROUP), span); return Ok(None); } "textureBarrier" => { @@ -2667,7 +2763,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let rctx = ctx.runtime_expression_ctx(span)?; rctx.block - .push(crate::Statement::Barrier(crate::Barrier::TEXTURE), span); + .push(ir::Statement::ControlBarrier(ir::Barrier::TEXTURE), span); return Ok(None); } "workgroupUniformLoad" => { @@ -2677,9 +2773,9 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let pointer = self.expression(expr, ctx)?; let result_ty = match *resolve_inner!(ctx, pointer) { - crate::TypeInner::Pointer { + ir::TypeInner::Pointer { base, - space: crate::AddressSpace::WorkGroup, + space: ir::AddressSpace::WorkGroup, } => base, ref other => { log::error!("Type {other:?} passed to workgroupUniformLoad"); @@ -2688,12 +2784,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } }; let result = ctx.interrupt_emitter( - crate::Expression::WorkGroupUniformLoadResult { ty: result_ty }, + ir::Expression::WorkGroupUniformLoadResult { ty: result_ty }, span, )?; let rctx = ctx.runtime_expression_ctx(span)?; rctx.block.push( - crate::Statement::WorkGroupUniformLoad { pointer, result }, + ir::Statement::WorkGroupUniformLoad { pointer, result }, span, ); @@ -2708,15 +2804,21 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let coordinate = self.expression(args.next()?, ctx)?; - let (_, arrayed) = ctx.image_data(image, image_span)?; + let (class, arrayed) = ctx.image_data(image, image_span)?; let array_index = arrayed .then(|| { args.min_args += 1; self.expression(args.next()?, ctx) }) .transpose()?; + let scalar = if let ir::ImageClass::Storage { format, .. } = class { + format.into() + } else { + return Err(Box::new(Error::NotStorageTexture(image_span))); + }; - let value = self.expression(args.next()?, ctx)?; + let value = + self.expression_with_leaf_scalar(args.next()?, scalar, ctx)?; args.finish()?; @@ -2724,7 +2826,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { rctx.block .extend(rctx.emitter.finish(&rctx.function.expressions)); rctx.emitter.start(&rctx.function.expressions); - let stmt = crate::Statement::ImageStore { + let stmt = ir::Statement::ImageStore { image, coordinate, array_index, @@ -2765,7 +2867,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { args.finish()?; - crate::Expression::ImageLoad { + ir::Expression::ImageLoad { image, coordinate, array_index, @@ -2783,9 +2885,9 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .transpose()?; args.finish()?; - crate::Expression::ImageQuery { + ir::Expression::ImageQuery { image, - query: crate::ImageQuery::Size { level }, + query: ir::ImageQuery::Size { level }, } } "textureNumLevels" => { @@ -2793,9 +2895,9 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let image = self.expression(args.next()?, ctx)?; args.finish()?; - crate::Expression::ImageQuery { + ir::Expression::ImageQuery { image, - query: crate::ImageQuery::NumLevels, + query: ir::ImageQuery::NumLevels, } } "textureNumLayers" => { @@ -2803,9 +2905,9 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let image = self.expression(args.next()?, ctx)?; args.finish()?; - crate::Expression::ImageQuery { + ir::Expression::ImageQuery { image, - query: crate::ImageQuery::NumLayers, + query: ir::ImageQuery::NumLayers, } } "textureNumSamples" => { @@ -2813,9 +2915,9 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let image = self.expression(args.next()?, ctx)?; args.finish()?; - crate::Expression::ImageQuery { + ir::Expression::ImageQuery { image, - query: crate::ImageQuery::NumSamples, + query: ir::ImageQuery::NumSamples, } } "rayQueryInitialize" => { @@ -2826,7 +2928,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { args.finish()?; let _ = ctx.module.generate_ray_desc_type(); - let fun = crate::RayQueryFunction::Initialize { + let fun = ir::RayQueryFunction::Initialize { acceleration_structure, descriptor, }; @@ -2836,7 +2938,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .extend(rctx.emitter.finish(&rctx.function.expressions)); rctx.emitter.start(&rctx.function.expressions); rctx.block - .push(crate::Statement::RayQuery { query, fun }, span); + .push(ir::Statement::RayQuery { query, fun }, span); return Ok(None); } "getCommittedHitVertexPositions" => { @@ -2846,7 +2948,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let _ = ctx.module.generate_vertex_return_type(); - crate::Expression::RayQueryVertexPositions { + ir::Expression::RayQueryVertexPositions { query, committed: true, } @@ -2858,7 +2960,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let _ = ctx.module.generate_vertex_return_type(); - crate::Expression::RayQueryVertexPositions { + ir::Expression::RayQueryVertexPositions { query, committed: false, } @@ -2868,14 +2970,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let query = self.ray_query_pointer(args.next()?, ctx)?; args.finish()?; - let result = ctx.interrupt_emitter( - crate::Expression::RayQueryProceedResult, - span, - )?; - let fun = crate::RayQueryFunction::Proceed { result }; + let result = + ctx.interrupt_emitter(ir::Expression::RayQueryProceedResult, span)?; + let fun = ir::RayQueryFunction::Proceed { result }; let rctx = ctx.runtime_expression_ctx(span)?; rctx.block - .push(crate::Statement::RayQuery { query, fun }, span); + .push(ir::Statement::RayQuery { query, fun }, span); return Ok(Some(result)); } "rayQueryGenerateIntersection" => { @@ -2884,10 +2984,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let hit_t = self.expression(args.next()?, ctx)?; args.finish()?; - let fun = crate::RayQueryFunction::GenerateIntersection { hit_t }; + let fun = ir::RayQueryFunction::GenerateIntersection { hit_t }; let rctx = ctx.runtime_expression_ctx(span)?; rctx.block - .push(crate::Statement::RayQuery { query, fun }, span); + .push(ir::Statement::RayQuery { query, fun }, span); return Ok(None); } "rayQueryConfirmIntersection" => { @@ -2895,10 +2995,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let query = self.ray_query_pointer(args.next()?, ctx)?; args.finish()?; - let fun = crate::RayQueryFunction::ConfirmIntersection; + let fun = ir::RayQueryFunction::ConfirmIntersection; let rctx = ctx.runtime_expression_ctx(span)?; rctx.block - .push(crate::Statement::RayQuery { query, fun }, span); + .push(ir::Statement::RayQuery { query, fun }, span); return Ok(None); } "rayQueryTerminate" => { @@ -2906,10 +3006,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let query = self.ray_query_pointer(args.next()?, ctx)?; args.finish()?; - let fun = crate::RayQueryFunction::Terminate; + let fun = ir::RayQueryFunction::Terminate; let rctx = ctx.runtime_expression_ctx(span)?; rctx.block - .push(crate::Statement::RayQuery { query, fun }, span); + .push(ir::Statement::RayQuery { query, fun }, span); return Ok(None); } "rayQueryGetCommittedIntersection" => { @@ -2918,7 +3018,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { args.finish()?; let _ = ctx.module.generate_ray_intersection_type(); - crate::Expression::RayQueryGetIntersection { + ir::Expression::RayQueryGetIntersection { query, committed: true, } @@ -2929,7 +3029,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { args.finish()?; let _ = ctx.module.generate_ray_intersection_type(); - crate::Expression::RayQueryGetIntersection { + ir::Expression::RayQueryGetIntersection { query, committed: false, } @@ -2954,11 +3054,82 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }; args.finish()?; - let result = ctx - .interrupt_emitter(crate::Expression::SubgroupBallotResult, span)?; + let result = + ctx.interrupt_emitter(ir::Expression::SubgroupBallotResult, span)?; let rctx = ctx.runtime_expression_ctx(span)?; rctx.block - .push(crate::Statement::SubgroupBallot { result, predicate }, span); + .push(ir::Statement::SubgroupBallot { result, predicate }, span); + return Ok(Some(result)); + } + "quadSwapX" => { + let mut args = ctx.prepare_args(arguments, 1, span); + + let argument = self.expression(args.next()?, ctx)?; + args.finish()?; + + let ty = ctx.register_type(argument)?; + + let result = ctx.interrupt_emitter( + crate::Expression::SubgroupOperationResult { ty }, + span, + )?; + let rctx = ctx.runtime_expression_ctx(span)?; + rctx.block.push( + crate::Statement::SubgroupGather { + mode: crate::GatherMode::QuadSwap(crate::Direction::X), + argument, + result, + }, + span, + ); + return Ok(Some(result)); + } + + "quadSwapY" => { + let mut args = ctx.prepare_args(arguments, 1, span); + + let argument = self.expression(args.next()?, ctx)?; + args.finish()?; + + let ty = ctx.register_type(argument)?; + + let result = ctx.interrupt_emitter( + crate::Expression::SubgroupOperationResult { ty }, + span, + )?; + let rctx = ctx.runtime_expression_ctx(span)?; + rctx.block.push( + crate::Statement::SubgroupGather { + mode: crate::GatherMode::QuadSwap(crate::Direction::Y), + argument, + result, + }, + span, + ); + return Ok(Some(result)); + } + + "quadSwapDiagonal" => { + let mut args = ctx.prepare_args(arguments, 1, span); + + let argument = self.expression(args.next()?, ctx)?; + args.finish()?; + + let ty = ctx.register_type(argument)?; + + let result = ctx.interrupt_emitter( + crate::Expression::SubgroupOperationResult { ty }, + span, + )?; + let rctx = ctx.runtime_expression_ctx(span)?; + rctx.block.push( + crate::Statement::SubgroupGather { + mode: crate::GatherMode::QuadSwap(crate::Direction::Diagonal), + argument, + result, + }, + span, + ); return Ok(Some(result)); } _ => { @@ -2973,24 +3144,270 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } } + /// Generate a Naga IR [`Math`] expression. + /// + /// Generate Naga IR for a call to the [`MathFunction`] `fun`, whose + /// unlowered arguments are `ast_arguments`. + /// + /// The `span` argument should give the span of the function name in the + /// call expression. + /// + /// [`Math`]: ir::Expression::Math + /// [`MathFunction`]: ir::MathFunction + fn math_function_helper( + &mut self, + span: Span, + fun: ir::MathFunction, + ast_arguments: &[Handle>], + ctx: &mut ExpressionContext<'source, '_, '_>, + ) -> Result<'source, ir::Expression> { + let mut lowered_arguments = Vec::with_capacity(ast_arguments.len()); + for &arg in ast_arguments { + let lowered = self.expression_for_abstract(arg, ctx)?; + ctx.grow_types(lowered)?; + lowered_arguments.push(lowered); + } + + let fun_overloads = fun.overloads(); + let rule = self.resolve_overloads(span, fun, fun_overloads, &lowered_arguments, ctx)?; + self.apply_automatic_conversions_for_call(&rule, &mut lowered_arguments, ctx)?; + + // If this function returns a predeclared type, register it + // in `Module::special_types`. The typifier will expect to + // be able to find it there. + if let proc::Conclusion::Predeclared(predeclared) = rule.conclusion { + ctx.module.generate_predeclared_type(predeclared); + } + + Ok(ir::Expression::Math { + fun, + arg: lowered_arguments[0], + arg1: lowered_arguments.get(1).cloned(), + arg2: lowered_arguments.get(2).cloned(), + arg3: lowered_arguments.get(3).cloned(), + }) + } + + /// Choose the right overload for a function call. + /// + /// Return a [`Rule`] representing the most preferred overload in + /// `overloads` to apply to `arguments`, or return an error explaining why + /// the call is not valid. + /// + /// Use `fun` to identify the function being called in error messages; + /// `span` should be the span of the function name in the call expression. + /// + /// [`Rule`]: proc::Rule + fn resolve_overloads( + &self, + span: Span, + fun: F, + overloads: O, + arguments: &[Handle], + ctx: &ExpressionContext<'source, '_, '_>, + ) -> Result<'source, proc::Rule> + where + O: proc::OverloadSet, + F: TryToWgsl + core::fmt::Debug + Copy, + { + let mut remaining_overloads = overloads.clone(); + let min_arguments = remaining_overloads.min_arguments(); + let max_arguments = remaining_overloads.max_arguments(); + if arguments.len() < min_arguments { + return Err(Box::new(Error::WrongArgumentCount { + span, + expected: min_arguments as u32..max_arguments as u32, + found: arguments.len() as u32, + })); + } + if arguments.len() > max_arguments { + return Err(Box::new(Error::TooManyArguments { + function: fun.to_wgsl_for_diagnostics(), + call_span: span, + arg_span: ctx.get_expression_span(arguments[max_arguments]), + max_arguments: max_arguments as _, + })); + } + + log::debug!( + "Initial overloads: {:#?}", + remaining_overloads.for_debug(&ctx.module.types) + ); + + for (arg_index, &arg) in arguments.iter().enumerate() { + let arg_type_resolution = &ctx.typifier()[arg]; + let arg_inner = arg_type_resolution.inner_with(&ctx.module.types); + log::debug!( + "Supplying argument {arg_index} of type {:?}", + arg_type_resolution.for_debug(&ctx.module.types) + ); + let next_remaining_overloads = + remaining_overloads.arg(arg_index, arg_inner, &ctx.module.types); + + // If any argument is not a constant expression, then no overloads + // that accept abstract values should be considered. + // (`OverloadSet::concrete_only` is supposed to help impose this + // restriction.) However, no `MathFunction` accepts a mix of + // abstract and concrete arguments, so we don't need to worry + // about that here. + + log::debug!( + "Remaining overloads: {:#?}", + next_remaining_overloads.for_debug(&ctx.module.types) + ); + + // If the set of remaining overloads is empty, then this argument's type + // was unacceptable. Diagnose the problem and produce an error message. + if next_remaining_overloads.is_empty() { + let function = fun.to_wgsl_for_diagnostics(); + let call_span = span; + let arg_span = ctx.get_expression_span(arg); + let arg_ty = ctx.as_diagnostic_display(arg_type_resolution).to_string(); + + // Is this type *ever* permitted for the arg_index'th argument? + // For example, `bool` is never permitted for `max`. + let only_this_argument = overloads.arg(arg_index, arg_inner, &ctx.module.types); + if only_this_argument.is_empty() { + // No overload of `fun` accepts this type as the + // arg_index'th argument. Determine the set of types that + // would ever be allowed there. + let allowed: Vec = overloads + .allowed_args(arg_index, &ctx.module.to_ctx()) + .iter() + .map(|ty| ctx.type_resolution_to_string(ty)) + .collect(); + + if allowed.is_empty() { + // No overload of `fun` accepts any argument at this + // index, so it's a simple case of excess arguments. + // However, since each `MathFunction`'s overloads all + // have the same arity, we should have detected this + // earlier. + unreachable!("expected all overloads to have the same arity"); + } + + // Some overloads of `fun` do accept this many arguments, + // but none accept one of this type. + return Err(Box::new(Error::WrongArgumentType { + function, + call_span, + arg_span, + arg_index: arg_index as u32, + arg_ty, + allowed, + })); + } + + // This argument's type is accepted by some overloads---just + // not those overloads that remain, given the prior arguments. + // For example, `max` accepts `f32` as its second argument - + // but not if the first was `i32`. + + // Build a list of the types that would have been accepted here, + // given the prior arguments. + let allowed: Vec = remaining_overloads + .allowed_args(arg_index, &ctx.module.to_ctx()) + .iter() + .map(|ty| ctx.type_resolution_to_string(ty)) + .collect(); + + // Re-run the argument list to determine which prior argument + // made this one unacceptable. + let mut remaining_overloads = overloads; + for (prior_index, &prior_expr) in arguments.iter().enumerate() { + let prior_type_resolution = &ctx.typifier()[prior_expr]; + let prior_ty = prior_type_resolution.inner_with(&ctx.module.types); + remaining_overloads = + remaining_overloads.arg(prior_index, prior_ty, &ctx.module.types); + if remaining_overloads + .arg(arg_index, arg_inner, &ctx.module.types) + .is_empty() + { + // This is the argument that killed our dreams. + let inconsistent_span = ctx.get_expression_span(arguments[prior_index]); + let inconsistent_ty = + ctx.as_diagnostic_display(prior_type_resolution).to_string(); + + if allowed.is_empty() { + // Some overloads did accept `ty` at `arg_index`, but + // given the arguments up through `prior_expr`, we see + // no types acceptable at `arg_index`. This means that some + // overloads expect fewer arguments than others. However, + // each `MathFunction`'s overloads have the same arity, so this + // should be impossible. + unreachable!("expected all overloads to have the same arity"); + } + + // Report `arg`'s type as inconsistent with `prior_expr`'s + return Err(Box::new(Error::InconsistentArgumentType { + function, + call_span, + arg_span, + arg_index: arg_index as u32, + arg_ty, + inconsistent_span, + inconsistent_index: prior_index as u32, + inconsistent_ty, + allowed, + })); + } + } + unreachable!("Failed to eliminate argument type when re-tried"); + } + remaining_overloads = next_remaining_overloads; + } + + // Select the most preferred type rule for this call, + // given the argument types supplied above. + Ok(remaining_overloads.most_preferred()) + } + + /// Apply automatic type conversions for a function call. + /// + /// Apply whatever automatic conversions are needed to pass `arguments` to + /// the function overload described by `rule`. Update `arguments` to refer + /// to the converted arguments. + fn apply_automatic_conversions_for_call( + &self, + rule: &proc::Rule, + arguments: &mut [Handle], + ctx: &mut ExpressionContext<'source, '_, '_>, + ) -> Result<'source, ()> { + for (i, argument) in arguments.iter_mut().enumerate() { + let goal_inner = rule.arguments[i].inner_with(&ctx.module.types); + let converted = match goal_inner.scalar_for_conversions(&ctx.module.types) { + Some(goal_scalar) => { + let arg_span = ctx.get_expression_span(*argument); + ctx.try_automatic_conversion_for_leaf_scalar(*argument, goal_scalar, arg_span)? + } + // No conversion is necessary. + None => *argument, + }; + + *argument = converted; + } + + Ok(()) + } + fn atomic_pointer( &mut self, expr: Handle>, ctx: &mut ExpressionContext<'source, '_, '_>, - ) -> Result<'source, Handle> { + ) -> Result<'source, (Handle, ir::Scalar)> { let span = ctx.ast_expressions.get_span(expr); let pointer = self.expression(expr, ctx)?; match *resolve_inner!(ctx, pointer) { - crate::TypeInner::Pointer { base, .. } => match ctx.module.types[base].inner { - crate::TypeInner::Atomic { .. } => Ok(pointer), + ir::TypeInner::Pointer { base, .. } => match ctx.module.types[base].inner { + ir::TypeInner::Atomic(scalar) => Ok((pointer, scalar)), ref other => { - log::error!("Pointer type to {:?} passed to atomic op", other); + log::error!("Pointer type to {other:?} passed to atomic op"); Err(Box::new(Error::InvalidAtomicPointer(span))) } }, ref other => { - log::error!("Type {:?} passed to atomic op", other); + log::error!("Type {other:?} passed to atomic op"); Err(Box::new(Error::InvalidAtomicPointer(span))) } } @@ -2999,15 +3416,15 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { fn atomic_helper( &mut self, span: Span, - fun: crate::AtomicFunction, + fun: ir::AtomicFunction, args: &[Handle>], is_statement: bool, ctx: &mut ExpressionContext<'source, '_, '_>, - ) -> Result<'source, Option>> { + ) -> Result<'source, Option>> { let mut args = ctx.prepare_args(args, 2, span); - let pointer = self.atomic_pointer(args.next()?, ctx)?; - let value = self.expression(args.next()?, ctx)?; + let (pointer, scalar) = self.atomic_pointer(args.next()?, ctx)?; + let value = self.expression_with_leaf_scalar(args.next()?, scalar, ctx)?; let value_inner = resolve_inner!(ctx, value); args.finish()?; @@ -3015,12 +3432,11 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { // operation, generate a no-result form of the `Atomic` statement, so // that we can pass validation with only `SHADER_INT64_ATOMIC_MIN_MAX` // whenever possible. - let is_64_bit_min_max = - matches!(fun, crate::AtomicFunction::Min | crate::AtomicFunction::Max) - && matches!( - *value_inner, - crate::TypeInner::Scalar(crate::Scalar { width: 8, .. }) - ); + let is_64_bit_min_max = matches!(fun, ir::AtomicFunction::Min | ir::AtomicFunction::Max) + && matches!( + *value_inner, + ir::TypeInner::Scalar(ir::Scalar { width: 8, .. }) + ); let result = if is_64_bit_min_max && is_statement { let rctx = ctx.runtime_expression_ctx(span)?; rctx.block @@ -3030,7 +3446,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } else { let ty = ctx.register_type(value)?; Some(ctx.interrupt_emitter( - crate::Expression::AtomicResult { + ir::Expression::AtomicResult { ty, comparison: false, }, @@ -3039,7 +3455,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }; let rctx = ctx.runtime_expression_ctx(span)?; rctx.block.push( - crate::Statement::Atomic { + ir::Statement::Atomic { pointer, fun, value, @@ -3056,21 +3472,24 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { args: &[Handle>], span: Span, ctx: &mut ExpressionContext<'source, '_, '_>, - ) -> Result<'source, crate::Expression> { + ) -> Result<'source, ir::Expression> { let mut args = ctx.prepare_args(args, fun.min_argument_count(), span); fn get_image_and_span<'source>( lowerer: &mut Lowerer<'source, '_>, args: &mut ArgumentContext<'_, 'source>, ctx: &mut ExpressionContext<'source, '_, '_>, - ) -> Result<'source, (Handle, Span)> { + ) -> Result<'source, (Handle, Span)> { let image = args.next()?; let image_span = ctx.ast_expressions.get_span(image); - let image = lowerer.expression(image, ctx)?; + let image = lowerer.expression_for_abstract(image, ctx)?; Ok((image, image_span)) } - let (image, image_span, gather) = match fun { + let image; + let image_span; + let gather; + match fun { Texture::Gather => { let image_or_component = args.next()?; let image_or_component_span = ctx.ast_expressions.get_span(image_or_component); @@ -3078,88 +3497,123 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let lowered_image_or_component = self.expression(image_or_component, ctx)?; match *resolve_inner!(ctx, lowered_image_or_component) { - crate::TypeInner::Image { - class: crate::ImageClass::Depth { .. }, + ir::TypeInner::Image { + class: ir::ImageClass::Depth { .. }, .. - } => ( - lowered_image_or_component, - image_or_component_span, - Some(crate::SwizzleComponent::X), - ), + } => { + image = lowered_image_or_component; + image_span = image_or_component_span; + gather = Some(ir::SwizzleComponent::X); + } _ => { - let (image, image_span) = get_image_and_span(self, &mut args, ctx)?; - ( - image, - image_span, - Some(ctx.gather_component( - lowered_image_or_component, - image_or_component_span, - span, - )?), - ) + (image, image_span) = get_image_and_span(self, &mut args, ctx)?; + gather = Some(ctx.gather_component( + lowered_image_or_component, + image_or_component_span, + span, + )?); } } } Texture::GatherCompare => { - let (image, image_span) = get_image_and_span(self, &mut args, ctx)?; - (image, image_span, Some(crate::SwizzleComponent::X)) + (image, image_span) = get_image_and_span(self, &mut args, ctx)?; + gather = Some(ir::SwizzleComponent::X); } _ => { - let (image, image_span) = get_image_and_span(self, &mut args, ctx)?; - (image, image_span, None) + (image, image_span) = get_image_and_span(self, &mut args, ctx)?; + gather = None; } }; - let sampler = self.expression(args.next()?, ctx)?; + let sampler = self.expression_for_abstract(args.next()?, ctx)?; - let coordinate = self.expression(args.next()?, ctx)?; + let coordinate = self.expression_with_leaf_scalar(args.next()?, ir::Scalar::F32, ctx)?; + let clamp_to_edge = matches!(fun, Texture::SampleBaseClampToEdge); - let (_, arrayed) = ctx.image_data(image, image_span)?; + let (class, arrayed) = ctx.image_data(image, image_span)?; let array_index = arrayed .then(|| self.expression(args.next()?, ctx)) .transpose()?; - let (level, depth_ref) = match fun { - Texture::Gather => (crate::SampleLevel::Zero, None), + let level; + let depth_ref; + match fun { + Texture::Gather => { + level = ir::SampleLevel::Zero; + depth_ref = None; + } Texture::GatherCompare => { - let reference = self.expression(args.next()?, ctx)?; - (crate::SampleLevel::Zero, Some(reference)) + let reference = + self.expression_with_leaf_scalar(args.next()?, ir::Scalar::F32, ctx)?; + level = ir::SampleLevel::Zero; + depth_ref = Some(reference); } - Texture::Sample => (crate::SampleLevel::Auto, None), + Texture::Sample => { + level = ir::SampleLevel::Auto; + depth_ref = None; + } Texture::SampleBias => { - let bias = self.expression(args.next()?, ctx)?; - (crate::SampleLevel::Bias(bias), None) + let bias = self.expression_with_leaf_scalar(args.next()?, ir::Scalar::F32, ctx)?; + level = ir::SampleLevel::Bias(bias); + depth_ref = None; } Texture::SampleCompare => { - let reference = self.expression(args.next()?, ctx)?; - (crate::SampleLevel::Auto, Some(reference)) + let reference = + self.expression_with_leaf_scalar(args.next()?, ir::Scalar::F32, ctx)?; + level = ir::SampleLevel::Auto; + depth_ref = Some(reference); } Texture::SampleCompareLevel => { - let reference = self.expression(args.next()?, ctx)?; - (crate::SampleLevel::Zero, Some(reference)) + let reference = + self.expression_with_leaf_scalar(args.next()?, ir::Scalar::F32, ctx)?; + level = ir::SampleLevel::Zero; + depth_ref = Some(reference); } Texture::SampleGrad => { - let x = self.expression(args.next()?, ctx)?; - let y = self.expression(args.next()?, ctx)?; - (crate::SampleLevel::Gradient { x, y }, None) + let x = self.expression_with_leaf_scalar(args.next()?, ir::Scalar::F32, ctx)?; + let y = self.expression_with_leaf_scalar(args.next()?, ir::Scalar::F32, ctx)?; + level = ir::SampleLevel::Gradient { x, y }; + depth_ref = None; } Texture::SampleLevel => { - let level = self.expression(args.next()?, ctx)?; - (crate::SampleLevel::Exact(level), None) + let exact = match class { + // When applied to depth textures, `textureSampleLevel`'s + // `level` argument is an `i32` or `u32`. + ir::ImageClass::Depth { .. } => self.expression(args.next()?, ctx)?, + + // When applied to other sampled types, its `level` argument + // is an `f32`. + ir::ImageClass::Sampled { .. } => { + self.expression_with_leaf_scalar(args.next()?, ir::Scalar::F32, ctx)? + } + + // Sampling `External` textures with a specified level isn't + // allowed, and sampling `Storage` textures isn't allowed at + // all. Let the validator report the error. + ir::ImageClass::Storage { .. } | ir::ImageClass::External => { + self.expression(args.next()?, ctx)? + } + }; + level = ir::SampleLevel::Exact(exact); + depth_ref = None; + } + Texture::SampleBaseClampToEdge => { + level = crate::SampleLevel::Zero; + depth_ref = None; } }; let offset = args .next() - .map(|arg| self.expression(arg, &mut ctx.as_const())) + .map(|arg| self.expression_with_leaf_scalar(arg, ir::Scalar::I32, &mut ctx.as_const())) .ok() .transpose()?; args.finish()?; - Ok(crate::Expression::ImageSample { + Ok(ir::Expression::ImageSample { image, sampler, gather, @@ -3168,17 +3622,18 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { offset, level, depth_ref, + clamp_to_edge, }) } fn subgroup_operation_helper( &mut self, span: Span, - op: crate::SubgroupOperation, - collective_op: crate::CollectiveOperation, + op: ir::SubgroupOperation, + collective_op: ir::CollectiveOperation, arguments: &[Handle>], ctx: &mut ExpressionContext<'source, '_, '_>, - ) -> Result<'source, Handle> { + ) -> Result<'source, Handle> { let mut args = ctx.prepare_args(arguments, 1, span); let argument = self.expression(args.next()?, ctx)?; @@ -3186,11 +3641,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let ty = ctx.register_type(argument)?; - let result = - ctx.interrupt_emitter(crate::Expression::SubgroupOperationResult { ty }, span)?; + let result = ctx.interrupt_emitter(ir::Expression::SubgroupOperationResult { ty }, span)?; let rctx = ctx.runtime_expression_ctx(span)?; rctx.block.push( - crate::Statement::SubgroupCollectiveOperation { + ir::Statement::SubgroupCollectiveOperation { op, collective_op, argument, @@ -3207,23 +3661,24 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { mode: SubgroupGather, arguments: &[Handle>], ctx: &mut ExpressionContext<'source, '_, '_>, - ) -> Result<'source, Handle> { + ) -> Result<'source, Handle> { let mut args = ctx.prepare_args(arguments, 2, span); let argument = self.expression(args.next()?, ctx)?; use SubgroupGather as Sg; let mode = if let Sg::BroadcastFirst = mode { - crate::GatherMode::BroadcastFirst + ir::GatherMode::BroadcastFirst } else { let index = self.expression(args.next()?, ctx)?; match mode { - Sg::Broadcast => crate::GatherMode::Broadcast(index), - Sg::Shuffle => crate::GatherMode::Shuffle(index), - Sg::ShuffleDown => crate::GatherMode::ShuffleDown(index), - Sg::ShuffleUp => crate::GatherMode::ShuffleUp(index), - Sg::ShuffleXor => crate::GatherMode::ShuffleXor(index), Sg::BroadcastFirst => unreachable!(), + Sg::Broadcast => ir::GatherMode::Broadcast(index), + Sg::Shuffle => ir::GatherMode::Shuffle(index), + Sg::ShuffleDown => ir::GatherMode::ShuffleDown(index), + Sg::ShuffleUp => ir::GatherMode::ShuffleUp(index), + Sg::ShuffleXor => ir::GatherMode::ShuffleXor(index), + Sg::QuadBroadcast => ir::GatherMode::QuadBroadcast(index), } }; @@ -3231,11 +3686,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let ty = ctx.register_type(argument)?; - let result = - ctx.interrupt_emitter(crate::Expression::SubgroupOperationResult { ty }, span)?; + let result = ctx.interrupt_emitter(ir::Expression::SubgroupOperationResult { ty }, span)?; let rctx = ctx.runtime_expression_ctx(span)?; rctx.block.push( - crate::Statement::SubgroupGather { + ir::Statement::SubgroupGather { mode, argument, result, @@ -3250,15 +3704,37 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { s: &ast::Struct<'source>, span: Span, ctx: &mut GlobalContext<'source, '_, '_>, - ) -> Result<'source, Handle> { + ) -> Result<'source, Handle> { let mut offset = 0; - let mut struct_alignment = Alignment::ONE; + let mut struct_alignment = proc::Alignment::ONE; let mut members = Vec::with_capacity(s.members.len()); + let mut doc_comments: Vec>> = Vec::new(); + for member in s.members.iter() { let ty = self.resolve_ast_type(member.ty, &mut ctx.as_const())?; - ctx.layouter.update(ctx.module.to_ctx()).unwrap(); + ctx.layouter.update(ctx.module.to_ctx()).map_err(|err| { + let LayoutErrorInner::TooLarge = err.inner else { + unreachable!("unexpected layout error: {err:?}"); + }; + // Since anonymous types of struct members don't get a span, + // associate the error with the member. The layouter could have + // failed on any type that was pending layout, but if it wasn't + // the current struct member, it wasn't a struct member at all, + // because we resolve struct members one-by-one. + if ty == err.ty { + Box::new(Error::StructMemberTooLarge { + member_name_span: member.name.span, + }) + } else { + // Lots of type definitions don't get spans, so this error + // message may not be very useful. + Box::new(Error::TypeTooLarge { + span: ctx.module.types.get_span(err.ty), + }) + } + })?; let member_min_size = ctx.layouter[ty].size; let member_min_alignment = ctx.layouter[ty].alignment; @@ -3276,7 +3752,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let member_alignment = if let Some(align_expr) = member.align { let (align, span) = self.const_u32(align_expr, &mut ctx.as_const())?; - if let Some(alignment) = Alignment::new(align) { + if let Some(alignment) = proc::Alignment::new(align) { if alignment < member_min_alignment { return Err(Box::new(Error::AlignAttributeTooLow( span, @@ -3297,7 +3773,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { offset = member_alignment.round_up(offset); struct_alignment = struct_alignment.max(member_alignment); - members.push(crate::StructMember { + if !member.doc_comments.is_empty() { + doc_comments.push(Some( + member.doc_comments.iter().map(|s| s.to_string()).collect(), + )); + } + members.push(ir::StructMember { name: Some(member.name.name.to_owned()), ty, binding, @@ -3305,21 +3786,32 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }); offset += member_size; + if offset > crate::valid::MAX_TYPE_SIZE { + return Err(Box::new(Error::TypeTooLarge { span })); + } } let size = struct_alignment.round_up(offset); - let inner = crate::TypeInner::Struct { + let inner = ir::TypeInner::Struct { members, span: size, }; let handle = ctx.module.types.insert( - crate::Type { + ir::Type { name: Some(s.name.name.to_string()), inner, }, span, ); + for (i, c) in doc_comments.drain(..).enumerate() { + if let Some(comment) = c { + ctx.module + .get_or_insert_default_doc_comments() + .struct_members + .insert((handle, i), comment); + } + } Ok(handle) } @@ -3335,10 +3827,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { .to_ctx() .eval_expr_to_u32(expr) .map_err(|err| match err { - crate::proc::U32EvalError::NonConst => { - Error::ExpectedConstExprConcreteIntegerScalar(span) - } - crate::proc::U32EvalError::Negative => Error::ExpectedNonNegative(span), + proc::U32EvalError::NonConst => Error::ExpectedConstExprConcreteIntegerScalar(span), + proc::U32EvalError::Negative => Error::ExpectedNonNegative(span), })?; Ok((value, span)) } @@ -3347,7 +3837,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { &mut self, size: ast::ArraySize<'source>, ctx: &mut ExpressionContext<'source, '_, '_>, - ) -> Result<'source, crate::ArraySize> { + ) -> Result<'source, ir::ArraySize> { Ok(match size { ast::ArraySize::Constant(expr) => { let span = ctx.ast_expressions.get_span(expr); @@ -3356,23 +3846,23 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { Ok(value) => { let len = ctx.const_eval_expr_to_u32(value).map_err(|err| { Box::new(match err { - crate::proc::U32EvalError::NonConst => { + proc::U32EvalError::NonConst => { Error::ExpectedConstExprConcreteIntegerScalar(span) } - crate::proc::U32EvalError::Negative => { + proc::U32EvalError::Negative => { Error::ExpectedPositiveArrayLength(span) } }) })?; let size = NonZeroU32::new(len).ok_or(Error::ExpectedPositiveArrayLength(span))?; - crate::ArraySize::Constant(size) + ir::ArraySize::Constant(size) } Err(err) => { if let Error::ConstantEvaluatorError(ref ty, _) = *err { match **ty { - crate::proc::ConstantEvaluatorError::OverrideExpr => { - crate::ArraySize::Pending(self.array_size_override( + proc::ConstantEvaluatorError::OverrideExpr => { + ir::ArraySize::Pending(self.array_size_override( expr, &mut ctx.as_global().as_override(), span, @@ -3388,7 +3878,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } } } - ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, + ast::ArraySize::Dynamic => ir::ArraySize::Dynamic, }) } @@ -3397,16 +3887,16 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { size_expr: Handle>, ctx: &mut ExpressionContext<'source, '_, '_>, span: Span, - ) -> Result<'source, Handle> { + ) -> Result<'source, Handle> { let expr = self.expression(size_expr, ctx)?; match resolve_inner!(ctx, expr).scalar_kind().ok_or(0) { - Ok(crate::ScalarKind::Sint) | Ok(crate::ScalarKind::Uint) => Ok({ - if let crate::Expression::Override(handle) = ctx.module.global_expressions[expr] { + Ok(ir::ScalarKind::Sint) | Ok(ir::ScalarKind::Uint) => Ok({ + if let ir::Expression::Override(handle) = ctx.module.global_expressions[expr] { handle } else { let ty = ctx.register_type(expr)?; ctx.module.overrides.append( - crate::Override { + ir::Override { name: None, id: None, ty, @@ -3430,22 +3920,22 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { /// If `handle` refers to a type cached in [`SpecialTypes`], /// `name` may be ignored. /// - /// [`SpecialTypes`]: crate::SpecialTypes + /// [`SpecialTypes`]: ir::SpecialTypes fn resolve_named_ast_type( &mut self, handle: Handle>, name: Option, ctx: &mut ExpressionContext<'source, '_, '_>, - ) -> Result<'source, Handle> { + ) -> Result<'source, Handle> { let inner = match ctx.types[handle] { ast::Type::Scalar(scalar) => scalar.to_inner_scalar(), ast::Type::Vector { size, ty, ty_span } => { let ty = self.resolve_ast_type(ty, ctx)?; let scalar = match ctx.module.types[ty].inner { - crate::TypeInner::Scalar(sc) => sc, + ir::TypeInner::Scalar(sc) => sc, _ => return Err(Box::new(Error::UnknownScalarType(ty_span))), }; - crate::TypeInner::Vector { size, scalar } + ir::TypeInner::Vector { size, scalar } } ast::Type::Matrix { rows, @@ -3455,11 +3945,11 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { } => { let ty = self.resolve_ast_type(ty, ctx)?; let scalar = match ctx.module.types[ty].inner { - crate::TypeInner::Scalar(sc) => sc, + ir::TypeInner::Scalar(sc) => sc, _ => return Err(Box::new(Error::UnknownScalarType(ty_span))), }; match scalar.kind { - crate::ScalarKind::Float => crate::TypeInner::Matrix { + ir::ScalarKind::Float => ir::TypeInner::Matrix { columns, rows, scalar, @@ -3470,35 +3960,64 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { ast::Type::Atomic(scalar) => scalar.to_inner_atomic(), ast::Type::Pointer { base, space } => { let base = self.resolve_ast_type(base, ctx)?; - crate::TypeInner::Pointer { base, space } + ir::TypeInner::Pointer { base, space } } ast::Type::Array { base, size } => { let base = self.resolve_ast_type(base, &mut ctx.as_const())?; let size = self.array_size(size, ctx)?; - ctx.layouter.update(ctx.module.to_ctx()).unwrap(); + // Determine the size of the base type, if needed. + ctx.layouter.update(ctx.module.to_ctx()).map_err(|err| { + let LayoutErrorInner::TooLarge = err.inner else { + unreachable!("unexpected layout error: {err:?}"); + }; + // Lots of type definitions don't get spans, so this error + // message may not be very useful. + Box::new(Error::TypeTooLarge { + span: ctx.module.types.get_span(err.ty), + }) + })?; let stride = ctx.layouter[base].to_stride(); - crate::TypeInner::Array { base, size, stride } + ir::TypeInner::Array { base, size, stride } } ast::Type::Image { dim, arrayed, class, - } => crate::TypeInner::Image { - dim, - arrayed, - class, - }, - ast::Type::Sampler { comparison } => crate::TypeInner::Sampler { comparison }, - ast::Type::AccelerationStructure { vertex_return } => { - crate::TypeInner::AccelerationStructure { vertex_return } + } => { + if class == crate::ImageClass::External { + // Other than the WGSL backend, every backend that supports + // external textures does so by lowering them to a set of + // ordinary textures and some parameters saying how to + // sample from them. We don't know which backend will + // consume the `Module` we're building, but in case it's not + // WGSL, populate `SpecialTypes::external_texture_params` + // and `SpecialTypes::external_texture_transfer_function` + // with the types the backend will use for the parameter + // buffer. + // + // Neither of these are the type we are lowering here: + // that's an ordinary `TypeInner::Image`. But the fact we + // are lowering a `texture_external` implies the backends + // may need these additional types too. + ctx.module.generate_external_texture_types(); + } + ir::TypeInner::Image { + dim, + arrayed, + class, + } } - ast::Type::RayQuery { vertex_return } => crate::TypeInner::RayQuery { vertex_return }, + ast::Type::Sampler { comparison } => ir::TypeInner::Sampler { comparison }, + ast::Type::AccelerationStructure { vertex_return } => { + ir::TypeInner::AccelerationStructure { vertex_return } + } + ast::Type::RayQuery { vertex_return } => ir::TypeInner::RayQuery { vertex_return }, ast::Type::BindingArray { base, size } => { let base = self.resolve_ast_type(base, ctx)?; let size = self.array_size(size, ctx)?; - crate::TypeInner::BindingArray { base, size } + ir::TypeInner::BindingArray { base, size } } ast::Type::RayDesc => { return Ok(ctx.module.generate_ray_desc_type()); @@ -3523,18 +4042,18 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { &mut self, handle: Handle>, ctx: &mut ExpressionContext<'source, '_, '_>, - ) -> Result<'source, Handle> { + ) -> Result<'source, Handle> { self.resolve_named_ast_type(handle, None, ctx) } fn binding( &mut self, binding: &Option>, - ty: Handle, + ty: Handle, ctx: &mut GlobalContext<'source, '_, '_>, - ) -> Result<'source, Option> { + ) -> Result<'source, Option> { Ok(match *binding { - Some(ast::Binding::BuiltIn(b)) => Some(crate::Binding::BuiltIn(b)), + Some(ast::Binding::BuiltIn(b)) => Some(ir::Binding::BuiltIn(b)), Some(ast::Binding::Location { location, interpolation, @@ -3547,11 +4066,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { None }; - let mut binding = crate::Binding::Location { + let mut binding = ir::Binding::Location { location: self.const_u32(location, &mut ctx.as_const())?.0, interpolation, sampling, blend_src, + per_primitive: false, }; binding.apply_default_interpolation(&ctx.module.types[ty].inner); Some(binding) @@ -3564,37 +4084,37 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { &mut self, expr: Handle>, ctx: &mut ExpressionContext<'source, '_, '_>, - ) -> Result<'source, Handle> { + ) -> Result<'source, Handle> { let span = ctx.ast_expressions.get_span(expr); let pointer = self.expression(expr, ctx)?; match *resolve_inner!(ctx, pointer) { - crate::TypeInner::Pointer { base, .. } => match ctx.module.types[base].inner { - crate::TypeInner::RayQuery { .. } => Ok(pointer), + ir::TypeInner::Pointer { base, .. } => match ctx.module.types[base].inner { + ir::TypeInner::RayQuery { .. } => Ok(pointer), ref other => { - log::error!("Pointer type to {:?} passed to ray query op", other); + log::error!("Pointer type to {other:?} passed to ray query op"); Err(Box::new(Error::InvalidRayQueryPointer(span))) } }, ref other => { - log::error!("Type {:?} passed to ray query op", other); + log::error!("Type {other:?} passed to ray query op"); Err(Box::new(Error::InvalidRayQueryPointer(span))) } } } } -impl crate::AtomicFunction { +impl ir::AtomicFunction { pub fn map(word: &str) -> Option { Some(match word { - "atomicAdd" => crate::AtomicFunction::Add, - "atomicSub" => crate::AtomicFunction::Subtract, - "atomicAnd" => crate::AtomicFunction::And, - "atomicOr" => crate::AtomicFunction::InclusiveOr, - "atomicXor" => crate::AtomicFunction::ExclusiveOr, - "atomicMin" => crate::AtomicFunction::Min, - "atomicMax" => crate::AtomicFunction::Max, - "atomicExchange" => crate::AtomicFunction::Exchange { compare: None }, + "atomicAdd" => ir::AtomicFunction::Add, + "atomicSub" => ir::AtomicFunction::Subtract, + "atomicAnd" => ir::AtomicFunction::And, + "atomicOr" => ir::AtomicFunction::InclusiveOr, + "atomicXor" => ir::AtomicFunction::ExclusiveOr, + "atomicMin" => ir::AtomicFunction::Min, + "atomicMax" => ir::AtomicFunction::Max, + "atomicExchange" => ir::AtomicFunction::Exchange { compare: None }, _ => return None, }) } diff --git a/naga/src/front/wgsl/mod.rs b/naga/src/front/wgsl/mod.rs index 977829a21..ba41dc801 100644 --- a/naga/src/front/wgsl/mod.rs +++ b/naga/src/front/wgsl/mod.rs @@ -11,10 +11,15 @@ mod parse; #[cfg(test)] mod tests; +pub use parse::directive::enable_extension::{ + EnableExtension, ImplementedEnableExtension, UnimplementedEnableExtension, +}; + pub use crate::front::wgsl::error::ParseError; pub use crate::front::wgsl::parse::directive::language_extension::{ ImplementedLanguageExtension, LanguageExtension, UnimplementedLanguageExtension, }; +pub use crate::front::wgsl::parse::Options; use alloc::boxed::Box; use thiserror::Error; @@ -31,21 +36,32 @@ pub(crate) type Result<'a, T> = core::result::Result>>; pub struct Frontend { parser: Parser, + options: Options, } impl Frontend { pub const fn new() -> Self { Self { parser: Parser::new(), + options: Options::new(), } } + pub const fn new_with_options(options: Options) -> Self { + Self { + parser: Parser::new(), + options, + } + } + pub fn set_options(&mut self, options: Options) { + self.options = options; + } pub fn parse(&mut self, source: &str) -> core::result::Result { self.inner(source).map_err(|x| x.as_parse_error(source)) } fn inner<'a>(&mut self, source: &'a str) -> Result<'a, crate::Module> { - let tu = self.parser.parse(source)?; + let tu = self.parser.parse(source, &self.options)?; let index = index::Index::generate(&tu)?; let module = Lowerer::new(&index).lower(tu)?; diff --git a/naga/src/front/wgsl/parse/ast.rs b/naga/src/front/wgsl/parse/ast.rs index a237cd743..345e9c4c4 100644 --- a/naga/src/front/wgsl/parse/ast.rs +++ b/naga/src/front/wgsl/parse/ast.rs @@ -40,6 +40,10 @@ pub struct TranslationUnit<'a> { /// See [`DiagnosticFilterNode`] for details on how the tree is represented and used in /// validation. pub diagnostic_filter_leaf: Option>, + + /// Doc comments appearing first in the file. + /// This serves as documentation for the whole TranslationUnit. + pub doc_comments: Vec<&'a str>, } #[derive(Debug, Clone, Copy)] @@ -137,6 +141,7 @@ pub struct Function<'a> { pub result: Option>, pub body: Block<'a>, pub diagnostic_filter_leaf: Option>, + pub doc_comments: Vec<&'a str>, } #[derive(Debug)] @@ -163,6 +168,7 @@ pub struct GlobalVariable<'a> { pub binding: Option>, pub ty: Option>>, pub init: Option>>, + pub doc_comments: Vec<&'a str>, } #[derive(Debug)] @@ -172,12 +178,14 @@ pub struct StructMember<'a> { pub binding: Option>, pub align: Option>>, pub size: Option>>, + pub doc_comments: Vec<&'a str>, } #[derive(Debug)] pub struct Struct<'a> { pub name: Ident<'a>, pub members: Vec>, + pub doc_comments: Vec<&'a str>, } #[derive(Debug)] @@ -191,6 +199,7 @@ pub struct Const<'a> { pub name: Ident<'a>, pub ty: Option>>, pub init: Handle>, + pub doc_comments: Vec<&'a str>, } #[derive(Debug)] diff --git a/naga/src/front/wgsl/parse/conv.rs b/naga/src/front/wgsl/parse/conv.rs index e130fb9d0..de07ba2e3 100644 --- a/naga/src/front/wgsl/parse/conv.rs +++ b/naga/src/front/wgsl/parse/conv.rs @@ -20,17 +20,23 @@ pub fn map_address_space(word: &str, span: Span) -> Result<'_, crate::AddressSpa } } -pub fn map_built_in(word: &str, span: Span) -> Result<'_, crate::BuiltIn> { - Ok(match word { +pub fn map_built_in( + enable_extensions: &EnableExtensions, + word: &str, + span: Span, +) -> Result<'static, crate::BuiltIn> { + let built_in = match word { "position" => crate::BuiltIn::Position { invariant: false }, // vertex "vertex_index" => crate::BuiltIn::VertexIndex, "instance_index" => crate::BuiltIn::InstanceIndex, "view_index" => crate::BuiltIn::ViewIndex, + "clip_distances" => crate::BuiltIn::ClipDistance, // fragment "front_facing" => crate::BuiltIn::FrontFacing, "frag_depth" => crate::BuiltIn::FragDepth, "primitive_index" => crate::BuiltIn::PrimitiveIndex, + "barycentric" => crate::BuiltIn::Barycentric, "sample_index" => crate::BuiltIn::SampleIndex, "sample_mask" => crate::BuiltIn::SampleMask, // compute @@ -45,7 +51,19 @@ pub fn map_built_in(word: &str, span: Span) -> Result<'_, crate::BuiltIn> { "subgroup_size" => crate::BuiltIn::SubgroupSize, "subgroup_invocation_id" => crate::BuiltIn::SubgroupInvocationId, _ => return Err(Box::new(Error::UnknownBuiltin(span))), - }) + }; + match built_in { + crate::BuiltIn::ClipDistance => { + if !enable_extensions.contains(ImplementedEnableExtension::ClipDistances) { + return Err(Box::new(Error::EnableExtensionNotEnabled { + span, + kind: ImplementedEnableExtension::ClipDistances.into(), + })); + } + } + _ => {} + } + Ok(built_in) } pub fn map_interpolation(word: &str, span: Span) -> Result<'_, crate::Interpolation> { @@ -98,7 +116,7 @@ pub fn map_storage_format(word: &str, span: Span) -> Result<'_, crate::StorageFo "rgba8sint" => Sf::Rgba8Sint, "rgb10a2uint" => Sf::Rgb10a2Uint, "rgb10a2unorm" => Sf::Rgb10a2Unorm, - "rg11b10float" => Sf::Rg11b10Ufloat, + "rg11b10ufloat" => Sf::Rg11b10Ufloat, "r64uint" => Sf::R64Uint, "rg32uint" => Sf::Rg32Uint, "rg32sint" => Sf::Rg32Sint, @@ -236,6 +254,8 @@ pub fn map_standard_fun(word: &str) -> Option { "pow" => Mf::Pow, // geometry "dot" => Mf::Dot, + "dot4I8Packed" => Mf::Dot4I8Packed, + "dot4U8Packed" => Mf::Dot4U8Packed, "cross" => Mf::Cross, "distance" => Mf::Distance, "length" => Mf::Length, @@ -271,6 +291,8 @@ pub fn map_standard_fun(word: &str) -> Option { "pack2x16float" => Mf::Pack2x16float, "pack4xI8" => Mf::Pack4xI8, "pack4xU8" => Mf::Pack4xU8, + "pack4xI8Clamp" => Mf::Pack4xI8Clamp, + "pack4xU8Clamp" => Mf::Pack4xU8Clamp, // data unpacking "unpack4x8snorm" => Mf::Unpack4x8snorm, "unpack4x8unorm" => Mf::Unpack4x8unorm, diff --git a/naga/src/front/wgsl/parse/directive/enable_extension.rs b/naga/src/front/wgsl/parse/directive/enable_extension.rs index 4fa979988..38d6d6719 100644 --- a/naga/src/front/wgsl/parse/directive/enable_extension.rs +++ b/naga/src/front/wgsl/parse/directive/enable_extension.rs @@ -13,6 +13,7 @@ pub struct EnableExtensions { dual_source_blending: bool, /// Whether `enable f16;` was written earlier in the shader module. f16: bool, + clip_distances: bool, } impl EnableExtensions { @@ -20,6 +21,7 @@ impl EnableExtensions { Self { f16: false, dual_source_blending: false, + clip_distances: false, } } @@ -28,6 +30,7 @@ impl EnableExtensions { let field = match ext { ImplementedEnableExtension::DualSourceBlending => &mut self.dual_source_blending, ImplementedEnableExtension::F16 => &mut self.f16, + ImplementedEnableExtension::ClipDistances => &mut self.clip_distances, }; *field = true; } @@ -37,6 +40,7 @@ impl EnableExtensions { match ext { ImplementedEnableExtension::DualSourceBlending => self.dual_source_blending, ImplementedEnableExtension::F16 => self.f16, + ImplementedEnableExtension::ClipDistances => self.clip_distances, } } } @@ -66,17 +70,21 @@ impl EnableExtension { const F16: &'static str = "f16"; const CLIP_DISTANCES: &'static str = "clip_distances"; const DUAL_SOURCE_BLENDING: &'static str = "dual_source_blending"; + const SUBGROUPS: &'static str = "subgroups"; + const PRIMITIVE_INDEX: &'static str = "primitive_index"; /// Convert from a sentinel word in WGSL into its associated [`EnableExtension`], if possible. - pub(crate) fn from_ident(word: &str, span: Span) -> Result { + pub(crate) fn from_ident(word: &str, span: Span) -> Result<'_, Self> { Ok(match word { Self::F16 => Self::Implemented(ImplementedEnableExtension::F16), - Self::CLIP_DISTANCES => { - Self::Unimplemented(UnimplementedEnableExtension::ClipDistances) - } + Self::CLIP_DISTANCES => Self::Implemented(ImplementedEnableExtension::ClipDistances), Self::DUAL_SOURCE_BLENDING => { Self::Implemented(ImplementedEnableExtension::DualSourceBlending) } + Self::SUBGROUPS => Self::Unimplemented(UnimplementedEnableExtension::Subgroups), + Self::PRIMITIVE_INDEX => { + Self::Unimplemented(UnimplementedEnableExtension::PrimitiveIndex) + } _ => return Err(Box::new(Error::UnknownEnableExtension(span, word))), }) } @@ -87,9 +95,11 @@ impl EnableExtension { Self::Implemented(kind) => match kind { ImplementedEnableExtension::DualSourceBlending => Self::DUAL_SOURCE_BLENDING, ImplementedEnableExtension::F16 => Self::F16, + ImplementedEnableExtension::ClipDistances => Self::CLIP_DISTANCES, }, Self::Unimplemented(kind) => match kind { - UnimplementedEnableExtension::ClipDistances => Self::CLIP_DISTANCES, + UnimplementedEnableExtension::Subgroups => Self::SUBGROUPS, + UnimplementedEnableExtension::PrimitiveIndex => Self::PRIMITIVE_INDEX, }, } } @@ -98,23 +108,18 @@ impl EnableExtension { /// A variant of [`EnableExtension::Implemented`]. #[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)] pub enum ImplementedEnableExtension { - /// Enables the `blend_src` attribute in WGSL. - /// - /// In the WGSL standard, this corresponds to [`enable dual_source_blending;`]. - /// - /// [`enable dual_source_blending;`]: https://www.w3.org/TR/WGSL/#extension-dual_source_blending - DualSourceBlending, /// Enables `f16`/`half` primitive support in all shader languages. /// /// In the WGSL standard, this corresponds to [`enable f16;`]. /// /// [`enable f16;`]: https://www.w3.org/TR/WGSL/#extension-f16 F16, -} - -/// A variant of [`EnableExtension::Unimplemented`]. -#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)] -pub enum UnimplementedEnableExtension { + /// Enables the `blend_src` attribute in WGSL. + /// + /// In the WGSL standard, this corresponds to [`enable dual_source_blending;`]. + /// + /// [`enable dual_source_blending;`]: https://www.w3.org/TR/WGSL/#extension-dual_source_blending + DualSourceBlending, /// Enables the `clip_distances` variable in WGSL. /// /// In the WGSL standard, this corresponds to [`enable clip_distances;`]. @@ -123,10 +128,28 @@ pub enum UnimplementedEnableExtension { ClipDistances, } +/// A variant of [`EnableExtension::Unimplemented`]. +#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)] +pub enum UnimplementedEnableExtension { + /// Enables subgroup built-ins in all languages. + /// + /// In the WGSL standard, this corresponds to [`enable subgroups;`]. + /// + /// [`enable subgroups;`]: https://www.w3.org/TR/WGSL/#extension-subgroups + Subgroups, + /// Enables the `@builtin(primitive_index)` attribute in WGSL. + /// + /// In the WGSL standard, this corresponds to [`enable primitive-index;`]. + /// + /// [`enable primitive-index;`]: https://www.w3.org/TR/WGSL/#extension-primitive_index + PrimitiveIndex, +} + impl UnimplementedEnableExtension { pub(crate) const fn tracking_issue_num(self) -> u16 { match self { - Self::ClipDistances => 6236, + Self::Subgroups => 5555, + Self::PrimitiveIndex => 8236, } } } diff --git a/naga/src/front/wgsl/parse/directive/language_extension.rs b/naga/src/front/wgsl/parse/directive/language_extension.rs index 4a48ccd91..586e9b763 100644 --- a/naga/src/front/wgsl/parse/directive/language_extension.rs +++ b/naga/src/front/wgsl/parse/directive/language_extension.rs @@ -2,8 +2,6 @@ //! //! The focal point of this module is the [`LanguageExtension`] API. -use strum::VariantArray; - /// A language extension recognized by Naga, but not guaranteed to be present in all environments. /// /// WGSL spec.: @@ -24,11 +22,11 @@ impl LanguageExtension { /// Convert from a sentinel word in WGSL into its associated [`LanguageExtension`], if possible. pub fn from_ident(s: &str) -> Option { Some(match s { - Self::READONLY_AND_READWRITE_STORAGE_TEXTURES => Self::Unimplemented( - UnimplementedLanguageExtension::ReadOnlyAndReadWriteStorageTextures, - ), + Self::READONLY_AND_READWRITE_STORAGE_TEXTURES => { + Self::Implemented(ImplementedLanguageExtension::ReadOnlyAndReadWriteStorageTextures) + } Self::PACKED4X8_INTEGER_DOT_PRODUCT => { - Self::Unimplemented(UnimplementedLanguageExtension::Packed4x8IntegerDotProduct) + Self::Implemented(ImplementedLanguageExtension::Packed4x8IntegerDotProduct) } Self::UNRESTRICTED_POINTER_PARAMETERS => { Self::Unimplemented(UnimplementedLanguageExtension::UnrestrictedPointerParameters) @@ -45,12 +43,6 @@ impl LanguageExtension { match self { Self::Implemented(kind) => kind.to_ident(), Self::Unimplemented(kind) => match kind { - UnimplementedLanguageExtension::ReadOnlyAndReadWriteStorageTextures => { - Self::READONLY_AND_READWRITE_STORAGE_TEXTURES - } - UnimplementedLanguageExtension::Packed4x8IntegerDotProduct => { - Self::PACKED4X8_INTEGER_DOT_PRODUCT - } UnimplementedLanguageExtension::UnrestrictedPointerParameters => { Self::UNRESTRICTED_POINTER_PARAMETERS } @@ -60,12 +52,22 @@ impl LanguageExtension { } /// A variant of [`LanguageExtension::Implemented`]. -#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, VariantArray)] +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +#[cfg_attr(test, derive(strum::VariantArray))] pub enum ImplementedLanguageExtension { + ReadOnlyAndReadWriteStorageTextures, + Packed4x8IntegerDotProduct, PointerCompositeAccess, } impl ImplementedLanguageExtension { + /// A slice of all variants of [`ImplementedLanguageExtension`]. + pub const VARIANTS: &'static [Self] = &[ + Self::ReadOnlyAndReadWriteStorageTextures, + Self::Packed4x8IntegerDotProduct, + Self::PointerCompositeAccess, + ]; + /// Returns slice of all variants of [`ImplementedLanguageExtension`]. pub const fn all() -> &'static [Self] { Self::VARIANTS @@ -74,6 +76,12 @@ impl ImplementedLanguageExtension { /// Maps this [`ImplementedLanguageExtension`] into the sentinel word associated with it in WGSL. pub const fn to_ident(self) -> &'static str { match self { + ImplementedLanguageExtension::ReadOnlyAndReadWriteStorageTextures => { + LanguageExtension::READONLY_AND_READWRITE_STORAGE_TEXTURES + } + ImplementedLanguageExtension::Packed4x8IntegerDotProduct => { + LanguageExtension::PACKED4X8_INTEGER_DOT_PRODUCT + } ImplementedLanguageExtension::PointerCompositeAccess => { LanguageExtension::POINTER_COMPOSITE_ACCESS } @@ -81,19 +89,25 @@ impl ImplementedLanguageExtension { } } +#[test] +/// Asserts that the manual implementation of VARIANTS is the same as the derived strum version would be +/// while still allowing strum to be a dev-only dependency +fn test_manual_variants_array_is_correct() { + assert_eq!( + ::VARIANTS, + ImplementedLanguageExtension::VARIANTS + ); +} + /// A variant of [`LanguageExtension::Unimplemented`]. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum UnimplementedLanguageExtension { - ReadOnlyAndReadWriteStorageTextures, - Packed4x8IntegerDotProduct, UnrestrictedPointerParameters, } impl UnimplementedLanguageExtension { pub(crate) const fn tracking_issue_num(self) -> u16 { match self { - Self::ReadOnlyAndReadWriteStorageTextures => 6204, - Self::Packed4x8IntegerDotProduct => 6445, Self::UnrestrictedPointerParameters => 5158, } } diff --git a/naga/src/front/wgsl/parse/lexer.rs b/naga/src/front/wgsl/parse/lexer.rs index 378af3d93..d0a803398 100644 --- a/naga/src/front/wgsl/parse/lexer.rs +++ b/naga/src/front/wgsl/parse/lexer.rs @@ -5,7 +5,7 @@ use crate::front::wgsl::parse::{conv, Number}; use crate::front::wgsl::Scalar; use crate::Span; -use alloc::boxed::Box; +use alloc::{boxed::Box, vec::Vec}; type TokenSpan<'a> = (Token<'a>, Span); @@ -25,6 +25,8 @@ pub enum Token<'a> { Arrow, Unknown(char), Trivia, + DocComment(&'a str), + ModuleDocComment(&'a str), End, } @@ -47,8 +49,10 @@ fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str) { /// - Otherwise, interpret `<<` and `>>` as shift operators: /// `Token::LogicalOperation` tokens. /// +/// If `ignore_doc_comments` is true, doc comments are treated as [`Token::Trivia`]. +/// /// [§3.1 Parsing]: https://gpuweb.github.io/gpuweb/wgsl/#parsing -fn consume_token(input: &str, generic: bool) -> (Token<'_>, &str) { +fn consume_token(input: &str, generic: bool, ignore_doc_comments: bool) -> (Token<'_>, &str) { let mut chars = input.chars(); let cur = match chars.next() { Some(c) => c, @@ -84,12 +88,37 @@ fn consume_token(input: &str, generic: bool) -> (Token<'_>, &str) { let og_chars = chars.as_str(); match chars.next() { Some('/') => { - let _ = chars.position(is_comment_end); - (Token::Trivia, chars.as_str()) + let mut input_chars = input.char_indices(); + let doc_comment_end = input_chars + .find_map(|(index, c)| is_comment_end(c).then_some(index)) + .unwrap_or(input.len()); + let token = match chars.next() { + Some('/') if !ignore_doc_comments => { + Token::DocComment(&input[..doc_comment_end]) + } + Some('!') if !ignore_doc_comments => { + Token::ModuleDocComment(&input[..doc_comment_end]) + } + _ => Token::Trivia, + }; + (token, input_chars.as_str()) } Some('*') => { + let next_c = chars.next(); + + enum CommentType { + Doc, + ModuleDoc, + Normal, + } + let comment_type = match next_c { + Some('*') if !ignore_doc_comments => CommentType::Doc, + Some('!') if !ignore_doc_comments => CommentType::ModuleDoc, + _ => CommentType::Normal, + }; + let mut depth = 1; - let mut prev = None; + let mut prev = next_c; for c in &mut chars { match (prev, c) { @@ -97,7 +126,19 @@ fn consume_token(input: &str, generic: bool) -> (Token<'_>, &str) { prev = None; depth -= 1; if depth == 0 { - return (Token::Trivia, chars.as_str()); + let rest = chars.as_str(); + let token = match comment_type { + CommentType::Doc => { + let doc_comment_end = input.len() - rest.len(); + Token::DocComment(&input[..doc_comment_end]) + } + CommentType::ModuleDoc => { + let doc_comment_end = input.len() - rest.len(); + Token::ModuleDocComment(&input[..doc_comment_end]) + } + CommentType::Normal => Token::Trivia, + }; + return (token, rest); } } (Some('/'), '*') => { @@ -170,6 +211,7 @@ fn consume_token(input: &str, generic: bool) -> (Token<'_>, &str) { /// Returns whether or not a char is a comment end /// (Unicode Pattern_White_Space excluding U+0020, U+0009, U+200E and U+200F) +/// const fn is_comment_end(c: char) -> bool { match c { '\u{000a}'..='\u{000d}' | '\u{0085}' | '\u{2028}' | '\u{2029}' => true, @@ -220,16 +262,21 @@ pub(in crate::front::wgsl) struct Lexer<'a> { /// statements. last_end_offset: usize, + /// Whether or not to ignore doc comments. + /// If `true`, doc comments are treated as [`Token::Trivia`]. + ignore_doc_comments: bool, + pub(in crate::front::wgsl) enable_extensions: EnableExtensions, } impl<'a> Lexer<'a> { - pub(in crate::front::wgsl) const fn new(input: &'a str) -> Self { + pub(in crate::front::wgsl) const fn new(input: &'a str, ignore_doc_comments: bool) -> Self { Lexer { input, source: input, last_end_offset: 0, enable_extensions: EnableExtensions::empty(), + ignore_doc_comments, } } @@ -255,7 +302,7 @@ impl<'a> Lexer<'a> { pub(in crate::front::wgsl) fn start_byte_offset(&mut self) -> usize { loop { // Eat all trivia because `next` doesn't eat trailing trivia. - let (token, rest) = consume_token(self.input, false); + let (token, rest) = consume_token(self.input, false, true); if let Token::Trivia = token { self.input = rest; } else { @@ -271,6 +318,40 @@ impl<'a> Lexer<'a> { (token, rest) } + /// Collect all module doc comments until a non doc token is found. + pub(in crate::front::wgsl) fn accumulate_module_doc_comments(&mut self) -> Vec<&'a str> { + let mut doc_comments = Vec::new(); + loop { + // ignore blankspace + self.input = consume_any(self.input, is_blankspace).1; + + let (token, rest) = consume_token(self.input, false, self.ignore_doc_comments); + if let Token::ModuleDocComment(doc_comment) = token { + self.input = rest; + doc_comments.push(doc_comment); + } else { + return doc_comments; + } + } + } + + /// Collect all doc comments until a non doc token is found. + pub(in crate::front::wgsl) fn accumulate_doc_comments(&mut self) -> Vec<&'a str> { + let mut doc_comments = Vec::new(); + loop { + // ignore blankspace + self.input = consume_any(self.input, is_blankspace).1; + + let (token, rest) = consume_token(self.input, false, self.ignore_doc_comments); + if let Token::DocComment(doc_comment) = token { + self.input = rest; + doc_comments.push(doc_comment); + } else { + return doc_comments; + } + } + } + const fn current_byte_offset(&self) -> usize { self.source.len() - self.input.len() } @@ -285,7 +366,7 @@ impl<'a> Lexer<'a> { /// occur, but not angle brackets. #[must_use] pub(in crate::front::wgsl) fn next(&mut self) -> TokenSpan<'a> { - self.next_impl(false) + self.next_impl(false, true) } /// Return the next non-whitespace token from `self`. @@ -294,16 +375,25 @@ impl<'a> Lexer<'a> { /// but not bit shift operators. #[must_use] pub(in crate::front::wgsl) fn next_generic(&mut self) -> TokenSpan<'a> { - self.next_impl(true) + self.next_impl(true, true) + } + + #[cfg(test)] + pub fn next_with_unignored_doc_comments(&mut self) -> TokenSpan<'a> { + self.next_impl(false, false) } /// Return the next non-whitespace token from `self`, with a span. /// /// See [`consume_token`] for the meaning of `generic`. - fn next_impl(&mut self, generic: bool) -> TokenSpan<'a> { + fn next_impl(&mut self, generic: bool, ignore_doc_comments: bool) -> TokenSpan<'a> { let mut start_byte_offset = self.current_byte_offset(); loop { - let (token, rest) = consume_token(self.input, generic); + let (token, rest) = consume_token( + self.input, + generic, + ignore_doc_comments || self.ignore_doc_comments, + ); self.input = rest; match token { Token::Trivia => start_byte_offset = self.current_byte_offset(), @@ -516,9 +606,31 @@ impl<'a> Lexer<'a> { #[cfg(test)] #[track_caller] fn sub_test(source: &str, expected_tokens: &[Token]) { - let mut lex = Lexer::new(source); + sub_test_with(true, source, expected_tokens); +} + +#[cfg(test)] +#[track_caller] +fn sub_test_with_and_without_doc_comments(source: &str, expected_tokens: &[Token]) { + sub_test_with(false, source, expected_tokens); + sub_test_with( + true, + source, + expected_tokens + .iter() + .filter(|v| !matches!(**v, Token::DocComment(_) | Token::ModuleDocComment(_))) + .cloned() + .collect::>() + .as_slice(), + ); +} + +#[cfg(test)] +#[track_caller] +fn sub_test_with(ignore_doc_comments: bool, source: &str, expected_tokens: &[Token]) { + let mut lex = Lexer::new(source, ignore_doc_comments); for &token in expected_tokens { - assert_eq!(lex.next().0, token); + assert_eq!(lex.next_with_unignored_doc_comments().0, token); } assert_eq!(lex.next().0, Token::End); } @@ -737,11 +849,13 @@ fn test_tokens() { sub_test("No¾", &[Token::Word("No"), Token::Unknown('¾')]); sub_test("No好", &[Token::Word("No好")]); sub_test("_No", &[Token::Word("_No")]); - sub_test( + + sub_test_with_and_without_doc_comments( "*/*/***/*//=/*****//", &[ Token::Operation('*'), Token::AssignmentOperation('/'), + Token::DocComment("/*****/"), Token::Operation('/'), ], ); @@ -807,3 +921,132 @@ fn test_variable_decl() { ], ); } + +#[test] +fn test_comments() { + sub_test("// Single comment", &[]); + + sub_test( + "/* multi + line + comment */", + &[], + ); + sub_test( + "/* multi + line + comment */ + // and another", + &[], + ); +} + +#[test] +fn test_doc_comments() { + sub_test_with_and_without_doc_comments( + "/// Single comment", + &[Token::DocComment("/// Single comment")], + ); + + sub_test_with_and_without_doc_comments( + "/** multi + line + comment */", + &[Token::DocComment( + "/** multi + line + comment */", + )], + ); + sub_test_with_and_without_doc_comments( + "/** multi + line + comment */ + /// and another", + &[ + Token::DocComment( + "/** multi + line + comment */", + ), + Token::DocComment("/// and another"), + ], + ); +} + +#[test] +fn test_doc_comment_nested() { + sub_test_with_and_without_doc_comments( + "/** + a comment with nested one /** + nested comment + */ + */ + const a : i32 = 2;", + &[ + Token::DocComment( + "/** + a comment with nested one /** + nested comment + */ + */", + ), + Token::Word("const"), + Token::Word("a"), + Token::Separator(':'), + Token::Word("i32"), + Token::Operation('='), + Token::Number(Ok(Number::AbstractInt(2))), + Token::Separator(';'), + ], + ); +} + +#[test] +fn test_doc_comment_long_character() { + sub_test_with_and_without_doc_comments( + "/// π/2 + /// D(𝐡) = ─────────────────────────────────────────────────── +/// παₜα_b((𝐡 ⋅ 𝐭)² / αₜ²) + (𝐡 ⋅ 𝐛)² / α_b² +` + const a : i32 = 2;", + &[ + Token::DocComment("/// π/2"), + Token::DocComment("/// D(𝐡) = ───────────────────────────────────────────────────"), + Token::DocComment("/// παₜα_b((𝐡 ⋅ 𝐭)² / αₜ²) + (𝐡 ⋅ 𝐛)² / α_b² +`"), + Token::Word("const"), + Token::Word("a"), + Token::Separator(':'), + Token::Word("i32"), + Token::Operation('='), + Token::Number(Ok(Number::AbstractInt(2))), + Token::Separator(';'), + ], + ); +} + +#[test] +fn test_doc_comments_module() { + sub_test_with_and_without_doc_comments( + "//! Comment Module + //! Another one. + /*! Different module comment */ + /// Trying to break module comment + // Trying to break module comment again + //! After a regular comment is ok. + /*! Different module comment again */ + + //! After a break is supported. + const + //! After anything else is not.", + &[ + Token::ModuleDocComment("//! Comment Module"), + Token::ModuleDocComment("//! Another one."), + Token::ModuleDocComment("/*! Different module comment */"), + Token::DocComment("/// Trying to break module comment"), + Token::ModuleDocComment("//! After a regular comment is ok."), + Token::ModuleDocComment("/*! Different module comment again */"), + Token::ModuleDocComment("//! After a break is supported."), + Token::Word("const"), + ], + ); +} diff --git a/naga/src/front/wgsl/parse/mod.rs b/naga/src/front/wgsl/parse/mod.rs index af6c5ac09..c01ba4de3 100644 --- a/naga/src/front/wgsl/parse/mod.rs +++ b/naga/src/front/wgsl/parse/mod.rs @@ -199,8 +199,10 @@ impl<'a> BindingParser<'a> { "builtin" => { lexer.expect(Token::Paren('('))?; let (raw, span) = lexer.next_ident_with_span()?; - self.built_in - .set(conv::map_built_in(raw, span)?, name_span)?; + self.built_in.set( + conv::map_built_in(&lexer.enable_extensions, raw, span)?, + name_span, + )?; lexer.expect(Token::Paren(')'))?; } "interpolate" => { @@ -233,6 +235,7 @@ impl<'a> BindingParser<'a> { lexer.expect(Token::Paren('('))?; self.blend_src .set(parser.general_expression(lexer, ctx)?, name_span)?; + lexer.skip(Token::Separator(',')); lexer.expect(Token::Paren(')'))?; } _ => return Err(Box::new(Error::UnknownAttribute(name_span))), @@ -275,6 +278,21 @@ impl<'a> BindingParser<'a> { } } +/// Configuration for the whole parser run. +pub struct Options { + /// Controls whether the parser should parse doc comments. + pub parse_doc_comments: bool, +} + +impl Options { + /// Creates a new [`Options`] without doc comments parsing. + pub const fn new() -> Self { + Options { + parse_doc_comments: false, + } + } +} + pub struct Parser { rules: Vec<(Rule, usize)>, recursion_depth: u32, @@ -659,6 +677,7 @@ impl Parser { | "texture_depth_cube" | "texture_depth_cube_array" | "texture_depth_multisampled_2d" + | "texture_external" | "texture_storage_1d" | "texture_storage_1d_array" | "texture_storage_2d" @@ -1326,6 +1345,7 @@ impl Parser { binding: None, ty, init, + doc_comments: Vec::new(), }) } @@ -1346,6 +1366,9 @@ impl Parser { ExpectedToken::Token(Token::Separator(',')), ))); } + + let doc_comments = lexer.accumulate_doc_comments(); + let (mut size, mut align) = (ParsedAttribute::default(), ParsedAttribute::default()); self.push_rule_span(Rule::Attribute, lexer); let mut bind_parser = BindingParser::default(); @@ -1381,6 +1404,7 @@ impl Parser { binding, size: size.value, align: align.value, + doc_comments, }); if !member_names.insert(name.name) { @@ -1845,6 +1869,11 @@ impl Parser { arrayed: false, class: crate::ImageClass::Depth { multi: true }, }, + "texture_external" => ast::Type::Image { + dim: crate::ImageDimension::D2, + arrayed: false, + class: crate::ImageClass::External, + }, "texture_storage_1d" => { let (format, access) = lexer.next_format_generic()?; ast::Type::Image { @@ -2092,7 +2121,7 @@ impl Parser { let _ = lexer.next(); this.pop_rule_span(lexer); } - (Token::Paren('{') | Token::Attribute, _) => { + (token, _) if is_start_of_compound_statement(token) => { let (inner, span) = this.block(lexer, ctx, brace_nesting_level)?; block.stmts.push(ast::Statement { kind: ast::StatementKind::Block(inner), @@ -2258,11 +2287,14 @@ impl Parser { let value = loop { let value = this.switch_value(lexer, ctx)?; if lexer.skip(Token::Separator(',')) { - if lexer.skip(Token::Separator(':')) { + // list of values ends with ':' or a compound statement + let next_token = lexer.peek().0; + if next_token == Token::Separator(':') + || is_start_of_compound_statement(next_token) + { break value; } } else { - lexer.skip(Token::Separator(':')); break value; } cases.push(ast::SwitchCase { @@ -2272,6 +2304,8 @@ impl Parser { }); }; + lexer.skip(Token::Separator(':')); + let body = this.block(lexer, ctx, brace_nesting_level)?.0; cases.push(ast::SwitchCase { @@ -2708,6 +2742,7 @@ impl Parser { result, body, diagnostic_filter_leaf, + doc_comments: Vec::new(), }; // done @@ -2750,6 +2785,8 @@ impl Parser { lexer: &mut Lexer<'a>, out: &mut ast::TranslationUnit<'a>, ) -> Result<'a, ()> { + let doc_comments = lexer.accumulate_doc_comments(); + // read attributes let mut binding = None; let mut stage = ParsedAttribute::default(); @@ -2838,15 +2875,17 @@ impl Parser { workgroup_size.set(new_workgroup_size, name_span)?; } "early_depth_test" => { - let conservative = if lexer.skip(Token::Paren('(')) { - let (ident, ident_span) = lexer.next_ident_with_span()?; - let value = conv::map_conservative_depth(ident, ident_span)?; - lexer.expect(Token::Paren(')'))?; - Some(value) + lexer.expect(Token::Paren('('))?; + let (ident, ident_span) = lexer.next_ident_with_span()?; + let value = if ident == "force" { + crate::EarlyDepthTest::Force } else { - None + crate::EarlyDepthTest::Allow { + conservative: conv::map_conservative_depth(ident, ident_span)?, + } }; - early_depth_test.set(crate::EarlyDepthTest { conservative }, name_span)?; + lexer.expect(Token::Paren(')'))?; + early_depth_test.set(value, name_span)?; } "must_use" => { must_use.set(name_span, name_span)?; @@ -2891,7 +2930,12 @@ impl Parser { let name = lexer.next_ident()?; let members = self.struct_body(lexer, &mut ctx)?; - Some(ast::GlobalDeclKind::Struct(ast::Struct { name, members })) + + Some(ast::GlobalDeclKind::Struct(ast::Struct { + name, + members, + doc_comments, + })) } (Token::Word("alias"), _) => { ensure_no_diag_attrs("`alias`es".into(), diagnostic_filters)?; @@ -2919,7 +2963,12 @@ impl Parser { let init = self.general_expression(lexer, &mut ctx)?; lexer.expect(Token::Separator(';'))?; - Some(ast::GlobalDeclKind::Const(ast::Const { name, ty, init })) + Some(ast::GlobalDeclKind::Const(ast::Const { + name, + ty, + init, + doc_comments, + })) } (Token::Word("override"), _) => { ensure_no_diag_attrs("`override`s".into(), diagnostic_filters)?; @@ -2952,6 +3001,7 @@ impl Parser { let mut var = self.variable_decl(lexer, &mut ctx)?; var.binding = binding.take(); + var.doc_comments = doc_comments; Some(ast::GlobalDeclKind::Var(var)) } (Token::Word("fn"), _) => { @@ -2981,6 +3031,7 @@ impl Parser { } else { None }, + doc_comments, ..function })) } @@ -3028,14 +3079,21 @@ impl Parser { } } - pub fn parse<'a>(&mut self, source: &'a str) -> Result<'a, ast::TranslationUnit<'a>> { + pub fn parse<'a>( + &mut self, + source: &'a str, + options: &Options, + ) -> Result<'a, ast::TranslationUnit<'a>> { self.reset(); - let mut lexer = Lexer::new(source); + let mut lexer = Lexer::new(source, !options.parse_doc_comments); let mut tu = ast::TranslationUnit::default(); let mut enable_extensions = EnableExtensions::empty(); let mut diagnostic_filters = DiagnosticFilterMap::new(); + // Parse module doc comments. + tu.doc_comments = lexer.accumulate_module_doc_comments(); + // Parse directives. while let Ok((ident, _directive_ident_span)) = lexer.peek_ident_with_span() { if let Some(kind) = DirectiveKind::from_ident(ident) { @@ -3191,3 +3249,7 @@ impl Parser { }) } } + +const fn is_start_of_compound_statement<'a>(token: Token<'a>) -> bool { + matches!(token, Token::Attribute | Token::Paren('{')) +} diff --git a/naga/src/front/wgsl/tests.rs b/naga/src/front/wgsl/tests.rs index bdcd35d8a..149f5d329 100644 --- a/naga/src/front/wgsl/tests.rs +++ b/naga/src/front/wgsl/tests.rs @@ -627,7 +627,7 @@ fn parse_texture_load_store_expecting_four_args() { for (func, texture) in [ ( "textureStore", - "texture_storage_2d_array", + "texture_storage_2d_array", ), ("textureLoad", "texture_2d_array"), ] { diff --git a/naga/src/ir/mod.rs b/naga/src/ir/mod.rs index fa7bf6379..4093d823b 100644 --- a/naga/src/ir/mod.rs +++ b/naga/src/ir/mod.rs @@ -221,7 +221,7 @@ An override expression can be evaluated at pipeline creation time. mod block; -use alloc::{string::String, vec::Vec}; +use alloc::{boxed::Box, string::String, vec::Vec}; #[cfg(feature = "arbitrary")] use arbitrary::Arbitrary; @@ -237,19 +237,27 @@ use crate::{FastIndexMap, NamedExpressions}; pub use block::Block; -/// Early fragment tests. +/// Explicitly allows early depth/stencil tests. /// -/// In a standard situation, if a driver determines that it is possible to switch on early depth test, it will. +/// Normally, depth/stencil tests are performed after fragment shading. However, as an optimization, +/// most drivers will move the depth/stencil tests before fragment shading if this does not +/// have any observable consequences. This optimization is disabled under the following +/// circumstances: +/// - `discard` is called in the fragment shader. +/// - The fragment shader writes to the depth buffer. +/// - The fragment shader writes to any storage bindings. /// -/// Typical situations when early depth test is switched off: -/// - Calling `discard` in a shader. -/// - Writing to the depth buffer, unless ConservativeDepth is enabled. +/// When `EarlyDepthTest` is set, it is allowed to perform an early depth/stencil test even if the +/// above conditions are not met. When [`EarlyDepthTest::Force`] is used, depth/stencil tests +/// **must** be performed before fragment shading. /// -/// To use in a shader: +/// To force early depth/stencil tests in a shader: /// - GLSL: `layout(early_fragment_tests) in;` /// - HLSL: `Attribute earlydepthstencil` /// - SPIR-V: `ExecutionMode EarlyFragmentTests` -/// - WGSL: `@early_depth_test` +/// - WGSL: `@early_depth_test(force)` +/// +/// This may also be enabled in a shader by specifying a [`ConservativeDepth`]. /// /// For more, see: /// - @@ -259,8 +267,24 @@ pub use block::Block; #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] -pub struct EarlyDepthTest { - pub conservative: Option, +pub enum EarlyDepthTest { + /// Requires depth/stencil tests to be performed before fragment shading. + /// + /// This will disable depth/stencil tests after fragment shading, so discarding the fragment + /// or overwriting the fragment depth will have no effect. + Force, + + /// Allows an additional depth/stencil test to be performed before fragment shading. + /// + /// It is up to the driver to decide whether early tests are performed. Unlike `Force`, this + /// does not disable depth/stencil tests after fragment shading. + Allow { + /// Specifies restrictions on how the depth value can be modified within the fragment + /// shader. + /// + /// This may be taken into account when deciding whether to perform early tests. + conservative: ConservativeDepth, + }, } /// Enables adjusting depth without disabling early Z. @@ -296,13 +320,21 @@ pub enum ConservativeDepth { #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] -#[allow(missing_docs)] // The names are self evident pub enum ShaderStage { + /// A vertex shader, in a render pipeline. Vertex, - Fragment, - Compute, + + /// A task shader, in a mesh render pipeline. Task, + + /// A mesh shader, in a mesh render pipeline. Mesh, + + /// A fragment shader, in a render pipeline. + Fragment, + + /// Compute pipeline shader. + Compute, } /// Addressing space of variables. @@ -323,8 +355,24 @@ pub enum AddressSpace { Storage { access: StorageAccess }, /// Opaque handles, such as samplers and images. Handle, + /// Push constants. + /// + /// A [`Module`] may contain at most one [`GlobalVariable`] in + /// this address space. Its contents are provided not by a buffer + /// but by `SetPushConstant` pass commands, allowing the CPU to + /// establish different values for each draw/dispatch. + /// + /// `PushConstant` variables may not contain `f16` values, even if + /// the [`SHADER_FLOAT16`] capability is enabled. + /// + /// Backends generally place tight limits on the size of + /// `PushConstant` variables. + /// + /// [`SHADER_FLOAT16`]: crate::valid::Capabilities::SHADER_FLOAT16 PushConstant, + /// Task shader to mesh shader payload + TaskPayload, } /// Built-in inputs and outputs. @@ -333,36 +381,75 @@ pub enum AddressSpace { #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] pub enum BuiltIn { + /// Written in vertex/mesh shaders, read in fragment shaders Position { invariant: bool }, + /// Read in task, mesh, vertex, and fragment shaders ViewIndex, - // vertex + + /// Read in vertex shaders BaseInstance, + /// Read in vertex shaders BaseVertex, + /// Written in vertex & mesh shaders ClipDistance, + /// Written in vertex & mesh shaders CullDistance, + /// Read in vertex shaders InstanceIndex, + /// Written in vertex & mesh shaders PointSize, + /// Read in vertex shaders VertexIndex, + /// Read in vertex & task shaders, or mesh shaders in pipelines without task shaders DrawID, - // fragment + + /// Written in fragment shaders FragDepth, + /// Read in fragment shaders PointCoord, + /// Read in fragment shaders FrontFacing, + /// Read in fragment shaders, in the future may written in mesh shaders PrimitiveIndex, + /// Read in fragment shaders + Barycentric, + /// Read in fragment shaders SampleIndex, + /// Read or written in fragment shaders SampleMask, - // compute + + /// Read in compute, task, and mesh shaders GlobalInvocationId, + /// Read in compute, task, and mesh shaders LocalInvocationId, + /// Read in compute, task, and mesh shaders LocalInvocationIndex, + /// Read in compute, task, and mesh shaders WorkGroupId, + /// Read in compute, task, and mesh shaders WorkGroupSize, + /// Read in compute, task, and mesh shaders NumWorkGroups, - // subgroup + + /// Read in compute, task, and mesh shaders NumSubgroups, + /// Read in compute, task, and mesh shaders SubgroupId, + /// Read in compute, fragment, task, and mesh shaders SubgroupSize, + /// Read in compute, fragment, task, and mesh shaders SubgroupInvocationId, + + /// Written in task shaders + MeshTaskSize, + /// Written in mesh shaders + CullPrimitive, + /// Written in mesh shaders + PointIndex, + /// Written in mesh shaders + LineIndices, + /// Written in mesh shaders + TriangleIndices, } /// Number of bytes per scalar. @@ -387,6 +474,18 @@ impl VectorSize { pub const MAX: usize = Self::Quad as usize; } +impl From for u8 { + fn from(size: VectorSize) -> u8 { + size as u8 + } +} + +impl From for u32 { + fn from(size: VectorSize) -> u32 { + size as u32 + } +} + /// Primitive type for a scalar. #[repr(u8)] #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] @@ -616,6 +715,8 @@ pub enum ImageClass { /// Multi-sampled depth image. multi: bool, }, + /// External texture. + External, /// Storage image. Storage { format: StorageFormat, @@ -636,6 +737,15 @@ pub struct Type { } /// Enum with additional information, depending on the kind of type. +/// +/// Comparison using `==` is not reliable in the case of [`Pointer`], +/// [`ValuePointer`], or [`Struct`] variants. For these variants, +/// use [`TypeInner::non_struct_equivalent`] or [`compare_types`]. +/// +/// [`compare_types`]: crate::proc::compare_types +/// [`ValuePointer`]: TypeInner::ValuePointer +/// [`Pointer`]: TypeInner::Pointer +/// [`Struct`]: TypeInner::Struct #[derive(Clone, Debug, Eq, Hash, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] @@ -656,8 +766,9 @@ pub enum TypeInner { /// Pointer to another type. /// /// Pointers to scalars and vectors should be treated as equivalent to - /// [`ValuePointer`] types. Use the [`TypeInner::equivalent`] method to - /// compare types in a way that treats pointers correctly. + /// [`ValuePointer`] types. Use either [`TypeInner::non_struct_equivalent`] + /// or [`compare_types`] to compare types in a way that treats pointers + /// correctly. /// /// ## Pointers to non-`SIZED` types /// @@ -679,6 +790,7 @@ pub enum TypeInner { /// [`ValuePointer`]: TypeInner::ValuePointer /// [`GlobalVariable`]: Expression::GlobalVariable /// [`AccessIndex`]: Expression::AccessIndex + /// [`compare_types`]: crate::proc::compare_types Pointer { base: Handle, space: AddressSpace, @@ -690,12 +802,13 @@ pub enum TypeInner { /// `Scalar` or `Vector` type. This is for use in [`TypeResolution::Value`] /// variants; see the documentation for [`TypeResolution`] for details. /// - /// Use the [`TypeInner::equivalent`] method to compare types that could be - /// pointers, to ensure that `Pointer` and `ValuePointer` types are - /// recognized as equivalent. + /// Use [`TypeInner::non_struct_equivalent`] or [`compare_types`] to compare + /// types that could be pointers, to ensure that `Pointer` and + /// `ValuePointer` types are recognized as equivalent. /// /// [`TypeResolution`]: crate::proc::TypeResolution /// [`TypeResolution::Value`]: crate::proc::TypeResolution::Value + /// [`compare_types`]: crate::proc::compare_types ValuePointer { size: Option, scalar: Scalar, @@ -744,9 +857,15 @@ pub enum TypeInner { /// struct, which may be a dynamically sized [`Array`]. The /// `Struct` type itself is `SIZED` when all its members are `SIZED`. /// + /// Two structure types with different names are not equivalent. Because + /// this variant does not contain the name, it is not possible to use it + /// to compare struct types. Use [`compare_types`] to compare two types + /// that may be structs. + /// /// [`DATA`]: crate::valid::TypeFlags::DATA /// [`SIZED`]: crate::∅TypeFlags::SIZED /// [`Array`]: TypeInner::Array + /// [`compare_types`]: crate::proc::compare_types Struct { members: Vec, //TODO: should this be unaligned? @@ -875,6 +994,9 @@ pub enum Binding { /// Indexed location. /// + /// This is a value passed to a [`Fragment`] shader from a [`Vertex`] or + /// [`Mesh`] shader. + /// /// Values passed from the [`Vertex`] stage to the [`Fragment`] stage must /// have their `interpolation` defaulted (i.e. not `None`) by the front end /// as appropriate for that language. @@ -888,14 +1010,30 @@ pub enum Binding { /// interpolation must be `Flat`. /// /// [`Vertex`]: crate::ShaderStage::Vertex + /// [`Mesh`]: crate::ShaderStage::Mesh /// [`Fragment`]: crate::ShaderStage::Fragment Location { location: u32, interpolation: Option, sampling: Option, + /// Optional `blend_src` index used for dual source blending. /// See blend_src: Option, + + /// Whether the binding is a per-primitive binding for use with mesh shaders. + /// + /// This must be `true` if this binding is a mesh shader primitive output, or such + /// an output's corresponding fragment shader input. It must be `false` otherwise. + /// + /// A stage's outputs must all have unique `location` numbers, regardless of + /// whether they are per-primitive; a mesh shader's per-vertex and per-primitive + /// outputs share the same location numbering space. + /// + /// Per-primitive values are not interpolated at all and are not dependent on the + /// vertices or pixel location. For example, it may be used to store a + /// non-interpolated normal vector. + per_primitive: bool, }, } @@ -1130,6 +1268,8 @@ pub enum MathFunction { Pow, // geometry Dot, + Dot4I8Packed, + Dot4U8Packed, Outer, Cross, Distance, @@ -1167,6 +1307,8 @@ pub enum MathFunction { Pack2x16float, Pack4xI8, Pack4xU8, + Pack4xI8Clamp, + Pack4xU8Clamp, // data unpacking Unpack4x8snorm, Unpack4x8unorm, @@ -1257,6 +1399,20 @@ pub enum GatherMode { ShuffleUp(Handle), /// Each gathers from their lane xored with the given by the expression ShuffleXor(Handle), + /// All gather from the same quad lane at the index given by the expression + QuadBroadcast(Handle), + /// Each gathers from the opposite quad lane along the given direction + QuadSwap(Direction), +} + +#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] +pub enum Direction { + X = 0, + Y = 1, + Diagonal = 2, } #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] @@ -1449,6 +1605,10 @@ pub enum Expression { offset: Option>, level: SampleLevel, depth_ref: Option>, + /// Whether the sampling operation should clamp each component of + /// `coordinate` to the range `[half_texel, 1 - half_texel]`, regardless + /// of `sampler`. + clamp_to_edge: bool, }, /// Load a texel from an image. @@ -1632,10 +1792,12 @@ pub enum Expression { query: Handle, committed: bool, }, + /// Result of a [`SubgroupBallot`] statement. /// /// [`SubgroupBallot`]: Statement::SubgroupBallot SubgroupBallotResult, + /// Result of a [`SubgroupCollectiveOperation`] or [`SubgroupGather`] statement. /// /// [`SubgroupCollectiveOperation`]: Statement::SubgroupCollectiveOperation @@ -1856,7 +2018,12 @@ pub enum Statement { /// Synchronize invocations within the work group. /// The `Barrier` flags control which memory accesses should be synchronized. /// If empty, this becomes purely an execution barrier. - Barrier(Barrier), + ControlBarrier(Barrier), + + /// Synchronize invocations within the work group. + /// The `Barrier` flags control which memory accesses should be synchronized. + MemoryBarrier(Barrier), + /// Stores a value at an address. /// /// For [`TypeInner::Atomic`] type behind the pointer, the value @@ -2044,6 +2211,8 @@ pub enum Statement { /// The specific operation we're performing on `query`. fun: RayQueryFunction, }, + /// A mesh shader intrinsic. + MeshFunction(MeshFunction), /// Calculate a bitmask using a boolean from each active thread in the subgroup SubgroupBallot { /// The [`SubgroupBallotResult`] expression representing this load's result. @@ -2217,6 +2386,12 @@ pub struct EntryPoint { pub workgroup_size_overrides: Option<[Option>; 3]>, /// The entrance function. pub function: Function, + /// Information for [`Mesh`] shaders. + /// + /// [`Mesh`]: ShaderStage::Mesh + pub mesh_info: Option, + /// The unique global variable used as a task payload from task shader to mesh shader + pub task_payload: Option>, } /// Return types predeclared for the frexp, modf, and atomicCompareExchangeWeak built-in functions. @@ -2263,6 +2438,51 @@ pub struct SpecialTypes { /// Call [`Module::generate_vertex_return_type`] pub ray_vertex_return: Option>, + /// Struct containing parameters required by some backends to emit code for + /// [`ImageClass::External`] textures. + /// + /// See `wgpu_core::device::resource::ExternalTextureParams` for the + /// documentation of each field. + /// + /// In WGSL, this type would be: + /// + /// ```ignore + /// struct NagaExternalTextureParams { // align size offset + /// yuv_conversion_matrix: mat4x4, // 16 64 0 + /// gamut_conversion_matrix: mat3x3, // 16 48 64 + /// src_tf: NagaExternalTextureTransferFn, // 4 16 112 + /// dst_tf: NagaExternalTextureTransferFn, // 4 16 128 + /// sample_transform: mat3x2, // 8 24 144 + /// load_transform: mat3x2, // 8 24 168 + /// size: vec2, // 8 8 192 + /// num_planes: u32, // 4 4 200 + /// } // whole struct: 16 208 + /// ``` + /// + /// Call [`Module::generate_external_texture_types`] to populate this if + /// needed. + pub external_texture_params: Option>, + + /// Struct describing a gamma encoding transfer function. Member of + /// `NagaExternalTextureParams`, describing how the backend should perform + /// color space conversion when sampling from [`ImageClass::External`] + /// textures. + /// + /// In WGSL, this type would be: + /// + /// ```ignore + /// struct NagaExternalTextureTransferFn { // align size offset + /// a: f32, // 4 4 0 + /// b: f32, // 4 4 4 + /// g: f32, // 4 4 8 + /// k: f32, // 4 4 12 + /// } // whole struct: 4 16 + /// ``` + /// + /// Call [`Module::generate_external_texture_types`] to populate this if + /// needed. + pub external_texture_transfer_function: Option>, + /// Types for predeclared wgsl types instantiated on demand. /// /// Call [`Module::generate_predeclared_type`] to populate this if @@ -2326,6 +2546,88 @@ pub enum RayQueryIntersection { Aabb = 3, } +/// Doc comments preceding items. +/// +/// These can be used to generate automated documentation, +/// IDE hover information or translate shaders with their context comments. +#[derive(Debug, Default, Clone)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] +pub struct DocComments { + pub types: FastIndexMap, Vec>, + // The key is: + // - key.0: the handle to the Struct + // - key.1: the index of the `StructMember`. + pub struct_members: FastIndexMap<(Handle, usize), Vec>, + pub entry_points: FastIndexMap>, + pub functions: FastIndexMap, Vec>, + pub constants: FastIndexMap, Vec>, + pub global_variables: FastIndexMap, Vec>, + // Top level comments, appearing before any space. + pub module: Vec, +} + +/// The output topology for a mesh shader. Note that mesh shaders don't allow things like triangle-strips. +#[derive(Debug, Clone, Copy)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] +pub enum MeshOutputTopology { + /// Outputs individual vertices to be rendered as points. + Points, + /// Outputs groups of 2 vertices to be renderedas lines . + Lines, + /// Outputs groups of 3 vertices to be rendered as triangles. + Triangles, +} + +/// Information specific to mesh shader entry points. +#[derive(Debug, Clone)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] +#[allow(dead_code)] +pub struct MeshStageInfo { + /// The type of primitive outputted. + pub topology: MeshOutputTopology, + /// The maximum number of vertices a mesh shader may output. + pub max_vertices: u32, + /// If pipeline constants are used, the expressions that override `max_vertices` + pub max_vertices_override: Option>, + /// The maximum number of primitives a mesh shader may output. + pub max_primitives: u32, + /// If pipeline constants are used, the expressions that override `max_primitives` + pub max_primitives_override: Option>, + /// The type used by vertex outputs, i.e. what is passed to `setVertex`. + pub vertex_output_type: Handle, + /// The type used by primitive outputs, i.e. what is passed to `setPrimitive`. + pub primitive_output_type: Handle, +} + +/// Mesh shader intrinsics +#[derive(Debug, Clone, Copy)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr(feature = "arbitrary", derive(Arbitrary))] +pub enum MeshFunction { + /// Sets the number of vertices and primitives that will be outputted. + SetMeshOutputs { + vertex_count: Handle, + primitive_count: Handle, + }, + /// Sets the output vertex at a given index. + SetVertex { + index: Handle, + value: Handle, + }, + /// Sets the output primitive at a given index. + SetPrimitive { + index: Handle, + value: Handle, + }, +} + /// Shader module. /// /// A module is a set of constants, global variables and functions, as well as @@ -2411,4 +2713,6 @@ pub struct Module { /// See [`DiagnosticFilterNode`] for details on how the tree is represented and used in /// validation. pub diagnostic_filter_leaf: Option>, + /// Doc comments. + pub doc_comments: Option>, } diff --git a/naga/src/keywords/wgsl.rs b/naga/src/keywords/wgsl.rs index 82be25ed4..8ec0dd59c 100644 --- a/naga/src/keywords/wgsl.rs +++ b/naga/src/keywords/wgsl.rs @@ -4,9 +4,8 @@ Keywords for [WGSL][wgsl] (WebGPU Shading Language). [wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html */ -use std::sync::LazyLock; - -use hashbrown::HashSet; +use crate::proc::KeywordSet; +use crate::racy_lock::RacyLock; // https://gpuweb.github.io/gpuweb/wgsl/#keyword-summary // last sync: https://github.com/gpuweb/gpuweb/blob/39f2321f547c8f0b7f473cf1d47fba30b1691303/wgsl/index.bs @@ -37,6 +36,7 @@ pub const RESERVED: &[&str] = &[ "texture_3d", "texture_cube", "texture_cube_array", + "texture_external", "texture_multisampled_2d", "texture_storage_1d", "texture_storage_2d", @@ -238,11 +238,4 @@ pub const RESERVED: &[&str] = &[ /// significant time during [`Namer::reset`](crate::proc::Namer::reset). /// /// See for benchmarks. -pub static RESERVED_SET: LazyLock> = LazyLock::new(|| { - let mut set = HashSet::default(); - set.reserve(RESERVED.len()); - for &word in RESERVED { - set.insert(word); - } - set -}); +pub static RESERVED_SET: RacyLock = RacyLock::new(|| KeywordSet::from_iter(RESERVED)); diff --git a/naga/src/lib.rs b/naga/src/lib.rs index 5000ba57d..af990fb1d 100644 --- a/naga/src/lib.rs +++ b/naga/src/lib.rs @@ -75,7 +75,8 @@ void main() { clippy::derive_partial_eq_without_eq, clippy::needless_borrowed_reference, clippy::single_match, - clippy::enum_variant_names + clippy::enum_variant_names, + clippy::result_large_err )] #![warn( trivial_casts, @@ -100,18 +101,7 @@ void main() { )] #![no_std] -#[cfg(any( - test, - spv_out, - - // Need OnceLock - hlsl_out, - msl_out, - wgsl_out, - - feature = "spv-in", - feature = "wgsl-in" -))] +#[cfg(std)] extern crate std; extern crate alloc; @@ -119,7 +109,6 @@ extern crate alloc; mod arena; pub mod back; pub mod common; -#[cfg(feature = "compact")] pub mod compact; pub mod diagnostic_filter; pub mod error; @@ -128,6 +117,7 @@ pub mod ir; pub mod keywords; mod non_max_u32; pub mod proc; +mod racy_lock; mod span; pub mod valid; diff --git a/naga/src/proc/constant_evaluator.rs b/naga/src/proc/constant_evaluator.rs index 406dbbef5..1e0c5ac15 100644 --- a/naga/src/proc/constant_evaluator.rs +++ b/naga/src/proc/constant_evaluator.rs @@ -268,6 +268,392 @@ gen_component_wise_extractor! { ], } +/// Vectors with a concrete element type. +#[derive(Debug)] +enum LiteralVector { + F64(ArrayVec), + F32(ArrayVec), + F16(ArrayVec), + U32(ArrayVec), + I32(ArrayVec), + U64(ArrayVec), + I64(ArrayVec), + Bool(ArrayVec), + AbstractInt(ArrayVec), + AbstractFloat(ArrayVec), +} + +impl LiteralVector { + #[allow(clippy::missing_const_for_fn, reason = "MSRV")] + fn len(&self) -> usize { + match *self { + LiteralVector::F64(ref v) => v.len(), + LiteralVector::F32(ref v) => v.len(), + LiteralVector::F16(ref v) => v.len(), + LiteralVector::U32(ref v) => v.len(), + LiteralVector::I32(ref v) => v.len(), + LiteralVector::U64(ref v) => v.len(), + LiteralVector::I64(ref v) => v.len(), + LiteralVector::Bool(ref v) => v.len(), + LiteralVector::AbstractInt(ref v) => v.len(), + LiteralVector::AbstractFloat(ref v) => v.len(), + } + } + + /// Creates [`LiteralVector`] of size 1 from single [`Literal`] + fn from_literal(literal: Literal) -> Self { + match literal { + Literal::F64(e) => Self::F64(ArrayVec::from_iter(iter::once(e))), + Literal::F32(e) => Self::F32(ArrayVec::from_iter(iter::once(e))), + Literal::U32(e) => Self::U32(ArrayVec::from_iter(iter::once(e))), + Literal::I32(e) => Self::I32(ArrayVec::from_iter(iter::once(e))), + Literal::U64(e) => Self::U64(ArrayVec::from_iter(iter::once(e))), + Literal::I64(e) => Self::I64(ArrayVec::from_iter(iter::once(e))), + Literal::Bool(e) => Self::Bool(ArrayVec::from_iter(iter::once(e))), + Literal::AbstractInt(e) => Self::AbstractInt(ArrayVec::from_iter(iter::once(e))), + Literal::AbstractFloat(e) => Self::AbstractFloat(ArrayVec::from_iter(iter::once(e))), + Literal::F16(e) => Self::F16(ArrayVec::from_iter(iter::once(e))), + } + } + + /// Creates [`LiteralVector`] from [`ArrayVec`] of [`Literal`]s. + /// Returns error if components types do not match. + /// # Panics + /// Panics if vector is empty + fn from_literal_vec( + components: ArrayVec, + ) -> Result { + assert!(!components.is_empty()); + Ok(match components[0] { + Literal::I32(_) => Self::I32( + components + .iter() + .map(|l| match l { + &Literal::I32(v) => Ok(v), + // TODO: should we handle abstract int here? + _ => Err(ConstantEvaluatorError::InvalidMathArg), + }) + .collect::>()?, + ), + Literal::U32(_) => Self::U32( + components + .iter() + .map(|l| match l { + &Literal::U32(v) => Ok(v), + _ => Err(ConstantEvaluatorError::InvalidMathArg), + }) + .collect::>()?, + ), + Literal::I64(_) => Self::I64( + components + .iter() + .map(|l| match l { + &Literal::I64(v) => Ok(v), + _ => Err(ConstantEvaluatorError::InvalidMathArg), + }) + .collect::>()?, + ), + Literal::U64(_) => Self::U64( + components + .iter() + .map(|l| match l { + &Literal::U64(v) => Ok(v), + _ => Err(ConstantEvaluatorError::InvalidMathArg), + }) + .collect::>()?, + ), + Literal::F32(_) => Self::F32( + components + .iter() + .map(|l| match l { + &Literal::F32(v) => Ok(v), + _ => Err(ConstantEvaluatorError::InvalidMathArg), + }) + .collect::>()?, + ), + Literal::F64(_) => Self::F64( + components + .iter() + .map(|l| match l { + &Literal::F64(v) => Ok(v), + _ => Err(ConstantEvaluatorError::InvalidMathArg), + }) + .collect::>()?, + ), + Literal::Bool(_) => Self::Bool( + components + .iter() + .map(|l| match l { + &Literal::Bool(v) => Ok(v), + _ => Err(ConstantEvaluatorError::InvalidMathArg), + }) + .collect::>()?, + ), + Literal::AbstractInt(_) => Self::AbstractInt( + components + .iter() + .map(|l| match l { + &Literal::AbstractInt(v) => Ok(v), + _ => Err(ConstantEvaluatorError::InvalidMathArg), + }) + .collect::>()?, + ), + Literal::AbstractFloat(_) => Self::AbstractFloat( + components + .iter() + .map(|l| match l { + &Literal::AbstractFloat(v) => Ok(v), + _ => Err(ConstantEvaluatorError::InvalidMathArg), + }) + .collect::>()?, + ), + Literal::F16(_) => Self::F16( + components + .iter() + .map(|l| match l { + &Literal::F16(v) => Ok(v), + _ => Err(ConstantEvaluatorError::InvalidMathArg), + }) + .collect::>()?, + ), + }) + } + + #[allow(dead_code)] + /// Returns [`ArrayVec`] of [`Literal`]s + fn to_literal_vec(&self) -> ArrayVec { + match *self { + LiteralVector::F64(ref v) => v.iter().map(|e| Literal::F64(*e)).collect(), + LiteralVector::F32(ref v) => v.iter().map(|e| Literal::F32(*e)).collect(), + LiteralVector::F16(ref v) => v.iter().map(|e| Literal::F16(*e)).collect(), + LiteralVector::U32(ref v) => v.iter().map(|e| Literal::U32(*e)).collect(), + LiteralVector::I32(ref v) => v.iter().map(|e| Literal::I32(*e)).collect(), + LiteralVector::U64(ref v) => v.iter().map(|e| Literal::U64(*e)).collect(), + LiteralVector::I64(ref v) => v.iter().map(|e| Literal::I64(*e)).collect(), + LiteralVector::Bool(ref v) => v.iter().map(|e| Literal::Bool(*e)).collect(), + LiteralVector::AbstractInt(ref v) => { + v.iter().map(|e| Literal::AbstractInt(*e)).collect() + } + LiteralVector::AbstractFloat(ref v) => { + v.iter().map(|e| Literal::AbstractFloat(*e)).collect() + } + } + } + + #[allow(dead_code)] + /// Puts self into eval's expressions arena and returns handle to it + fn register_as_evaluated_expr( + &self, + eval: &mut ConstantEvaluator<'_>, + span: Span, + ) -> Result, ConstantEvaluatorError> { + let lit_vec = self.to_literal_vec(); + assert!(!lit_vec.is_empty()); + let expr = if lit_vec.len() == 1 { + Expression::Literal(lit_vec[0]) + } else { + Expression::Compose { + ty: eval.types.insert( + Type { + name: None, + inner: TypeInner::Vector { + size: match lit_vec.len() { + 2 => crate::VectorSize::Bi, + 3 => crate::VectorSize::Tri, + 4 => crate::VectorSize::Quad, + _ => unreachable!(), + }, + scalar: lit_vec[0].scalar(), + }, + }, + Span::UNDEFINED, + ), + components: lit_vec + .iter() + .map(|&l| eval.register_evaluated_expr(Expression::Literal(l), span)) + .collect::>()?, + } + }; + eval.register_evaluated_expr(expr, span) + } +} + +/// A macro for matching on [`LiteralVector`] variants. +/// +/// `Float` variant expands to `F16`, `F32`, `F64` and `AbstractFloat`. +/// `Integer` variant expands to `I32`, `I64`, `U32`, `U64` and `AbstractInt`. +/// +/// For output both [`Literal`] (fold) and [`LiteralVector`] (map) are supported. +/// +/// Example usage: +/// +/// ```rust,ignore +/// match_literal_vector!(match v => Literal { +/// F16 => |v| {v.sum()}, +/// Integer => |v| {v.sum()}, +/// U32 => |v| -> I32 {v.sum()}, // optionally override return type +/// }) +/// ``` +/// +/// ```rust,ignore +/// match_literal_vector!(match (e1, e2) => LiteralVector { +/// F16 => |e1, e2| {e1+e2}, +/// Integer => |e1, e2| {e1+e2}, +/// U32 => |e1, e2| -> I32 {e1+e2}, // optionally override return type +/// }) +/// ``` +macro_rules! match_literal_vector { + (match $lit_vec:expr => $out:ident { + $( + $ty:ident => |$($var:ident),+| $(-> $ret:ident)? { $body:expr } + ),+ + $(,)? + }) => { + match_literal_vector!(@inner_start $lit_vec; $out; [$($ty),+]; [$({ $($var),+ ; $($ret)? ; $body }),+]) + }; + + (@inner_start + $lit_vec:expr; + $out:ident; + [$($ty:ident),+]; + [$({ $($var:ident),+ ; $($ret:ident)? ; $body:expr }),+] + ) => { + match_literal_vector!(@inner + $lit_vec; + $out; + [$($ty),+]; + [] <> [$({ $($var),+ ; $($ret)? ; $body }),+] + ) + }; + + (@inner + $lit_vec:expr; + $out:ident; + [$ty:ident $(, $ty1:ident)*]; + [$({$_ty:ident ; $($_var:ident),+ ; $($_ret:ident)? ; $_body:expr}),*] <> + [$({ $($var:ident),+ ; $($ret:ident)? ; $body:expr }),+] + ) => { + match_literal_vector!(@inner + $ty; + $lit_vec; + $out; + [$($ty1),*]; + [$({$_ty ; $($_var),+ ; $($_ret)? ; $_body}),*] <> + [$({ $($var),+ ; $($ret)? ; $body }),+] + ) + }; + (@inner + Integer; + $lit_vec:expr; + $out:ident; + [$($ty:ident),*]; + [$({$_ty:ident ; $($_var:ident),+ ; $($_ret:ident)? ; $_body:expr}),*] <> + [ + { $($var:ident),+ ; $($ret:ident)? ; $body:expr } + $(,{ $($var1:ident),+ ; $($ret1:ident)? ; $body1:expr })* + ] + ) => { + match_literal_vector!(@inner + $lit_vec; + $out; + [U32, I32, U64, I64, AbstractInt $(, $ty)*]; + [$({$_ty ; $($_var),+ ; $($_ret)? ; $_body}),*] <> + [ + { $($var),+ ; $($ret)? ; $body }, // U32 + { $($var),+ ; $($ret)? ; $body }, // I32 + { $($var),+ ; $($ret)? ; $body }, // U64 + { $($var),+ ; $($ret)? ; $body }, // I64 + { $($var),+ ; $($ret)? ; $body } // AbstractInt + $(,{ $($var1),+ ; $($ret1)? ; $body1 })* + ] + ) + }; + (@inner + Float; + $lit_vec:expr; + $out:ident; + [$($ty:ident),*]; + [$({$_ty:ident ; $($_var:ident),+ ; $($_ret:ident)? ; $_body:expr}),*] <> + [ + { $($var:ident),+ ; $($ret:ident)? ; $body:expr } + $(,{ $($var1:ident),+ ; $($ret1:ident)? ; $body1:expr })* + ] + ) => { + match_literal_vector!(@inner + $lit_vec; + $out; + [F16, F32, F64, AbstractFloat $(, $ty)*]; + [$({$_ty ; $($_var),+ ; $($_ret)? ; $_body}),*] <> + [ + { $($var),+ ; $($ret)? ; $body }, // F16 + { $($var),+ ; $($ret)? ; $body }, // F32 + { $($var),+ ; $($ret)? ; $body }, // F64 + { $($var),+ ; $($ret)? ; $body } // AbstractFloat + $(,{ $($var1),+ ; $($ret1)? ; $body1 })* + ] + ) + }; + (@inner + $ty:ident; + $lit_vec:expr; + $out:ident; + [$ty1:ident $(,$ty2:ident)*]; + [$({$_ty:ident ; $($_var:ident),+ ; $($_ret:ident)? ; $_body:expr}),*] <> [ + { $($var:ident),+ ; $($ret:ident)? ; $body:expr } + $(, { $($var1:ident),+ ; $($ret1:ident)? ; $body1:expr })* + ] + ) => { + match_literal_vector!(@inner + $ty1; + $lit_vec; + $out; + [$($ty2),*]; + [ + $({$_ty ; $($_var),+ ; $($_ret)? ; $_body},)* + { $ty; $($var),+ ; $($ret)? ; $body } + ] <> + [$({ $($var1),+ ; $($ret1)? ; $body1 }),*] + + ) + }; + (@inner + $ty:ident; + $lit_vec:expr; + $out:ident; + []; + [$({$_ty:ident ; $($_var:ident),+ ; $($_ret:ident)? ; $_body:expr}),*] <> + [{ $($var:ident),+ ; $($ret:ident)? ; $body:expr }] + ) => { + match_literal_vector!(@inner_finish + $lit_vec; + $out; + [ + $({ $_ty ; $($_var),+ ; $($_ret)? ; $_body },)* + { $ty; $($var),+ ; $($ret)? ; $body } + ] + ) + }; + (@inner_finish + $lit_vec:expr; + $out:ident; + [$({$ty:ident ; $($var:ident),+ ; $($ret:ident)? ; $body:expr}),+] + ) => { + match $lit_vec { + $( + #[allow(unused_parens)] + ($(LiteralVector::$ty(ref $var)),+) => { Ok(match_literal_vector!(@expand_ret $out; $ty $(; $ret)? ; $body)) } + )+ + _ => Err(ConstantEvaluatorError::InvalidMathArg), + } + }; + (@expand_ret $out:ident; $ty:ident; $body:expr) => { + $out::$ty($body) + }; + (@expand_ret $out:ident; $_ty:ident; $ret:ident; $body:expr) => { + $out::$ret($body) + }; +} + #[derive(Debug)] enum Behavior<'a> { Wgsl(WgslRestrictions<'a>), @@ -363,8 +749,6 @@ struct FunctionLocalData<'a> { #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] pub enum ExpressionKind { - /// If const is also implemented as const - ImplConst, Const, Override, Runtime, @@ -392,21 +776,13 @@ impl ExpressionKindTracker { } pub fn is_const(&self, h: Handle) -> bool { - matches!( - self.type_of(h), - ExpressionKind::Const | ExpressionKind::ImplConst - ) - } - - /// Returns `true` if naga can also evaluate expression as const - pub fn is_impl_const(&self, h: Handle) -> bool { - matches!(self.type_of(h), ExpressionKind::ImplConst) + matches!(self.type_of(h), ExpressionKind::Const) } pub fn is_const_or_override(&self, h: Handle) -> bool { matches!( self.type_of(h), - ExpressionKind::Const | ExpressionKind::Override | ExpressionKind::ImplConst + ExpressionKind::Const | ExpressionKind::Override ) } @@ -427,14 +803,13 @@ impl ExpressionKindTracker { } fn type_of_with_expr(&self, expr: &Expression) -> ExpressionKind { - use crate::MathFunction as Mf; match *expr { Expression::Literal(_) | Expression::ZeroValue(_) | Expression::Constant(_) => { - ExpressionKind::ImplConst + ExpressionKind::Const } Expression::Override(_) => ExpressionKind::Override, Expression::Compose { ref components, .. } => { - let mut expr_type = ExpressionKind::ImplConst; + let mut expr_type = ExpressionKind::Const; for component in components { expr_type = expr_type.max(self.type_of(*component)) } @@ -445,16 +820,13 @@ impl ExpressionKindTracker { Expression::Access { base, index } => self.type_of(base).max(self.type_of(index)), Expression::Swizzle { vector, .. } => self.type_of(vector), Expression::Unary { expr, .. } => self.type_of(expr), - Expression::Binary { left, right, .. } => self - .type_of(left) - .max(self.type_of(right)) - .max(ExpressionKind::Const), + Expression::Binary { left, right, .. } => self.type_of(left).max(self.type_of(right)), Expression::Math { - fun, arg, arg1, arg2, arg3, + .. } => self .type_of(arg) .max( @@ -468,33 +840,8 @@ impl ExpressionKindTracker { .max( arg3.map(|arg| self.type_of(arg)) .unwrap_or(ExpressionKind::Const), - ) - .max( - if matches!( - fun, - Mf::Dot - | Mf::Outer - | Mf::Distance - | Mf::Length - | Mf::Normalize - | Mf::FaceForward - | Mf::Reflect - | Mf::Refract - | Mf::Ldexp - | Mf::Modf - | Mf::Mix - | Mf::Frexp - ) { - ExpressionKind::Const - } else { - ExpressionKind::ImplConst - }, ), - Expression::As { convert, expr, .. } => self.type_of(expr).max(if convert.is_some() { - ExpressionKind::ImplConst - } else { - ExpressionKind::Const - }), + Expression::As { expr, .. } => self.type_of(expr), Expression::Select { condition, accept, @@ -502,8 +849,7 @@ impl ExpressionKindTracker { } => self .type_of(condition) .max(self.type_of(accept)) - .max(self.type_of(reject)) - .max(ExpressionKind::Const), + .max(self.type_of(reject)), Expression::Relational { argument, .. } => self.type_of(argument), Expression::ArrayLength(expr) => self.type_of(expr), _ => ExpressionKind::Runtime, @@ -603,6 +949,27 @@ pub enum ConstantEvaluatorError { RuntimeExpr, #[error("Unexpected override-expression")] OverrideExpr, + #[error("Expected boolean expression for condition argument of `select`, got something else")] + SelectScalarConditionNotABool, + #[error( + "Expected vectors of the same size for reject and accept args., got {:?} and {:?}", + reject, + accept + )] + SelectVecRejectAcceptSizeMismatch { + reject: crate::VectorSize, + accept: crate::VectorSize, + }, + #[error("Expected boolean vector for condition arg., got something else")] + SelectConditionNotAVecBool, + #[error( + "Expected same number of vector components between condition, accept, and reject args., got something else", + )] + SelectConditionVecSizeMismatch, + #[error( + "Expected reject and accept args. to be scalars of vectors of the same type, got something else", + )] + SelectAcceptRejectTypeMismatch, } impl<'a> ConstantEvaluator<'a> { @@ -722,7 +1089,7 @@ impl<'a> ConstantEvaluator<'a> { } } - pub fn to_ctx(&self) -> crate::proc::GlobalCtx { + pub fn to_ctx(&self) -> crate::proc::GlobalCtx<'_> { crate::proc::GlobalCtx { types: self.types, constants: self.constants, @@ -797,7 +1164,6 @@ impl<'a> ConstantEvaluator<'a> { span: Span, ) -> Result, ConstantEvaluatorError> { match self.expression_kind_tracker.type_of_with_expr(&expr) { - ExpressionKind::ImplConst => self.try_eval_and_append_impl(&expr, span), ExpressionKind::Const => { let eval_result = self.try_eval_and_append_impl(&expr, span); // We should be able to evaluate `Const` expressions at this @@ -864,7 +1230,7 @@ impl<'a> ConstantEvaluator<'a> { expr: &Expression, span: Span, ) -> Result, ConstantEvaluatorError> { - log::trace!("try_eval_and_append: {:?}", expr); + log::trace!("try_eval_and_append: {expr:?}"); match *expr { Expression::Constant(c) if self.is_global_arena() => { // "See through" the constant and use its initializer. @@ -945,9 +1311,19 @@ impl<'a> ConstantEvaluator<'a> { )), } } - Expression::Select { .. } => Err(ConstantEvaluatorError::NotImplemented( - "select built-in function".into(), - )), + Expression::Select { + reject, + accept, + condition, + } => { + let mut arg = |expr| self.check_and_get(expr); + + let reject = arg(reject)?; + let accept = arg(accept)?; + let condition = arg(condition)?; + + self.select(reject, accept, condition, span) + } Expression::Relational { fun, argument } => { let argument = self.check_and_get(argument)?; self.relational(fun, argument, span) @@ -1121,7 +1497,7 @@ impl<'a> ConstantEvaluator<'a> { Scalar::AbstractFloat([e]) => Ok(Scalar::AbstractFloat([e.abs()])), Scalar::F32([e]) => Ok(Scalar::F32([e.abs()])), Scalar::F16([e]) => Ok(Scalar::F16([e.abs()])), - Scalar::AbstractInt([e]) => Ok(Scalar::AbstractInt([e.abs()])), + Scalar::AbstractInt([e]) => Ok(Scalar::AbstractInt([e.wrapping_abs()])), Scalar::I32([e]) => Ok(Scalar::I32([e.wrapping_abs()])), Scalar::U32([e]) => Ok(Scalar::U32([e])), // TODO: just re-use the expression, ezpz Scalar::I64([e]) => Ok(Scalar::I64([e.wrapping_abs()])), @@ -1188,6 +1564,11 @@ impl<'a> ConstantEvaluator<'a> { crate::MathFunction::Atan => { component_wise_float!(self, span, [arg], |e| { Ok([e.atan()]) }) } + crate::MathFunction::Atan2 => { + component_wise_float!(self, span, [arg, arg1.unwrap()], |y, x| { + Ok([y.atan2(x)]) + }) + } crate::MathFunction::Asinh => { component_wise_float!(self, span, [arg], |e| { Ok([e.asinh()]) }) } @@ -1213,8 +1594,8 @@ impl<'a> ConstantEvaluator<'a> { } crate::MathFunction::Round => { component_wise_float(self, span, [arg], |e| match e { - Float::Abstract([e]) => Ok(Float::Abstract([e.round_ties_even()])), - Float::F32([e]) => Ok(Float::F32([e.round_ties_even()])), + Float::Abstract([e]) => Ok(Float::Abstract([libm::rint(e)])), + Float::F32([e]) => Ok(Float::F32([libm::rintf(e)])), Float::F16([e]) => { // TODO: `round_ties_even` is not available on `half::f16` yet. // @@ -1347,14 +1728,178 @@ impl<'a> ConstantEvaluator<'a> { } // vector + crate::MathFunction::Dot4I8Packed => { + self.packed_dot_product(arg, arg1.unwrap(), span, true) + } + crate::MathFunction::Dot4U8Packed => { + self.packed_dot_product(arg, arg1.unwrap(), span, false) + } crate::MathFunction::Cross => self.cross_product(arg, arg1.unwrap(), span), + crate::MathFunction::Dot => { + // https://www.w3.org/TR/WGSL/#dot-builtin + let e1 = self.extract_vec(arg, false)?; + let e2 = self.extract_vec(arg1.unwrap(), false)?; + if e1.len() != e2.len() { + return Err(ConstantEvaluatorError::InvalidMathArg); + } - fun => Err(ConstantEvaluatorError::NotImplemented(format!( - "{fun:?} built-in function" - ))), + fn int_dot

(a: &[P], b: &[P]) -> Result + where + P: num_traits::PrimInt + num_traits::CheckedAdd + num_traits::CheckedMul, + { + a.iter() + .zip(b.iter()) + .map(|(&aa, bb)| aa.checked_mul(bb)) + .try_fold(P::zero(), |acc, x| { + if let Some(x) = x { + acc.checked_add(&x) + } else { + None + } + }) + .ok_or(ConstantEvaluatorError::Overflow( + "in dot built-in".to_string(), + )) + } + + let result = match_literal_vector!(match (e1, e2) => Literal { + Float => |e1, e2| { e1.iter().zip(e2.iter()).map(|(&aa, &bb)| aa * bb).sum() }, + Integer => |e1, e2| { int_dot(e1, e2)? }, + })?; + self.register_evaluated_expr(Expression::Literal(result), span) + } + crate::MathFunction::Length => { + // https://www.w3.org/TR/WGSL/#length-builtin + let e1 = self.extract_vec(arg, true)?; + + fn float_length(e: &[F]) -> F + where + F: core::ops::Mul, + F: num_traits::Float + iter::Sum, + { + e.iter().map(|&ei| ei * ei).sum::().sqrt() + } + + let result = match_literal_vector!(match e1 => Literal { + Float => |e1| { float_length(e1) }, + })?; + self.register_evaluated_expr(Expression::Literal(result), span) + } + crate::MathFunction::Distance => { + // https://www.w3.org/TR/WGSL/#distance-builtin + let e1 = self.extract_vec(arg, true)?; + let e2 = self.extract_vec(arg1.unwrap(), true)?; + if e1.len() != e2.len() { + return Err(ConstantEvaluatorError::InvalidMathArg); + } + + fn float_distance(a: &[F], b: &[F]) -> F + where + F: core::ops::Mul, + F: num_traits::Float + iter::Sum + core::ops::Sub, + { + a.iter() + .zip(b.iter()) + .map(|(&aa, &bb)| aa - bb) + .map(|ei| ei * ei) + .sum::() + .sqrt() + } + let result = match_literal_vector!(match (e1, e2) => Literal { + Float => |e1, e2| { float_distance(e1, e2) }, + })?; + self.register_evaluated_expr(Expression::Literal(result), span) + } + crate::MathFunction::Normalize => { + // https://www.w3.org/TR/WGSL/#normalize-builtin + let e1 = self.extract_vec(arg, true)?; + + fn float_normalize(e: &[F]) -> ArrayVec + where + F: core::ops::Mul, + F: num_traits::Float + iter::Sum, + { + let len = e.iter().map(|&ei| ei * ei).sum::().sqrt(); + e.iter().map(|&ei| ei / len).collect() + } + + let result = match_literal_vector!(match e1 => LiteralVector { + Float => |e1| { float_normalize(e1) }, + })?; + result.register_as_evaluated_expr(self, span) + } + + // unimplemented + crate::MathFunction::Modf + | crate::MathFunction::Frexp + | crate::MathFunction::Ldexp + | crate::MathFunction::Outer + | crate::MathFunction::FaceForward + | crate::MathFunction::Reflect + | crate::MathFunction::Refract + | crate::MathFunction::Mix + | crate::MathFunction::SmoothStep + | crate::MathFunction::Inverse + | crate::MathFunction::Transpose + | crate::MathFunction::Determinant + | crate::MathFunction::QuantizeToF16 + | crate::MathFunction::ExtractBits + | crate::MathFunction::InsertBits + | crate::MathFunction::Pack4x8snorm + | crate::MathFunction::Pack4x8unorm + | crate::MathFunction::Pack2x16snorm + | crate::MathFunction::Pack2x16unorm + | crate::MathFunction::Pack2x16float + | crate::MathFunction::Pack4xI8 + | crate::MathFunction::Pack4xU8 + | crate::MathFunction::Pack4xI8Clamp + | crate::MathFunction::Pack4xU8Clamp + | crate::MathFunction::Unpack4x8snorm + | crate::MathFunction::Unpack4x8unorm + | crate::MathFunction::Unpack2x16snorm + | crate::MathFunction::Unpack2x16unorm + | crate::MathFunction::Unpack2x16float + | crate::MathFunction::Unpack4xI8 + | crate::MathFunction::Unpack4xU8 => Err(ConstantEvaluatorError::NotImplemented( + format!("{fun:?} built-in function"), + )), } } + /// Dot product of two packed vectors (`dot4I8Packed` and `dot4U8Packed`) + fn packed_dot_product( + &mut self, + a: Handle, + b: Handle, + span: Span, + signed: bool, + ) -> Result, ConstantEvaluatorError> { + let Expression::Literal(Literal::U32(a)) = self.expressions[a] else { + return Err(ConstantEvaluatorError::InvalidMathArg); + }; + let Expression::Literal(Literal::U32(b)) = self.expressions[b] else { + return Err(ConstantEvaluatorError::InvalidMathArg); + }; + + let result = if signed { + Literal::I32( + (a & 0xFF) as i8 as i32 * (b & 0xFF) as i8 as i32 + + ((a >> 8) & 0xFF) as i8 as i32 * ((b >> 8) & 0xFF) as i8 as i32 + + ((a >> 16) & 0xFF) as i8 as i32 * ((b >> 16) & 0xFF) as i8 as i32 + + ((a >> 24) & 0xFF) as i8 as i32 * ((b >> 24) & 0xFF) as i8 as i32, + ) + } else { + Literal::U32( + (a & 0xFF) * (b & 0xFF) + + ((a >> 8) & 0xFF) * ((b >> 8) & 0xFF) + + ((a >> 16) & 0xFF) * ((b >> 16) & 0xFF) + + ((a >> 24) & 0xFF) * ((b >> 24) & 0xFF), + ) + }; + + self.register_evaluated_expr(Expression::Literal(result), span) + } + /// Vector cross product. fn cross_product( &mut self, @@ -1364,8 +1909,8 @@ impl<'a> ConstantEvaluator<'a> { ) -> Result, ConstantEvaluatorError> { use Literal as Li; - let (a, ty) = self.extract_vec::<3>(a)?; - let (b, _) = self.extract_vec::<3>(b)?; + let (a, ty) = self.extract_vec_with_size::<3>(a)?; + let (b, _) = self.extract_vec_with_size::<3>(b)?; let product = match (a, b) { ( @@ -1432,7 +1977,7 @@ impl<'a> ConstantEvaluator<'a> { /// values. /// /// Also return the type handle from the `Compose` expression. - fn extract_vec( + fn extract_vec_with_size( &mut self, expr: Handle, ) -> Result<([Literal; N], Handle), ConstantEvaluatorError> { @@ -1456,6 +2001,39 @@ impl<'a> ConstantEvaluator<'a> { Ok((value, ty)) } + /// Extract the values of a `vecN` from `expr`. + /// + /// Return the value of `expr`, whose type is `vecN` for some + /// vector size `N` and scalar `S`, as an array of `N` [`Literal`] + /// values. + /// + /// Also return the type handle from the `Compose` expression. + fn extract_vec( + &mut self, + expr: Handle, + allow_single: bool, + ) -> Result { + let span = self.expressions.get_span(expr); + let expr = self.eval_zero_value_and_splat(expr, span)?; + + match self.expressions[expr] { + Expression::Literal(literal) if allow_single => { + Ok(LiteralVector::from_literal(literal)) + } + Expression::Compose { ty, ref components } => { + let components: ArrayVec = + crate::proc::flatten_compose(ty, components, self.expressions, self.types) + .map(|expr| match self.expressions[expr] { + Expression::Literal(l) => Ok(l), + _ => Err(ConstantEvaluatorError::InvalidMathArg), + }) + .collect::>()?; + LiteralVector::from_literal_vec(components) + } + _ => Err(ConstantEvaluatorError::InvalidMathArg), + } + } + fn array_length( &mut self, array: Handle, @@ -1810,6 +2388,10 @@ impl<'a> ConstantEvaluator<'a> { Literal::AbstractFloat(v) => v, _ => return make_error(), }), + Sc::ABSTRACT_INT => Literal::AbstractInt(match literal { + Literal::AbstractInt(v) => v, + _ => return make_error(), + }), _ => { log::debug!("Constant evaluator refused to convert value to {target:?}"); return make_error(); @@ -2268,10 +2850,13 @@ impl<'a> ConstantEvaluator<'a> { | BinaryOperator::And | BinaryOperator::ExclusiveOr | BinaryOperator::InclusiveOr - | BinaryOperator::LogicalAnd - | BinaryOperator::LogicalOr | BinaryOperator::ShiftLeft | BinaryOperator::ShiftRight => left_ty, + + BinaryOperator::LogicalAnd | BinaryOperator::LogicalOr => { + // Not supported on vectors + return Err(ConstantEvaluatorError::InvalidBinaryOpArgs); + } }; let components = components @@ -2459,6 +3044,116 @@ impl<'a> ConstantEvaluator<'a> { Ok(resolution) } + + fn select( + &mut self, + reject: Handle, + accept: Handle, + condition: Handle, + span: Span, + ) -> Result, ConstantEvaluatorError> { + let mut arg = |arg| self.eval_zero_value_and_splat(arg, span); + + let reject = arg(reject)?; + let accept = arg(accept)?; + let condition = arg(condition)?; + + let select_single_component = + |this: &mut Self, reject_scalar, reject, accept, condition| { + let accept = this.cast(accept, reject_scalar, span)?; + if condition { + Ok(accept) + } else { + Ok(reject) + } + }; + + match (&self.expressions[reject], &self.expressions[accept]) { + (&Expression::Literal(reject_lit), &Expression::Literal(_accept_lit)) => { + let reject_scalar = reject_lit.scalar(); + let &Expression::Literal(Literal::Bool(condition)) = &self.expressions[condition] + else { + return Err(ConstantEvaluatorError::SelectScalarConditionNotABool); + }; + select_single_component(self, reject_scalar, reject, accept, condition) + } + ( + &Expression::Compose { + ty: reject_ty, + components: ref reject_components, + }, + &Expression::Compose { + ty: accept_ty, + components: ref accept_components, + }, + ) => { + let ty_deets = |ty| { + let (size, scalar) = self.types[ty].inner.vector_size_and_scalar().unwrap(); + (size.unwrap(), scalar) + }; + + let expected_vec_size = { + let [(reject_vec_size, _), (accept_vec_size, _)] = + [reject_ty, accept_ty].map(ty_deets); + + if reject_vec_size != accept_vec_size { + return Err(ConstantEvaluatorError::SelectVecRejectAcceptSizeMismatch { + reject: reject_vec_size, + accept: accept_vec_size, + }); + } + reject_vec_size + }; + + let condition_components = match self.expressions[condition] { + Expression::Literal(Literal::Bool(condition)) => { + vec![condition; (expected_vec_size as u8).into()] + } + Expression::Compose { + ty: condition_ty, + components: ref condition_components, + } => { + let (condition_vec_size, condition_scalar) = ty_deets(condition_ty); + if condition_scalar.kind != ScalarKind::Bool { + return Err(ConstantEvaluatorError::SelectConditionNotAVecBool); + } + if condition_vec_size != expected_vec_size { + return Err(ConstantEvaluatorError::SelectConditionVecSizeMismatch); + } + condition_components + .iter() + .copied() + .map(|component| match &self.expressions[component] { + &Expression::Literal(Literal::Bool(condition)) => condition, + _ => unreachable!(), + }) + .collect() + } + + _ => return Err(ConstantEvaluatorError::SelectConditionNotAVecBool), + }; + + let evaluated = Expression::Compose { + ty: reject_ty, + components: reject_components + .clone() + .into_iter() + .zip(accept_components.clone().into_iter()) + .zip(condition_components.into_iter()) + .map(|((reject, accept), condition)| { + let reject_scalar = match &self.expressions[reject] { + &Expression::Literal(lit) => lit.scalar(), + _ => unreachable!(), + }; + select_single_component(self, reject_scalar, reject, accept, condition) + }) + .collect::>()?, + }; + self.register_evaluated_expr(evaluated, span) + } + _ => Err(ConstantEvaluatorError::SelectAcceptRejectTypeMismatch), + } + } } fn first_trailing_bit(concrete_int: ConcreteInt<1>) -> ConcreteInt<1> { @@ -2633,11 +3328,11 @@ fn first_leading_bit_smoke() { trait TryFromAbstract: Sized { /// Convert an abstract literal `value` to `Self`. /// - /// Since Naga's `AbstractInt` and `AbstractFloat` exist to support + /// Since Naga's [`AbstractInt`] and [`AbstractFloat`] exist to support /// WGSL, we follow WGSL's conversion rules here: /// /// - WGSL §6.1.2. Conversion Rank says that automatic conversions - /// from `AbstractInt` to an integer type are either lossless or an + /// from [`AbstractInt`] to an integer type are either lossless or an /// error. /// /// - WGSL §15.7.6 Floating Point Conversion says that conversions @@ -2651,7 +3346,7 @@ trait TryFromAbstract: Sized { /// conversion from AbstractFloat to integer types. /// /// [`AbstractInt`]: crate::Literal::AbstractInt - /// [`Float`]: crate::Literal::Float + /// [`AbstractFloat`]: crate::Literal::AbstractFloat fn try_from_abstract(value: T) -> Result; } diff --git a/naga/src/proc/index.rs b/naga/src/proc/index.rs index 9f1c0ddb7..87eaac777 100644 --- a/naga/src/proc/index.rs +++ b/naga/src/proc/index.rs @@ -2,8 +2,10 @@ Definitions for index bounds checking. */ +use core::iter::{self, zip}; + use crate::arena::{Handle, HandleSet, UniqueArena}; -use crate::valid; +use crate::{valid, FastHashSet}; /// How should code generated by Naga do bounds checks? /// @@ -97,8 +99,8 @@ pub struct BoundsCheckPolicies { /// /// [`GlobalVariable`]: crate::GlobalVariable /// [`space`]: crate::GlobalVariable::space - /// [`Restrict`]: crate::back::BoundsCheckPolicy::Restrict - /// [`ReadZeroSkipWrite`]: crate::back::BoundsCheckPolicy::ReadZeroSkipWrite + /// [`Restrict`]: crate::proc::BoundsCheckPolicy::Restrict + /// [`ReadZeroSkipWrite`]: crate::proc::BoundsCheckPolicy::ReadZeroSkipWrite /// [`Access`]: crate::Expression::Access /// [`AccessIndex`]: crate::Expression::AccessIndex /// [`Storage`]: crate::AddressSpace::Storage @@ -340,6 +342,128 @@ pub fn access_needs_check( Some(length) } +/// Items returned by the [`bounds_check_iter`] iterator. +#[cfg_attr(not(feature = "msl-out"), allow(dead_code))] +pub(crate) struct BoundsCheck { + /// The base of the [`Access`] or [`AccessIndex`] expression. + /// + /// [`Access`]: crate::Expression::Access + /// [`AccessIndex`]: crate::Expression::AccessIndex + pub base: Handle, + + /// The index being accessed. + pub index: GuardedIndex, + + /// The length of `base`. + pub length: IndexableLength, +} + +/// Returns an iterator of accesses within the chain of `Access` and +/// `AccessIndex` expressions starting from `chain` that may need to be +/// bounds-checked at runtime. +/// +/// Items are yielded as [`BoundsCheck`] instances. +/// +/// Accesses through a struct are omitted, since you never need a bounds check +/// for accessing a struct field. +/// +/// If `chain` isn't an `Access` or `AccessIndex` expression at all, the +/// iterator is empty. +pub(crate) fn bounds_check_iter<'a>( + mut chain: Handle, + module: &'a crate::Module, + function: &'a crate::Function, + info: &'a valid::FunctionInfo, +) -> impl Iterator + 'a { + iter::from_fn(move || { + let (next_expr, result) = match function.expressions[chain] { + crate::Expression::Access { base, index } => { + (base, Some((base, GuardedIndex::Expression(index)))) + } + crate::Expression::AccessIndex { base, index } => { + // Don't try to check indices into structs. Validation already took + // care of them, and access_needs_check doesn't handle that case. + let mut base_inner = info[base].ty.inner_with(&module.types); + if let crate::TypeInner::Pointer { base, .. } = *base_inner { + base_inner = &module.types[base].inner; + } + match *base_inner { + crate::TypeInner::Struct { .. } => (base, None), + _ => (base, Some((base, GuardedIndex::Known(index)))), + } + } + _ => return None, + }; + chain = next_expr; + Some(result) + }) + .flatten() + .filter_map(|(base, index)| { + access_needs_check(base, index, module, &function.expressions, info).map(|length| { + BoundsCheck { + base, + index, + length, + } + }) + }) +} + +/// Returns all the types which we need out-of-bounds locals for; that is, +/// all of the types which the code might attempt to get an out-of-bounds +/// pointer to, in which case we yield a pointer to the out-of-bounds local +/// of the correct type. +pub fn oob_local_types( + module: &crate::Module, + function: &crate::Function, + info: &valid::FunctionInfo, + policies: BoundsCheckPolicies, +) -> FastHashSet> { + let mut result = FastHashSet::default(); + + if policies.index != BoundsCheckPolicy::ReadZeroSkipWrite { + return result; + } + + for statement in &function.body { + // The only situation in which we end up actually needing to create an + // out-of-bounds pointer is when passing one to a function. + // + // This is because pointers are never baked; they're just inlined everywhere + // they're used. That means that loads can just return 0, and stores can just do + // nothing; functions are the only case where you actually *have* to produce a + // pointer. + if let crate::Statement::Call { + function: callee, + ref arguments, + .. + } = *statement + { + // Now go through the arguments of the function looking for pointers which need bounds checks. + for (arg_info, &arg) in zip(&module.functions[callee].arguments, arguments) { + match module.types[arg_info.ty].inner { + crate::TypeInner::ValuePointer { .. } => { + // `ValuePointer`s should only ever be used when resolving the types of + // expressions, since the arena can no longer be modified at that point; things + // in the arena should always use proper `Pointer`s. + unreachable!("`ValuePointer` found in arena") + } + crate::TypeInner::Pointer { base, .. } => { + if bounds_check_iter(arg, module, function, info) + .next() + .is_some() + { + result.insert(base); + } + } + _ => continue, + }; + } + } + } + result +} + impl GuardedIndex { /// Make a `GuardedIndex::Known` from a `GuardedIndex::Expression` if possible. /// diff --git a/naga/src/proc/keyword_set.rs b/naga/src/proc/keyword_set.rs new file mode 100644 index 000000000..c2ad5dd55 --- /dev/null +++ b/naga/src/proc/keyword_set.rs @@ -0,0 +1,178 @@ +use core::{fmt, hash}; + +use crate::racy_lock::RacyLock; +use crate::FastHashSet; + +/// A case-sensitive set of strings, +/// for use with [`Namer`][crate::proc::Namer] to avoid collisions with keywords and other reserved +/// identifiers. +/// +/// This is currently implemented as a hash table. +/// Future versions of Naga may change the implementation based on speed and code size +/// considerations. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct KeywordSet(FastHashSet<&'static str>); + +impl KeywordSet { + /// Returns a new mutable empty set. + pub fn new() -> Self { + Self::default() + } + + /// Returns a reference to the empty set. + pub fn empty() -> &'static Self { + static EMPTY: RacyLock = RacyLock::new(Default::default); + &EMPTY + } + + /// Returns whether the set contains the given string. + #[inline] + pub fn contains(&self, identifier: &str) -> bool { + self.0.contains(identifier) + } +} + +impl Default for &'static KeywordSet { + fn default() -> Self { + KeywordSet::empty() + } +} + +impl FromIterator<&'static str> for KeywordSet { + fn from_iter>(iter: T) -> Self { + Self(iter.into_iter().collect()) + } +} + +/// Accepts double references so that `KeywordSet::from_iter(&["foo"])` works. +impl<'a> FromIterator<&'a &'static str> for KeywordSet { + fn from_iter>(iter: T) -> Self { + Self::from_iter(iter.into_iter().copied()) + } +} + +impl Extend<&'static str> for KeywordSet { + #[expect( + clippy::useless_conversion, + reason = "doing .into_iter() sooner reduces distinct monomorphizations" + )] + fn extend>(&mut self, iter: T) { + self.0.extend(iter.into_iter()) + } +} + +/// Accepts double references so that `.extend(&["foo"])` works. +impl<'a> Extend<&'a &'static str> for KeywordSet { + fn extend>(&mut self, iter: T) { + self.extend(iter.into_iter().copied()) + } +} + +/// A case-insensitive, ASCII-only set of strings, +/// for use with [`Namer`][crate::proc::Namer] to avoid collisions with keywords and other reserved +/// identifiers. +/// +/// This is currently implemented as a hash table. +/// Future versions of Naga may change the implementation based on speed and code size +/// considerations. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct CaseInsensitiveKeywordSet(FastHashSet>); + +impl CaseInsensitiveKeywordSet { + /// Returns a new mutable empty set. + pub fn new() -> Self { + Self::default() + } + + /// Returns a reference to the empty set. + pub fn empty() -> &'static Self { + static EMPTY: RacyLock = RacyLock::new(Default::default); + &EMPTY + } + + /// Returns whether the set contains the given string, with comparison + /// by [`str::eq_ignore_ascii_case()`]. + #[inline] + pub fn contains(&self, identifier: &str) -> bool { + self.0.contains(&AsciiUniCase(identifier)) + } +} + +impl Default for &'static CaseInsensitiveKeywordSet { + fn default() -> Self { + CaseInsensitiveKeywordSet::empty() + } +} + +impl FromIterator<&'static str> for CaseInsensitiveKeywordSet { + fn from_iter>(iter: T) -> Self { + Self( + iter.into_iter() + .inspect(debug_assert_ascii) + .map(AsciiUniCase) + .collect(), + ) + } +} + +/// Accepts double references so that `CaseInsensitiveKeywordSet::from_iter(&["foo"])` works. +impl<'a> FromIterator<&'a &'static str> for CaseInsensitiveKeywordSet { + fn from_iter>(iter: T) -> Self { + Self::from_iter(iter.into_iter().copied()) + } +} + +impl Extend<&'static str> for CaseInsensitiveKeywordSet { + fn extend>(&mut self, iter: T) { + self.0.extend( + iter.into_iter() + .inspect(debug_assert_ascii) + .map(AsciiUniCase), + ) + } +} + +/// Accepts double references so that `.extend(&["foo"])` works. +impl<'a> Extend<&'a &'static str> for CaseInsensitiveKeywordSet { + fn extend>(&mut self, iter: T) { + self.extend(iter.into_iter().copied()) + } +} + +/// A string wrapper type with an ascii case insensitive Eq and Hash impl +#[derive(Clone, Copy)] +struct AsciiUniCase + ?Sized>(S); + +impl> fmt::Debug for AsciiUniCase { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.as_ref().fmt(f) + } +} + +impl> PartialEq for AsciiUniCase { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.0.as_ref().eq_ignore_ascii_case(other.0.as_ref()) + } +} + +impl> Eq for AsciiUniCase {} + +impl> hash::Hash for AsciiUniCase { + #[inline] + fn hash(&self, hasher: &mut H) { + for byte in self + .0 + .as_ref() + .as_bytes() + .iter() + .map(|b| b.to_ascii_lowercase()) + { + hasher.write_u8(byte); + } + } +} + +fn debug_assert_ascii(s: &&'static str) { + debug_assert!(s.is_ascii(), "{s:?} not ASCII") +} diff --git a/naga/src/proc/layouter.rs b/naga/src/proc/layouter.rs index 0001d92f2..204a523c9 100644 --- a/naga/src/proc/layouter.rs +++ b/naga/src/proc/layouter.rs @@ -1,6 +1,9 @@ use core::{fmt::Display, num::NonZeroU32, ops}; -use crate::arena::{Handle, HandleVec}; +use crate::{ + arena::{Handle, HandleVec}, + valid::MAX_TYPE_SIZE, +}; /// A newtype struct where its only valid values are powers of 2 #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)] @@ -121,6 +124,12 @@ impl ops::Index> for Layouter { } } +/// Errors generated by the `Layouter`. +/// +/// All of these errors can be produced when validating an arbitrary module. +/// When processing WGSL source, only the `TooLarge` error should be +/// produced by the `Layouter`, as the front-end should not produce IR +/// that would result in the other errors. #[derive(Clone, Copy, Debug, PartialEq, thiserror::Error)] pub enum LayoutErrorInner { #[error("Array element type {0:?} doesn't exist")] @@ -129,6 +138,8 @@ pub enum LayoutErrorInner { InvalidStructMemberType(u32, Handle), #[error("Type width must be a power of two")] NonPowerOfTwoWidth, + #[error("Size exceeds limit of {MAX_TYPE_SIZE} bytes")] + TooLarge, } #[derive(Clone, Copy, Debug, PartialEq, thiserror::Error)] @@ -168,7 +179,10 @@ impl Layouter { use crate::TypeInner as Ti; for (ty_handle, ty) in gctx.types.iter().skip(self.layouts.len()) { - let size = ty.inner.size(gctx); + let size = ty + .inner + .try_size(gctx) + .ok_or_else(|| LayoutErrorInner::TooLarge.with(ty_handle))?; let layout = match ty.inner { Ti::Scalar(scalar) | Ti::Atomic(scalar) => { let alignment = Alignment::new(scalar.width as u32) diff --git a/naga/src/proc/mod.rs b/naga/src/proc/mod.rs index 787a2f1a6..eca63ee4f 100644 --- a/naga/src/proc/mod.rs +++ b/naga/src/proc/mod.rs @@ -5,8 +5,10 @@ mod constant_evaluator; mod emitter; pub mod index; +mod keyword_set; mod layouter; mod namer; +mod overloads; mod terminator; mod type_methods; mod typifier; @@ -16,12 +18,14 @@ pub use constant_evaluator::{ }; pub use emitter::Emitter; pub use index::{BoundsCheckPolicies, BoundsCheckPolicy, IndexableLength, IndexableLengthError}; +pub use keyword_set::{CaseInsensitiveKeywordSet, KeywordSet}; pub use layouter::{Alignment, LayoutError, LayoutErrorInner, Layouter, TypeLayout}; -pub use namer::{EntryPointIndex, NameKey, Namer}; +pub use namer::{EntryPointIndex, ExternalTextureNameKey, NameKey, Namer}; +pub use overloads::{Conclusion, MissingSpecialType, OverloadSet, Rule}; pub use terminator::ensure_block_returns; use thiserror::Error; pub use type_methods::min_max_float_representable_by; -pub use typifier::{ResolveContext, ResolveError, TypeResolution}; +pub use typifier::{compare_types, ResolveContext, ResolveError, TypeResolution}; impl From for super::Scalar { fn from(format: super::StorageFormat) -> Self { @@ -119,6 +123,8 @@ impl crate::Literal { (value, crate::ScalarKind::Sint, 8) => Some(Self::I64(value as _)), (1, crate::ScalarKind::Bool, crate::BOOL_WIDTH) => Some(Self::Bool(true)), (0, crate::ScalarKind::Bool, crate::BOOL_WIDTH) => Some(Self::Bool(false)), + (value, crate::ScalarKind::AbstractInt, 8) => Some(Self::AbstractInt(value as _)), + (value, crate::ScalarKind::AbstractFloat, 8) => Some(Self::AbstractFloat(value as _)), _ => None, } } @@ -173,6 +179,9 @@ impl super::AddressSpace { crate::AddressSpace::Storage { access } => access, crate::AddressSpace::Handle => Sa::LOAD, crate::AddressSpace::PushConstant => Sa::LOAD, + // TaskPayload isn't always writable, but this is checked for elsewhere, + // when not using multiple payloads and matching the entry payload is checked. + crate::AddressSpace::TaskPayload => Sa::LOAD | Sa::STORE, } } } @@ -219,6 +228,8 @@ impl super::MathFunction { Self::Pow => 2, // geometry Self::Dot => 2, + Self::Dot4I8Packed => 2, + Self::Dot4U8Packed => 2, Self::Outer => 2, Self::Cross => 2, Self::Distance => 2, @@ -256,6 +267,8 @@ impl super::MathFunction { Self::Pack2x16float => 1, Self::Pack4xI8 => 1, Self::Pack4xU8 => 1, + Self::Pack4xI8Clamp => 1, + Self::Pack4xU8Clamp => 1, // data unpacking Self::Unpack4x8snorm => 1, Self::Unpack4x8unorm => 1, @@ -375,6 +388,7 @@ impl super::ImageClass { match self { crate::ImageClass::Sampled { multi, .. } | crate::ImageClass::Depth { multi } => multi, crate::ImageClass::Storage { .. } => false, + crate::ImageClass::External => false, } } @@ -382,6 +396,7 @@ impl super::ImageClass { match self { crate::ImageClass::Sampled { multi, .. } | crate::ImageClass::Depth { multi } => !multi, crate::ImageClass::Storage { .. } => false, + crate::ImageClass::External => false, } } @@ -399,6 +414,10 @@ impl crate::Module { global_expressions: &self.global_expressions, } } + + pub fn compare_types(&self, lhs: &TypeResolution, rhs: &TypeResolution) -> bool { + compare_types(lhs, rhs, &self.types) + } } #[derive(Debug)] @@ -487,6 +506,10 @@ impl GlobalCtx<'_> { _ => get(*self, handle, arena), } } + + pub fn compare_types(&self, lhs: &TypeResolution, rhs: &TypeResolution) -> bool { + compare_types(lhs, rhs, self.types) + } } #[derive(Error, Debug, Clone, Copy, PartialEq)] @@ -608,6 +631,15 @@ pub fn flatten_compose<'arenas>( .take(size) } +impl super::ShaderStage { + pub const fn compute_like(self) -> bool { + match self { + Self::Vertex | Self::Fragment => false, + Self::Compute | Self::Task | Self::Mesh => true, + } + } +} + #[test] fn test_matrix_size() { let module = crate::Module::default(); diff --git a/naga/src/proc/namer.rs b/naga/src/proc/namer.rs index 6b831cce7..127e346f3 100644 --- a/naga/src/proc/namer.rs +++ b/naga/src/proc/namer.rs @@ -4,14 +4,50 @@ use alloc::{ string::{String, ToString}, vec::Vec, }; -use core::hash::{Hash, Hasher}; -use hashbrown::HashSet; -use crate::{arena::Handle, FastHashMap, FastHashSet}; +use crate::{ + arena::Handle, + proc::{keyword_set::CaseInsensitiveKeywordSet, KeywordSet}, + FastHashMap, +}; pub type EntryPointIndex = u16; const SEPARATOR: char = '_'; +/// A component of a lowered external texture. +/// +/// Whereas the WGSL backend implements [`ImageClass::External`] +/// images directly, most other Naga backends lower them to a +/// collection of ordinary textures that represent individual planes +/// (as received from a video decoder, perhaps), together with a +/// struct of parameters saying how they should be cropped, sampled, +/// and color-converted. +/// +/// This lowering means that individual globals and function +/// parameters in Naga IR must be split out by the backends into +/// collections of globals and parameters of simpler types. +/// +/// A value of this enum serves as a name key for one specific +/// component in the lowered representation of an external texture. +/// That is, these keys are for variables/parameters that do not exist +/// in the Naga IR, only in its lowered form. +/// +/// [`ImageClass::External`]: crate::ir::ImageClass::External +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub enum ExternalTextureNameKey { + Plane(usize), + Params, +} + +impl ExternalTextureNameKey { + const ALL: &[(&str, ExternalTextureNameKey)] = &[ + ("_plane0", ExternalTextureNameKey::Plane(0)), + ("_plane1", ExternalTextureNameKey::Plane(1)), + ("_plane2", ExternalTextureNameKey::Plane(2)), + ("_params", ExternalTextureNameKey::Params), + ]; +} + #[derive(Debug, Eq, Hash, PartialEq)] pub enum NameKey { Constant(Handle), @@ -21,36 +57,43 @@ pub enum NameKey { Function(Handle), FunctionArgument(Handle, u32), FunctionLocal(Handle, Handle), + + /// A local variable used by ReadZeroSkipWrite bounds-check policy + /// when it needs to produce a pointer-typed result for an OOB access. + /// These are unique per accessed type, so the second element is a + /// type handle. See docs for [`crate::back::msl`]. + FunctionOobLocal(Handle, Handle), + EntryPoint(EntryPointIndex), EntryPointLocal(EntryPointIndex, Handle), EntryPointArgument(EntryPointIndex, u32), + + /// Entry point version of `FunctionOobLocal`. + EntryPointOobLocal(EntryPointIndex, Handle), + + /// A global variable holding a component of a lowered external texture. + /// + /// See [`ExternalTextureNameKey`] for details. + ExternalTextureGlobalVariable(Handle, ExternalTextureNameKey), + + /// A function argument holding a component of a lowered external + /// texture. + /// + /// See [`ExternalTextureNameKey`] for details. + ExternalTextureFunctionArgument(Handle, u32, ExternalTextureNameKey), } /// This processor assigns names to all the things in a module /// that may need identifiers in a textual backend. +#[derive(Default)] pub struct Namer { /// The last numeric suffix used for each base name. Zero means "no suffix". unique: FastHashMap, - keywords: &'static HashSet<&'static str>, - keywords_case_insensitive: FastHashSet>, + keywords: &'static KeywordSet, + keywords_case_insensitive: &'static CaseInsensitiveKeywordSet, reserved_prefixes: Vec<&'static str>, } -#[cfg(any(wgsl_out, glsl_out, msl_out, hlsl_out, test))] -impl Default for Namer { - fn default() -> Self { - use std::sync::LazyLock; - static DEFAULT_KEYWORDS: LazyLock> = LazyLock::new(HashSet::default); - - Self { - unique: Default::default(), - keywords: &DEFAULT_KEYWORDS, - keywords_case_insensitive: Default::default(), - reserved_prefixes: Default::default(), - } - } -} - impl Namer { /// Return a form of `string` suitable for use as the base of an identifier. /// @@ -75,20 +118,37 @@ impl Namer { { Cow::Borrowed(string) } else { - let mut filtered = string - .chars() - .filter(|&c| c.is_ascii_alphanumeric() || c == '_') - .fold(String::new(), |mut s, c| { - if s.ends_with('_') && c == '_' { - return s; - } + let mut filtered = string.chars().fold(String::new(), |mut s, c| { + let c = match c { + // Make several common characters in C++-ish types become snake case + // separators. + ':' | '<' | '>' | ',' => '_', + c => c, + }; + let had_underscore_at_end = s.ends_with('_'); + if had_underscore_at_end && c == '_' { + return s; + } + if c.is_ascii_alphanumeric() || c == '_' { s.push(c); - s - }); + } else { + use core::fmt::Write as _; + if !s.is_empty() && !had_underscore_at_end { + s.push('_'); + } + write!(s, "u{:04x}_", c as u32).unwrap(); + } + s + }); let stripped_len = filtered.trim_end_matches(SEPARATOR).len(); filtered.truncate(stripped_len); if filtered.is_empty() { filtered.push_str("unnamed"); + } else if filtered.starts_with(|c: char| c.is_ascii_digit()) { + unreachable!( + "internal error: invalid identifier starting with ASCII digit {:?}", + filtered.chars().nth(0) + ) } Cow::Owned(filtered) }; @@ -135,13 +195,11 @@ impl Namer { let mut suffixed = base.to_string(); if base.ends_with(char::is_numeric) || self.keywords.contains(base.as_ref()) - || self - .keywords_case_insensitive - .contains(&AsciiUniCase(base.as_ref())) + || self.keywords_case_insensitive.contains(base.as_ref()) { suffixed.push(SEPARATOR); } - debug_assert!(!self.keywords.contains::(&suffixed)); + debug_assert!(!self.keywords.contains(&suffixed)); // `self.unique` wants to own its keys. This allocates only if we haven't // already done so earlier. self.unique.insert(base.into_owned(), 0); @@ -172,8 +230,8 @@ impl Namer { pub fn reset( &mut self, module: &crate::Module, - reserved_keywords: &'static HashSet<&'static str>, - reserved_keywords_case_insensitive: &[&'static str], + reserved_keywords: &'static KeywordSet, + reserved_keywords_case_insensitive: &'static CaseInsensitiveKeywordSet, reserved_prefixes: &[&'static str], output: &mut FastHashMap, ) { @@ -182,16 +240,7 @@ impl Namer { self.unique.clear(); self.keywords = reserved_keywords; - - debug_assert!(reserved_keywords_case_insensitive - .iter() - .all(|s| s.is_ascii())); - self.keywords_case_insensitive.clear(); - self.keywords_case_insensitive.extend( - reserved_keywords_case_insensitive - .iter() - .map(|string| (AsciiUniCase(*string))), - ); + self.keywords_case_insensitive = reserved_keywords_case_insensitive; // Choose fallback names for anonymous entry point return types. let mut entrypoint_type_fallbacks = FastHashMap::default(); @@ -261,6 +310,27 @@ impl Namer { for (index, arg) in fun.arguments.iter().enumerate() { let name = self.call_or(&arg.name, "param"); output.insert(NameKey::FunctionArgument(fun_handle, index as u32), name); + + if matches!( + module.types[arg.ty].inner, + crate::TypeInner::Image { + class: crate::ImageClass::External, + .. + } + ) { + let base = arg.name.as_deref().unwrap_or("param"); + for &(suffix, ext_key) in ExternalTextureNameKey::ALL { + let name = self.call(&format!("{base}_{suffix}")); + output.insert( + NameKey::ExternalTextureFunctionArgument( + fun_handle, + index as u32, + ext_key, + ), + name, + ); + } + } } for (handle, var) in fun.local_variables.iter() { let name = self.call_or(&var.name, "local"); @@ -271,6 +341,23 @@ impl Namer { for (handle, var) in module.global_variables.iter() { let name = self.call_or(&var.name, "global"); output.insert(NameKey::GlobalVariable(handle), name); + + if matches!( + module.types[var.ty].inner, + crate::TypeInner::Image { + class: crate::ImageClass::External, + .. + } + ) { + let base = var.name.as_deref().unwrap_or("global"); + for &(suffix, ext_key) in ExternalTextureNameKey::ALL { + let name = self.call(&format!("{base}_{suffix}")); + output.insert( + NameKey::ExternalTextureGlobalVariable(handle, ext_key), + name, + ); + } + } } for (handle, constant) in module.constants.iter() { @@ -290,33 +377,6 @@ impl Namer { } } -/// A string wrapper type with an ascii case insensitive Eq and Hash impl -struct AsciiUniCase + ?Sized>(S); - -impl> PartialEq for AsciiUniCase { - #[inline] - fn eq(&self, other: &Self) -> bool { - self.0.as_ref().eq_ignore_ascii_case(other.0.as_ref()) - } -} - -impl> Eq for AsciiUniCase {} - -impl> Hash for AsciiUniCase { - #[inline] - fn hash(&self, hasher: &mut H) { - for byte in self - .0 - .as_ref() - .as_bytes() - .iter() - .map(|b| b.to_ascii_lowercase()) - { - hasher.write_u8(byte); - } - } -} - #[test] fn test() { let mut namer = Namer::default(); diff --git a/naga/src/proc/overloads/any_overload_set.rs b/naga/src/proc/overloads/any_overload_set.rs new file mode 100644 index 000000000..f3228bb07 --- /dev/null +++ b/naga/src/proc/overloads/any_overload_set.rs @@ -0,0 +1,120 @@ +//! Dynamically dispatched [`OverloadSet`]s. + +use crate::common::DiagnosticDebug; +use crate::ir; +use crate::proc::overloads::{list, regular, OverloadSet, Rule}; +use crate::proc::{GlobalCtx, TypeResolution}; + +use alloc::vec::Vec; +use core::fmt; + +macro_rules! define_any_overload_set { + { $( $module:ident :: $name:ident, )* } => { + /// An [`OverloadSet`] that dynamically dispatches to concrete implementations. + #[derive(Clone)] + pub(in crate::proc::overloads) enum AnyOverloadSet { + $( + $name ( $module :: $name ), + )* + } + + $( + impl From<$module::$name> for AnyOverloadSet { + fn from(concrete: $module::$name) -> Self { + AnyOverloadSet::$name(concrete) + } + } + )* + + impl OverloadSet for AnyOverloadSet { + fn is_empty(&self) -> bool { + match *self { + $( + AnyOverloadSet::$name(ref x) => x.is_empty(), + )* + } + } + + fn min_arguments(&self) -> usize { + match *self { + $( + AnyOverloadSet::$name(ref x) => x.min_arguments(), + )* + } + } + + fn max_arguments(&self) -> usize { + match *self { + $( + AnyOverloadSet::$name(ref x) => x.max_arguments(), + )* + } + } + + fn arg( + &self, + i: usize, + ty: &ir::TypeInner, + types: &crate::UniqueArena, + ) -> Self { + match *self { + $( + AnyOverloadSet::$name(ref x) => AnyOverloadSet::$name(x.arg(i, ty, types)), + )* + } + } + + fn concrete_only(self, types: &crate::UniqueArena) -> Self { + match self { + $( + AnyOverloadSet::$name(x) => AnyOverloadSet::$name(x.concrete_only(types)), + )* + } + } + + fn most_preferred(&self) -> Rule { + match *self { + $( + AnyOverloadSet::$name(ref x) => x.most_preferred(), + )* + } + } + + fn overload_list(&self, gctx: &GlobalCtx<'_>) -> Vec { + match *self { + $( + AnyOverloadSet::$name(ref x) => x.overload_list(gctx), + )* + } + } + + fn allowed_args(&self, i: usize, gctx: &GlobalCtx<'_>) -> Vec { + match *self { + $( + AnyOverloadSet::$name(ref x) => x.allowed_args(i, gctx), + )* + } + } + + fn for_debug(&self, types: &crate::UniqueArena) -> impl fmt::Debug { + DiagnosticDebug((self, types)) + } + } + + impl fmt::Debug for DiagnosticDebug<(&AnyOverloadSet, &crate::UniqueArena)> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (set, types) = self.0; + match *set { + $( + AnyOverloadSet::$name(ref x) => DiagnosticDebug((x, types)).fmt(f), + )* + } + } + } + } +} + +define_any_overload_set! { + list::List, + regular::Regular, +} diff --git a/naga/src/proc/overloads/constructor_set.rs b/naga/src/proc/overloads/constructor_set.rs new file mode 100644 index 000000000..eeb831d39 --- /dev/null +++ b/naga/src/proc/overloads/constructor_set.rs @@ -0,0 +1,174 @@ +//! A set of type constructors, represented as a bitset. + +use crate::ir; +use crate::proc::overloads::one_bits_iter::OneBitsIter; + +bitflags::bitflags! { + /// A set of type constructors. + #[derive(Copy, Clone, Debug, PartialEq)] + pub(crate) struct ConstructorSet: u16 { + const SCALAR = 1 << 0; + const VEC2 = 1 << 1; + const VEC3 = 1 << 2; + const VEC4 = 1 << 3; + const MAT2X2 = 1 << 4; + const MAT2X3 = 1 << 5; + const MAT2X4 = 1 << 6; + const MAT3X2 = 1 << 7; + const MAT3X3 = 1 << 8; + const MAT3X4 = 1 << 9; + const MAT4X2 = 1 << 10; + const MAT4X3 = 1 << 11; + const MAT4X4 = 1 << 12; + + const VECN = Self::VEC2.bits() + | Self::VEC3.bits() + | Self::VEC4.bits(); + } +} + +impl ConstructorSet { + /// Return the single-member set containing `inner`'s constructor. + pub const fn singleton(inner: &ir::TypeInner) -> ConstructorSet { + use ir::TypeInner as Ti; + use ir::VectorSize as Vs; + match *inner { + Ti::Scalar(_) => Self::SCALAR, + Ti::Vector { size, scalar: _ } => match size { + Vs::Bi => Self::VEC2, + Vs::Tri => Self::VEC3, + Vs::Quad => Self::VEC4, + }, + Ti::Matrix { + columns, + rows, + scalar: _, + } => match (columns, rows) { + (Vs::Bi, Vs::Bi) => Self::MAT2X2, + (Vs::Bi, Vs::Tri) => Self::MAT2X3, + (Vs::Bi, Vs::Quad) => Self::MAT2X4, + (Vs::Tri, Vs::Bi) => Self::MAT3X2, + (Vs::Tri, Vs::Tri) => Self::MAT3X3, + (Vs::Tri, Vs::Quad) => Self::MAT3X4, + (Vs::Quad, Vs::Bi) => Self::MAT4X2, + (Vs::Quad, Vs::Tri) => Self::MAT4X3, + (Vs::Quad, Vs::Quad) => Self::MAT4X4, + }, + _ => Self::empty(), + } + } + + pub const fn is_singleton(self) -> bool { + self.bits().is_power_of_two() + } + + /// Return an iterator over this set's members. + /// + /// Members are produced as singleton, in order from most general to least. + pub fn members(self) -> impl Iterator { + OneBitsIter::new(self.bits() as u64).map(|bit| Self::from_bits(bit as u16).unwrap()) + } + + /// Return the size of the sole element of `self`. + /// + /// # Panics + /// + /// Panic if `self` is not a singleton. + pub fn size(self) -> ConstructorSize { + use ir::VectorSize as Vs; + use ConstructorSize as Cs; + + match self { + ConstructorSet::SCALAR => Cs::Scalar, + ConstructorSet::VEC2 => Cs::Vector(Vs::Bi), + ConstructorSet::VEC3 => Cs::Vector(Vs::Tri), + ConstructorSet::VEC4 => Cs::Vector(Vs::Quad), + ConstructorSet::MAT2X2 => Cs::Matrix { + columns: Vs::Bi, + rows: Vs::Bi, + }, + ConstructorSet::MAT2X3 => Cs::Matrix { + columns: Vs::Bi, + rows: Vs::Tri, + }, + ConstructorSet::MAT2X4 => Cs::Matrix { + columns: Vs::Bi, + rows: Vs::Quad, + }, + ConstructorSet::MAT3X2 => Cs::Matrix { + columns: Vs::Tri, + rows: Vs::Bi, + }, + ConstructorSet::MAT3X3 => Cs::Matrix { + columns: Vs::Tri, + rows: Vs::Tri, + }, + ConstructorSet::MAT3X4 => Cs::Matrix { + columns: Vs::Tri, + rows: Vs::Quad, + }, + ConstructorSet::MAT4X2 => Cs::Matrix { + columns: Vs::Quad, + rows: Vs::Bi, + }, + ConstructorSet::MAT4X3 => Cs::Matrix { + columns: Vs::Quad, + rows: Vs::Tri, + }, + ConstructorSet::MAT4X4 => Cs::Matrix { + columns: Vs::Quad, + rows: Vs::Quad, + }, + _ => unreachable!("ConstructorSet was not a singleton"), + } + } +} + +/// The sizes a member of [`ConstructorSet`] might have. +#[derive(Clone, Copy)] +pub enum ConstructorSize { + /// The constructor is [`SCALAR`]. + /// + /// [`SCALAR`]: ConstructorSet::SCALAR + Scalar, + + /// The constructor is `VECN` for some `N`. + Vector(ir::VectorSize), + + /// The constructor is `MATCXR` for some `C` and `R`. + Matrix { + columns: ir::VectorSize, + rows: ir::VectorSize, + }, +} + +impl ConstructorSize { + /// Construct a [`TypeInner`] for a type with this size and the given `scalar`. + /// + /// [`TypeInner`]: ir::TypeInner + pub const fn to_inner(self, scalar: ir::Scalar) -> ir::TypeInner { + match self { + Self::Scalar => ir::TypeInner::Scalar(scalar), + Self::Vector(size) => ir::TypeInner::Vector { size, scalar }, + Self::Matrix { columns, rows } => ir::TypeInner::Matrix { + columns, + rows, + scalar, + }, + } + } +} + +macro_rules! constructor_set { + ( $( $constr:ident )|* ) => { + { + use $crate::proc::overloads::constructor_set::ConstructorSet; + ConstructorSet::empty() + $( + .union(ConstructorSet::$constr) + )* + } + } +} + +pub(in crate::proc::overloads) use constructor_set; diff --git a/naga/src/proc/overloads/list.rs b/naga/src/proc/overloads/list.rs new file mode 100644 index 000000000..a10e9b63a --- /dev/null +++ b/naga/src/proc/overloads/list.rs @@ -0,0 +1,182 @@ +//! An [`OverloadSet`] represented as a vector of rules. +//! +//! [`OverloadSet`]: crate::proc::overloads::OverloadSet + +use crate::common::{DiagnosticDebug, ForDebug, ForDebugWithTypes}; +use crate::ir; +use crate::proc::overloads::one_bits_iter::OneBitsIter; +use crate::proc::overloads::Rule; +use crate::proc::{GlobalCtx, TypeResolution}; + +use alloc::rc::Rc; +use alloc::vec::Vec; +use core::fmt; + +/// A simple list of overloads. +/// +/// Note that this type is not quite as general as it looks, in that +/// the implementation of `most_preferred` doesn't work for arbitrary +/// lists of overloads. See the documentation for [`List::rules`] for +/// details. +#[derive(Clone)] +pub(in crate::proc::overloads) struct List { + /// A bitmask of which elements of `rules` are included in the set. + members: u64, + + /// A list of type rules that are members of the set. + /// + /// These must be listed in order such that every rule in the list + /// is always more preferred than all subsequent rules in the + /// list. If there is no such arrangement of rules, then you + /// cannot use `List` to represent the overload set. + rules: Rc>, +} + +impl List { + pub(in crate::proc::overloads) fn from_rules(rules: Vec) -> List { + List { + members: len_to_full_mask(rules.len()), + rules: Rc::new(rules), + } + } + + fn members(&self) -> impl Iterator { + OneBitsIter::new(self.members).map(|mask| { + let index = mask.trailing_zeros() as usize; + (mask, &self.rules[index]) + }) + } + + fn filter(&self, mut pred: F) -> List + where + F: FnMut(&Rule) -> bool, + { + let mut filtered_members = 0; + for (mask, rule) in self.members() { + if pred(rule) { + filtered_members |= mask; + } + } + + List { + members: filtered_members, + rules: self.rules.clone(), + } + } +} + +impl crate::proc::overloads::OverloadSet for List { + fn is_empty(&self) -> bool { + self.members == 0 + } + + fn min_arguments(&self) -> usize { + self.members() + .fold(None, |best, (_, rule)| { + // This is different from `max_arguments` because + // `

(filename: P) -> Result where - P: AsRef, + P: AsRef, { unsafe { libloading::Library::new(filename) }.map(|inner| Self { inner }) } @@ -153,10 +160,10 @@ impl D3D12Lib { ) -> Result, crate::DeviceError> { // Calls windows::Win32::Graphics::Direct3D12::D3D12CreateDevice on d3d12.dll type Fun = extern "system" fn( - padapter: *mut core::ffi::c_void, + padapter: *mut ffi::c_void, minimumfeaturelevel: Direct3D::D3D_FEATURE_LEVEL, riid: *const windows_core::GUID, - ppdevice: *mut *mut core::ffi::c_void, + ppdevice: *mut *mut ffi::c_void, ) -> windows_core::HRESULT; let func: libloading::Symbol = unsafe { self.lib.get(c"D3D12CreateDevice".to_bytes()) }?; @@ -196,8 +203,8 @@ impl D3D12Lib { type Fun = extern "system" fn( prootsignature: *const Direct3D12::D3D12_ROOT_SIGNATURE_DESC, version: Direct3D12::D3D_ROOT_SIGNATURE_VERSION, - ppblob: *mut *mut core::ffi::c_void, - pperrorblob: *mut *mut core::ffi::c_void, + ppblob: *mut *mut ffi::c_void, + pperrorblob: *mut *mut ffi::c_void, ) -> windows_core::HRESULT; let func: libloading::Symbol = unsafe { self.lib.get(c"D3D12SerializeRootSignature".to_bytes()) }?; @@ -237,7 +244,7 @@ impl D3D12Lib { // Calls windows::Win32::Graphics::Direct3D12::D3D12GetDebugInterface on d3d12.dll type Fun = extern "system" fn( riid: *const windows_core::GUID, - ppvdebug: *mut *mut core::ffi::c_void, + ppvdebug: *mut *mut ffi::c_void, ) -> windows_core::HRESULT; let func: libloading::Symbol = unsafe { self.lib.get(c"D3D12GetDebugInterface".to_bytes()) }?; @@ -275,7 +282,7 @@ impl DxgiLib { type Fun = extern "system" fn( flags: u32, riid: *const windows_core::GUID, - pdebug: *mut *mut core::ffi::c_void, + pdebug: *mut *mut ffi::c_void, ) -> windows_core::HRESULT; let func: libloading::Symbol = unsafe { self.lib.get(c"DXGIGetDebugInterface1".to_bytes()) }?; @@ -305,7 +312,7 @@ impl DxgiLib { type Fun = extern "system" fn( flags: Dxgi::DXGI_CREATE_FACTORY_FLAGS, riid: *const windows_core::GUID, - ppfactory: *mut *mut core::ffi::c_void, + ppfactory: *mut *mut ffi::c_void, ) -> windows_core::HRESULT; let func: libloading::Symbol = unsafe { self.lib.get(c"CreateDXGIFactory2".to_bytes()) }?; @@ -328,7 +335,7 @@ impl DxgiLib { // Calls windows::Win32::Graphics::Dxgi::CreateDXGIFactory1 on dxgi.dll type Fun = extern "system" fn( riid: *const windows_core::GUID, - ppfactory: *mut *mut core::ffi::c_void, + ppfactory: *mut *mut ffi::c_void, ) -> windows_core::HRESULT; let func: libloading::Symbol = unsafe { self.lib.get(c"CreateDXGIFactory1".to_bytes()) }?; @@ -384,7 +391,7 @@ impl Deref for D3DBlob { impl D3DBlob { unsafe fn as_slice(&self) -> &[u8] { - unsafe { std::slice::from_raw_parts(self.GetBufferPointer().cast(), self.GetBufferSize()) } + unsafe { core::slice::from_raw_parts(self.GetBufferPointer().cast(), self.GetBufferSize()) } } unsafe fn as_c_str(&self) -> Result<&ffi::CStr, ffi::FromBytesUntilNulError> { @@ -396,6 +403,8 @@ impl D3DBlob { pub struct Api; impl crate::Api for Api { + const VARIANT: wgt::Backend = wgt::Backend::Dx12; + type Instance = Instance; type Surface = Surface; type Adapter = Adapter; @@ -456,13 +465,22 @@ pub struct Instance { factory: DxgiFactory, factory_media: Option, library: Arc, + dcomp_lib: Arc, supports_allow_tearing: bool, + presentation_system: wgt::Dx12SwapchainKind, _lib_dxgi: DxgiLib, flags: wgt::InstanceFlags, - dxc_container: Option>, + memory_budget_thresholds: wgt::MemoryBudgetThresholds, + compiler_container: Arc, + options: wgt::Dx12BackendOptions, } impl Instance { + /// Get the raw DXGI factory associated with this instance. + pub unsafe fn raw_factory4(&self) -> &Dxgi::IDXGIFactory4 { + self.factory.deref() + } + pub unsafe fn create_surface_from_visual(&self, visual: *mut ffi::c_void) -> Surface { let visual = unsafe { DirectComposition::IDCompositionVisual::from_raw_borrowed(&visual) } .expect("COM pointer should not be NULL"); @@ -472,6 +490,7 @@ impl Instance { target: SurfaceTarget::Visual(visual.to_owned()), supports_allow_tearing: self.supports_allow_tearing, swap_chain: RwLock::new(None), + options: self.options.clone(), } } @@ -489,6 +508,7 @@ impl Instance { target: SurfaceTarget::SurfaceHandle(surface_handle), supports_allow_tearing: self.supports_allow_tearing, swap_chain: RwLock::new(None), + options: self.options.clone(), } } @@ -505,6 +525,7 @@ impl Instance { target: SurfaceTarget::SwapChainPanel(swap_chain_panel.to_owned()), supports_allow_tearing: self.supports_allow_tearing, swap_chain: RwLock::new(None), + options: self.options.clone(), } } } @@ -519,7 +540,7 @@ struct SwapChain { // when the swapchain is destroyed resources: Vec, /// Handle is freed in [`Self::release_resources()`] - waitable: Foundation::HANDLE, + waitable: Option, acquired_count: usize, present_mode: wgt::PresentMode, format: wgt::TextureFormat, @@ -529,6 +550,11 @@ struct SwapChain { enum SurfaceTarget { /// Borrowed, lifetime externally managed WndHandle(Foundation::HWND), + /// `handle` is borrowed, lifetime externally managed + VisualFromWndHandle { + handle: Foundation::HWND, + dcomp_state: Mutex, + }, Visual(DirectComposition::IDCompositionVisual), /// Borrowed, lifetime externally managed SurfaceHandle(Foundation::HANDLE), @@ -541,11 +567,24 @@ pub struct Surface { target: SurfaceTarget, supports_allow_tearing: bool, swap_chain: RwLock>, + options: wgt::Dx12BackendOptions, } unsafe impl Send for Surface {} unsafe impl Sync for Surface {} +impl Surface { + pub fn swap_chain(&self) -> Option { + Some(self.swap_chain.read().as_ref()?.raw.clone()) + } + + /// Returns the waitable handle associated with this swap chain, if any. + /// Handle is only valid while the swap chain is alive. + pub unsafe fn waitable_handle(&self) -> Option { + self.swap_chain.read().as_ref()?.waitable + } +} + #[derive(Debug, Clone, Copy)] enum MemoryArchitecture { Unified { @@ -566,6 +605,17 @@ struct PrivateCapabilities { suballocation_supported: bool, shader_model: naga::back::hlsl::ShaderModel, max_sampler_descriptor_heap_size: u32, + unrestricted_buffer_texture_copy_pitch_supported: bool, +} + +impl PrivateCapabilities { + fn texture_data_placement_alignment(&self) -> u64 { + if self.unrestricted_buffer_texture_copy_pitch_supported { + 4 + } else { + D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT.into() + } + } } #[derive(Default)] @@ -579,17 +629,26 @@ pub struct Adapter { raw: DxgiAdapter, device: Direct3D12::ID3D12Device, library: Arc, + dcomp_lib: Arc, private_caps: PrivateCapabilities, presentation_timer: auxil::dxgi::time::PresentationTimer, // Note: this isn't used right now, but we'll need it later. #[allow(unused)] workarounds: Workarounds, - dxc_container: Option>, + memory_budget_thresholds: wgt::MemoryBudgetThresholds, + compiler_container: Arc, + options: wgt::Dx12BackendOptions, } unsafe impl Send for Adapter {} unsafe impl Sync for Adapter {} +impl Adapter { + pub fn as_raw(&self) -> &Dxgi::IDXGIAdapter3 { + &self.raw + } +} + struct Event(pub Foundation::HANDLE); impl Event { pub fn create(manual_reset: bool, initial_state: bool) -> Result { @@ -609,21 +668,23 @@ impl Drop for Event { /// Helper structure for waiting for GPU. struct Idler { fence: Direct3D12::ID3D12Fence, - event: Event, } #[derive(Debug, Clone)] struct CommandSignatures { draw: Direct3D12::ID3D12CommandSignature, draw_indexed: Direct3D12::ID3D12CommandSignature, + draw_mesh: Option, dispatch: Direct3D12::ID3D12CommandSignature, } struct DeviceShared { + adapter: DxgiAdapter, zero_buffer: Direct3D12::ID3D12Resource, cmd_signatures: CommandSignatures, heap_views: descriptor::GeneralHeap, sampler_heap: sampler::SamplerHeap, + private_caps: PrivateCapabilities, } unsafe impl Send for DeviceShared {} @@ -633,20 +694,22 @@ pub struct Device { raw: Direct3D12::ID3D12Device, present_queue: Direct3D12::ID3D12CommandQueue, idler: Idler, - private_caps: PrivateCapabilities, features: wgt::Features, shared: Arc, + options: wgt::Dx12BackendOptions, // CPU only pools - rtv_pool: Mutex, + rtv_pool: Arc>, dsv_pool: Mutex, srv_uav_pool: Mutex, // library library: Arc, + dcomp_lib: Arc, #[cfg(feature = "renderdoc")] render_doc: auxil::renderdoc::RenderDoc, null_rtv_handle: descriptor::Handle, - mem_allocator: Mutex, - dxc_container: Option>, + mem_allocator: Allocator, + compiler_container: Arc, + shader_cache: Mutex, counters: Arc, } @@ -654,6 +717,7 @@ impl Drop for Device { fn drop(&mut self) { self.rtv_pool.lock().free_handle(self.null_rtv_handle); if self + .shared .private_caps .instance_flags .contains(wgt::InstanceFlags::VALIDATION) @@ -786,6 +850,13 @@ pub struct CommandEncoder { allocator: Direct3D12::ID3D12CommandAllocator, device: Direct3D12::ID3D12Device, shared: Arc, + mem_allocator: Allocator, + + rtv_pool: Arc>, + temp_rtv_handles: Vec, + + intermediate_copy_bufs: Vec, + null_rtv_handle: descriptor::Handle, list: Option, free_lists: Vec, @@ -824,8 +895,11 @@ unsafe impl Sync for CommandBuffer {} #[derive(Debug)] pub struct Buffer { resource: Direct3D12::ID3D12Resource, + // While the allocation also has _a_ size, it may not + // be the same as the original size of the buffer, + // as the allocation size varies for assorted reasons. size: wgt::BufferAddress, - allocation: Option, + allocation: suballocation::Allocation, } unsafe impl Send for Buffer {} @@ -855,7 +929,7 @@ pub struct Texture { size: wgt::Extent3d, mip_level_count: u32, sample_count: u32, - allocation: Option, + allocation: suballocation::Allocation, } impl Texture { @@ -867,7 +941,7 @@ impl Texture { impl crate::DynTexture for Texture {} impl crate::DynSurfaceTexture for Texture {} -impl std::borrow::Borrow for Texture { +impl core::borrow::Borrow for Texture { fn borrow(&self) -> &dyn crate::DynTexture { self } @@ -903,8 +977,10 @@ impl Texture { pub struct TextureView { raw_format: Dxgi::Common::DXGI_FORMAT, aspects: crate::FormatAspects, - /// only used by resolve - target_base: (Direct3D12::ID3D12Resource, u32), + dimension: wgt::TextureViewDimension, + texture: Direct3D12::ID3D12Resource, + subresource_index: u32, + mip_slice: u32, handle_srv: Option, handle_uav: Option, handle_rtv: Option, @@ -974,7 +1050,7 @@ enum DynamicBuffer { #[derive(Debug)] struct SamplerIndexBuffer { buffer: Direct3D12::ID3D12Resource, - allocation: Option, + allocation: suballocation::Allocation, } #[derive(Debug)] @@ -1007,13 +1083,13 @@ struct BindGroupInfo { #[derive(Debug, Clone)] struct RootConstantInfo { root_index: RootIndex, - range: std::ops::Range, + range: core::ops::Range, } #[derive(Debug, Clone)] struct DynamicStorageBufferOffsets { root_index: RootIndex, - range: std::ops::Range, + range: core::ops::Range, } #[derive(Debug, Clone)] @@ -1050,16 +1126,39 @@ impl crate::DynPipelineLayout for PipelineLayout {} #[derive(Debug)] pub struct ShaderModule { - naga: crate::NagaShader, - raw_name: Option, + source: ShaderModuleSource, + raw_name: Option, runtime_checks: wgt::ShaderRuntimeChecks, } impl crate::DynShaderModule for ShaderModule {} +#[derive(Default)] +pub struct ShaderCache { + nr_of_shaders_compiled: u32, + entries: HashMap, +} + +#[derive(PartialEq, Eq, Hash)] +pub(super) struct ShaderCacheKey { + source: String, + entry_point: String, + stage: naga::ShaderStage, + shader_model: naga::back::hlsl::ShaderModel, +} + +pub(super) struct ShaderCacheValue { + /// This is the value of [`ShaderCache::nr_of_shaders_compiled`] + /// at the time the cache entry was last used. + last_used: u32, + shader: CompiledShader, +} + +#[derive(Clone)] pub(super) enum CompiledShader { Dxc(Direct3D::Dxc::IDxcBlob), Fxc(Direct3D::ID3DBlob), + Precompiled(Vec), } impl CompiledShader { @@ -1073,10 +1172,12 @@ impl CompiledShader { pShaderBytecode: unsafe { shader.GetBufferPointer() }, BytecodeLength: unsafe { shader.GetBufferSize() }, }, + CompiledShader::Precompiled(shader) => Direct3D12::D3D12_SHADER_BYTECODE { + pShaderBytecode: shader.as_ptr().cast(), + BytecodeLength: shader.len(), + }, } } - - unsafe fn destroy(self) {} } #[derive(Debug)] @@ -1084,7 +1185,7 @@ pub struct RenderPipeline { raw: Direct3D12::ID3D12PipelineState, layout: PipelineLayoutShared, topology: Direct3D::D3D_PRIMITIVE_TOPOLOGY, - vertex_strides: [Option; crate::MAX_VERTEX_BUFFERS], + vertex_strides: [Option; crate::MAX_VERTEX_BUFFERS], } impl crate::DynRenderPipeline for RenderPipeline {} @@ -1111,33 +1212,42 @@ impl crate::DynPipelineCache for PipelineCache {} #[derive(Debug)] pub struct AccelerationStructure { resource: Direct3D12::ID3D12Resource, - allocation: Option, + allocation: suballocation::Allocation, } impl crate::DynAccelerationStructure for AccelerationStructure {} impl SwapChain { unsafe fn release_resources(mut self) -> Dxgi::IDXGISwapChain3 { - unsafe { Foundation::HANDLE::free(&mut self.waitable) }; + if let Some(mut waitable) = self.waitable.take() { + unsafe { Foundation::HANDLE::free(&mut waitable) }; + } self.raw } unsafe fn wait( &mut self, - timeout: Option, + timeout: Option, ) -> Result { let timeout_ms = match timeout { Some(duration) => duration.as_millis() as u32, None => Threading::INFINITE, }; - match unsafe { Threading::WaitForSingleObject(self.waitable, timeout_ms) } { - Foundation::WAIT_ABANDONED | Foundation::WAIT_FAILED => Err(crate::SurfaceError::Lost), - Foundation::WAIT_OBJECT_0 => Ok(true), - Foundation::WAIT_TIMEOUT => Ok(false), - other => { - log::error!("Unexpected wait status: 0x{:x?}", other); - Err(crate::SurfaceError::Lost) + + if let Some(waitable) = self.waitable { + match unsafe { Threading::WaitForSingleObject(waitable, timeout_ms) } { + Foundation::WAIT_ABANDONED | Foundation::WAIT_FAILED => { + Err(crate::SurfaceError::Lost) + } + Foundation::WAIT_OBJECT_0 => Ok(true), + Foundation::WAIT_TIMEOUT => Ok(false), + other => { + log::error!("Unexpected wait status: 0x{other:x?}"); + Err(crate::SurfaceError::Lost) + } } + } else { + Ok(true) } } } @@ -1215,7 +1325,9 @@ impl crate::Surface for Surface { Flags: flags.0 as u32, }; let swap_chain1 = match self.target { - SurfaceTarget::Visual(_) | SurfaceTarget::SwapChainPanel(_) => { + SurfaceTarget::Visual(_) + | SurfaceTarget::VisualFromWndHandle { .. } + | SurfaceTarget::SwapChainPanel(_) => { profiling::scope!("IDXGIFactory2::CreateSwapChainForComposition"); unsafe { self.factory.CreateSwapChainForComposition( @@ -1256,12 +1368,40 @@ impl crate::Surface for Surface { }; let swap_chain1 = swap_chain1.map_err(|err| { - log::error!("SwapChain creation error: {}", err); + log::error!("SwapChain creation error: {err}"); crate::SurfaceError::Other("swapchain creation") })?; match &self.target { SurfaceTarget::WndHandle(_) | SurfaceTarget::SurfaceHandle(_) => {} + SurfaceTarget::VisualFromWndHandle { + handle, + dcomp_state, + } => { + let mut dcomp_state = dcomp_state.lock(); + let dcomp_state = + unsafe { dcomp_state.get_or_init(&device.dcomp_lib, handle) }?; + // Set the new swap chain as the content for the backing visual + // and commit the changes to the composition visual tree. + { + profiling::scope!("IDCompositionVisual::SetContent"); + unsafe { dcomp_state.visual.SetContent(&swap_chain1) }.map_err( + |err| { + log::error!("IDCompositionVisual::SetContent failed: {err}"); + crate::SurfaceError::Other("IDCompositionVisual::SetContent") + }, + )?; + } + + // Commit the changes to the composition device. + { + profiling::scope!("IDCompositionDevice::Commit"); + unsafe { dcomp_state.device.Commit() }.map_err(|err| { + log::error!("IDCompositionDevice::Commit failed: {err}"); + crate::SurfaceError::Other("IDCompositionDevice::Commit") + })?; + } + } SurfaceTarget::Visual(visual) => { if let Err(err) = unsafe { visual.SetContent(&swap_chain1) } { log::error!("Unable to SetContent: {err}"); @@ -1299,13 +1439,21 @@ impl crate::Surface for Surface { .into_device_result("MakeWindowAssociation")?; } SurfaceTarget::Visual(_) + | SurfaceTarget::VisualFromWndHandle { .. } | SurfaceTarget::SurfaceHandle(_) | SurfaceTarget::SwapChainPanel(_) => {} } unsafe { swap_chain.SetMaximumFrameLatency(config.maximum_frame_latency) } .into_device_result("SetMaximumFrameLatency")?; - let waitable = unsafe { swap_chain.GetFrameLatencyWaitableObject() }; + + let waitable = match device.options.latency_waitable_object { + wgt::Dx12UseFrameLatencyWaitableObject::None => None, + wgt::Dx12UseFrameLatencyWaitableObject::Wait + | wgt::Dx12UseFrameLatencyWaitableObject::DontWait => { + Some(unsafe { swap_chain.GetFrameLatencyWaitableObject() }) + } + }; let mut resources = Vec::with_capacity(swap_chain_buffer as usize); for i in 0..swap_chain_buffer { @@ -1346,13 +1494,19 @@ impl crate::Surface for Surface { unsafe fn acquire_texture( &self, - timeout: Option, + timeout: Option, _fence: &Fence, ) -> Result>, crate::SurfaceError> { let mut swapchain = self.swap_chain.write(); let sc = swapchain.as_mut().unwrap(); - unsafe { sc.wait(timeout) }?; + match self.options.latency_waitable_object { + wgt::Dx12UseFrameLatencyWaitableObject::None + | wgt::Dx12UseFrameLatencyWaitableObject::DontWait => {} + wgt::Dx12UseFrameLatencyWaitableObject::Wait => { + unsafe { sc.wait(timeout) }?; + } + } let base_index = unsafe { sc.raw.GetCurrentBackBufferIndex() } as usize; let index = (base_index + sc.acquired_count) % sc.resources.len(); @@ -1365,7 +1519,10 @@ impl crate::Surface for Surface { size: sc.size, mip_level_count: 1, sample_count: 1, - allocation: None, + allocation: suballocation::Allocation::none( + suballocation::AllocationType::Texture, + sc.format.theoretical_memory_footprint(sc.size), + ), }; Ok(Some(crate::AcquiredSurfaceTexture { texture, @@ -1440,3 +1597,136 @@ impl crate::Queue for Queue { (1_000_000_000.0 / frequency as f64) as f32 } } +#[derive(Debug)] +pub struct DxilPassthroughShader { + pub shader: Vec, + pub entry_point: String, + pub num_workgroups: (u32, u32, u32), +} + +#[derive(Debug)] +pub struct HlslPassthroughShader { + pub shader: String, + pub entry_point: String, + pub num_workgroups: (u32, u32, u32), +} + +#[derive(Debug)] +pub enum ShaderModuleSource { + Naga(crate::NagaShader), + DxilPassthrough(DxilPassthroughShader), + HlslPassthrough(HlslPassthroughShader), +} + +#[repr(C)] +#[derive(Debug)] +struct MeshShaderPipelineStateStream { + root_signature: *mut Direct3D12::ID3D12RootSignature, + task_shader: Direct3D12::D3D12_SHADER_BYTECODE, + mesh_shader: Direct3D12::D3D12_SHADER_BYTECODE, + pixel_shader: Direct3D12::D3D12_SHADER_BYTECODE, + blend_state: Direct3D12::D3D12_BLEND_DESC, + sample_mask: u32, + rasterizer_state: Direct3D12::D3D12_RASTERIZER_DESC, + depth_stencil_state: Direct3D12::D3D12_DEPTH_STENCIL_DESC, + primitive_topology_type: Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE, + rtv_formats: Direct3D12::D3D12_RT_FORMAT_ARRAY, + dsv_format: Dxgi::Common::DXGI_FORMAT, + sample_desc: Dxgi::Common::DXGI_SAMPLE_DESC, + node_mask: u32, + cached_pso: Direct3D12::D3D12_CACHED_PIPELINE_STATE, + flags: Direct3D12::D3D12_PIPELINE_STATE_FLAGS, +} +impl MeshShaderPipelineStateStream { + /// # Safety + /// + /// Returned bytes contain pointers into this struct, for them to be valid, + /// this struct may be at the same location. As if `as_bytes<'a>(&'a self) -> Vec + 'a` + pub unsafe fn to_bytes(&self) -> Vec { + use Direct3D12::*; + let mut bytes = Vec::new(); + + macro_rules! push_subobject { + ($subobject_type:expr, $data:expr) => {{ + // Ensure 8-byte alignment for the subobject start + let alignment = 8; + let aligned_length = bytes.len().next_multiple_of(alignment); + bytes.resize(aligned_length, 0); + + // Append the type tag (u32) + let tag: u32 = $subobject_type.0 as u32; + bytes.extend_from_slice(&tag.to_ne_bytes()); + + // Align the data + let obj_align = align_of_val(&$data); + let data_start = bytes.len().next_multiple_of(obj_align); + bytes.resize(data_start, 0); + + // Append the data itself + #[allow(clippy::ptr_as_ptr, trivial_casts)] + let data_ptr = &$data as *const _ as *const u8; + let data_size = size_of_val(&$data); + let slice = unsafe { core::slice::from_raw_parts(data_ptr, data_size) }; + bytes.extend_from_slice(slice); + }}; + } + push_subobject!( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, + self.root_signature + ); + if !self.task_shader.pShaderBytecode.is_null() { + push_subobject!(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS, self.task_shader); + } + push_subobject!(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, self.mesh_shader); + if !self.pixel_shader.pShaderBytecode.is_null() { + push_subobject!(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, self.pixel_shader); + } + push_subobject!(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, self.blend_state); + push_subobject!( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, + self.sample_mask + ); + push_subobject!( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, + self.rasterizer_state + ); + push_subobject!( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, + self.depth_stencil_state + ); + push_subobject!( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, + self.primitive_topology_type + ); + if self.rtv_formats.NumRenderTargets != 0 { + push_subobject!( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, + self.rtv_formats + ); + } + if self.dsv_format != Dxgi::Common::DXGI_FORMAT_UNKNOWN { + push_subobject!( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, + self.dsv_format + ); + } + push_subobject!( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, + self.sample_desc + ); + if self.node_mask != 0 { + push_subobject!( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK, + self.node_mask + ); + } + if !self.cached_pso.pCachedBlob.is_null() { + push_subobject!( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO, + self.cached_pso + ); + } + push_subobject!(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, self.flags); + bytes + } +} diff --git a/wgpu-hal/src/dx12/sampler.rs b/wgpu-hal/src/dx12/sampler.rs index b4570fe1b..4b58a0b42 100644 --- a/wgpu-hal/src/dx12/sampler.rs +++ b/wgpu-hal/src/dx12/sampler.rs @@ -2,7 +2,7 @@ //! //! Nearly identical to the Vulkan sampler cache, with added descriptor heap management. -use std::vec::Vec; +use alloc::vec::Vec; use hashbrown::{hash_map::Entry, HashMap}; @@ -43,8 +43,8 @@ impl PartialEq for HashableSamplerDesc { impl Eq for HashableSamplerDesc {} -impl std::hash::Hash for HashableSamplerDesc { - fn hash(&self, state: &mut H) { +impl core::hash::Hash for HashableSamplerDesc { + fn hash(&self, state: &mut H) { self.0.Filter.0.hash(state); self.0.AddressU.0.hash(state); self.0.AddressV.0.hash(state); @@ -226,8 +226,7 @@ impl SamplerHeap { let Entry::Occupied(mut hash_map_entry) = state.mapping.entry(HashableSamplerDesc(desc)) else { log::error!( - "Tried to destroy a sampler that doesn't exist. Sampler description: {:#?}", - desc + "Tried to destroy a sampler that doesn't exist. Sampler description: {desc:#?}" ); return; }; diff --git a/wgpu-hal/src/dx12/shader_compilation.rs b/wgpu-hal/src/dx12/shader_compilation.rs index 834409eef..7d6aaae61 100644 --- a/wgpu-hal/src/dx12/shader_compilation.rs +++ b/wgpu-hal/src/dx12/shader_compilation.rs @@ -1,28 +1,232 @@ -use std::{ffi::CStr, path::PathBuf, string::String, vec::Vec}; +use alloc::{string::String, vec::Vec}; +use core::ffi::CStr; +use std::path::PathBuf; use crate::auxil::dxgi::result::HResult; use thiserror::Error; use windows::{ core::{Interface, PCSTR, PCWSTR}, - Win32::Graphics::Direct3D::{Dxc, Fxc}, + Win32::Graphics::Direct3D::{Dxc, Fxc, ID3DBlob, D3D_SHADER_MACRO}, }; -// Currently this will use Dxc if it is chosen as the dx12 compiler at `Instance` creation time, and will -// fallback to FXC if the Dxc libraries (dxil.dll and dxcompiler.dll) are not found, or if Fxc is chosen at' -// `Instance` creation time. +pub(super) enum CompilerContainer { + Fxc(CompilerFxc), + DynamicDxc(CompilerDynamicDxc), + #[cfg_attr(not(static_dxc), allow(unused))] + StaticDxc(CompilerStaticDxc), +} -pub(super) fn compile_fxc( +pub(super) struct CompilerFxc { + fxc: FxcLib, +} + +pub(super) struct CompilerDynamicDxc { + max_shader_model: wgt::DxcShaderModel, + compiler: Dxc::IDxcCompiler3, + // Has to be held onto for the lifetime of the device otherwise shaders will fail to compile. + // Only needed when using dynamic linking. + _dxc: DxcLib, +} + +pub(super) struct CompilerStaticDxc { + max_shader_model: wgt::DxcShaderModel, + compiler: Dxc::IDxcCompiler3, +} + +#[derive(Debug, Error)] +pub(super) enum GetContainerError { + #[error(transparent)] + Device(#[from] crate::DeviceError), + #[error("Failed to load {0}: {1}")] + FailedToLoad(&'static str, libloading::Error), +} + +impl CompilerContainer { + pub(super) fn new_fxc() -> Result { + FxcLib::new_dynamic().map(|fxc| Self::Fxc(CompilerFxc { fxc })) + } + + pub(super) fn new_dynamic_dxc( + dxc_path: PathBuf, + max_shader_model: wgt::DxcShaderModel, + ) -> Result { + let dxc = DxcLib::new_dynamic(dxc_path) + .map_err(|e| GetContainerError::FailedToLoad("dxcompiler.dll", e))?; + + let compiler = dxc.create_instance::()?; + + Ok(Self::DynamicDxc(CompilerDynamicDxc { + max_shader_model, + compiler, + _dxc: dxc, + })) + } + + /// Creates a [`CompilerContainer`] that delegates to the statically-linked version of DXC. + pub(super) fn new_static_dxc() -> Result { + #[cfg(static_dxc)] + { + unsafe { + let compiler = dxc_create_instance::(|clsid, iid, ppv| { + windows_core::HRESULT(mach_dxcompiler_rs::DxcCreateInstance( + clsid.cast(), + iid.cast(), + ppv, + )) + })?; + + Ok(CompilerContainer::StaticDxc(CompilerStaticDxc { + max_shader_model: wgt::DxcShaderModel::V6_7, + compiler, + })) + } + } + #[cfg(not(static_dxc))] + { + panic!("Attempted to create a static DXC shader compiler, but the static-dxc feature was not enabled") + } + } + + pub(super) fn max_shader_model(&self) -> Option { + match self { + CompilerContainer::Fxc(..) => None, + CompilerContainer::DynamicDxc(CompilerDynamicDxc { + max_shader_model, .. + }) + | CompilerContainer::StaticDxc(CompilerStaticDxc { + max_shader_model, .. + }) => Some(max_shader_model.clone()), + } + } + + pub(super) fn compile( + &self, + device: &super::Device, + source: &str, + source_name: Option<&CStr>, + raw_ep: &str, + stage_bit: wgt::ShaderStages, + full_stage: &str, + ) -> Result { + match self { + CompilerContainer::Fxc(CompilerFxc { fxc }) => compile_fxc( + device, + source, + source_name, + raw_ep, + stage_bit, + full_stage, + fxc, + ), + CompilerContainer::DynamicDxc(CompilerDynamicDxc { compiler, .. }) + | CompilerContainer::StaticDxc(CompilerStaticDxc { compiler, .. }) => compile_dxc( + device, + source, + source_name, + raw_ep, + stage_bit, + full_stage, + compiler, + ), + } + } +} + +type D3DCompileFn = unsafe extern "system" fn( + psrcdata: *const core::ffi::c_void, + srcdatasize: usize, + psourcename: PCSTR, + pdefines: *const D3D_SHADER_MACRO, + pinclude: *mut core::ffi::c_void, + pentrypoint: PCSTR, + ptarget: PCSTR, + flags1: u32, + flags2: u32, + ppcode: *mut *mut core::ffi::c_void, + pperrormsgs: *mut *mut core::ffi::c_void, +) -> windows_core::HRESULT; + +#[derive(Debug)] +struct FxcLib { + // `d3dcompile_fn` points into `_lib`, so `_lib` must be held for as long + // as we want to keep compiling shaders with FXC. + _lib: crate::dx12::DynLib, + d3dcompile_fn: D3DCompileFn, +} + +impl FxcLib { + const PATH: &str = "d3dcompiler_47.dll"; + + fn new_dynamic() -> Result { + unsafe { + let lib = crate::dx12::DynLib::new(Self::PATH) + .map_err(|e| GetContainerError::FailedToLoad(FxcLib::PATH, e))?; + let d3dcompile_fn: D3DCompileFn = *lib.get::(c"D3DCompile".to_bytes())?; + + Ok(Self { + _lib: lib, + d3dcompile_fn, + }) + } + } + + #[allow(clippy::too_many_arguments)] + fn compile( + &self, + source: &str, + source_name: Option<&CStr>, + raw_ep: &str, + full_stage: &str, + compile_flags: u32, + shader_data: &mut Option, + error: &mut Option, + ) -> Result, crate::DeviceError> { + unsafe { + let raw_ep = alloc::ffi::CString::new(raw_ep).unwrap(); + let full_stage = alloc::ffi::CString::new(full_stage).unwrap(); + + // If no name has been set, D3DCompile wants the null pointer. + let source_name = source_name + .map(|cstr| cstr.as_ptr().cast()) + .unwrap_or(core::ptr::null()); + + let shader_data: *mut Option = shader_data; + let error: *mut Option = error; + + { + profiling::scope!("Fxc::D3DCompile"); + Ok((self.d3dcompile_fn)( + source.as_ptr().cast(), + source.len(), + PCSTR(source_name), + core::ptr::null(), + core::ptr::null_mut(), + PCSTR(raw_ep.as_ptr().cast()), + PCSTR(full_stage.as_ptr().cast()), + compile_flags, + 0, + shader_data.cast(), + error.cast(), + ) + .ok()) + } + } + } +} + +fn compile_fxc( device: &super::Device, source: &str, source_name: Option<&CStr>, raw_ep: &str, stage_bit: wgt::ShaderStages, full_stage: &str, + fxc: &FxcLib, ) -> Result { profiling::scope!("compile_fxc"); - let mut shader_data = None; let mut compile_flags = Fxc::D3DCOMPILE_ENABLE_STRICTNESS; if device + .shared .private_caps .instance_flags .contains(wgt::InstanceFlags::DEBUG) @@ -30,32 +234,17 @@ pub(super) fn compile_fxc( compile_flags |= Fxc::D3DCOMPILE_DEBUG | Fxc::D3DCOMPILE_SKIP_OPTIMIZATION; } - let raw_ep = std::ffi::CString::new(raw_ep).unwrap(); - let full_stage = std::ffi::CString::new(full_stage).unwrap(); - - // If no name has been set, D3DCompile wants the null pointer. - let source_name = source_name - .map(|cstr| cstr.as_ptr().cast()) - .unwrap_or(core::ptr::null()); - + let mut shader_data = None; let mut error = None; - let hr = unsafe { - profiling::scope!("Fxc::D3DCompile"); - Fxc::D3DCompile( - // TODO: Update low-level bindings to accept a slice here - source.as_ptr().cast(), - source.len(), - PCSTR(source_name), - None, - None, - PCSTR(raw_ep.as_ptr().cast()), - PCSTR(full_stage.as_ptr().cast()), - compile_flags, - 0, - &mut shader_data, - Some(&mut error), - ) - }; + let hr = fxc.compile( + source, + source_name, + raw_ep, + full_stage, + compile_flags, + &mut shader_data, + &mut error, + )?; match hr { Ok(()) => { @@ -65,9 +254,9 @@ pub(super) fn compile_fxc( Err(e) => { let mut full_msg = format!("FXC D3DCompile error ({e})"); if let Some(error) = error { - use std::fmt::Write as _; + use core::fmt::Write as _; let message = unsafe { - std::slice::from_raw_parts( + core::slice::from_raw_parts( error.GetBufferPointer().cast(), error.GetBufferSize(), ) @@ -133,89 +322,6 @@ unsafe fn dxc_create_instance( result__.ok_or(crate::DeviceError::Unexpected) } -// Destructor order should be fine since _dxil and _dxc don't rely on each other. -pub(super) struct DxcContainer { - pub(super) max_shader_model: wgt::DxcShaderModel, - compiler: Dxc::IDxcCompiler3, - utils: Dxc::IDxcUtils, - validator: Option, - // Has to be held onto for the lifetime of the device otherwise shaders will fail to compile. - // Only needed when using dynamic linking. - _dxc: Option, - // Also Has to be held onto for the lifetime of the device otherwise shaders will fail to validate. - // Only needed when using dynamic linking. - _dxil: Option, -} - -#[derive(Debug, Error)] -pub(super) enum GetDynamicDXCContainerError { - #[error(transparent)] - Device(#[from] crate::DeviceError), - #[error("Failed to load {0}: {1}")] - FailedToLoad(&'static str, libloading::Error), -} - -pub(super) fn get_dynamic_dxc_container( - dxc_path: PathBuf, - dxil_path: PathBuf, - max_shader_model: wgt::DxcShaderModel, -) -> Result { - let dxc = DxcLib::new_dynamic(dxc_path) - .map_err(|e| GetDynamicDXCContainerError::FailedToLoad("dxcompiler.dll", e))?; - - let dxil = DxcLib::new_dynamic(dxil_path) - .map_err(|e| GetDynamicDXCContainerError::FailedToLoad("dxil.dll", e))?; - - let compiler = dxc.create_instance::()?; - let utils = dxc.create_instance::()?; - let validator = dxil.create_instance::()?; - - Ok(DxcContainer { - max_shader_model, - compiler, - utils, - validator: Some(validator), - _dxc: Some(dxc), - _dxil: Some(dxil), - }) -} - -/// Creates a [`DxcContainer`] that delegates to the statically-linked version of DXC. -pub(super) fn get_static_dxc_container() -> Result { - #[cfg(static_dxc)] - { - unsafe { - let compiler = dxc_create_instance::(|clsid, iid, ppv| { - windows_core::HRESULT(mach_dxcompiler_rs::DxcCreateInstance( - clsid.cast(), - iid.cast(), - ppv, - )) - })?; - let utils = dxc_create_instance::(|clsid, iid, ppv| { - windows_core::HRESULT(mach_dxcompiler_rs::DxcCreateInstance( - clsid.cast(), - iid.cast(), - ppv, - )) - })?; - - Ok(DxcContainer { - max_shader_model: wgt::DxcShaderModel::V6_7, - compiler, - utils, - validator: None, - _dxc: None, - _dxil: None, - }) - } - } - #[cfg(not(static_dxc))] - { - panic!("Attempted to create a static DXC shader compiler, but the static-dxc feature was not enabled") - } -} - /// Owned PCWSTR #[allow(clippy::upper_case_acronyms)] struct OPCWSTR { @@ -251,14 +357,14 @@ fn as_err_str(blob: &Dxc::IDxcBlobUtf8) -> Result<&str, crate::DeviceError> { .map_err(|_| crate::DeviceError::Unexpected) } -pub(super) fn compile_dxc( +fn compile_dxc( device: &crate::dx12::Device, source: &str, source_name: Option<&CStr>, raw_ep: &str, stage_bit: wgt::ShaderStages, full_stage: &str, - dxc_container: &DxcContainer, + compiler: &Dxc::IDxcCompiler3, ) -> Result { profiling::scope!("compile_dxc"); @@ -285,11 +391,8 @@ pub(super) fn compile_dxc( Dxc::DXC_ARG_ENABLE_STRICTNESS, ]); - if dxc_container.validator.is_some() { - compile_args.push(Dxc::DXC_ARG_SKIP_VALIDATION); // Disable implicit validation to work around bugs when dxil.dll isn't in the local directory.) - } - if device + .shared .private_caps .instance_flags .contains(wgt::InstanceFlags::DEBUG) @@ -308,12 +411,9 @@ pub(super) fn compile_dxc( Encoding: Dxc::DXC_CP_UTF8.0, }; - let compile_res: Dxc::IDxcResult = unsafe { - dxc_container - .compiler - .Compile(&buffer, Some(&compile_args), None) - } - .into_device_result("Compile")?; + let compile_res: Dxc::IDxcResult = + unsafe { compiler.Compile(&buffer, Some(&compile_args), None) } + .into_device_result("Compile")?; drop(compile_args); drop(source_name); @@ -333,25 +433,5 @@ pub(super) fn compile_dxc( let blob = get_output::(&compile_res, Dxc::DXC_OUT_OBJECT)?; - if let Some(validator) = &dxc_container.validator { - let err_blob = { - let res = unsafe { validator.Validate(&blob, Dxc::DxcValidatorFlags_InPlaceEdit) } - .into_device_result("Validate")?; - - unsafe { res.GetErrorBuffer() }.into_device_result("GetErrorBuffer")? - }; - - let size = unsafe { err_blob.GetBufferSize() }; - if size != 0 { - let err_blob = unsafe { dxc_container.utils.GetBlobAsUtf8(&err_blob) } - .into_device_result("GetBlobAsUtf8")?; - let err = as_err_str(&err_blob)?; - return Err(crate::PipelineError::Linkage( - stage_bit, - format!("DXC validation error: {err}"), - )); - } - } - Ok(crate::dx12::CompiledShader::Dxc(blob)) } diff --git a/wgpu-hal/src/dx12/suballocation.rs b/wgpu-hal/src/dx12/suballocation.rs index 89ce6c5d0..8cee41023 100644 --- a/wgpu-hal/src/dx12/suballocation.rs +++ b/wgpu-hal/src/dx12/suballocation.rs @@ -1,250 +1,625 @@ +use alloc::sync::Arc; use gpu_allocator::{d3d12::AllocationCreateDesc, MemoryLocation}; use parking_lot::Mutex; -use windows::Win32::Graphics::Direct3D12; +use windows::Win32::Graphics::{Direct3D12, Dxgi}; -use crate::auxil::dxgi::result::HResult as _; +use crate::{ + auxil::dxgi::{name::ObjectExt, result::HResult as _}, + dx12::conv, +}; #[derive(Debug)] -pub(crate) struct GpuAllocatorWrapper { - pub(crate) allocator: gpu_allocator::d3d12::Allocator, +pub(crate) enum AllocationType { + Buffer, + Texture, + AccelerationStructure, } #[derive(Debug)] -pub(crate) struct AllocationWrapper { - pub(crate) allocation: gpu_allocator::d3d12::Allocation, +enum AllocationInner { + /// This resource is suballocated from a heap. + Placed { + inner: gpu_allocator::d3d12::Allocation, + }, + /// This resource is a committed resource and does not belong to a + /// suballocated heap. We store an approximate size, so we can manage our counters + /// correctly. + /// + /// This is only used for Intel Xe drivers, which have a bug that + /// prevents suballocation from working correctly. + Committed { size: u64 }, } -pub(crate) fn create_allocator_wrapper( - raw: &Direct3D12::ID3D12Device, - memory_hints: &wgt::MemoryHints, -) -> Result, crate::DeviceError> { - // TODO: the allocator's configuration should take hardware capability into - // account. - let mb = 1024 * 1024; - let allocation_sizes = match memory_hints { - wgt::MemoryHints::Performance => gpu_allocator::AllocationSizes::default(), - wgt::MemoryHints::MemoryUsage => gpu_allocator::AllocationSizes::new(8 * mb, 4 * mb), - wgt::MemoryHints::Manual { - suballocated_device_memory_block_size, - } => { - // TODO: Would it be useful to expose the host size in memory hints - // instead of always using half of the device size? - let device_size = suballocated_device_memory_block_size.start; - let host_size = device_size / 2; - gpu_allocator::AllocationSizes::new(device_size, host_size) +#[derive(Debug)] +pub(crate) struct Allocation { + inner: AllocationInner, + ty: AllocationType, +} + +impl Allocation { + pub fn placed(inner: gpu_allocator::d3d12::Allocation, ty: AllocationType) -> Self { + Self { + inner: AllocationInner::Placed { inner }, + ty, } - }; + } - match gpu_allocator::d3d12::Allocator::new(&gpu_allocator::d3d12::AllocatorCreateDesc { - device: gpu_allocator::d3d12::ID3D12DeviceVersion::Device(raw.clone()), - debug_settings: Default::default(), - allocation_sizes, - }) { - Ok(allocator) => Ok(Mutex::new(GpuAllocatorWrapper { allocator })), - Err(e) => { - log::error!("Failed to create d3d12 allocator, error: {}", e); - Err(e)? + pub fn none(ty: AllocationType, size: u64) -> Self { + Self { + inner: AllocationInner::Committed { size }, + ty, + } + } + + pub fn size(&self) -> u64 { + match self.inner { + AllocationInner::Placed { ref inner } => inner.size(), + AllocationInner::Committed { size } => size, } } } -pub(crate) fn create_buffer_resource( - device: &crate::dx12::Device, - desc: &crate::BufferDescriptor, - raw_desc: Direct3D12::D3D12_RESOURCE_DESC, -) -> Result<(Direct3D12::ID3D12Resource, Option), crate::DeviceError> { - let is_cpu_read = desc.usage.contains(wgt::BufferUses::MAP_READ); - let is_cpu_write = desc.usage.contains(wgt::BufferUses::MAP_WRITE); - - // Workaround for Intel Xe drivers - if !device.private_caps.suballocation_supported { - return create_committed_buffer_resource(device, desc, raw_desc) - .map(|resource| (resource, None)); - } - - let location = match (is_cpu_read, is_cpu_write) { - (true, true) => MemoryLocation::CpuToGpu, - (true, false) => MemoryLocation::GpuToCpu, - (false, true) => MemoryLocation::CpuToGpu, - (false, false) => MemoryLocation::GpuOnly, - }; - - let name = desc.label.unwrap_or("Unlabeled buffer"); - - let mut allocator = device.mem_allocator.lock(); - - let allocation_desc = AllocationCreateDesc::from_d3d12_resource_desc( - allocator.allocator.device(), - &raw_desc, - name, - location, - ); - let allocation = allocator.allocator.allocate(&allocation_desc)?; - let mut resource = None; - - unsafe { - device.raw.CreatePlacedResource( - allocation.heap(), - allocation.offset(), - &raw_desc, - Direct3D12::D3D12_RESOURCE_STATE_COMMON, - None, - &mut resource, - ) - } - .into_device_result("Placed buffer creation")?; - - let resource = resource.ok_or(crate::DeviceError::Unexpected)?; - - device - .counters - .buffer_memory - .add(allocation.size() as isize); - - Ok((resource, Some(AllocationWrapper { allocation }))) +#[derive(Clone)] +pub(crate) struct Allocator { + inner: Arc>, + device_memblock_size: u64, + host_memblock_size: u64, + pub memory_budget_thresholds: wgt::MemoryBudgetThresholds, } -pub(crate) fn create_texture_resource( - device: &crate::dx12::Device, - desc: &crate::TextureDescriptor, - raw_desc: Direct3D12::D3D12_RESOURCE_DESC, -) -> Result<(Direct3D12::ID3D12Resource, Option), crate::DeviceError> { - // Workaround for Intel Xe drivers - if !device.private_caps.suballocation_supported { - return create_committed_texture_resource(device, desc, raw_desc) - .map(|resource| (resource, None)); +impl Allocator { + pub(crate) fn new( + raw: &Direct3D12::ID3D12Device, + memory_hints: &wgt::MemoryHints, + memory_budget_thresholds: wgt::MemoryBudgetThresholds, + ) -> Result { + // TODO: the allocator's configuration should take hardware capability into + // account. + const MB: u64 = 1024 * 1024; + let (device_memblock_size, host_memblock_size) = match memory_hints { + wgt::MemoryHints::Performance => (256 * MB, 64 * MB), + wgt::MemoryHints::MemoryUsage => (8 * MB, 4 * MB), + wgt::MemoryHints::Manual { + suballocated_device_memory_block_size, + } => { + // TODO: Would it be useful to expose the host size in memory hints + // instead of always using half of the device size? + let device_size = suballocated_device_memory_block_size.start; + let host_size = device_size / 2; + (device_size, host_size) + } + }; + + // gpu_allocator clamps the sizes between 4MiB and 256MiB, but we clamp them ourselves since we use + // the sizes when detecting high memory pressure and there is no way to query the values otherwise. + + let device_memblock_size = device_memblock_size.clamp(4 * MB, 256 * MB); + let host_memblock_size = host_memblock_size.clamp(4 * MB, 256 * MB); + + let allocation_sizes = + gpu_allocator::AllocationSizes::new(device_memblock_size, host_memblock_size); + + let allocator_desc = gpu_allocator::d3d12::AllocatorCreateDesc { + device: gpu_allocator::d3d12::ID3D12DeviceVersion::Device(raw.clone()), + debug_settings: Default::default(), + allocation_sizes, + }; + + let allocator = gpu_allocator::d3d12::Allocator::new(&allocator_desc).inspect_err(|e| { + log::error!("Failed to create d3d12 allocator, error: {e}"); + })?; + + Ok(Self { + inner: Arc::new(Mutex::new(allocator)), + device_memblock_size, + host_memblock_size, + memory_budget_thresholds, + }) } - let location = MemoryLocation::GpuOnly; + pub(crate) fn generate_report(&self) -> wgt::AllocatorReport { + let mut upstream = self.inner.lock().generate_report(); - let name = desc.label.unwrap_or("Unlabeled texture"); + let allocations = upstream + .allocations + .iter_mut() + .map(|alloc| wgt::AllocationReport { + name: core::mem::take(&mut alloc.name), + offset: alloc.offset, + size: alloc.size, + }) + .collect(); - let mut allocator = device.mem_allocator.lock(); - let allocation_desc = AllocationCreateDesc::from_d3d12_resource_desc( - allocator.allocator.device(), - &raw_desc, - name, - location, - ); - let allocation = allocator.allocator.allocate(&allocation_desc)?; - let mut resource = None; + let blocks = upstream + .blocks + .iter() + .map(|block| wgt::MemoryBlockReport { + size: block.size, + allocations: block.allocations.clone(), + }) + .collect(); - unsafe { - device.raw.CreatePlacedResource( - allocation.heap(), - allocation.offset(), - &raw_desc, - Direct3D12::D3D12_RESOURCE_STATE_COMMON, - None, // clear value - &mut resource, - ) + wgt::AllocatorReport { + allocations, + blocks, + total_allocated_bytes: upstream.total_allocated_bytes, + total_reserved_bytes: upstream.total_reserved_bytes, + } } - .into_device_result("Placed texture creation")?; - - let resource = resource.ok_or(crate::DeviceError::Unexpected)?; - - device - .counters - .texture_memory - .add(allocation.size() as isize); - - Ok((resource, Some(AllocationWrapper { allocation }))) } -pub(crate) fn create_acceleration_structure_resource( - device: &crate::dx12::Device, - desc: &crate::AccelerationStructureDescriptor, - raw_desc: Direct3D12::D3D12_RESOURCE_DESC, -) -> Result<(Direct3D12::ID3D12Resource, Option), crate::DeviceError> { - // Workaround for Intel Xe drivers - if !device.private_caps.suballocation_supported { - return create_committed_acceleration_structure_resource(device, desc, raw_desc) - .map(|resource| (resource, None)); +/// To allow us to construct buffers from both a `Device` and `CommandEncoder` +/// without needing each function to take a million arguments, we create a +/// borrowed context struct that contains the relevant members. +pub(crate) struct DeviceAllocationContext<'a> { + pub(crate) raw: &'a Direct3D12::ID3D12Device, + pub(crate) shared: &'a super::DeviceShared, + pub(crate) mem_allocator: &'a Allocator, + pub(crate) counters: &'a wgt::HalCounters, +} + +impl<'a> From<&'a super::Device> for DeviceAllocationContext<'a> { + fn from(device: &'a super::Device) -> Self { + Self { + raw: &device.raw, + shared: &device.shared, + mem_allocator: &device.mem_allocator, + counters: &device.counters, + } + } +} + +impl<'a> From<&'a super::CommandEncoder> for DeviceAllocationContext<'a> { + fn from(encoder: &'a super::CommandEncoder) -> Self { + Self { + raw: &encoder.device, + shared: &encoder.shared, + mem_allocator: &encoder.mem_allocator, + counters: &encoder.counters, + } + } +} + +impl<'a> DeviceAllocationContext<'a> { + /////////////////////// + // Resource Creation // + /////////////////////// + + pub(crate) fn create_buffer( + &self, + desc: &crate::BufferDescriptor, + ) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> { + let is_cpu_read = desc.usage.contains(wgt::BufferUses::MAP_READ); + let is_cpu_write = desc.usage.contains(wgt::BufferUses::MAP_WRITE); + + let location = match (is_cpu_read, is_cpu_write) { + (true, true) => MemoryLocation::CpuToGpu, + (true, false) => MemoryLocation::GpuToCpu, + (false, true) => MemoryLocation::CpuToGpu, + (false, false) => MemoryLocation::GpuOnly, + }; + + let raw_desc = conv::map_buffer_descriptor(desc); + let allocation_info = + self.error_if_would_oom_on_resource_allocation(&raw_desc, location)?; + + let (resource, allocation) = if self.shared.private_caps.suballocation_supported { + self.create_placed_buffer(desc, raw_desc, allocation_info, location)? + } else { + self.create_committed_buffer(raw_desc, location)? + }; + + if let Some(label) = desc.label { + resource.set_name(label)?; + } + + self.counters.buffer_memory.add(allocation.size() as isize); + + Ok((resource, allocation)) } - let location = MemoryLocation::GpuOnly; + pub(crate) fn create_texture( + &self, + desc: &crate::TextureDescriptor, + raw_desc: Direct3D12::D3D12_RESOURCE_DESC, + ) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> { + let location = MemoryLocation::GpuOnly; + let allocation_info = + self.error_if_would_oom_on_resource_allocation(&raw_desc, location)?; - let name = desc.label.unwrap_or("Unlabeled acceleration structure"); + let (resource, allocation) = if self.shared.private_caps.suballocation_supported { + self.create_placed_texture(desc, raw_desc, allocation_info, location)? + } else { + self.create_committed_texture(desc, raw_desc)? + }; - let mut allocator = device.mem_allocator.lock(); + if let Some(label) = desc.label { + resource.set_name(label)?; + } - let allocation_desc = AllocationCreateDesc::from_d3d12_resource_desc( - allocator.allocator.device(), - &raw_desc, - name, - location, - ); - let allocation = allocator.allocator.allocate(&allocation_desc)?; - let mut resource = None; + self.counters.texture_memory.add(allocation.size() as isize); - unsafe { - device.raw.CreatePlacedResource( - allocation.heap(), - allocation.offset(), - &raw_desc, - Direct3D12::D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE, - None, - &mut resource, - ) + Ok((resource, allocation)) } - .into_device_result("Placed acceleration structure creation")?; - let resource = resource.ok_or(crate::DeviceError::Unexpected)?; + pub(crate) fn create_acceleration_structure( + &self, + desc: &crate::AccelerationStructureDescriptor, + raw_desc: Direct3D12::D3D12_RESOURCE_DESC, + ) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> { + let location = MemoryLocation::GpuOnly; + let allocation_info = + self.error_if_would_oom_on_resource_allocation(&raw_desc, location)?; - device - .counters - .acceleration_structure_memory - .add(allocation.size() as isize); + let (resource, allocation) = if self.shared.private_caps.suballocation_supported { + self.create_placed_acceleration_structure(desc, raw_desc, allocation_info, location)? + } else { + self.create_committed_acceleration_structure(desc, raw_desc)? + }; - Ok((resource, Some(AllocationWrapper { allocation }))) -} + if let Some(label) = desc.label { + resource.set_name(label)?; + } -pub(crate) fn free_buffer_allocation( - device: &crate::dx12::Device, - allocation: AllocationWrapper, - allocator: &Mutex, -) { - device - .counters - .buffer_memory - .sub(allocation.allocation.size() as isize); - match allocator.lock().allocator.free(allocation.allocation) { - Ok(_) => (), - // TODO: Don't panic here - Err(e) => panic!("Failed to destroy dx12 buffer, {e}"), - }; -} + self.counters + .acceleration_structure_memory + .add(allocation.size() as isize); -pub(crate) fn free_texture_allocation( - device: &crate::dx12::Device, - allocation: AllocationWrapper, - allocator: &Mutex, -) { - device - .counters - .texture_memory - .sub(allocation.allocation.size() as isize); - match allocator.lock().allocator.free(allocation.allocation) { - Ok(_) => (), - // TODO: Don't panic here - Err(e) => panic!("Failed to destroy dx12 texture, {e}"), - }; -} + Ok((resource, allocation)) + } -pub(crate) fn free_acceleration_structure_allocation( - device: &crate::dx12::Device, - allocation: AllocationWrapper, - allocator: &Mutex, -) { - device - .counters - .acceleration_structure_memory - .sub(allocation.allocation.size() as isize); - match allocator.lock().allocator.free(allocation.allocation) { - Ok(_) => (), - // TODO: Don't panic here - Err(e) => panic!("Failed to destroy dx12 acceleration structure, {e}"), - }; + ////////////////////////// + // Resource Destruction // + ////////////////////////// + + pub(crate) fn free_resource( + &self, + resource: Direct3D12::ID3D12Resource, + allocation: Allocation, + ) { + // Make sure the resource is released before we free the allocation. + drop(resource); + + let counter = match allocation.ty { + AllocationType::Buffer => &self.counters.buffer_memory, + AllocationType::Texture => &self.counters.texture_memory, + AllocationType::AccelerationStructure => &self.counters.acceleration_structure_memory, + }; + counter.sub(allocation.size() as isize); + + if let AllocationInner::Placed { inner } = allocation.inner { + match self.mem_allocator.inner.lock().free(inner) { + Ok(_) => (), + // TODO: Don't panic here + Err(e) => panic!("Failed to destroy dx12 {:?}, {e}", allocation.ty), + }; + } + } + + /////////////////////////////// + // Placed Resource Creation /// + /////////////////////////////// + + fn create_placed_buffer( + &self, + desc: &crate::BufferDescriptor<'_>, + raw_desc: Direct3D12::D3D12_RESOURCE_DESC, + allocation_info: Direct3D12::D3D12_RESOURCE_ALLOCATION_INFO, + location: MemoryLocation, + ) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> { + let name = desc.label.unwrap_or("Unlabeled buffer"); + + let mut allocator = self.mem_allocator.inner.lock(); + + let allocation_desc = AllocationCreateDesc { + name, + location, + size: allocation_info.SizeInBytes, + alignment: allocation_info.Alignment, + resource_category: gpu_allocator::d3d12::ResourceCategory::from(&raw_desc), + }; + + let allocation = allocator.allocate(&allocation_desc)?; + let mut resource = None; + unsafe { + self.raw.CreatePlacedResource( + allocation.heap(), + allocation.offset(), + &raw_desc, + Direct3D12::D3D12_RESOURCE_STATE_COMMON, + None, + &mut resource, + ) + } + .into_device_result("Placed buffer creation")?; + + let resource = resource.ok_or(crate::DeviceError::Unexpected)?; + let wrapped_allocation = Allocation::placed(allocation, AllocationType::Buffer); + + Ok((resource, wrapped_allocation)) + } + + fn create_placed_texture( + &self, + desc: &crate::TextureDescriptor<'_>, + raw_desc: Direct3D12::D3D12_RESOURCE_DESC, + allocation_info: Direct3D12::D3D12_RESOURCE_ALLOCATION_INFO, + location: MemoryLocation, + ) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> { + let name = desc.label.unwrap_or("Unlabeled texture"); + + let mut allocator = self.mem_allocator.inner.lock(); + + let allocation_desc = AllocationCreateDesc { + name, + location, + size: allocation_info.SizeInBytes, + alignment: allocation_info.Alignment, + resource_category: gpu_allocator::d3d12::ResourceCategory::from(&raw_desc), + }; + + let allocation = allocator.allocate(&allocation_desc)?; + let mut resource = None; + unsafe { + self.raw.CreatePlacedResource( + allocation.heap(), + allocation.offset(), + &raw_desc, + Direct3D12::D3D12_RESOURCE_STATE_COMMON, + None, // clear value + &mut resource, + ) + } + .into_device_result("Placed texture creation")?; + + let resource = resource.ok_or(crate::DeviceError::Unexpected)?; + let wrapped_allocation = Allocation::placed(allocation, AllocationType::Texture); + + Ok((resource, wrapped_allocation)) + } + + fn create_placed_acceleration_structure( + &self, + desc: &crate::AccelerationStructureDescriptor<'_>, + raw_desc: Direct3D12::D3D12_RESOURCE_DESC, + allocation_info: Direct3D12::D3D12_RESOURCE_ALLOCATION_INFO, + location: MemoryLocation, + ) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> { + let name = desc.label.unwrap_or("Unlabeled acceleration structure"); + + let mut allocator = self.mem_allocator.inner.lock(); + + let allocation_desc = AllocationCreateDesc { + name, + location, + size: allocation_info.SizeInBytes, + alignment: allocation_info.Alignment, + resource_category: gpu_allocator::d3d12::ResourceCategory::from(&raw_desc), + }; + + let allocation = allocator.allocate(&allocation_desc)?; + let mut resource = None; + unsafe { + self.raw.CreatePlacedResource( + allocation.heap(), + allocation.offset(), + &raw_desc, + Direct3D12::D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE, + None, + &mut resource, + ) + } + .into_device_result("Placed acceleration structure creation")?; + + let resource = resource.ok_or(crate::DeviceError::Unexpected)?; + let wrapped_allocation = + Allocation::placed(allocation, AllocationType::AccelerationStructure); + + Ok((resource, wrapped_allocation)) + } + + ///////////////////////////////// + // Committed Resource Creation // + ///////////////////////////////// + + fn create_committed_buffer( + &self, + raw_desc: Direct3D12::D3D12_RESOURCE_DESC, + location: MemoryLocation, + ) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> { + let is_uma = matches!( + self.shared.private_caps.memory_architecture, + crate::dx12::MemoryArchitecture::Unified { .. } + ); + + let heap_properties = Direct3D12::D3D12_HEAP_PROPERTIES { + Type: Direct3D12::D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: match location { + MemoryLocation::GpuOnly => Direct3D12::D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE, + MemoryLocation::CpuToGpu => Direct3D12::D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE, + MemoryLocation::GpuToCpu => Direct3D12::D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + _ => unreachable!(), + }, + MemoryPoolPreference: match (is_uma, location) { + // On dedicated GPUs, we only use L1 for GPU-only allocations. + (false, MemoryLocation::GpuOnly) => Direct3D12::D3D12_MEMORY_POOL_L1, + (_, _) => Direct3D12::D3D12_MEMORY_POOL_L0, + }, + CreationNodeMask: 0, + VisibleNodeMask: 0, + }; + + let mut resource = None; + + unsafe { + self.raw.CreateCommittedResource( + &heap_properties, + if self.shared.private_caps.heap_create_not_zeroed { + Direct3D12::D3D12_HEAP_FLAG_CREATE_NOT_ZEROED + } else { + Direct3D12::D3D12_HEAP_FLAG_NONE + }, + &raw_desc, + Direct3D12::D3D12_RESOURCE_STATE_COMMON, + None, + &mut resource, + ) + } + .into_device_result("Committed buffer creation")?; + + let resource = resource.ok_or(crate::DeviceError::Unexpected)?; + let wrapped_allocation = Allocation::none(AllocationType::Buffer, raw_desc.Width); + + Ok((resource, wrapped_allocation)) + } + + fn create_committed_texture( + &self, + desc: &crate::TextureDescriptor, + raw_desc: Direct3D12::D3D12_RESOURCE_DESC, + ) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> { + let heap_properties = Direct3D12::D3D12_HEAP_PROPERTIES { + Type: Direct3D12::D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: Direct3D12::D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE, + MemoryPoolPreference: match self.shared.private_caps.memory_architecture { + crate::dx12::MemoryArchitecture::NonUnified => Direct3D12::D3D12_MEMORY_POOL_L1, + crate::dx12::MemoryArchitecture::Unified { .. } => Direct3D12::D3D12_MEMORY_POOL_L0, + }, + CreationNodeMask: 0, + VisibleNodeMask: 0, + }; + + let mut resource = None; + + unsafe { + self.raw.CreateCommittedResource( + &heap_properties, + if self.shared.private_caps.heap_create_not_zeroed { + Direct3D12::D3D12_HEAP_FLAG_CREATE_NOT_ZEROED + } else { + Direct3D12::D3D12_HEAP_FLAG_NONE + }, + &raw_desc, + Direct3D12::D3D12_RESOURCE_STATE_COMMON, + None, // clear value + &mut resource, + ) + } + .into_device_result("Committed texture creation")?; + + let resource = resource.ok_or(crate::DeviceError::Unexpected)?; + let wrapped_allocation = Allocation::none( + AllocationType::Texture, + desc.format.theoretical_memory_footprint(desc.size), + ); + + Ok((resource, wrapped_allocation)) + } + + fn create_committed_acceleration_structure( + &self, + desc: &crate::AccelerationStructureDescriptor, + raw_desc: Direct3D12::D3D12_RESOURCE_DESC, + ) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> { + let heap_properties = Direct3D12::D3D12_HEAP_PROPERTIES { + Type: Direct3D12::D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: Direct3D12::D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE, + MemoryPoolPreference: match self.shared.private_caps.memory_architecture { + crate::dx12::MemoryArchitecture::NonUnified => Direct3D12::D3D12_MEMORY_POOL_L1, + crate::dx12::MemoryArchitecture::Unified { .. } => Direct3D12::D3D12_MEMORY_POOL_L0, + }, + CreationNodeMask: 0, + VisibleNodeMask: 0, + }; + + let mut resource = None; + + unsafe { + self.raw.CreateCommittedResource( + &heap_properties, + if self.shared.private_caps.heap_create_not_zeroed { + Direct3D12::D3D12_HEAP_FLAG_CREATE_NOT_ZEROED + } else { + Direct3D12::D3D12_HEAP_FLAG_NONE + }, + &raw_desc, + Direct3D12::D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE, + None, + &mut resource, + ) + } + .into_device_result("Committed acceleration structure creation")?; + + let resource = resource.ok_or(crate::DeviceError::Unexpected)?; + let wrapped_allocation = Allocation::none(AllocationType::AccelerationStructure, desc.size); + + Ok((resource, wrapped_allocation)) + } + + fn error_if_would_oom_on_resource_allocation( + &self, + desc: &Direct3D12::D3D12_RESOURCE_DESC, + location: MemoryLocation, + ) -> Result { + let allocation_info = unsafe { + self.raw + .GetResourceAllocationInfo(0, core::slice::from_ref(desc)) + }; + + // Some versions of WARP return SizeInBytes == 0 for very large + // allocations. Proceeding to attempt to allocate a zero-sized resource + // will result in a device lost error, so it seems preferable to return + // an out of memory error now. + if allocation_info.SizeInBytes == 0 { + return Err(crate::DeviceError::OutOfMemory); + } + + let Some(threshold) = self + .mem_allocator + .memory_budget_thresholds + .for_resource_creation + else { + return Ok(allocation_info); + }; + + let memory_segment_group = match location { + MemoryLocation::Unknown => unreachable!(), + MemoryLocation::GpuOnly => Dxgi::DXGI_MEMORY_SEGMENT_GROUP_LOCAL, + MemoryLocation::CpuToGpu | MemoryLocation::GpuToCpu => { + match self.shared.private_caps.memory_architecture { + super::MemoryArchitecture::Unified { .. } => { + Dxgi::DXGI_MEMORY_SEGMENT_GROUP_LOCAL + } + super::MemoryArchitecture::NonUnified => { + Dxgi::DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL + } + } + } + }; + + let info = self + .shared + .adapter + .query_video_memory_info(memory_segment_group)?; + + let memblock_size = match location { + MemoryLocation::Unknown => unreachable!(), + MemoryLocation::GpuOnly => self.mem_allocator.device_memblock_size, + MemoryLocation::CpuToGpu | MemoryLocation::GpuToCpu => { + self.mem_allocator.host_memblock_size + } + }; + + if info + .CurrentUsage + .checked_add(allocation_info.SizeInBytes.max(memblock_size)) + .is_none_or(|usage| usage >= info.Budget / 100 * threshold as u64) + { + return Err(crate::DeviceError::OutOfMemory); + } + + Ok(allocation_info) + } } impl From for crate::DeviceError { @@ -252,7 +627,7 @@ impl From for crate::DeviceError { match result { gpu_allocator::AllocationError::OutOfMemory => Self::OutOfMemory, gpu_allocator::AllocationError::FailedToMap(e) => { - log::error!("DX12 gpu-allocator: Failed to map: {}", e); + log::error!("DX12 gpu-allocator: Failed to map: {e}"); Self::Lost } gpu_allocator::AllocationError::NoCompatibleMemoryTypeFound => { @@ -264,15 +639,12 @@ impl From for crate::DeviceError { Self::Lost } gpu_allocator::AllocationError::InvalidAllocatorCreateDesc(e) => { - log::error!( - "DX12 gpu-allocator: Invalid Allocator Creation Description: {}", - e - ); + log::error!("DX12 gpu-allocator: Invalid Allocator Creation Description: {e}"); Self::Lost } gpu_allocator::AllocationError::Internal(e) => { - log::error!("DX12 gpu-allocator: Internal Error: {}", e); + log::error!("DX12 gpu-allocator: Internal Error: {e}"); Self::Lost } gpu_allocator::AllocationError::BarrierLayoutNeedsDevice10 @@ -283,125 +655,3 @@ impl From for crate::DeviceError { } } } - -pub(crate) fn create_committed_buffer_resource( - device: &crate::dx12::Device, - desc: &crate::BufferDescriptor, - raw_desc: Direct3D12::D3D12_RESOURCE_DESC, -) -> Result { - let is_cpu_read = desc.usage.contains(wgt::BufferUses::MAP_READ); - let is_cpu_write = desc.usage.contains(wgt::BufferUses::MAP_WRITE); - - let heap_properties = Direct3D12::D3D12_HEAP_PROPERTIES { - Type: Direct3D12::D3D12_HEAP_TYPE_CUSTOM, - CPUPageProperty: if is_cpu_read { - Direct3D12::D3D12_CPU_PAGE_PROPERTY_WRITE_BACK - } else if is_cpu_write { - Direct3D12::D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE - } else { - Direct3D12::D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE - }, - MemoryPoolPreference: match device.private_caps.memory_architecture { - crate::dx12::MemoryArchitecture::NonUnified if !is_cpu_read && !is_cpu_write => { - Direct3D12::D3D12_MEMORY_POOL_L1 - } - _ => Direct3D12::D3D12_MEMORY_POOL_L0, - }, - CreationNodeMask: 0, - VisibleNodeMask: 0, - }; - - let mut resource = None; - - unsafe { - device.raw.CreateCommittedResource( - &heap_properties, - if device.private_caps.heap_create_not_zeroed { - Direct3D12::D3D12_HEAP_FLAG_CREATE_NOT_ZEROED - } else { - Direct3D12::D3D12_HEAP_FLAG_NONE - }, - &raw_desc, - Direct3D12::D3D12_RESOURCE_STATE_COMMON, - None, - &mut resource, - ) - } - .into_device_result("Committed buffer creation")?; - - resource.ok_or(crate::DeviceError::Unexpected) -} - -pub(crate) fn create_committed_texture_resource( - device: &crate::dx12::Device, - _desc: &crate::TextureDescriptor, - raw_desc: Direct3D12::D3D12_RESOURCE_DESC, -) -> Result { - let heap_properties = Direct3D12::D3D12_HEAP_PROPERTIES { - Type: Direct3D12::D3D12_HEAP_TYPE_CUSTOM, - CPUPageProperty: Direct3D12::D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE, - MemoryPoolPreference: match device.private_caps.memory_architecture { - crate::dx12::MemoryArchitecture::NonUnified => Direct3D12::D3D12_MEMORY_POOL_L1, - crate::dx12::MemoryArchitecture::Unified { .. } => Direct3D12::D3D12_MEMORY_POOL_L0, - }, - CreationNodeMask: 0, - VisibleNodeMask: 0, - }; - - let mut resource = None; - - unsafe { - device.raw.CreateCommittedResource( - &heap_properties, - if device.private_caps.heap_create_not_zeroed { - Direct3D12::D3D12_HEAP_FLAG_CREATE_NOT_ZEROED - } else { - Direct3D12::D3D12_HEAP_FLAG_NONE - }, - &raw_desc, - Direct3D12::D3D12_RESOURCE_STATE_COMMON, - None, // clear value - &mut resource, - ) - } - .into_device_result("Committed texture creation")?; - - resource.ok_or(crate::DeviceError::Unexpected) -} - -pub(crate) fn create_committed_acceleration_structure_resource( - device: &crate::dx12::Device, - _desc: &crate::AccelerationStructureDescriptor, - raw_desc: Direct3D12::D3D12_RESOURCE_DESC, -) -> Result { - let heap_properties = Direct3D12::D3D12_HEAP_PROPERTIES { - Type: Direct3D12::D3D12_HEAP_TYPE_CUSTOM, - CPUPageProperty: Direct3D12::D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE, - MemoryPoolPreference: match device.private_caps.memory_architecture { - crate::dx12::MemoryArchitecture::NonUnified => Direct3D12::D3D12_MEMORY_POOL_L1, - _ => Direct3D12::D3D12_MEMORY_POOL_L0, - }, - CreationNodeMask: 0, - VisibleNodeMask: 0, - }; - - let mut resource = None; - - unsafe { - device.raw.CreateCommittedResource( - &heap_properties, - if device.private_caps.heap_create_not_zeroed { - Direct3D12::D3D12_HEAP_FLAG_CREATE_NOT_ZEROED - } else { - Direct3D12::D3D12_HEAP_FLAG_NONE - }, - &raw_desc, - Direct3D12::D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE, - None, - &mut resource, - ) - } - .into_device_result("Committed acceleration structure creation")?; - - resource.ok_or(crate::DeviceError::Unexpected) -} diff --git a/wgpu-hal/src/dx12/view.rs b/wgpu-hal/src/dx12/view.rs index fa8f2a4d6..e541ac239 100644 --- a/wgpu-hal/src/dx12/view.rs +++ b/wgpu-hal/src/dx12/view.rs @@ -250,16 +250,10 @@ impl ViewDescriptor { PlaneSlice: aspects_to_plane(self.aspects), } } - wgt::TextureViewDimension::D3 => { - desc.ViewDimension = Direct3D12::D3D12_RTV_DIMENSION_TEXTURE3D; - desc.Anonymous.Texture3D = Direct3D12::D3D12_TEX3D_RTV { - MipSlice: self.mip_level_base, - FirstWSlice: self.array_layer_base, - WSize: self.array_layer_count, - } - } - wgt::TextureViewDimension::Cube | wgt::TextureViewDimension::CubeArray => { - panic!("Unable to view texture as cube RTV") + wgt::TextureViewDimension::D3 + | wgt::TextureViewDimension::Cube + | wgt::TextureViewDimension::CubeArray => { + panic!("Unable to view texture as cube or 3D RTV") } } @@ -337,7 +331,7 @@ impl ViewDescriptor { wgt::TextureViewDimension::D3 | wgt::TextureViewDimension::Cube | wgt::TextureViewDimension::CubeArray => { - panic!("Unable to view texture as cube or 3D RTV") + panic!("Unable to view texture as cube or 3D DSV") } } diff --git a/wgpu-hal/src/dynamic/command.rs b/wgpu-hal/src/dynamic/command.rs index a33930262..a4fbfdbf6 100644 --- a/wgpu-hal/src/dynamic/command.rs +++ b/wgpu-hal/src/dynamic/command.rs @@ -94,7 +94,7 @@ pub trait DynCommandEncoder: DynResource + core::fmt::Debug { unsafe fn begin_render_pass( &mut self, desc: &RenderPassDescriptor, - ); + ) -> Result<(), DeviceError>; unsafe fn end_render_pass(&mut self); unsafe fn set_render_pipeline(&mut self, pipeline: &dyn DynRenderPipeline); @@ -394,7 +394,7 @@ impl DynCommandEncoder for C { unsafe fn begin_render_pass( &mut self, desc: &RenderPassDescriptor, - ) { + ) -> Result<(), DeviceError> { let color_attachments = desc .color_attachments .iter() @@ -415,7 +415,7 @@ impl DynCommandEncoder for C { .depth_stencil_attachment .as_ref() .map(|ds| ds.expect_downcast()), - multiview: desc.multiview, + multiview_mask: desc.multiview_mask, timestamp_writes: desc .timestamp_writes .as_ref() @@ -424,7 +424,7 @@ impl DynCommandEncoder for C { .occlusion_query_set .map(|set| set.expect_downcast_ref()), }; - unsafe { C::begin_render_pass(self, &desc) }; + unsafe { C::begin_render_pass(self, &desc) } } unsafe fn end_render_pass(&mut self) { @@ -730,6 +730,7 @@ impl<'a> ColorAttachment<'a, dyn DynTextureView> { pub fn expect_downcast(&self) -> ColorAttachment<'a, B> { ColorAttachment { target: self.target.expect_downcast(), + depth_slice: self.depth_slice, resolve_target: self.resolve_target.as_ref().map(|rt| rt.expect_downcast()), ops: self.ops, clear_value: self.clear_value, diff --git a/wgpu-hal/src/dynamic/device.rs b/wgpu-hal/src/dynamic/device.rs index c0de61f88..eea26ac89 100644 --- a/wgpu-hal/src/dynamic/device.rs +++ b/wgpu-hal/src/dynamic/device.rs @@ -4,10 +4,10 @@ use crate::{ AccelerationStructureBuildSizes, AccelerationStructureDescriptor, Api, BindGroupDescriptor, BindGroupLayoutDescriptor, BufferDescriptor, BufferMapping, CommandEncoderDescriptor, ComputePipelineDescriptor, Device, DeviceError, FenceValue, - GetAccelerationStructureBuildSizesDescriptor, Label, MemoryRange, MeshPipelineDescriptor, - PipelineCacheDescriptor, PipelineCacheError, PipelineError, PipelineLayoutDescriptor, - RenderPipelineDescriptor, SamplerDescriptor, ShaderError, ShaderInput, ShaderModuleDescriptor, - TextureDescriptor, TextureViewDescriptor, TlasInstance, + GetAccelerationStructureBuildSizesDescriptor, Label, MemoryRange, PipelineCacheDescriptor, + PipelineCacheError, PipelineError, PipelineLayoutDescriptor, RenderPipelineDescriptor, + SamplerDescriptor, ShaderError, ShaderInput, ShaderModuleDescriptor, TextureDescriptor, + TextureViewDescriptor, TlasInstance, }; use super::{ @@ -100,14 +100,6 @@ pub trait DynDevice: DynResource { dyn DynPipelineCache, >, ) -> Result, PipelineError>; - unsafe fn create_mesh_pipeline( - &self, - desc: &MeshPipelineDescriptor< - dyn DynPipelineLayout, - dyn DynShaderModule, - dyn DynPipelineCache, - >, - ) -> Result, PipelineError>; unsafe fn destroy_render_pipeline(&self, pipeline: Box); unsafe fn create_compute_pipeline( @@ -143,11 +135,11 @@ pub trait DynDevice: DynResource { &self, fence: &dyn DynFence, value: FenceValue, - timeout_ms: u32, + timeout: Option, ) -> Result; - unsafe fn start_capture(&self) -> bool; - unsafe fn stop_capture(&self); + unsafe fn start_graphics_debugger_capture(&self) -> bool; + unsafe fn stop_graphics_debugger_capture(&self); unsafe fn pipeline_cache_get_data(&self, cache: &dyn DynPipelineCache) -> Option>; @@ -171,6 +163,8 @@ pub trait DynDevice: DynResource { fn get_internal_counters(&self) -> wgt::HalCounters; fn generate_allocator_report(&self) -> Option; + + fn check_if_oom(&self) -> Result<(), DeviceError>; } impl DynDevice for D { @@ -343,6 +337,11 @@ impl DynDevice for D { .iter() .map(|a| a.expect_downcast_ref()) .collect(); + let external_textures: Vec<_> = desc + .external_textures + .iter() + .map(|et| et.clone().expect_downcast()) + .collect(); let desc = BindGroupDescriptor { label: desc.label.to_owned(), @@ -352,6 +351,7 @@ impl DynDevice for D { textures: &textures, entries: desc.entries, acceleration_structures: &acceleration_structures, + external_textures: &external_textures, }; unsafe { D::create_bind_group(self, &desc) } @@ -386,14 +386,28 @@ impl DynDevice for D { let desc = RenderPipelineDescriptor { label: desc.label, layout: desc.layout.expect_downcast_ref(), - vertex_buffers: desc.vertex_buffers, - vertex_stage: desc.vertex_stage.clone().expect_downcast(), + vertex_processor: match &desc.vertex_processor { + crate::VertexProcessor::Standard { + vertex_buffers, + vertex_stage, + } => crate::VertexProcessor::Standard { + vertex_buffers, + vertex_stage: vertex_stage.clone().expect_downcast(), + }, + crate::VertexProcessor::Mesh { + task_stage: task, + mesh_stage: mesh, + } => crate::VertexProcessor::Mesh { + task_stage: task.as_ref().map(|a| a.clone().expect_downcast()), + mesh_stage: mesh.clone().expect_downcast(), + }, + }, primitive: desc.primitive, depth_stencil: desc.depth_stencil.clone(), multisample: desc.multisample, fragment_stage: desc.fragment_stage.clone().map(|f| f.expect_downcast()), color_targets: desc.color_targets, - multiview: desc.multiview, + multiview_mask: desc.multiview_mask, cache: desc.cache.map(|c| c.expect_downcast_ref()), }; @@ -401,32 +415,6 @@ impl DynDevice for D { .map(|b| -> Box { Box::new(b) }) } - unsafe fn create_mesh_pipeline( - &self, - desc: &MeshPipelineDescriptor< - dyn DynPipelineLayout, - dyn DynShaderModule, - dyn DynPipelineCache, - >, - ) -> Result, PipelineError> { - let desc = MeshPipelineDescriptor { - label: desc.label, - layout: desc.layout.expect_downcast_ref(), - task_stage: desc.task_stage.clone().map(|f| f.expect_downcast()), - mesh_stage: desc.mesh_stage.clone().expect_downcast(), - primitive: desc.primitive, - depth_stencil: desc.depth_stencil.clone(), - multisample: desc.multisample, - fragment_stage: desc.fragment_stage.clone().map(|f| f.expect_downcast()), - color_targets: desc.color_targets, - multiview: desc.multiview, - cache: desc.cache.map(|c| c.expect_downcast_ref()), - }; - - unsafe { D::create_mesh_pipeline(self, &desc) } - .map(|b| -> Box { Box::new(b) }) - } - unsafe fn destroy_render_pipeline(&self, pipeline: Box) { unsafe { D::destroy_render_pipeline(self, pipeline.unbox()) }; } @@ -498,18 +486,18 @@ impl DynDevice for D { &self, fence: &dyn DynFence, value: FenceValue, - timeout_ms: u32, + timeout: Option, ) -> Result { let fence = fence.expect_downcast_ref(); - unsafe { D::wait(self, fence, value, timeout_ms) } + unsafe { D::wait(self, fence, value, timeout) } } - unsafe fn start_capture(&self) -> bool { - unsafe { D::start_capture(self) } + unsafe fn start_graphics_debugger_capture(&self) -> bool { + unsafe { D::start_graphics_debugger_capture(self) } } - unsafe fn stop_capture(&self) { - unsafe { D::stop_capture(self) } + unsafe fn stop_graphics_debugger_capture(&self) { + unsafe { D::stop_graphics_debugger_capture(self) } } unsafe fn pipeline_cache_get_data(&self, cache: &dyn DynPipelineCache) -> Option> { @@ -563,4 +551,8 @@ impl DynDevice for D { fn generate_allocator_report(&self) -> Option { D::generate_allocator_report(self) } + + fn check_if_oom(&self) -> Result<(), DeviceError> { + D::check_if_oom(self) + } } diff --git a/wgpu-hal/src/dynamic/mod.rs b/wgpu-hal/src/dynamic/mod.rs index a8dbae94e..85d8ca004 100644 --- a/wgpu-hal/src/dynamic/mod.rs +++ b/wgpu-hal/src/dynamic/mod.rs @@ -23,7 +23,8 @@ use wgt::WasmNotSendSync; use crate::{ AccelerationStructureAABBs, AccelerationStructureEntries, AccelerationStructureInstances, AccelerationStructureTriangleIndices, AccelerationStructureTriangleTransform, - AccelerationStructureTriangles, BufferBinding, ProgrammableStage, TextureBinding, + AccelerationStructureTriangles, BufferBinding, ExternalTextureBinding, ProgrammableStage, + TextureBinding, }; /// Base trait for all resources, allows downcasting via [`Any`]. @@ -143,6 +144,16 @@ impl<'a> TextureBinding<'a, dyn DynTextureView> { } } +impl<'a> ExternalTextureBinding<'a, dyn DynBuffer, dyn DynTextureView> { + pub fn expect_downcast( + self, + ) -> ExternalTextureBinding<'a, B, T> { + let planes = self.planes.map(|plane| plane.expect_downcast()); + let params = self.params.expect_downcast(); + ExternalTextureBinding { planes, params } + } +} + impl<'a> ProgrammableStage<'a, dyn DynShaderModule> { fn expect_downcast(self) -> ProgrammableStage<'a, T> { ProgrammableStage { diff --git a/wgpu-hal/src/gles/adapter.rs b/wgpu-hal/src/gles/adapter.rs index a4370f819..6ee5f7137 100644 --- a/wgpu-hal/src/gles/adapter.rs +++ b/wgpu-hal/src/gles/adapter.rs @@ -187,8 +187,10 @@ impl super::Adapter { device: 0, device_type: inferred_device_type, driver: "".to_owned(), + device_pci_bus_id: String::new(), driver_info: version, backend: wgt::Backend::Gl, + transient_saves_memory: false, } } @@ -220,9 +222,9 @@ impl super::Adapter { let vendor = unsafe { gl.get_parameter_string(vendor_const) }; let renderer = unsafe { gl.get_parameter_string(renderer_const) }; let version = unsafe { gl.get_parameter_string(glow::VERSION) }; - log::debug!("Vendor: {}", vendor); - log::debug!("Renderer: {}", renderer); - log::debug!("Version: {}", version); + log::debug!("Vendor: {vendor}"); + log::debug!("Renderer: {renderer}"); + log::debug!("Version: {version}"); let full_ver = Self::parse_full_version(&version).ok(); let es_ver = full_ver.map_or_else(|| Self::parse_version(&version).ok(), |_| None); @@ -293,7 +295,7 @@ impl super::Adapter { } }; - log::debug!("Supported GL Extensions: {:#?}", extensions); + log::debug!("Supported GL Extensions: {extensions:#?}"); let supported = |(req_es_major, req_es_minor), (req_full_major, req_full_minor)| { let es_supported = es_ver @@ -385,7 +387,7 @@ impl super::Adapter { | wgt::DownlevelFlags::NON_POWER_OF_TWO_MIPMAPPED_TEXTURES | wgt::DownlevelFlags::CUBE_ARRAY_TEXTURES | wgt::DownlevelFlags::COMPARISON_SAMPLERS - | wgt::DownlevelFlags::VERTEX_AND_INSTANCE_INDEX_RESPECTS_RESPECTIVE_FIRST_VALUE_IN_INDIRECT_DRAW; + | wgt::DownlevelFlags::SHADER_F16_IN_F32; downlevel_flags.set(wgt::DownlevelFlags::COMPUTE_SHADERS, supports_compute); downlevel_flags.set( wgt::DownlevelFlags::FRAGMENT_WRITABLE_STORAGE, @@ -466,6 +468,10 @@ impl super::Adapter { extensions.contains("GL_EXT_blend_func_extended") || extensions.contains("GL_ARB_blend_func_extended"), ); + features.set( + wgt::Features::CLIP_DISTANCES, + full_ver.is_some() || extensions.contains("GL_EXT_clip_cull_distance"), + ); features.set( wgt::Features::SHADER_PRIMITIVE_INDEX, supported((3, 2), (3, 2)) @@ -476,8 +482,6 @@ impl super::Adapter { wgt::Features::SHADER_EARLY_DEPTH_TEST, supported((3, 1), (4, 2)) || extensions.contains("GL_ARB_shader_image_load_store"), ); - // We emulate MDI with a loop of draw calls. - features.set(wgt::Features::MULTI_DRAW_INDIRECT, indirect_execution); if extensions.contains("GL_ARB_timer_query") { features.set(wgt::Features::TIMESTAMP_QUERY, true); features.set(wgt::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS, true); @@ -532,6 +536,7 @@ impl super::Adapter { .compressed_texture_astc_supports_ldr_profile() { features.insert(wgt::Features::TEXTURE_COMPRESSION_ASTC); + features.insert(wgt::Features::TEXTURE_COMPRESSION_ASTC_SLICED_3D); } if context .glow_context @@ -544,6 +549,7 @@ impl super::Adapter { #[cfg(any(native, Emscripten))] { features.insert(wgt::Features::TEXTURE_COMPRESSION_ASTC); + features.insert(wgt::Features::TEXTURE_COMPRESSION_ASTC_SLICED_3D); features.insert(wgt::Features::TEXTURE_COMPRESSION_ASTC_HDR); } } else { @@ -551,6 +557,11 @@ impl super::Adapter { wgt::Features::TEXTURE_COMPRESSION_ASTC, extensions.contains("GL_KHR_texture_compression_astc_ldr"), ); + features.set( + wgt::Features::TEXTURE_COMPRESSION_ASTC_SLICED_3D, + extensions.contains("GL_KHR_texture_compression_astc_ldr") + && extensions.contains("GL_KHR_texture_compression_astc_sliced_3d"), + ); features.set( wgt::Features::TEXTURE_COMPRESSION_ASTC_HDR, extensions.contains("GL_KHR_texture_compression_astc_hdr"), @@ -791,6 +802,18 @@ impl super::Adapter { max_compute_workgroups_per_dimension, max_buffer_size: i32::MAX as u64, max_non_sampler_bindings: u32::MAX, + + max_task_workgroup_total_count: 0, + max_task_workgroups_per_dimension: 0, + max_mesh_multiview_view_count: 0, + max_mesh_output_layers: 0, + + max_blas_primitive_count: 0, + max_blas_geometry_count: 0, + max_tlas_instance_count: 0, + max_acceleration_structures_per_shader_stage: 0, + + max_multiview_view_count: 0, }; let mut workarounds = super::Workarounds::empty(); @@ -895,7 +918,7 @@ impl super::Adapter { if !unsafe { gl.get_shader_compile_status(shader) } { let msg = unsafe { gl.get_shader_info_log(shader) }; if !msg.is_empty() { - log::error!("\tShader compile error: {}", msg); + log::error!("\tShader compile error: {msg}"); } unsafe { gl.delete_shader(shader) }; None @@ -932,7 +955,7 @@ impl super::Adapter { let linked_ok = unsafe { gl.get_program_link_status(program) }; let msg = unsafe { gl.get_program_info_log(program) }; if !msg.is_empty() { - log::warn!("Shader link error: {}", msg); + log::warn!("Shader link error: {msg}"); } if !linked_ok { return None; @@ -982,7 +1005,7 @@ impl crate::Adapter for super::Adapter { { Some(unsafe { Self::create_shader_clear_program(gl, self.shared.es) - .ok_or(crate::DeviceError::ResourceCreationFailed)? + .ok_or(crate::DeviceError::Lost)? }) } else { // If we don't need the workaround, don't waste time and resources compiling the clear program @@ -1145,6 +1168,7 @@ impl crate::Adapter for super::Adapter { | Tf::Depth24Plus | Tf::Depth24PlusStencil8 => depth, Tf::NV12 => empty, + Tf::P010 => empty, Tf::Rgb9e5Ufloat => filterable, Tf::Bc1RgbaUnorm | Tf::Bc1RgbaUnormSrgb diff --git a/wgpu-hal/src/gles/command.rs b/wgpu-hal/src/gles/command.rs index 6cdf0fbf8..6136b4fd0 100644 --- a/wgpu-hal/src/gles/command.rs +++ b/wgpu-hal/src/gles/command.rs @@ -37,6 +37,7 @@ pub(super) struct State { // The current state of the push constant data block. current_push_constant_data: [u32; super::MAX_PUSH_CONSTANTS], end_of_pass_timestamp: Option, + clip_distance_count: u32, } impl Default for State { @@ -65,6 +66,7 @@ impl Default for State { push_constant_descs: Default::default(), current_push_constant_data: [0; super::MAX_PUSH_CONSTANTS], end_of_pass_timestamp: Default::default(), + clip_distance_count: Default::default(), } } } @@ -496,7 +498,7 @@ impl crate::CommandEncoder for super::CommandEncoder { unsafe fn begin_render_pass( &mut self, desc: &crate::RenderPassDescriptor, - ) { + ) -> Result<(), crate::DeviceError> { debug_assert!(self.state.end_of_pass_timestamp.is_none()); if let Some(ref t) = desc.timestamp_writes { if let Some(index) = t.beginning_of_pass_write_index { @@ -523,6 +525,8 @@ impl crate::CommandEncoder for super::CommandEncoder { .any(|at| match at.target.view.inner { #[cfg(webgl)] super::TextureInner::ExternalFramebuffer { .. } => true, + #[cfg(native)] + super::TextureInner::ExternalNativeFramebuffer { .. } => true, _ => false, }); @@ -557,6 +561,7 @@ impl crate::CommandEncoder for super::CommandEncoder { self.cmd_buffer.commands.push(C::BindAttachment { attachment, view: cat.target.view.clone(), + depth_slice: cat.depth_slice, }); if let Some(ref rat) = cat.resolve_target { self.state @@ -578,6 +583,7 @@ impl crate::CommandEncoder for super::CommandEncoder { self.cmd_buffer.commands.push(C::BindAttachment { attachment, view: dsat.target.view.clone(), + depth_slice: None, }); if aspects.contains(crate::FormatAspects::DEPTH) && !dsat.depth_ops.contains(crate::AttachmentOps::STORE) @@ -665,6 +671,7 @@ impl crate::CommandEncoder for super::CommandEncoder { .push(C::ClearStencil(dsat.clear_value.1)); } } + Ok(()) } unsafe fn end_render_pass(&mut self) { for (attachment, dst) in self.state.resolve_attachments.drain(..) { @@ -976,6 +983,15 @@ impl crate::CommandEncoder for super::CommandEncoder { for ct in pipeline.color_targets.iter() { self.state.color_targets.push(ct.clone()); } + + // set clip plane count + if pipeline.inner.clip_distance_count != self.state.clip_distance_count { + self.cmd_buffer.commands.push(C::SetClipDistances { + old_count: self.state.clip_distance_count, + new_count: pipeline.inner.clip_distance_count, + }); + self.state.clip_distance_count = pipeline.inner.clip_distance_count; + } } unsafe fn set_index_buffer<'a>( diff --git a/wgpu-hal/src/gles/conv.rs b/wgpu-hal/src/gles/conv.rs index 7348f2f19..658165eeb 100644 --- a/wgpu-hal/src/gles/conv.rs +++ b/wgpu-hal/src/gles/conv.rs @@ -89,6 +89,7 @@ impl super::AdapterShared { glow::UNSIGNED_INT_24_8, ), Tf::NV12 => unreachable!(), + Tf::P010 => unreachable!(), Tf::Rgb9e5Ufloat => (glow::RGB9_E5, glow::RGB, glow::UNSIGNED_INT_5_9_9_9_REV), Tf::Bc1RgbaUnorm => (glow::COMPRESSED_RGBA_S3TC_DXT1_EXT, glow::RGBA, 0), Tf::Bc1RgbaUnormSrgb => (glow::COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, glow::RGBA, 0), @@ -237,9 +238,10 @@ pub(super) fn describe_vertex_format(vertex_format: wgt::VertexFormat) -> super: pub fn map_filter_modes( min: wgt::FilterMode, mag: wgt::FilterMode, - mip: wgt::FilterMode, + mip: wgt::MipmapFilterMode, ) -> (u32, u32) { use wgt::FilterMode as Fm; + use wgt::MipmapFilterMode as Mfm; let mag_filter = match mag { Fm::Nearest => glow::NEAREST, @@ -247,10 +249,10 @@ pub fn map_filter_modes( }; let min_filter = match (min, mip) { - (Fm::Nearest, Fm::Nearest) => glow::NEAREST_MIPMAP_NEAREST, - (Fm::Nearest, Fm::Linear) => glow::NEAREST_MIPMAP_LINEAR, - (Fm::Linear, Fm::Nearest) => glow::LINEAR_MIPMAP_NEAREST, - (Fm::Linear, Fm::Linear) => glow::LINEAR_MIPMAP_LINEAR, + (Fm::Nearest, Mfm::Nearest) => glow::NEAREST_MIPMAP_NEAREST, + (Fm::Nearest, Mfm::Linear) => glow::NEAREST_MIPMAP_LINEAR, + (Fm::Linear, Mfm::Nearest) => glow::LINEAR_MIPMAP_NEAREST, + (Fm::Linear, Mfm::Linear) => glow::LINEAR_MIPMAP_LINEAR, }; (min_filter, mag_filter) diff --git a/wgpu-hal/src/gles/device.rs b/wgpu-hal/src/gles/device.rs index e3f3f61a3..05741c18f 100644 --- a/wgpu-hal/src/gles/device.rs +++ b/wgpu-hal/src/gles/device.rs @@ -22,7 +22,8 @@ struct CompilationContext<'a> { sampler_map: &'a mut super::SamplerBindMap, name_binding_map: &'a mut NameBindingMap, push_constant_items: &'a mut Vec, - multiview: Option, + multiview_mask: Option, + clip_distance_count: &'a mut u32, } impl CompilationContext<'_> { @@ -103,6 +104,10 @@ impl CompilationContext<'_> { } *self.push_constant_items = reflection_info.push_constant_items; + + if naga_stage == naga::ShaderStage::Vertex { + *self.clip_distance_count = reflection_info.clip_distance_count; + } } } @@ -183,17 +188,17 @@ impl super::Device { unsafe { gl.shader_source(raw, shader) }; unsafe { gl.compile_shader(raw) }; - log::debug!("\tCompiled shader {:?}", raw); + log::debug!("\tCompiled shader {raw:?}"); let compiled_ok = unsafe { gl.get_shader_compile_status(raw) }; let msg = unsafe { gl.get_shader_info_log(raw) }; if compiled_ok { if !msg.is_empty() { - log::warn!("\tCompile: {}", msg); + log::warn!("\tCompile: {msg}"); } Ok(raw) } else { - log::error!("\tShader compilation failed: {}", msg); + log::error!("\tShader compilation failed: {msg}"); unsafe { gl.delete_shader(raw) }; Err(crate::PipelineError::Linkage( map_naga_stage(naga_stage), @@ -213,12 +218,15 @@ impl super::Device { let pipeline_options = glsl::PipelineOptions { shader_stage: naga_stage, entry_point: stage.entry_point.to_owned(), - multiview: context.multiview, + multiview: context + .multiview_mask + .map(|a| NonZeroU32::new(a.get().count_ones()).unwrap()), }; let (module, info) = naga::back::pipeline_constants::process_overrides( - &stage.module.naga.module, - &stage.module.naga.info, + &stage.module.source.module, + &stage.module.source.info, + Some((naga_stage, stage.entry_point)), stage.constants, ) .map_err(|e| { @@ -280,7 +288,7 @@ impl super::Device { crate::PipelineError::Linkage(map_naga_stage(naga_stage), msg) })?; - log::debug!("Naga generated shader:\n{}", output); + log::debug!("Naga generated shader:\n{output}"); context.consume_reflection( gl, @@ -300,7 +308,7 @@ impl super::Device { shaders: ArrayVec, { crate::MAX_CONCURRENT_SHADER_STAGES }>, layout: &super::PipelineLayout, #[cfg_attr(target_arch = "wasm32", allow(unused))] label: Option<&str>, - multiview: Option, + multiview_mask: Option, ) -> Result, crate::PipelineError> { let mut program_stages = ArrayVec::new(); let mut group_to_binding_to_slot = Vec::with_capacity(layout.group_infos.len()); @@ -333,7 +341,7 @@ impl super::Device { shaders, layout, label, - multiview, + multiview_mask, self.shared.shading_language_version, self.shared.private_caps, ) @@ -349,7 +357,7 @@ impl super::Device { shaders: ArrayVec, { crate::MAX_CONCURRENT_SHADER_STAGES }>, layout: &super::PipelineLayout, #[cfg_attr(target_arch = "wasm32", allow(unused))] label: Option<&str>, - multiview: Option, + multiview_mask: Option, glsl_version: naga::back::glsl::Version, private_caps: PrivateCapabilities, ) -> Result, crate::PipelineError> { @@ -371,6 +379,7 @@ impl super::Device { let mut sampler_map = [None; super::MAX_TEXTURE_SLOTS]; let mut has_stages = wgt::ShaderStages::empty(); let mut shaders_to_delete = ArrayVec::<_, { crate::MAX_CONCURRENT_SHADER_STAGES }>::new(); + let mut clip_distance_count = 0; for &(naga_stage, stage) in &shaders { has_stages |= map_naga_stage(naga_stage); @@ -383,7 +392,8 @@ impl super::Device { sampler_map: &mut sampler_map, name_binding_map: &mut name_binding_map, push_constant_items: pc_item, - multiview, + multiview_mask, + clip_distance_count: &mut clip_distance_count, }; let shader = Self::create_shader(gl, naga_stage, stage, context, program)?; @@ -414,7 +424,7 @@ impl super::Device { unsafe { gl.delete_shader(shader) }; } - log::debug!("\tLinked program {:?}", program); + log::debug!("\tLinked program {program:?}"); let linked_ok = unsafe { gl.get_program_link_status(program) }; let msg = unsafe { gl.get_program_info_log(program) }; @@ -422,7 +432,7 @@ impl super::Device { return Err(crate::PipelineError::Linkage(has_stages, msg)); } if !msg.is_empty() { - log::warn!("\tLink: {}", msg); + log::warn!("\tLink: {msg}"); } if !private_caps.contains(PrivateCapabilities::SHADER_BINDING_LAYOUT) { @@ -430,7 +440,7 @@ impl super::Device { // in the shader. We can't remap storage buffers this way. unsafe { gl.use_program(Some(program)) }; for (ref name, (register, slot)) in name_binding_map { - log::trace!("Get binding {:?} from program {:?}", name, program); + log::trace!("Get binding {name:?} from program {program:?}"); match register { super::BindingRegister::UniformBuffers => { let index = unsafe { gl.get_uniform_block_index(program, name) }.unwrap(); @@ -440,11 +450,7 @@ impl super::Device { super::BindingRegister::StorageBuffers => { let index = unsafe { gl.get_shader_storage_block_index(program, name) }.unwrap(); - log::error!( - "Unable to re-map shader storage block {} to {}", - name, - index - ); + log::error!("Unable to re-map shader storage block {name} to {index}"); return Err(crate::DeviceError::Lost.into()); } super::BindingRegister::Textures | super::BindingRegister::Images => { @@ -459,7 +465,7 @@ impl super::Device { for (stage_idx, stage_items) in push_constant_items.into_iter().enumerate() { for item in stage_items { - let naga_module = &shaders[stage_idx].1.module.naga.module; + let naga_module = &shaders[stage_idx].1.module.source.module; let type_inner = &naga_module.types[item.ty].inner; let location = unsafe { gl.get_uniform_location(program, &item.access_path) }; @@ -495,6 +501,7 @@ impl super::Device { sampler_map, first_instance_location, push_constant_descs: uniforms, + clip_distance_count, })) } } @@ -729,7 +736,8 @@ impl crate::Device for super::Device { let render_usage = wgt::TextureUses::COLOR_TARGET | wgt::TextureUses::DEPTH_STENCIL_WRITE - | wgt::TextureUses::DEPTH_STENCIL_READ; + | wgt::TextureUses::DEPTH_STENCIL_READ + | wgt::TextureUses::TRANSIENT; let format_desc = self.shared.describe_texture_format(desc.format); let inner = if render_usage.contains(desc.usage) @@ -969,6 +977,8 @@ impl crate::Device for super::Device { } #[cfg(webgl)] super::TextureInner::ExternalFramebuffer { .. } => {} + #[cfg(native)] + super::TextureInner::ExternalNativeFramebuffer { .. } => {} } } @@ -1192,6 +1202,7 @@ impl crate::Device for super::Device { .. } => &mut num_storage_buffers, wgt::BindingType::AccelerationStructure { .. } => unimplemented!(), + wgt::BindingType::ExternalTexture => unimplemented!(), }; binding_to_slot[entry.binding as usize] = *counter; @@ -1302,6 +1313,7 @@ impl crate::Device for super::Device { }) } wgt::BindingType::AccelerationStructure { .. } => unimplemented!(), + wgt::BindingType::ExternalTexture => unimplemented!(), }; contents.push(binding); } @@ -1325,11 +1337,16 @@ impl crate::Device for super::Device { self.counters.shader_modules.add(1); Ok(super::ShaderModule { - naga: match shader { - crate::ShaderInput::SpirV(_) => { - panic!("`Features::SPIRV_SHADER_PASSTHROUGH` is not enabled") - } + source: match shader { crate::ShaderInput::Naga(naga) => naga, + // The backend doesn't yet expose this feature so it should be fine + crate::ShaderInput::Glsl { .. } => unimplemented!(), + crate::ShaderInput::SpirV(_) + | crate::ShaderInput::Msl { .. } + | crate::ShaderInput::Dxil { .. } + | crate::ShaderInput::Hlsl { .. } => { + unreachable!() + } }, label: desc.label.map(|str| str.to_string()), id: self.shared.next_shader_id.fetch_add(1, Ordering::Relaxed), @@ -1348,19 +1365,27 @@ impl crate::Device for super::Device { super::PipelineCache, >, ) -> Result { + let (vertex_stage, vertex_buffers) = match &desc.vertex_processor { + crate::VertexProcessor::Standard { + vertex_buffers, + ref vertex_stage, + } => (vertex_stage, vertex_buffers), + crate::VertexProcessor::Mesh { .. } => unreachable!(), + }; let gl = &self.shared.context.lock(); let mut shaders = ArrayVec::new(); - shaders.push((naga::ShaderStage::Vertex, &desc.vertex_stage)); + shaders.push((naga::ShaderStage::Vertex, vertex_stage)); if let Some(ref fs) = desc.fragment_stage { shaders.push((naga::ShaderStage::Fragment, fs)); } - let inner = - unsafe { self.create_pipeline(gl, shaders, desc.layout, desc.label, desc.multiview) }?; + let inner = unsafe { + self.create_pipeline(gl, shaders, desc.layout, desc.label, desc.multiview_mask) + }?; let (vertex_buffers, vertex_attributes) = { let mut buffers = Vec::new(); let mut attributes = Vec::new(); - for (index, vb_layout) in desc.vertex_buffers.iter().enumerate() { + for (index, vb_layout) in vertex_buffers.iter().enumerate() { buffers.push(super::VertexBufferDesc { step: vb_layout.step_mode, stride: vb_layout.array_stride as u32, @@ -1415,16 +1440,6 @@ impl crate::Device for super::Device { alpha_to_coverage_enabled: desc.multisample.alpha_to_coverage_enabled, }) } - unsafe fn create_mesh_pipeline( - &self, - _desc: &crate::MeshPipelineDescriptor< - ::PipelineLayout, - ::ShaderModule, - ::PipelineCache, - >, - ) -> Result<::RenderPipeline, crate::PipelineError> { - unreachable!() - } unsafe fn destroy_render_pipeline(&self, pipeline: super::RenderPipeline) { // If the pipeline only has 2 strong references remaining, they're `pipeline` and `program_cache` @@ -1553,7 +1568,7 @@ impl crate::Device for super::Device { &self, fence: &super::Fence, wait_value: crate::FenceValue, - timeout_ms: u32, + timeout: Option, ) -> Result { if fence.satisfied(wait_value) { return Ok(true); @@ -1567,12 +1582,14 @@ impl crate::Device for super::Device { let timeout_ns = if cfg!(any(webgl, Emscripten)) { 0 } else { - (timeout_ms as u64 * 1_000_000).min(!0u32 as u64) + timeout + .map(|t| t.as_nanos().min(u32::MAX as u128) as u32) + .unwrap_or(u32::MAX) }; fence.wait(gl, wait_value, timeout_ns) } - unsafe fn start_capture(&self) -> bool { + unsafe fn start_graphics_debugger_capture(&self) -> bool { #[cfg(all(native, feature = "renderdoc"))] return unsafe { self.render_doc @@ -1581,7 +1598,7 @@ impl crate::Device for super::Device { #[allow(unreachable_code)] false } - unsafe fn stop_capture(&self) { + unsafe fn stop_graphics_debugger_capture(&self) { #[cfg(all(native, feature = "renderdoc"))] unsafe { self.render_doc @@ -1619,6 +1636,10 @@ impl crate::Device for super::Device { fn get_internal_counters(&self) -> wgt::HalCounters { self.counters.as_ref().clone() } + + fn check_if_oom(&self) -> Result<(), crate::DeviceError> { + Ok(()) + } } #[cfg(send_sync)] diff --git a/wgpu-hal/src/gles/egl.rs b/wgpu-hal/src/gles/egl.rs index 6f246cad1..824b07718 100644 --- a/wgpu-hal/src/gles/egl.rs +++ b/wgpu-hal/src/gles/egl.rs @@ -1,16 +1,6 @@ -#![allow(clippy::std_instead_of_alloc, clippy::std_instead_of_core)] - -use std::{ - ffi, - mem::ManuallyDrop, - os::raw, - ptr, - rc::Rc, - string::String, - sync::{Arc, LazyLock}, - time::Duration, - vec::Vec, -}; +use alloc::{rc::Rc, string::String, sync::Arc, vec::Vec}; +use core::{ffi, mem::ManuallyDrop, ptr, time::Duration}; +use std::sync::LazyLock; use glow::HasContext; use hashbrown::HashMap; @@ -32,14 +22,14 @@ const EGL_GL_COLORSPACE_KHR: u32 = 0x309D; const EGL_GL_COLORSPACE_SRGB_KHR: u32 = 0x3089; type XOpenDisplayFun = - unsafe extern "system" fn(display_name: *const raw::c_char) -> *mut raw::c_void; + unsafe extern "system" fn(display_name: *const ffi::c_char) -> *mut ffi::c_void; -type XCloseDisplayFun = unsafe extern "system" fn(display: *mut raw::c_void) -> raw::c_int; +type XCloseDisplayFun = unsafe extern "system" fn(display: *mut ffi::c_void) -> ffi::c_int; type WlDisplayConnectFun = - unsafe extern "system" fn(display_name: *const raw::c_char) -> *mut raw::c_void; + unsafe extern "system" fn(display_name: *const ffi::c_char) -> *mut ffi::c_void; -type WlDisplayDisconnectFun = unsafe extern "system" fn(display: *const raw::c_void); +type WlDisplayDisconnectFun = unsafe extern "system" fn(display: *const ffi::c_void); #[cfg(not(Emscripten))] type EglInstance = khronos_egl::DynamicInstance; @@ -48,32 +38,32 @@ type EglInstance = khronos_egl::DynamicInstance; type EglInstance = khronos_egl::Instance; type WlEglWindowCreateFun = unsafe extern "system" fn( - surface: *const raw::c_void, - width: raw::c_int, - height: raw::c_int, -) -> *mut raw::c_void; + surface: *const ffi::c_void, + width: ffi::c_int, + height: ffi::c_int, +) -> *mut ffi::c_void; type WlEglWindowResizeFun = unsafe extern "system" fn( - window: *const raw::c_void, - width: raw::c_int, - height: raw::c_int, - dx: raw::c_int, - dy: raw::c_int, + window: *const ffi::c_void, + width: ffi::c_int, + height: ffi::c_int, + dx: ffi::c_int, + dy: ffi::c_int, ); -type WlEglWindowDestroyFun = unsafe extern "system" fn(window: *const raw::c_void); +type WlEglWindowDestroyFun = unsafe extern "system" fn(window: *const ffi::c_void); -type EglLabel = *const raw::c_void; +type EglLabel = *const ffi::c_void; #[allow(clippy::upper_case_acronyms)] type EGLDEBUGPROCKHR = Option< unsafe extern "system" fn( error: khronos_egl::Enum, - command: *const raw::c_char, + command: *const ffi::c_char, message_type: u32, thread_label: EglLabel, object_label: EglLabel, - message: *const raw::c_char, + message: *const ffi::c_char, ), >; @@ -85,15 +75,15 @@ const EGL_DEBUG_MSG_INFO_KHR: u32 = 0x33BC; type EglDebugMessageControlFun = unsafe extern "system" fn( proc: EGLDEBUGPROCKHR, attrib_list: *const khronos_egl::Attrib, -) -> raw::c_int; +) -> ffi::c_int; unsafe extern "system" fn egl_debug_proc( error: khronos_egl::Enum, - command_raw: *const raw::c_char, + command_raw: *const ffi::c_char, message_type: u32, _thread_label: EglLabel, _object_label: EglLabel, - message_raw: *const raw::c_char, + message_raw: *const ffi::c_char, ) { let log_severity = match message_type { EGL_DEBUG_MSG_CRITICAL_KHR | EGL_DEBUG_MSG_ERROR_KHR => log::Level::Error, @@ -108,13 +98,7 @@ unsafe extern "system" fn egl_debug_proc( unsafe { ffi::CStr::from_ptr(message_raw) }.to_string_lossy() }; - log::log!( - log_severity, - "EGL '{}' code 0x{:x}: {}", - command, - error, - message, - ); + log::log!(log_severity, "EGL '{command}' code 0x{error:x}: {message}",); } /// A simple wrapper around an X11 or Wayland display handle. @@ -123,13 +107,13 @@ unsafe extern "system" fn egl_debug_proc( /// enum variant is the X11 variant #[derive(Debug)] enum DisplayRef { - X11(ptr::NonNull), + X11(ptr::NonNull), Wayland, } impl DisplayRef { /// Convenience for getting the underlying pointer - fn as_ptr(&self) -> *mut raw::c_void { + fn as_ptr(&self) -> *mut ffi::c_void { match *self { Self::X11(ptr) => ptr.as_ptr(), Self::Wayland => unreachable!(), @@ -152,8 +136,13 @@ impl Drop for DisplayOwner { fn drop(&mut self) { match self.display { DisplayRef::X11(ptr) => unsafe { - let func: libloading::Symbol = - self.library.get(c"XCloseDisplay".to_bytes()).unwrap(); + let Ok(func): Result, _> = self + .library + .get(c"XCloseDisplay".to_bytes()) + .inspect_err(|err| log::error!("Failed to load XCloseDisplay: {err:?}")) + else { + return; + }; func(ptr.as_ptr()); }, DisplayRef::Wayland => {} @@ -165,8 +154,10 @@ fn open_x_display() -> Option { log::debug!("Loading X11 library to get the current display"); unsafe { let library = find_library(&["libX11.so.6", "libX11.so"])?; - let func: libloading::Symbol = - library.get(c"XOpenDisplay".to_bytes()).unwrap(); + let func: libloading::Symbol = library + .get(c"XOpenDisplay".to_bytes()) + .inspect_err(|err| log::error!("Failed to load XOpenDisplay: {err:?}")) + .ok()?; let result = func(ptr::null()); ptr::NonNull::new(result).map(|ptr| DisplayOwner { display: DisplayRef::X11(ptr), @@ -194,10 +185,12 @@ fn test_wayland_display() -> Option { let client_library = find_library(&["libwayland-client.so.0", "libwayland-client.so"])?; let wl_display_connect: libloading::Symbol = client_library .get(c"wl_display_connect".to_bytes()) - .unwrap(); + .inspect_err(|err| log::error!("Failed to load wl_display_connect: {err:?}")) + .ok()?; let wl_display_disconnect: libloading::Symbol = client_library .get(c"wl_display_disconnect".to_bytes()) - .unwrap(); + .inspect_err(|err| log::error!("Failed to load wl_display_disconnect: {err:?}")) + .ok()?; let display = ptr::NonNull::new(wl_display_connect(ptr::null()))?; wl_display_disconnect(display.as_ptr()); find_library(&["libwayland-egl.so.1", "libwayland-egl.so"])? @@ -249,7 +242,7 @@ fn choose_config( let mut attributes = Vec::with_capacity(9); for tier_max in (0..tiers.len()).rev() { let name = tiers[tier_max].0; - log::debug!("\tTrying {}", name); + log::debug!("\tTrying {name}"); attributes.clear(); for &(_, tier_attr) in tiers[..=tier_max].iter() { @@ -285,7 +278,7 @@ fn choose_config( log::warn!("No config found!"); } Err(e) => { - log::error!("error in choose_first_config: {:?}", e); + log::error!("error in choose_first_config: {e:?}"); } } } @@ -355,7 +348,7 @@ impl AdapterContext { self.egl.as_ref().map(|egl| egl.version) } - pub fn raw_context(&self) -> *mut raw::c_void { + pub fn raw_context(&self) -> *mut ffi::c_void { match self.egl { Some(ref egl) => egl.raw.as_ptr(), None => ptr::null_mut(), @@ -399,7 +392,7 @@ pub struct AdapterContextLock<'a> { egl: Option>, } -impl<'a> std::ops::Deref for AdapterContextLock<'a> { +impl<'a> core::ops::Deref for AdapterContextLock<'a> { type Target = glow::Context; fn deref(&self) -> &Self::Target { @@ -410,9 +403,9 @@ impl<'a> std::ops::Deref for AdapterContextLock<'a> { impl<'a> Drop for AdapterContextLock<'a> { fn drop(&mut self) { if let Some(egl) = self.egl.take() { - egl.instance - .make_current(egl.display, None, None, None) - .unwrap(); + if let Err(err) = egl.instance.make_current(egl.display, None, None, None) { + log::error!("Failed to make EGL context current: {err:?}"); + } } } } @@ -429,7 +422,7 @@ impl AdapterContext { /// /// > **Note:** Calling this function **will** still lock the [`glow::Context`] which adds an /// > extra safe-guard against accidental concurrent access to the context. - pub unsafe fn get_without_egl_lock(&self) -> MappedMutexGuard { + pub unsafe fn get_without_egl_lock(&self) -> MappedMutexGuard<'_, glow::Context> { let guard = self .glow .try_lock_for(Duration::from_secs(CONTEXT_LOCK_TIMEOUT_SECS)) @@ -470,7 +463,7 @@ struct Inner { supports_native_window: bool, config: khronos_egl::Config, #[cfg_attr(Emscripten, allow(dead_code))] - wl_display: Option<*mut raw::c_void>, + wl_display: Option<*mut ffi::c_void>, #[cfg_attr(Emscripten, allow(dead_code))] force_gles_minor_version: wgt::Gles3MinorVersion, /// Method by which the framebuffer should support srgb @@ -517,6 +510,12 @@ fn terminate_display( } } +fn instance_err( + message: impl Into, +) -> impl FnOnce(E) -> crate::InstanceError { + move |e| crate::InstanceError::with_source(message.into(), e) +} + impl Inner { fn create( flags: wgt::InstanceFlags, @@ -524,20 +523,16 @@ impl Inner { display: khronos_egl::Display, force_gles_minor_version: wgt::Gles3MinorVersion, ) -> Result { - let version = initialize_display(&egl, display).map_err(|e| { - crate::InstanceError::with_source( - String::from("failed to initialize EGL display connection"), - e, - ) - })?; + let version = initialize_display(&egl, display) + .map_err(instance_err("failed to initialize EGL display connection"))?; let vendor = egl .query_string(Some(display), khronos_egl::VENDOR) - .unwrap(); + .map_err(instance_err("failed to query EGL vendor"))?; let display_extensions = egl .query_string(Some(display), khronos_egl::EXTENSIONS) - .unwrap() + .map_err(instance_err("failed to query EGL display extensions"))? .to_string_lossy(); - log::debug!("Display vendor {:?}, version {:?}", vendor, version,); + log::debug!("Display vendor {vendor:?}, version {version:?}",); log::debug!( "Display extensions: {:#?}", display_extensions.split_whitespace().collect::>() @@ -556,16 +551,19 @@ impl Inner { if log::max_level() >= log::LevelFilter::Trace { log::trace!("Configurations:"); - let config_count = egl.get_config_count(display).unwrap(); + let config_count = egl + .get_config_count(display) + .map_err(instance_err("failed to get config count"))?; let mut configurations = Vec::with_capacity(config_count); - egl.get_configs(display, &mut configurations).unwrap(); + egl.get_configs(display, &mut configurations) + .map_err(instance_err("failed to get configs"))?; for &config in configurations.iter() { - log::trace!("\tCONFORMANT=0x{:X}, RENDERABLE=0x{:X}, NATIVE_RENDERABLE=0x{:X}, SURFACE_TYPE=0x{:X}, ALPHA_SIZE={}", - egl.get_config_attrib(display, config, khronos_egl::CONFORMANT).unwrap(), - egl.get_config_attrib(display, config, khronos_egl::RENDERABLE_TYPE).unwrap(), - egl.get_config_attrib(display, config, khronos_egl::NATIVE_RENDERABLE).unwrap(), - egl.get_config_attrib(display, config, khronos_egl::SURFACE_TYPE).unwrap(), - egl.get_config_attrib(display, config, khronos_egl::ALPHA_SIZE).unwrap(), + log::trace!("\tCONFORMANT=0x{:X?}, RENDERABLE=0x{:X?}, NATIVE_RENDERABLE=0x{:X?}, SURFACE_TYPE=0x{:X?}, ALPHA_SIZE={:?}", + egl.get_config_attrib(display, config, khronos_egl::CONFORMANT), + egl.get_config_attrib(display, config, khronos_egl::RENDERABLE_TYPE), + egl.get_config_attrib(display, config, khronos_egl::NATIVE_RENDERABLE), + egl.get_config_attrib(display, config, khronos_egl::SURFACE_TYPE), + egl.get_config_attrib(display, config, khronos_egl::ALPHA_SIZE), ); } } @@ -575,7 +573,7 @@ impl Inner { let supports_opengl = if version >= (1, 4) { let client_apis = egl .query_string(Some(display), khronos_egl::CLIENT_APIS) - .unwrap() + .map_err(instance_err("failed to query EGL client APIs string"))? .to_string_lossy(); client_apis .split(' ') @@ -588,9 +586,8 @@ impl Inner { } else { khronos_egl::OPENGL_ES_API }) - .unwrap(); + .map_err(instance_err("failed to bind API"))?; - let needs_robustness = true; let mut khr_context_flags = 0; let supports_khr_context = display_extensions.contains("EGL_KHR_create_context"); @@ -627,53 +624,108 @@ impl Inner { log::debug!("\tEGL context: -debug"); } } - if needs_robustness { - //Note: the core version can fail if robustness is not supported - // (regardless of whether the extension is supported!). - // In fact, Angle does precisely that awful behavior, so we don't try it there. - if version >= (1, 5) && !display_extensions.contains("EGL_ANGLE_") { - log::debug!("\tEGL context: +robust access"); - context_attributes.push(khronos_egl::CONTEXT_OPENGL_ROBUST_ACCESS); - context_attributes.push(khronos_egl::TRUE as _); - } else if display_extensions.contains("EGL_EXT_create_context_robustness") { - log::debug!("\tEGL context: +robust access EXT"); - context_attributes.push(EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT); - context_attributes.push(khronos_egl::TRUE as _); - } else { - //Note: we aren't trying `EGL_CONTEXT_OPENGL_ROBUST_ACCESS_BIT_KHR` - // because it's for desktop GL only, not GLES. - log::warn!("\tEGL context: -robust access"); - } - } + if khr_context_flags != 0 { context_attributes.push(EGL_CONTEXT_FLAGS_KHR); context_attributes.push(khr_context_flags); } - context_attributes.push(khronos_egl::NONE); gl_context_attributes.extend(&context_attributes); gles_context_attributes.extend(&context_attributes); - let context = if supports_opengl { - egl.create_context(display, config, None, &gl_context_attributes) - .or_else(|_| { - egl.bind_api(khronos_egl::OPENGL_ES_API).unwrap(); + let context = { + enum Robustness { + Core, + Ext, + } + + let mut robustness = if version >= (1, 5) { + Some(Robustness::Core) + } else if display_extensions.contains("EGL_EXT_create_context_robustness") { + Some(Robustness::Ext) + } else { + None + }; + + loop { + let robustness_attributes = match robustness { + Some(Robustness::Core) => { + vec![ + khronos_egl::CONTEXT_OPENGL_ROBUST_ACCESS, + khronos_egl::TRUE as _, + khronos_egl::NONE, + ] + } + Some(Robustness::Ext) => { + vec![ + EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT, + khronos_egl::TRUE as _, + khronos_egl::NONE, + ] + } + None => vec![khronos_egl::NONE], + }; + + let mut gl_context_attributes = gl_context_attributes.clone(); + gl_context_attributes.extend(&robustness_attributes); + + let mut gles_context_attributes = gles_context_attributes.clone(); + gles_context_attributes.extend(&robustness_attributes); + + let result = if supports_opengl { + egl.create_context(display, config, None, &gl_context_attributes) + .or_else(|_| { + egl.bind_api(khronos_egl::OPENGL_ES_API)?; + egl.create_context(display, config, None, &gles_context_attributes) + }) + } else { egl.create_context(display, config, None, &gles_context_attributes) - }) - .map_err(|e| { - crate::InstanceError::with_source( - String::from("unable to create OpenGL or GLES 3.x context"), - e, - ) - }) - } else { - egl.create_context(display, config, None, &gles_context_attributes) - .map_err(|e| { - crate::InstanceError::with_source( - String::from("unable to create GLES 3.x context"), - e, - ) - }) + }; + + match (result, robustness) { + // We have a context at the requested robustness level + (Ok(_), robustness) => { + match robustness { + Some(Robustness::Core) => { + log::debug!("\tEGL context: +robust access"); + } + Some(Robustness::Ext) => { + log::debug!("\tEGL context: +robust access EXT"); + } + None => { + log::debug!("\tEGL context: -robust access"); + } + } + + break result; + } + + // BadAttribute could mean that context creation is not supported at the requested robustness level + // We try the next robustness level. + (Err(khronos_egl::Error::BadAttribute), Some(r)) => { + // Trying EXT robustness if Core robustness is not working + // and EXT robustness is supported. + robustness = if matches!(r, Robustness::Core) + && display_extensions.contains("EGL_EXT_create_context_robustness") + { + Some(Robustness::Ext) + } else { + None + }; + + continue; + } + + // Any other error, or depleted robustness levels, we give up. + _ => break result, + } + } + .map_err(|e| { + crate::InstanceError::with_source( + String::from("unable to create OpenGL or GLES 3.x context"), + e, + ) + }) }?; // Testing if context can be binded without surface @@ -727,11 +779,11 @@ impl Drop for Inner { .instance .destroy_context(self.egl.display, self.egl.raw) { - log::warn!("Error in destroy_context: {:?}", e); + log::warn!("Error in destroy_context: {e:?}"); } if let Err(e) = terminate_display(&self.egl.instance, self.egl.display) { - log::warn!("Error in terminate: {:?}", e); + log::warn!("Error in terminate: {e:?}"); } } } @@ -810,15 +862,9 @@ impl crate::Instance for Instance { } else { unsafe { khronos_egl::DynamicInstance::::load_required() } }; - let egl = match egl_result { - Ok(egl) => Arc::new(egl), - Err(e) => { - return Err(crate::InstanceError::with_source( - String::from("unable to open libEGL"), - e, - )); - } - }; + let egl = egl_result + .map(Arc::new) + .map_err(instance_err("unable to open libEGL"))?; let client_extensions = egl.query_string(None, khronos_egl::EXTENSIONS); @@ -853,76 +899,84 @@ impl crate::Instance for Instance { #[cfg(Emscripten)] let egl1_5: Option<&Arc> = Some(&egl); - let (display, display_owner, wsi_kind) = - if let (Some(library), Some(egl)) = (wayland_library, egl1_5) { - log::info!("Using Wayland platform"); - let display_attributes = [khronos_egl::ATTRIB_NONE]; - let display = unsafe { - egl.get_platform_display( - EGL_PLATFORM_WAYLAND_KHR, - khronos_egl::DEFAULT_DISPLAY, - &display_attributes, - ) - } - .unwrap(); - (display, Some(Rc::new(library)), WindowKind::Wayland) - } else if let (Some(display_owner), Some(egl)) = (x11_display_library, egl1_5) { - log::info!("Using X11 platform"); - let display_attributes = [khronos_egl::ATTRIB_NONE]; - let display = unsafe { - egl.get_platform_display( - EGL_PLATFORM_X11_KHR, - display_owner.display.as_ptr(), - &display_attributes, - ) - } - .unwrap(); - (display, Some(Rc::new(display_owner)), WindowKind::X11) - } else if let (Some(display_owner), Some(egl)) = (angle_x11_display_library, egl1_5) { - log::info!("Using Angle platform with X11"); - let display_attributes = [ - EGL_PLATFORM_ANGLE_NATIVE_PLATFORM_TYPE_ANGLE as khronos_egl::Attrib, - EGL_PLATFORM_X11_KHR as khronos_egl::Attrib, - EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED as khronos_egl::Attrib, - usize::from(desc.flags.contains(wgt::InstanceFlags::VALIDATION)), - khronos_egl::ATTRIB_NONE, - ]; - let display = unsafe { - egl.get_platform_display( - EGL_PLATFORM_ANGLE_ANGLE, - display_owner.display.as_ptr(), - &display_attributes, - ) - } - .unwrap(); - (display, Some(Rc::new(display_owner)), WindowKind::AngleX11) - } else if client_ext_str.contains("EGL_MESA_platform_surfaceless") { - log::warn!("No windowing system present. Using surfaceless platform"); - #[allow(clippy::unnecessary_literal_unwrap)] // This is only a literal on Emscripten - let egl = egl1_5.expect("Failed to get EGL 1.5 for surfaceless"); - let display = unsafe { - egl.get_platform_display( - EGL_PLATFORM_SURFACELESS_MESA, - khronos_egl::DEFAULT_DISPLAY, - &[khronos_egl::ATTRIB_NONE], - ) - } - .unwrap(); + let (display, display_owner, wsi_kind) = if let (Some(library), Some(egl)) = + (wayland_library, egl1_5) + { + log::info!("Using Wayland platform"); + let display_attributes = [khronos_egl::ATTRIB_NONE]; + let display = unsafe { + egl.get_platform_display( + EGL_PLATFORM_WAYLAND_KHR, + khronos_egl::DEFAULT_DISPLAY, + &display_attributes, + ) + } + .map_err(instance_err("failed to get Wayland display"))?; + (display, Some(Rc::new(library)), WindowKind::Wayland) + } else if let (Some(display_owner), Some(egl)) = (x11_display_library, egl1_5) { + log::info!("Using X11 platform"); + let display_attributes = [khronos_egl::ATTRIB_NONE]; + let display = unsafe { + egl.get_platform_display( + EGL_PLATFORM_X11_KHR, + display_owner.display.as_ptr(), + &display_attributes, + ) + } + .map_err(instance_err("failed to get x11 display"))?; + (display, Some(Rc::new(display_owner)), WindowKind::X11) + } else if let (Some(display_owner), Some(egl)) = (angle_x11_display_library, egl1_5) { + log::info!("Using Angle platform with X11"); + let display_attributes = [ + EGL_PLATFORM_ANGLE_NATIVE_PLATFORM_TYPE_ANGLE as khronos_egl::Attrib, + EGL_PLATFORM_X11_KHR as khronos_egl::Attrib, + EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED as khronos_egl::Attrib, + usize::from(desc.flags.contains(wgt::InstanceFlags::VALIDATION)), + khronos_egl::ATTRIB_NONE, + ]; + let display = unsafe { + egl.get_platform_display( + EGL_PLATFORM_ANGLE_ANGLE, + display_owner.display.as_ptr(), + &display_attributes, + ) + } + .map_err(instance_err("failed to get Angle display"))?; + (display, Some(Rc::new(display_owner)), WindowKind::AngleX11) + } else if client_ext_str.contains("EGL_MESA_platform_surfaceless") { + log::warn!("No windowing system present. Using surfaceless platform"); + #[allow(clippy::unnecessary_literal_unwrap)] // This is only a literal on Emscripten + let egl = egl1_5.expect("Failed to get EGL 1.5 for surfaceless"); + let display = unsafe { + egl.get_platform_display( + EGL_PLATFORM_SURFACELESS_MESA, + khronos_egl::DEFAULT_DISPLAY, + &[khronos_egl::ATTRIB_NONE], + ) + } + .map_err(instance_err("failed to get MESA display"))?; - (display, None, WindowKind::Unknown) - } else { - log::warn!("EGL_MESA_platform_surfaceless not available. Using default platform"); - let display = unsafe { egl.get_display(khronos_egl::DEFAULT_DISPLAY) }.unwrap(); - (display, None, WindowKind::Unknown) - }; + (display, None, WindowKind::Unknown) + } else { + log::warn!("EGL_MESA_platform_surfaceless not available. Using default platform"); + let display = unsafe { egl.get_display(khronos_egl::DEFAULT_DISPLAY) } + .ok_or_else(|| crate::InstanceError::new("Failed to get default display".into()))?; + (display, None, WindowKind::Unknown) + }; if desc.flags.contains(wgt::InstanceFlags::VALIDATION) && client_ext_str.contains("EGL_KHR_debug") { log::debug!("Enabling EGL debug output"); let function: EglDebugMessageControlFun = { - let addr = egl.get_proc_address("eglDebugMessageControlKHR").unwrap(); - unsafe { std::mem::transmute(addr) } + let addr = egl + .get_proc_address("eglDebugMessageControlKHR") + .ok_or_else(|| { + crate::InstanceError::new( + "failed to get `eglDebugMessageControlKHR` proc address".into(), + ) + })?; + unsafe { core::mem::transmute(addr) } }; let attributes = [ EGL_DEBUG_MSG_CRITICAL_KHR as khronos_egl::Attrib, @@ -983,7 +1037,7 @@ impl crate::Instance for Instance { inner.config, khronos_egl::NATIVE_VISUAL_ID, ) - .unwrap(); + .map_err(instance_err("failed to get config NATIVE_VISUAL_ID"))?; let ret = unsafe { ndk_sys::ANativeWindow_setBuffersGeometry( @@ -1018,7 +1072,7 @@ impl crate::Instance for Instance { */ log::warn!("Re-initializing Gles context due to Wayland window"); - use std::ops::DerefMut; + use core::ops::DerefMut; let display_attributes = [khronos_egl::ATTRIB_NONE]; let display = unsafe { @@ -1026,14 +1080,18 @@ impl crate::Instance for Instance { .egl .instance .upcast::() - .unwrap() + .ok_or_else(|| { + crate::InstanceError::new( + "EGL 1.5 is required for Wayland support".into(), + ) + })? .get_platform_display( EGL_PLATFORM_WAYLAND_KHR, display_handle.display.as_ptr(), &display_attributes, ) } - .unwrap(); + .map_err(instance_err("failed to get wayland display"))?; let new_inner = Inner::create( self.flags, @@ -1042,7 +1100,7 @@ impl crate::Instance for Instance { inner.force_gles_minor_version, )?; - let old_inner = std::mem::replace(inner.deref_mut(), new_inner); + let old_inner = core::mem::replace(inner.deref_mut(), new_inner); inner.wl_display = Some(display_handle.display.as_ptr()); drop(old_inner); @@ -1166,7 +1224,7 @@ impl super::Device { #[derive(Debug)] pub struct Swapchain { surface: khronos_egl::Surface, - wl_window: Option<*mut raw::c_void>, + wl_window: Option<*mut ffi::c_void>, framebuffer: glow::Framebuffer, renderbuffer: glow::Renderbuffer, /// Extent because the window lies @@ -1199,7 +1257,9 @@ impl Surface { ) -> Result<(), crate::SurfaceError> { let gl = unsafe { context.get_without_egl_lock() }; let swapchain = self.swapchain.read(); - let sc = swapchain.as_ref().unwrap(); + let sc = swapchain.as_ref().ok_or(crate::SurfaceError::Other( + "Surface has no swap-chain configured", + ))?; self.egl .instance @@ -1210,7 +1270,7 @@ impl Surface { Some(self.egl.raw), ) .map_err(|e| { - log::error!("make_current(surface) failed: {}", e); + log::error!("make_current(surface) failed: {e}"); crate::SurfaceError::Lost })?; @@ -1254,7 +1314,7 @@ impl Surface { .instance .swap_buffers(self.egl.display, sc.surface) .map_err(|e| { - log::error!("swap_buffers failed: {}", e); + log::error!("swap_buffers failed: {e}"); crate::SurfaceError::Lost // TODO: should we unset the current context here? })?; @@ -1262,7 +1322,7 @@ impl Surface { .instance .make_current(self.egl.display, None, None, None) .map_err(|e| { - log::error!("make_current(null) failed: {}", e); + log::error!("make_current(null) failed: {e}"); crate::SurfaceError::Lost })?; @@ -1272,7 +1332,7 @@ impl Surface { unsafe fn unconfigure_impl( &self, device: &super::Device, - ) -> Option<(khronos_egl::Surface, Option<*mut raw::c_void>)> { + ) -> Option<(khronos_egl::Surface, Option<*mut ffi::c_void>)> { let gl = &device.shared.context.lock(); match self.swapchain.write().take() { Some(sc) => { @@ -1325,9 +1385,20 @@ impl crate::Surface for Surface { } (WindowKind::Unknown, Rwh::OhosNdk(handle)) => handle.native_window.as_ptr(), (WindowKind::Wayland, Rwh::Wayland(handle)) => { - let library = &self.wsi.display_owner.as_ref().unwrap().library; + let library = &self + .wsi + .display_owner + .as_ref() + .ok_or(crate::SurfaceError::Other("No WSI display owner"))? + .library; let wl_egl_window_create: libloading::Symbol = - unsafe { library.get(c"wl_egl_window_create".to_bytes()) }.unwrap(); + unsafe { library.get(c"wl_egl_window_create".to_bytes()) }.map_err( + |_| { + crate::SurfaceError::Other( + "Failed to load `wl_egl_window_create", + ) + }, + )?; let window = unsafe { wl_egl_window_create(handle.surface.as_ptr(), 640, 480) } .cast(); @@ -1429,7 +1500,7 @@ impl crate::Surface for Surface { match raw_result { Ok(raw) => (raw, wl_window), Err(e) => { - log::warn!("Error in create_window_surface: {:?}", e); + log::warn!("Error in create_window_surface: {e:?}"); return Err(crate::SurfaceError::Lost); } } @@ -1437,9 +1508,16 @@ impl crate::Surface for Surface { }; if let Some(window) = wl_window { - let library = &self.wsi.display_owner.as_ref().unwrap().library; - let wl_egl_window_resize: libloading::Symbol = - unsafe { library.get(c"wl_egl_window_resize".to_bytes()) }.unwrap(); + let library = &self + .wsi + .display_owner + .as_ref() + .ok_or(crate::SurfaceError::Other("No WSI display owner"))? + .library; + let wl_egl_window_resize: libloading::Symbol = unsafe { + library.get(c"wl_egl_window_resize".to_bytes()) + } + .map_err(|_| crate::SurfaceError::Other("Failed to load `wl_egl_window_resize"))?; unsafe { wl_egl_window_resize( window, @@ -1523,7 +1601,9 @@ impl crate::Surface for Surface { _fence: &super::Fence, ) -> Result>, crate::SurfaceError> { let swapchain = self.swapchain.read(); - let sc = swapchain.as_ref().unwrap(); + let sc = swapchain.as_ref().ok_or(crate::SurfaceError::Other( + "Surface has no swap-chain configured", + ))?; let texture = super::Texture { inner: super::TextureInner::Renderbuffer { raw: sc.renderbuffer, diff --git a/wgpu-hal/src/gles/fence.rs b/wgpu-hal/src/gles/fence.rs index b29a63242..d5cd0ec42 100644 --- a/wgpu-hal/src/gles/fence.rs +++ b/wgpu-hal/src/gles/fence.rs @@ -102,7 +102,7 @@ impl Fence { &self, gl: &glow::Context, wait_value: crate::FenceValue, - timeout_ns: u64, + timeout_ns: u32, ) -> Result { let last_completed = self.last_completed.load(Ordering::Acquire); @@ -134,7 +134,7 @@ impl Fence { gl.client_wait_sync( gl_fence.sync, glow::SYNC_FLUSH_COMMANDS_BIT, - timeout_ns as i32, + timeout_ns.min(i32::MAX as u32) as i32, ) }; diff --git a/wgpu-hal/src/gles/mod.rs b/wgpu-hal/src/gles/mod.rs index ab434b90d..aeef34186 100644 --- a/wgpu-hal/src/gles/mod.rs +++ b/wgpu-hal/src/gles/mod.rs @@ -62,8 +62,6 @@ in shaders, getting buffers and builtins to work correctly is a bit tricky. We never emulate `base_vertex` and gl_VertexID behaves as `@builtin(vertex_index)` does, so we never need to do anything about that. -We always advertise support for `VERTEX_AND_INSTANCE_INDEX_RESPECTS_RESPECTIVE_FIRST_VALUE_IN_INDIRECT_DRAW`. - ### GL 4.2+ with ARB_shader_draw_parameters - `@builtin(instance_index)` translates to `gl_InstanceID + gl_BaseInstance` @@ -103,17 +101,17 @@ pub use fence::Fence; #[cfg(not(any(windows, webgl)))] pub use self::egl::{AdapterContext, AdapterContextLock}; #[cfg(not(any(windows, webgl)))] -use self::egl::{Instance, Surface}; +pub use self::egl::{Instance, Surface}; #[cfg(webgl)] pub use self::web::AdapterContext; #[cfg(webgl)] -use self::web::{Instance, Surface}; +pub use self::web::{Instance, Surface}; #[cfg(windows)] use self::wgl::AdapterContext; #[cfg(windows)] -use self::wgl::{Instance, Surface}; +pub use self::wgl::{Instance, Surface}; use alloc::{boxed::Box, string::String, string::ToString as _, sync::Arc, vec::Vec}; use core::{ @@ -143,6 +141,8 @@ const MAX_PUSH_CONSTANTS: usize = 64; const MAX_PUSH_CONSTANT_COMMANDS: usize = MAX_PUSH_CONSTANTS * crate::MAX_CONCURRENT_SHADER_STAGES; impl crate::Api for Api { + const VARIANT: wgt::Backend = wgt::Backend::Gl; + type Instance = Instance; type Surface = Surface; type Adapter = Adapter; @@ -368,9 +368,21 @@ pub enum TextureInner { target: BindTarget, }, #[cfg(webgl)] + /// Render to a `WebGLFramebuffer` + /// + /// This is a web feature ExternalFramebuffer { inner: web_sys::WebGlFramebuffer, }, + #[cfg(native)] + /// Render to a `glow::NativeFramebuffer` + /// Useful when the framebuffer to draw to + /// has a non-zero framebuffer ID + /// + /// This is a native feature + ExternalNativeFramebuffer { + inner: glow::NativeFramebuffer, + }, } #[cfg(send_sync)] @@ -387,6 +399,8 @@ impl TextureInner { Self::Texture { raw, target } => (raw, target), #[cfg(webgl)] Self::ExternalFramebuffer { .. } => panic!("Unexpected external framebuffer"), + #[cfg(native)] + Self::ExternalNativeFramebuffer { .. } => panic!("unexpected external framebuffer"), } } } @@ -394,13 +408,16 @@ impl TextureInner { #[derive(Debug)] pub struct Texture { pub inner: TextureInner, - pub drop_guard: Option, pub mip_level_count: u32, pub array_layer_count: u32, pub format: wgt::TextureFormat, #[allow(unused)] pub format_desc: TextureFormatDesc, pub copy_size: CopyExtent, + + // The `drop_guard` field must be the last field of this struct so it is dropped last. + // Do not add new fields after it. + pub drop_guard: Option, } impl crate::DynTexture for Texture {} @@ -591,7 +608,7 @@ type ShaderId = u32; #[derive(Debug)] pub struct ShaderModule { - naga: crate::NagaShader, + source: crate::NagaShader, label: Option, id: ShaderId, } @@ -657,6 +674,7 @@ struct PipelineInner { sampler_map: SamplerBindMap, first_instance_location: Option, push_constant_descs: ArrayVec, + clip_distance_count: u32, } #[derive(Clone, Debug)] @@ -904,6 +922,7 @@ enum Command { BindAttachment { attachment: u32, view: TextureView, + depth_slice: Option, }, ResolveAttachment { attachment: u32, @@ -993,6 +1012,10 @@ enum Command { /// Offset from the start of the `data_bytes` offset: u32, }, + SetClipDistances { + old_count: u32, + new_count: u32, + }, } #[derive(Default)] @@ -1080,14 +1103,11 @@ fn gl_debug_message_callback(source: u32, gltype: u32, id: u32, severity: u32, m let _ = std::panic::catch_unwind(|| { log::log!( log_severity, - "GLES: [{}/{}] ID {} : {}", - source_str, - type_str, - id, - message + "GLES: [{source_str}/{type_str}] ID {id} : {message}" ); }); + #[cfg(feature = "validation_canary")] if cfg!(debug_assertions) && log_severity == log::Level::Error { // Set canary and continue crate::VALIDATION_CANARY.add(message.to_string()); diff --git a/wgpu-hal/src/gles/queue.rs b/wgpu-hal/src/gles/queue.rs index 65bfe526e..5ce0cac30 100644 --- a/wgpu-hal/src/gles/queue.rs +++ b/wgpu-hal/src/gles/queue.rs @@ -13,6 +13,18 @@ fn extract_marker<'a>(data: &'a [u8], range: &core::ops::Range) -> &'a str core::str::from_utf8(&data[range.start as usize..range.end as usize]).unwrap() } +fn to_debug_str(s: &str) -> &str { + // The spec mentions that if the length given to debug functions is negative, + // the implementation will access the ptr and look for a null that terminates + // the string but some implementations will try to access the ptr even if the + // length is 0. + if s.is_empty() { + "" + } else { + s + } +} + fn get_2d_target(target: u32, array_layer: u32) -> u32 { const CUBEMAP_FACES: [u32; 6] = [ glow::TEXTURE_CUBE_MAP_POSITIVE_X, @@ -98,6 +110,7 @@ impl super::Queue { fbo_target: u32, attachment: u32, view: &super::TextureView, + depth_slice: Option, ) { match view.inner { super::TextureInner::Renderbuffer { raw } => { @@ -126,13 +139,18 @@ impl super::Queue { ) }; } else if is_layered_target(target) { + let layer = if target == glow::TEXTURE_3D { + depth_slice.unwrap() as i32 + } else { + view.array_layers.start as i32 + }; unsafe { gl.framebuffer_texture_layer( fbo_target, attachment, Some(raw), view.mip_levels.start as i32, - view.array_layers.start as i32, + layer, ) }; } else { @@ -152,6 +170,10 @@ impl super::Queue { super::TextureInner::ExternalFramebuffer { ref inner } => unsafe { gl.bind_external_framebuffer(glow::FRAMEBUFFER, inner); }, + #[cfg(native)] + super::TextureInner::ExternalNativeFramebuffer { ref inner } => unsafe { + gl.bind_framebuffer(glow::FRAMEBUFFER, Some(*inner)); + }, } } @@ -1096,8 +1118,11 @@ impl super::Queue { C::BindAttachment { attachment, ref view, + depth_slice, } => { - unsafe { self.set_attachment(gl, glow::DRAW_FRAMEBUFFER, attachment, view) }; + unsafe { + self.set_attachment(gl, glow::DRAW_FRAMEBUFFER, attachment, view, depth_slice) + }; } C::ResolveAttachment { attachment, @@ -1108,7 +1133,13 @@ impl super::Queue { unsafe { gl.read_buffer(attachment) }; unsafe { gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, Some(self.copy_fbo)) }; unsafe { - self.set_attachment(gl, glow::DRAW_FRAMEBUFFER, glow::COLOR_ATTACHMENT0, dst) + self.set_attachment( + gl, + glow::DRAW_FRAMEBUFFER, + glow::COLOR_ATTACHMENT0, + dst, + None, + ) }; unsafe { gl.blit_framebuffer( @@ -1567,7 +1598,7 @@ impl super::Queue { glow::DEBUG_TYPE_MARKER, DEBUG_ID, glow::DEBUG_SEVERITY_NOTIFICATION, - marker, + to_debug_str(marker), ) } }; @@ -1580,7 +1611,11 @@ impl super::Queue { .private_caps .contains(PrivateCapabilities::DEBUG_FNS) { - gl.push_debug_group(glow::DEBUG_SOURCE_APPLICATION, DEBUG_ID, marker) + gl.push_debug_group( + glow::DEBUG_SOURCE_APPLICATION, + DEBUG_ID, + to_debug_str(marker), + ) } }; } @@ -1805,6 +1840,20 @@ impl super::Queue { _ => panic!("Unsupported uniform datatype: {:?}!", uniform.ty), } } + C::SetClipDistances { + old_count, + new_count, + } => { + // Disable clip planes that are no longer active + for i in new_count..old_count { + unsafe { gl.disable(glow::CLIP_DISTANCE0 + i) }; + } + + // Enable clip planes that are now active + for i in old_count..new_count { + unsafe { gl.enable(glow::CLIP_DISTANCE0 + i) }; + } + } } } } @@ -1832,7 +1881,13 @@ impl crate::Queue for super::Queue { .private_caps .contains(PrivateCapabilities::DEBUG_FNS) { - unsafe { gl.push_debug_group(glow::DEBUG_SOURCE_APPLICATION, DEBUG_ID, label) }; + unsafe { + gl.push_debug_group( + glow::DEBUG_SOURCE_APPLICATION, + DEBUG_ID, + to_debug_str(label), + ) + }; } } diff --git a/wgpu-hal/src/gles/wgl.rs b/wgpu-hal/src/gles/wgl.rs index 13e276cfa..6a4c3863b 100644 --- a/wgpu-hal/src/gles/wgl.rs +++ b/wgpu-hal/src/gles/wgl.rs @@ -1,19 +1,16 @@ -#![allow(clippy::std_instead_of_alloc, clippy::std_instead_of_core)] - -use std::{ - borrow::ToOwned as _, - ffi::{c_void, CStr, CString}, +use alloc::{borrow::ToOwned as _, ffi::CString, string::String, sync::Arc, vec::Vec}; +use core::{ + ffi::{c_int, c_void, CStr}, mem::{self, ManuallyDrop}, - os::raw::c_int, ptr, - string::String, + time::Duration, +}; +use std::{ sync::{ mpsc::{sync_channel, SyncSender}, - Arc, LazyLock, + LazyLock, }, thread, - time::Duration, - vec::Vec, }; use glow::HasContext; @@ -102,7 +99,7 @@ pub struct AdapterContextLock<'a> { inner: MutexGuard<'a, Inner>, } -impl<'a> std::ops::Deref for AdapterContextLock<'a> { +impl<'a> core::ops::Deref for AdapterContextLock<'a> { type Target = glow::Context; fn deref(&self) -> &Self::Target { diff --git a/wgpu-hal/src/lib.rs b/wgpu-hal/src/lib.rs index aa997a2d9..8620d05a8 100644 --- a/wgpu-hal/src/lib.rs +++ b/wgpu-hal/src/lib.rs @@ -203,7 +203,7 @@ //! [wiki-debug]: https://github.com/gfx-rs/wgpu/wiki/Debugging-wgpu-Applications #![no_std] -#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] +#![cfg_attr(docsrs, feature(doc_cfg))] #![allow( // this happens on the GL backend, where it is both thread safe and non-thread safe in the same code. clippy::arc_with_non_send_sync, @@ -225,6 +225,8 @@ clippy::missing_safety_doc, // It gets in the way a lot and does not prevent bugs in practice. clippy::pattern_type_mismatch, + // We should investigate these. + clippy::large_enum_variant )] #![warn( clippy::alloc_instead_of_core, @@ -275,6 +277,11 @@ pub mod api { } mod dynamic; +#[cfg(feature = "validation_canary")] +mod validation_canary; + +#[cfg(feature = "validation_canary")] +pub use validation_canary::{ValidationCanary, VALIDATION_CANARY}; pub(crate) use dynamic::impl_dyn_resource; pub use dynamic::{ @@ -287,21 +294,28 @@ pub use dynamic::{ #[allow(unused)] use alloc::boxed::Box; -use alloc::{borrow::Cow, string::String, sync::Arc, vec::Vec}; +use alloc::{borrow::Cow, string::String, vec::Vec}; use core::{ borrow::Borrow, error::Error, fmt, - num::NonZeroU32, + num::{NonZeroU32, NonZeroU64}, ops::{Range, RangeInclusive}, ptr::NonNull, }; use bitflags::bitflags; -use parking_lot::Mutex; use thiserror::Error; use wgt::WasmNotSendSync; +cfg_if::cfg_if! { + if #[cfg(supports_ptr_atomics)] { + use alloc::sync::Arc; + } else if #[cfg(feature = "portable-atomic")] { + use portable_atomic_util::Arc; + } +} + // - Vertex + Fragment // - Compute // Task + Mesh + Fragment @@ -363,8 +377,6 @@ pub enum DeviceError { OutOfMemory, #[error("Device is lost")] Lost, - #[error("Creation of a resource failed for a reason other than running out of memory.")] - ResourceCreationFailed, #[error("Unexpected error variant (driver implementation is at fault)")] Unexpected, } @@ -446,14 +458,32 @@ impl InstanceError { } #[allow(dead_code)] // may be unused on some platforms pub(crate) fn with_source(message: String, source: impl Error + Send + Sync + 'static) -> Self { + cfg_if::cfg_if! { + if #[cfg(supports_ptr_atomics)] { + let source = Arc::new(source); + } else { + // TODO(https://github.com/rust-lang/rust/issues/18598): avoid indirection via Box once arbitrary types support unsized coercion + let source: Box = Box::new(source); + let source = Arc::from(source); + } + } Self { message, - source: Some(Arc::new(source)), + source: Some(source), } } } -pub trait Api: Clone + fmt::Debug + Sized { +/// All the types and methods that make up a implementation on top of a backend. +/// +/// Only the types that have non-dyn trait bounds have methods on them. Most methods +/// are either on [`CommandEncoder`] or [`Device`]. +/// +/// The api can either be used through generics (through use of this trait and associated +/// types) or dynamically through using the `Dyn*` traits. +pub trait Api: Clone + fmt::Debug + Sized + WasmNotSendSync + 'static { + const VARIANT: wgt::Backend; + type Instance: DynInstance + Instance; type Surface: DynSurface + Surface; type Adapter: DynAdapter + Adapter; @@ -901,15 +931,6 @@ pub trait Device: WasmNotSendSync { ::PipelineCache, >, ) -> Result<::RenderPipeline, PipelineError>; - #[allow(clippy::type_complexity)] - unsafe fn create_mesh_pipeline( - &self, - desc: &MeshPipelineDescriptor< - ::PipelineLayout, - ::ShaderModule, - ::PipelineCache, - >, - ) -> Result<::RenderPipeline, PipelineError>; unsafe fn destroy_render_pipeline(&self, pipeline: ::RenderPipeline); #[allow(clippy::type_complexity)] @@ -960,6 +981,9 @@ pub trait Device: WasmNotSendSync { /// Calling `wait` with a lower [`FenceValue`] than `fence`'s current value /// returns immediately. /// + /// If `timeout` is provided, the function will block indefinitely or until + /// an error is encountered. + /// /// Returns `Ok(true)` on success and `Ok(false)` on timeout. /// /// [`Fence`]: Api::Fence @@ -968,11 +992,26 @@ pub trait Device: WasmNotSendSync { &self, fence: &::Fence, value: FenceValue, - timeout_ms: u32, + timeout: Option, ) -> Result; - unsafe fn start_capture(&self) -> bool; - unsafe fn stop_capture(&self); + /// Start a graphics debugger capture. + /// + /// # Safety + /// + /// See [`wgpu::Device::start_graphics_debugger_capture`][api] for more details. + /// + /// [api]: ../wgpu/struct.Device.html#method.start_graphics_debugger_capture + unsafe fn start_graphics_debugger_capture(&self) -> bool; + + /// Stop a graphics debugger capture. + /// + /// # Safety + /// + /// See [`wgpu::Device::stop_graphics_debugger_capture`][api] for more details. + /// + /// [api]: ../wgpu/struct.Device.html#method.stop_graphics_debugger_capture + unsafe fn stop_graphics_debugger_capture(&self); #[allow(unused_variables)] unsafe fn pipeline_cache_get_data( @@ -1005,6 +1044,8 @@ pub trait Device: WasmNotSendSync { fn generate_allocator_report(&self) -> Option { None } + + fn check_if_oom(&self) -> Result<(), DeviceError>; } pub trait Queue: WasmNotSendSync { @@ -1015,9 +1056,9 @@ pub trait Queue: WasmNotSendSync { /// Update `fence` to `value` when the operation is complete. See /// [`Fence`] for details. /// - /// A `wgpu_hal` queue is "single threaded": all command buffers are - /// executed in the order they're submitted, with each buffer able to see - /// previous buffers' results. Specifically: + /// All command buffers submitted to a `wgpu_hal` queue are executed in the + /// order they're submitted, with each buffer able to observe the effects of + /// previous buffers' execution. Specifically: /// /// - If two calls to `submit` on a single `Queue` occur in a particular /// order (that is, they happen on the same thread, or on two threads that @@ -1394,7 +1435,7 @@ pub trait CommandEncoder: WasmNotSendSync + fmt::Debug { unsafe fn begin_render_pass( &mut self, desc: &RenderPassDescriptor<::QuerySet, ::TextureView>, - ); + ) -> Result<(), DeviceError>; /// End the current render pass. /// @@ -1696,7 +1737,7 @@ impl From for FormatAspects { wgt::TextureFormat::Depth32FloatStencil8 | wgt::TextureFormat::Depth24PlusStencil8 => { Self::DEPTH_STENCIL } - wgt::TextureFormat::NV12 => Self::PLANE_0 | Self::PLANE_1, + wgt::TextureFormat::NV12 | wgt::TextureFormat::P010 => Self::PLANE_0 | Self::PLANE_1, _ => Self::COLOR, } } @@ -1724,6 +1765,7 @@ bitflags!( pub struct InstanceDescriptor<'a> { pub name: &'a str, pub flags: wgt::InstanceFlags, + pub memory_budget_thresholds: wgt::MemoryBudgetThresholds, pub backend_options: wgt::BackendOptions, } @@ -1767,6 +1809,10 @@ pub struct Capabilities { pub downlevel: wgt::DownlevelCapabilities, } +/// An adapter with all the information needed to reason about its capabilities. +/// +/// These are either made by [`Instance::enumerate_adapters`] or by backend specific +/// methods on the backend [`Instance`] or [`Adapter`]. #[derive(Debug)] pub struct ExposedAdapter { pub adapter: A::Adapter, @@ -1821,6 +1867,10 @@ pub struct AcquiredSurfaceTexture { pub suboptimal: bool, } +/// An open connection to a device and a queue. +/// +/// This can be created from [`Adapter::open`] or backend +/// specific methods on the backend's [`Instance`] or [`Adapter`]. #[derive(Debug)] pub struct OpenDevice { pub device: A::Device, @@ -1898,7 +1948,7 @@ pub struct SamplerDescriptor<'a> { pub address_modes: [wgt::AddressMode; 3], pub mag_filter: wgt::FilterMode, pub min_filter: wgt::FilterMode, - pub mipmap_filter: wgt::FilterMode, + pub mipmap_filter: wgt::MipmapFilterMode, pub lod_clamp: Range, pub compare: Option, // Must in the range [1, 16]. @@ -1931,11 +1981,18 @@ pub struct PipelineLayoutDescriptor<'a, B: DynBindGroupLayout + ?Sized> { /// /// [`BindGroup`]: Api::BindGroup /// +/// ## Construction +/// +/// The recommended way to construct a `BufferBinding` is using the `binding` +/// method on a wgpu-core `Buffer`, which will validate the binding size +/// against the buffer size. A `new_unchecked` constructor is also provided for +/// cases where direct construction is necessary. +/// /// ## Accessible region /// /// `wgpu_hal` guarantees that shaders compiled with /// [`ShaderModuleDescriptor::runtime_checks`] set to `true` cannot read or -/// write data via this binding outside the *accessible region* of [`buffer`]: +/// write data via this binding outside the *accessible region* of a buffer: /// /// - The accessible region starts at [`offset`]. /// @@ -1955,28 +2012,39 @@ pub struct PipelineLayoutDescriptor<'a, B: DynBindGroupLayout + ?Sized> { /// parts of which buffers shaders might observe. This optimization is only /// sound if shader access is bounds-checked. /// -/// [`buffer`]: BufferBinding::buffer +/// ## Zero-length bindings +/// +/// Some back ends cannot tolerate zero-length regions; for example, see +/// [VUID-VkDescriptorBufferInfo-offset-00340][340] and +/// [VUID-VkDescriptorBufferInfo-range-00341][341], or the +/// documentation for GLES's [glBindBufferRange][bbr]. This documentation +/// previously stated that a `BufferBinding` must have `offset` strictly less +/// than the size of the buffer, but this restriction was not honored elsewhere +/// in the code, so has been removed. However, it remains the case that +/// some backends do not support zero-length bindings, so additional +/// logic is needed somewhere to handle this properly. See +/// [#3170](https://github.com/gfx-rs/wgpu/issues/3170). +/// /// [`offset`]: BufferBinding::offset /// [`size`]: BufferBinding::size /// [`Storage`]: wgt::BufferBindingType::Storage /// [`Uniform`]: wgt::BufferBindingType::Uniform +/// [340]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-VkDescriptorBufferInfo-offset-00340 +/// [341]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-VkDescriptorBufferInfo-range-00341 +/// [bbr]: https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glBindBufferRange.xhtml /// [woob]: https://gpuweb.github.io/gpuweb/wgsl/#out-of-bounds-access-sec #[derive(Debug)] pub struct BufferBinding<'a, B: DynBuffer + ?Sized> { /// The buffer being bound. - pub buffer: &'a B, + /// + /// This is not fully `pub` to prevent direct construction of + /// `BufferBinding`s, while still allowing public read access to the `offset` + /// and `size` properties. + pub(crate) buffer: &'a B, /// The offset at which the bound region starts. /// - /// This must be less than the size of the buffer. Some back ends - /// cannot tolerate zero-length regions; for example, see - /// [VUID-VkDescriptorBufferInfo-offset-00340][340] and - /// [VUID-VkDescriptorBufferInfo-range-00341][341], or the - /// documentation for GLES's [glBindBufferRange][bbr]. - /// - /// [340]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-VkDescriptorBufferInfo-offset-00340 - /// [341]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-VkDescriptorBufferInfo-range-00341 - /// [bbr]: https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glBindBufferRange.xhtml + /// This must be less or equal to the size of the buffer. pub offset: wgt::BufferAddress, /// The size of the region bound, in bytes. @@ -1987,7 +2055,8 @@ pub struct BufferBinding<'a, B: DynBuffer + ?Sized> { pub size: Option, } -impl<'a, T: DynBuffer + ?Sized> Clone for BufferBinding<'a, T> { +// We must implement this manually because `B` is not necessarily `Clone`. +impl Clone for BufferBinding<'_, B> { fn clone(&self) -> Self { BufferBinding { buffer: self.buffer, @@ -1997,6 +2066,64 @@ impl<'a, T: DynBuffer + ?Sized> Clone for BufferBinding<'a, T> { } } +/// Temporary convenience trait to let us call `.get()` on `u64`s in code that +/// really wants to be using `NonZeroU64`. +/// TODO(): remove this +pub trait ShouldBeNonZeroExt { + fn get(&self) -> u64; +} + +impl ShouldBeNonZeroExt for NonZeroU64 { + fn get(&self) -> u64 { + NonZeroU64::get(*self) + } +} + +impl ShouldBeNonZeroExt for u64 { + fn get(&self) -> u64 { + *self + } +} + +impl ShouldBeNonZeroExt for Option { + fn get(&self) -> u64 { + match *self { + Some(non_zero) => non_zero.get(), + None => 0, + } + } +} + +impl<'a, B: DynBuffer + ?Sized> BufferBinding<'a, B> { + /// Construct a `BufferBinding` with the given contents. + /// + /// When possible, use the `binding` method on a wgpu-core `Buffer` instead + /// of this method. `Buffer::binding` validates the size of the binding + /// against the size of the buffer. + /// + /// It is more difficult to provide a validating constructor here, due to + /// not having direct access to the size of a `DynBuffer`. + /// + /// SAFETY: The caller is responsible for ensuring that a binding of `size` + /// bytes starting at `offset` is contained within the buffer. + /// + /// The `S` type parameter is a temporary convenience to allow callers to + /// pass a zero size. When the zero-size binding issue is resolved, the + /// argument should just match the type of the member. + /// TODO(): remove the parameter + pub fn new_unchecked>>( + buffer: &'a B, + offset: wgt::BufferAddress, + size: S, + ) -> Self { + Self { + buffer, + offset, + size: size.into(), + } + } +} + #[derive(Debug)] pub struct TextureBinding<'a, T: DynTextureView + ?Sized> { pub view: &'a T, @@ -2012,6 +2139,23 @@ impl<'a, T: DynTextureView + ?Sized> Clone for TextureBinding<'a, T> { } } +#[derive(Debug)] +pub struct ExternalTextureBinding<'a, B: DynBuffer + ?Sized, T: DynTextureView + ?Sized> { + pub planes: [TextureBinding<'a, T>; 3], + pub params: BufferBinding<'a, B>, +} + +impl<'a, B: DynBuffer + ?Sized, T: DynTextureView + ?Sized> Clone + for ExternalTextureBinding<'a, B, T> +{ + fn clone(&self) -> Self { + ExternalTextureBinding { + planes: self.planes.clone(), + params: self.params.clone(), + } + } +} + /// cbindgen:ignore #[derive(Clone, Debug)] pub struct BindGroupEntry { @@ -2045,6 +2189,7 @@ pub struct BindGroupDescriptor< pub textures: &'a [TextureBinding<'a, T>], pub entries: &'a [BindGroupEntry], pub acceleration_structures: &'a [&'a A], + pub external_textures: &'a [ExternalTextureBinding<'a, B, T>], } #[derive(Clone, Debug)] @@ -2054,6 +2199,7 @@ pub struct CommandEncoderDescriptor<'a, Q: DynQueue + ?Sized> { } /// Naga shader module. +#[derive(Default)] pub struct NagaShader { /// Shader module IR. pub module: Cow<'static, naga::Module>, @@ -2075,7 +2221,27 @@ impl fmt::Debug for NagaShader { #[allow(clippy::large_enum_variant)] pub enum ShaderInput<'a> { Naga(NagaShader), + Msl { + shader: &'a str, + entry_point: String, + num_workgroups: (u32, u32, u32), + }, SpirV(&'a [u32]), + Dxil { + shader: &'a [u8], + entry_point: String, + num_workgroups: (u32, u32, u32), + }, + Hlsl { + shader: &'a str, + entry_point: String, + num_workgroups: (u32, u32, u32), + }, + Glsl { + shader: &'a str, + entry_point: String, + num_workgroups: (u32, u32, u32), + }, } pub struct ShaderModuleDescriptor<'a> { @@ -2156,6 +2322,20 @@ pub struct VertexBufferLayout<'a> { pub attributes: &'a [wgt::VertexAttribute], } +#[derive(Clone, Debug)] +pub enum VertexProcessor<'a, M: DynShaderModule + ?Sized> { + Standard { + /// The format of any vertex buffers used with this pipeline. + vertex_buffers: &'a [VertexBufferLayout<'a>], + /// The vertex stage for this pipeline. + vertex_stage: ProgrammableStage<'a, M>, + }, + Mesh { + task_stage: Option>, + mesh_stage: ProgrammableStage<'a, M>, + }, +} + /// Describes a render (graphics) pipeline. #[derive(Clone, Debug)] pub struct RenderPipelineDescriptor< @@ -2167,10 +2347,8 @@ pub struct RenderPipelineDescriptor< pub label: Label<'a>, /// The layout of bind groups for this pipeline. pub layout: &'a Pl, - /// The format of any vertex buffers used with this pipeline. - pub vertex_buffers: &'a [VertexBufferLayout<'a>], - /// The vertex stage for this pipeline. - pub vertex_stage: ProgrammableStage<'a, M>, + /// The vertex processing state(vertex shader + buffers or task + mesh shaders) + pub vertex_processor: VertexProcessor<'a, M>, /// The properties of the pipeline at the primitive assembly and rasterization level. pub primitive: wgt::PrimitiveState, /// The effect of draw calls on the depth and stencil aspects of the output target, if any. @@ -2183,34 +2361,7 @@ pub struct RenderPipelineDescriptor< pub color_targets: &'a [Option], /// If the pipeline will be used with a multiview render pass, this indicates how many array /// layers the attachments will have. - pub multiview: Option, - /// The cache which will be used and filled when compiling this pipeline - pub cache: Option<&'a Pc>, -} -pub struct MeshPipelineDescriptor< - 'a, - Pl: DynPipelineLayout + ?Sized, - M: DynShaderModule + ?Sized, - Pc: DynPipelineCache + ?Sized, -> { - pub label: Label<'a>, - /// The layout of bind groups for this pipeline. - pub layout: &'a Pl, - pub task_stage: Option>, - pub mesh_stage: ProgrammableStage<'a, M>, - /// The properties of the pipeline at the primitive assembly and rasterization level. - pub primitive: wgt::PrimitiveState, - /// The effect of draw calls on the depth and stencil aspects of the output target, if any. - pub depth_stencil: Option, - /// The multi-sampling properties of the pipeline. - pub multisample: wgt::MultisampleState, - /// The fragment stage for this pipeline. - pub fragment_stage: Option>, - /// The effect of draw calls on the color aspect of the output target. - pub color_targets: &'a [Option], - /// If the pipeline will be used with a multiview render pass, this indicates how many array - /// layers the attachments will have. - pub multiview: Option, + pub multiview_mask: Option, /// The cache which will be used and filled when compiling this pipeline pub cache: Option<&'a Pc>, } @@ -2287,6 +2438,36 @@ pub struct CopyExtent { pub depth: u32, } +impl From for CopyExtent { + fn from(value: wgt::Extent3d) -> Self { + let wgt::Extent3d { + width, + height, + depth_or_array_layers, + } = value; + Self { + width, + height, + depth: depth_or_array_layers, + } + } +} + +impl From for wgt::Extent3d { + fn from(value: CopyExtent) -> Self { + let CopyExtent { + width, + height, + depth, + } = value; + Self { + width, + height, + depth_or_array_layers: depth, + } + } +} + #[derive(Clone, Debug)] pub struct TextureCopy { pub src_base: TextureCopyBase, @@ -2312,6 +2493,7 @@ pub struct Attachment<'a, T: DynTextureView + ?Sized> { #[derive(Clone, Debug)] pub struct ColorAttachment<'a, T: DynTextureView + ?Sized> { pub target: Attachment<'a, T>, + pub depth_slice: Option, pub resolve_target: Option>, pub ops: AttachmentOps, pub clear_value: wgt::Color, @@ -2339,7 +2521,7 @@ pub struct RenderPassDescriptor<'a, Q: DynQuerySet + ?Sized, T: DynTextureView + pub sample_count: u32, pub color_attachments: &'a [Option>], pub depth_stencil_attachment: Option>, - pub multiview: Option, + pub multiview_mask: Option, pub timestamp_writes: Option>, pub occlusion_query_set: Option<&'a Q>, } @@ -2350,42 +2532,6 @@ pub struct ComputePassDescriptor<'a, Q: DynQuerySet + ?Sized> { pub timestamp_writes: Option>, } -/// Stores the text of any validation errors that have occurred since -/// the last call to `get_and_reset`. -/// -/// Each value is a validation error and a message associated with it, -/// or `None` if the error has no message from the api. -/// -/// This is used for internal wgpu testing only and _must not_ be used -/// as a way to check for errors. -/// -/// This works as a static because `cargo nextest` runs all of our -/// tests in separate processes, so each test gets its own canary. -/// -/// This prevents the issue of one validation error terminating the -/// entire process. -pub static VALIDATION_CANARY: ValidationCanary = ValidationCanary { - inner: Mutex::new(Vec::new()), -}; - -/// Flag for internal testing. -pub struct ValidationCanary { - inner: Mutex>, -} - -impl ValidationCanary { - #[allow(dead_code)] // in some configurations this function is dead - fn add(&self, msg: String) { - self.inner.lock().push(msg); - } - - /// Returns any API validation errors that have occurred in this process - /// since the last call to this function. - pub fn get_and_reset(&self) -> Vec { - self.inner.lock().drain(..).collect() - } -} - #[test] fn test_default_limits() { let limits = wgt::Limits::default(); diff --git a/wgpu-hal/src/metal/adapter.rs b/wgpu-hal/src/metal/adapter.rs index f9e02cbde..fa3d2fa8d 100644 --- a/wgpu-hal/src/metal/adapter.rs +++ b/wgpu-hal/src/metal/adapter.rs @@ -1,13 +1,33 @@ -use metal::{MTLFeatureSet, MTLGPUFamily, MTLLanguageVersion, MTLReadWriteTextureTier}; +use metal::{ + MTLArgumentBuffersTier, MTLCounterSamplingPoint, MTLFeatureSet, MTLGPUFamily, + MTLLanguageVersion, MTLPixelFormat, MTLReadWriteTextureTier, NSInteger, +}; use objc::{class, msg_send, sel, sel_impl}; use parking_lot::Mutex; use wgt::{AstcBlock, AstcChannel}; -use std::{sync::Arc, thread}; +use alloc::sync::Arc; use super::TimestampQuerySupport; -const MAX_COMMAND_BUFFERS: u64 = 2048; +/// Maximum number of command buffers for `MTLCommandQueue`s that we create. +/// +/// If a [new command buffer] is requested when Metal has run out of command +/// buffers, it waits indefinitely for one to become available. If the +/// outstanding command buffers are actively executing on the GPU, this will +/// happen relatively quickly. But if the outstanding command buffers will only +/// be recovered upon GC, and attempting to get a new command buffer prevents +/// forward progress towards that GC, there is a deadlock. +/// +/// This is mostly a problem for the CTS, which frequently creates command +/// buffers that it does not submit. It is unclear how likely command buffer +/// exhaustion is in real applications. +/// +/// This limit was increased from a previous value of 2048 for +/// . +/// +/// [new command buffer]: https://developer.apple.com/documentation/metal/mtlcommandqueue/makecommandbuffer()?language=objc +const MAX_COMMAND_BUFFERS: u64 = 4096; unsafe impl Send for super::Adapter {} unsafe impl Sync for super::Adapter {} @@ -270,6 +290,7 @@ impl crate::Adapter for super::Adapter { flags } Tf::NV12 => return Tfc::empty(), + Tf::P010 => return Tfc::empty(), Tf::Rgb9e5Ufloat => { if pc.msaa_apple3 { all_caps @@ -338,13 +359,6 @@ impl crate::Adapter for super::Adapter { &self, surface: &super::Surface, ) -> Option { - let current_extent = if surface.main_thread_id == thread::current().id() { - Some(surface.dimensions()) - } else { - log::warn!("Unable to get the current view dimensions on a non-main thread"); - None - }; - let mut formats = vec![ wgt::TextureFormat::Bgra8Unorm, wgt::TextureFormat::Bgra8UnormSrgb, @@ -376,7 +390,7 @@ impl crate::Adapter for super::Adapter { wgt::CompositeAlphaMode::PostMultiplied, ], - current_extent, + current_extent: Some(surface.dimensions()), usage: wgt::TextureUses::COLOR_TARGET | wgt::TextureUses::COPY_SRC | wgt::TextureUses::COPY_DST @@ -574,19 +588,18 @@ impl super::PrivateCapabilities { let mut timestamp_query_support = TimestampQuerySupport::empty(); if version.at_least((11, 0), (14, 0), os_is_mac) - && device.supports_counter_sampling(metal::MTLCounterSamplingPoint::AtStageBoundary) + && device.supports_counter_sampling(MTLCounterSamplingPoint::AtStageBoundary) { // If we don't support at stage boundary, don't support anything else. timestamp_query_support.insert(TimestampQuerySupport::STAGE_BOUNDARIES); - if device.supports_counter_sampling(metal::MTLCounterSamplingPoint::AtDrawBoundary) { + if device.supports_counter_sampling(MTLCounterSamplingPoint::AtDrawBoundary) { timestamp_query_support.insert(TimestampQuerySupport::ON_RENDER_ENCODER); } - if device.supports_counter_sampling(metal::MTLCounterSamplingPoint::AtDispatchBoundary) - { + if device.supports_counter_sampling(MTLCounterSamplingPoint::AtDispatchBoundary) { timestamp_query_support.insert(TimestampQuerySupport::ON_COMPUTE_ENCODER); } - if device.supports_counter_sampling(metal::MTLCounterSamplingPoint::AtBlitBoundary) { + if device.supports_counter_sampling(MTLCounterSamplingPoint::AtBlitBoundary) { timestamp_query_support.insert(TimestampQuerySupport::ON_BLIT_ENCODER); } // `TimestampQuerySupport::INSIDE_WGPU_PASSES` emerges from the other flags. @@ -664,6 +677,8 @@ impl super::PrivateCapabilities { || Self::supports_any(device, ASTC_PIXEL_FORMAT_FEATURES), // A13(Apple6) M1(Apple7) and later always support HDR ASTC pixel formats format_astc_hdr: family_check && device.supports_family(MTLGPUFamily::Apple6), + // Apple3 and later supports compressed volume texture formats including ASTC Sliced 3D + format_astc_3d: family_check && device.supports_family(MTLGPUFamily::Apple3), format_any8_unorm_srgb_all: Self::supports_any(device, ANY8_UNORM_SRGB_ALL), format_any8_unorm_srgb_no_write: !Self::supports_any(device, ANY8_UNORM_SRGB_ALL) && !os_is_mac, @@ -727,8 +742,7 @@ impl super::PrivateCapabilities { 31 }, max_samplers_per_stage: 16, - max_binding_array_elements: if argument_buffers == metal::MTLArgumentBuffersTier::Tier2 - { + max_binding_array_elements: if argument_buffers == MTLArgumentBuffersTier::Tier2 { 1_000_000 } else if family_check && device.supports_family(MTLGPUFamily::Apple4) { 96 @@ -752,8 +766,7 @@ impl super::PrivateCapabilities { buffer_alignment: if os_is_mac || os_is_xr { 256 } else { 64 }, max_buffer_size: if version.at_least((10, 14), (12, 0), os_is_mac) { // maxBufferLength available on macOS 10.14+ and iOS 12.0+ - let buffer_size: metal::NSInteger = - unsafe { msg_send![device.as_ref(), maxBufferLength] }; + let buffer_size: NSInteger = unsafe { msg_send![device.as_ref(), maxBufferLength] }; buffer_size as _ } else if os_is_mac { 1 << 30 // 1GB on macOS 10.11 and up @@ -889,6 +902,23 @@ impl super::PrivateCapabilities { && (device.supports_family(MTLGPUFamily::Apple7) || device.supports_family(MTLGPUFamily::Mac2)), supports_shared_event: version.at_least((10, 14), (12, 0), os_is_mac), + supported_vertex_amplification_factor: { + let mut factor = 1; + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=8 + // The table specifies either none, 2, 8, or unsupported, implying it is a relatively small power of 2 + // The bitmask only uses 32 bits, so it can't be higher even if the device for some reason claims to support that. + while factor < 32 && device.supports_vertex_amplification_count(factor * 2) { + factor *= 2 + } + factor as u32 + }, + shader_barycentrics: device.supports_shader_barycentric_coordinates(), + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=3 + supports_memoryless_storage: if family_check { + device.supports_family(MTLGPUFamily::Apple2) + } else { + version.at_least((11, 0), (10, 0), os_is_mac) + }, } } @@ -913,13 +943,12 @@ impl super::PrivateCapabilities { | F::TEXTURE_FORMAT_16BIT_NORM | F::SHADER_F16 | F::DEPTH32FLOAT_STENCIL8 - | F::BGRA8UNORM_STORAGE; + | F::BGRA8UNORM_STORAGE + | F::EXPERIMENTAL_PASSTHROUGH_SHADERS + | F::EXTERNAL_TEXTURE; features.set(F::FLOAT32_FILTERABLE, self.supports_float_filtering); - features.set( - F::INDIRECT_FIRST_INSTANCE | F::MULTI_DRAW_INDIRECT, - self.indirect_draw_dispatch, - ); + features.set(F::INDIRECT_FIRST_INSTANCE, self.indirect_draw_dispatch); features.set( F::TIMESTAMP_QUERY | F::TIMESTAMP_QUERY_INSIDE_ENCODERS, self.timestamp_query_support @@ -936,6 +965,7 @@ impl super::PrivateCapabilities { ); features.set(F::TEXTURE_COMPRESSION_ASTC, self.format_astc); features.set(F::TEXTURE_COMPRESSION_ASTC_HDR, self.format_astc_hdr); + features.set(F::TEXTURE_COMPRESSION_ASTC_SLICED_3D, self.format_astc_3d); features.set(F::TEXTURE_COMPRESSION_BC, self.format_bc); features.set(F::TEXTURE_COMPRESSION_BC_SLICED_3D, self.format_bc); // BC guarantees Sliced 3D features.set(F::TEXTURE_COMPRESSION_ETC2, self.format_eac_etc); @@ -953,7 +983,7 @@ impl super::PrivateCapabilities { | F::PARTIALLY_BOUND_BINDING_ARRAY, self.msl_version >= MTLLanguageVersion::V3_0 && self.supports_arrays_of_textures - && self.argument_buffers as u64 >= metal::MTLArgumentBuffersTier::Tier2 as u64, + && self.argument_buffers as u64 >= MTLArgumentBuffersTier::Tier2 as u64, ); features.set( F::SHADER_INT64, @@ -984,10 +1014,19 @@ impl super::PrivateCapabilities { features.set(F::RG11B10UFLOAT_RENDERABLE, self.format_rg11b10_all); + features.set( + F::SHADER_BARYCENTRICS, + self.shader_barycentrics && self.msl_version >= MTLLanguageVersion::V2_2, + ); + if self.supports_simd_scoped_operations { features.insert(F::SUBGROUP | F::SUBGROUP_BARRIER); } + if self.supported_vertex_amplification_factor > 1 { + features.insert(F::MULTIVIEW); + } + features } @@ -1018,7 +1057,6 @@ impl super::PrivateCapabilities { downlevel .flags .set(wgt::DownlevelFlags::ANISOTROPIC_FILTERING, true); - let base = wgt::Limits::default(); crate::Capabilities { limits: wgt::Limits { @@ -1063,6 +1101,28 @@ impl super::PrivateCapabilities { max_compute_workgroups_per_dimension: 0xFFFF, max_buffer_size: self.max_buffer_size, max_non_sampler_bindings: u32::MAX, + + max_task_workgroup_total_count: 0, + max_task_workgroups_per_dimension: 0, + max_mesh_multiview_view_count: 0, + max_mesh_output_layers: 0, + + max_blas_primitive_count: 0, // When added: 2^28 from https://developer.apple.com/documentation/metal/mtlaccelerationstructureusage/extendedlimits + max_blas_geometry_count: 0, // When added: 2^24 + max_tlas_instance_count: 0, // When added: 2^24 + // Unsure what this will be when added: acceleration structures count as a buffer so + // it may be worth using argument buffers for this all acceleration structures, then + // there will be no limit. + // From 2.17.7 in https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf + // > [Acceleration structures] are opaque objects that can be bound directly using + // buffer binding points or via argument buffers + max_acceleration_structures_per_shader_stage: 0, + + max_multiview_view_count: if self.supported_vertex_amplification_factor > 1 { + self.supported_vertex_amplification_factor + } else { + 0 + }, }, alignments: crate::Alignments { buffer_copy_offset: wgt::BufferSize::new(self.buffer_alignment).unwrap(), @@ -1078,146 +1138,147 @@ impl super::PrivateCapabilities { } } - pub fn map_format(&self, format: wgt::TextureFormat) -> metal::MTLPixelFormat { - use metal::MTLPixelFormat::*; + pub fn map_format(&self, format: wgt::TextureFormat) -> MTLPixelFormat { use wgt::TextureFormat as Tf; + use MTLPixelFormat as MTL; match format { - Tf::R8Unorm => R8Unorm, - Tf::R8Snorm => R8Snorm, - Tf::R8Uint => R8Uint, - Tf::R8Sint => R8Sint, - Tf::R16Uint => R16Uint, - Tf::R16Sint => R16Sint, - Tf::R16Unorm => R16Unorm, - Tf::R16Snorm => R16Snorm, - Tf::R16Float => R16Float, - Tf::Rg8Unorm => RG8Unorm, - Tf::Rg8Snorm => RG8Snorm, - Tf::Rg8Uint => RG8Uint, - Tf::Rg8Sint => RG8Sint, - Tf::Rg16Unorm => RG16Unorm, - Tf::Rg16Snorm => RG16Snorm, - Tf::R32Uint => R32Uint, - Tf::R32Sint => R32Sint, - Tf::R32Float => R32Float, - Tf::Rg16Uint => RG16Uint, - Tf::Rg16Sint => RG16Sint, - Tf::Rg16Float => RG16Float, - Tf::Rgba8Unorm => RGBA8Unorm, - Tf::Rgba8UnormSrgb => RGBA8Unorm_sRGB, - Tf::Bgra8UnormSrgb => BGRA8Unorm_sRGB, - Tf::Rgba8Snorm => RGBA8Snorm, - Tf::Bgra8Unorm => BGRA8Unorm, - Tf::Rgba8Uint => RGBA8Uint, - Tf::Rgba8Sint => RGBA8Sint, - Tf::Rgb10a2Uint => RGB10A2Uint, - Tf::Rgb10a2Unorm => RGB10A2Unorm, - Tf::Rg11b10Ufloat => RG11B10Float, + Tf::R8Unorm => MTL::R8Unorm, + Tf::R8Snorm => MTL::R8Snorm, + Tf::R8Uint => MTL::R8Uint, + Tf::R8Sint => MTL::R8Sint, + Tf::R16Uint => MTL::R16Uint, + Tf::R16Sint => MTL::R16Sint, + Tf::R16Unorm => MTL::R16Unorm, + Tf::R16Snorm => MTL::R16Snorm, + Tf::R16Float => MTL::R16Float, + Tf::Rg8Unorm => MTL::RG8Unorm, + Tf::Rg8Snorm => MTL::RG8Snorm, + Tf::Rg8Uint => MTL::RG8Uint, + Tf::Rg8Sint => MTL::RG8Sint, + Tf::Rg16Unorm => MTL::RG16Unorm, + Tf::Rg16Snorm => MTL::RG16Snorm, + Tf::R32Uint => MTL::R32Uint, + Tf::R32Sint => MTL::R32Sint, + Tf::R32Float => MTL::R32Float, + Tf::Rg16Uint => MTL::RG16Uint, + Tf::Rg16Sint => MTL::RG16Sint, + Tf::Rg16Float => MTL::RG16Float, + Tf::Rgba8Unorm => MTL::RGBA8Unorm, + Tf::Rgba8UnormSrgb => MTL::RGBA8Unorm_sRGB, + Tf::Bgra8UnormSrgb => MTL::BGRA8Unorm_sRGB, + Tf::Rgba8Snorm => MTL::RGBA8Snorm, + Tf::Bgra8Unorm => MTL::BGRA8Unorm, + Tf::Rgba8Uint => MTL::RGBA8Uint, + Tf::Rgba8Sint => MTL::RGBA8Sint, + Tf::Rgb10a2Uint => MTL::RGB10A2Uint, + Tf::Rgb10a2Unorm => MTL::RGB10A2Unorm, + Tf::Rg11b10Ufloat => MTL::RG11B10Float, // Ruint64 textures are emulated on metal - Tf::R64Uint => RG32Uint, - Tf::Rg32Uint => RG32Uint, - Tf::Rg32Sint => RG32Sint, - Tf::Rg32Float => RG32Float, - Tf::Rgba16Uint => RGBA16Uint, - Tf::Rgba16Sint => RGBA16Sint, - Tf::Rgba16Unorm => RGBA16Unorm, - Tf::Rgba16Snorm => RGBA16Snorm, - Tf::Rgba16Float => RGBA16Float, - Tf::Rgba32Uint => RGBA32Uint, - Tf::Rgba32Sint => RGBA32Sint, - Tf::Rgba32Float => RGBA32Float, - Tf::Stencil8 => Stencil8, - Tf::Depth16Unorm => Depth16Unorm, - Tf::Depth32Float => Depth32Float, - Tf::Depth32FloatStencil8 => Depth32Float_Stencil8, + Tf::R64Uint => MTL::RG32Uint, + Tf::Rg32Uint => MTL::RG32Uint, + Tf::Rg32Sint => MTL::RG32Sint, + Tf::Rg32Float => MTL::RG32Float, + Tf::Rgba16Uint => MTL::RGBA16Uint, + Tf::Rgba16Sint => MTL::RGBA16Sint, + Tf::Rgba16Unorm => MTL::RGBA16Unorm, + Tf::Rgba16Snorm => MTL::RGBA16Snorm, + Tf::Rgba16Float => MTL::RGBA16Float, + Tf::Rgba32Uint => MTL::RGBA32Uint, + Tf::Rgba32Sint => MTL::RGBA32Sint, + Tf::Rgba32Float => MTL::RGBA32Float, + Tf::Stencil8 => MTL::Stencil8, + Tf::Depth16Unorm => MTL::Depth16Unorm, + Tf::Depth32Float => MTL::Depth32Float, + Tf::Depth32FloatStencil8 => MTL::Depth32Float_Stencil8, Tf::Depth24Plus => { if self.format_depth24_stencil8 { - Depth24Unorm_Stencil8 + MTL::Depth24Unorm_Stencil8 } else { - Depth32Float + MTL::Depth32Float } } Tf::Depth24PlusStencil8 => { if self.format_depth24_stencil8 { - Depth24Unorm_Stencil8 + MTL::Depth24Unorm_Stencil8 } else { - Depth32Float_Stencil8 + MTL::Depth32Float_Stencil8 } } Tf::NV12 => unreachable!(), - Tf::Rgb9e5Ufloat => RGB9E5Float, - Tf::Bc1RgbaUnorm => BC1_RGBA, - Tf::Bc1RgbaUnormSrgb => BC1_RGBA_sRGB, - Tf::Bc2RgbaUnorm => BC2_RGBA, - Tf::Bc2RgbaUnormSrgb => BC2_RGBA_sRGB, - Tf::Bc3RgbaUnorm => BC3_RGBA, - Tf::Bc3RgbaUnormSrgb => BC3_RGBA_sRGB, - Tf::Bc4RUnorm => BC4_RUnorm, - Tf::Bc4RSnorm => BC4_RSnorm, - Tf::Bc5RgUnorm => BC5_RGUnorm, - Tf::Bc5RgSnorm => BC5_RGSnorm, - Tf::Bc6hRgbFloat => BC6H_RGBFloat, - Tf::Bc6hRgbUfloat => BC6H_RGBUfloat, - Tf::Bc7RgbaUnorm => BC7_RGBAUnorm, - Tf::Bc7RgbaUnormSrgb => BC7_RGBAUnorm_sRGB, - Tf::Etc2Rgb8Unorm => ETC2_RGB8, - Tf::Etc2Rgb8UnormSrgb => ETC2_RGB8_sRGB, - Tf::Etc2Rgb8A1Unorm => ETC2_RGB8A1, - Tf::Etc2Rgb8A1UnormSrgb => ETC2_RGB8A1_sRGB, - Tf::Etc2Rgba8Unorm => EAC_RGBA8, - Tf::Etc2Rgba8UnormSrgb => EAC_RGBA8_sRGB, - Tf::EacR11Unorm => EAC_R11Unorm, - Tf::EacR11Snorm => EAC_R11Snorm, - Tf::EacRg11Unorm => EAC_RG11Unorm, - Tf::EacRg11Snorm => EAC_RG11Snorm, + Tf::P010 => unreachable!(), + Tf::Rgb9e5Ufloat => MTL::RGB9E5Float, + Tf::Bc1RgbaUnorm => MTL::BC1_RGBA, + Tf::Bc1RgbaUnormSrgb => MTL::BC1_RGBA_sRGB, + Tf::Bc2RgbaUnorm => MTL::BC2_RGBA, + Tf::Bc2RgbaUnormSrgb => MTL::BC2_RGBA_sRGB, + Tf::Bc3RgbaUnorm => MTL::BC3_RGBA, + Tf::Bc3RgbaUnormSrgb => MTL::BC3_RGBA_sRGB, + Tf::Bc4RUnorm => MTL::BC4_RUnorm, + Tf::Bc4RSnorm => MTL::BC4_RSnorm, + Tf::Bc5RgUnorm => MTL::BC5_RGUnorm, + Tf::Bc5RgSnorm => MTL::BC5_RGSnorm, + Tf::Bc6hRgbFloat => MTL::BC6H_RGBFloat, + Tf::Bc6hRgbUfloat => MTL::BC6H_RGBUfloat, + Tf::Bc7RgbaUnorm => MTL::BC7_RGBAUnorm, + Tf::Bc7RgbaUnormSrgb => MTL::BC7_RGBAUnorm_sRGB, + Tf::Etc2Rgb8Unorm => MTL::ETC2_RGB8, + Tf::Etc2Rgb8UnormSrgb => MTL::ETC2_RGB8_sRGB, + Tf::Etc2Rgb8A1Unorm => MTL::ETC2_RGB8A1, + Tf::Etc2Rgb8A1UnormSrgb => MTL::ETC2_RGB8A1_sRGB, + Tf::Etc2Rgba8Unorm => MTL::EAC_RGBA8, + Tf::Etc2Rgba8UnormSrgb => MTL::EAC_RGBA8_sRGB, + Tf::EacR11Unorm => MTL::EAC_R11Unorm, + Tf::EacR11Snorm => MTL::EAC_R11Snorm, + Tf::EacRg11Unorm => MTL::EAC_RG11Unorm, + Tf::EacRg11Snorm => MTL::EAC_RG11Snorm, Tf::Astc { block, channel } => match channel { AstcChannel::Unorm => match block { - AstcBlock::B4x4 => ASTC_4x4_LDR, - AstcBlock::B5x4 => ASTC_5x4_LDR, - AstcBlock::B5x5 => ASTC_5x5_LDR, - AstcBlock::B6x5 => ASTC_6x5_LDR, - AstcBlock::B6x6 => ASTC_6x6_LDR, - AstcBlock::B8x5 => ASTC_8x5_LDR, - AstcBlock::B8x6 => ASTC_8x6_LDR, - AstcBlock::B8x8 => ASTC_8x8_LDR, - AstcBlock::B10x5 => ASTC_10x5_LDR, - AstcBlock::B10x6 => ASTC_10x6_LDR, - AstcBlock::B10x8 => ASTC_10x8_LDR, - AstcBlock::B10x10 => ASTC_10x10_LDR, - AstcBlock::B12x10 => ASTC_12x10_LDR, - AstcBlock::B12x12 => ASTC_12x12_LDR, + AstcBlock::B4x4 => MTL::ASTC_4x4_LDR, + AstcBlock::B5x4 => MTL::ASTC_5x4_LDR, + AstcBlock::B5x5 => MTL::ASTC_5x5_LDR, + AstcBlock::B6x5 => MTL::ASTC_6x5_LDR, + AstcBlock::B6x6 => MTL::ASTC_6x6_LDR, + AstcBlock::B8x5 => MTL::ASTC_8x5_LDR, + AstcBlock::B8x6 => MTL::ASTC_8x6_LDR, + AstcBlock::B8x8 => MTL::ASTC_8x8_LDR, + AstcBlock::B10x5 => MTL::ASTC_10x5_LDR, + AstcBlock::B10x6 => MTL::ASTC_10x6_LDR, + AstcBlock::B10x8 => MTL::ASTC_10x8_LDR, + AstcBlock::B10x10 => MTL::ASTC_10x10_LDR, + AstcBlock::B12x10 => MTL::ASTC_12x10_LDR, + AstcBlock::B12x12 => MTL::ASTC_12x12_LDR, }, AstcChannel::UnormSrgb => match block { - AstcBlock::B4x4 => ASTC_4x4_sRGB, - AstcBlock::B5x4 => ASTC_5x4_sRGB, - AstcBlock::B5x5 => ASTC_5x5_sRGB, - AstcBlock::B6x5 => ASTC_6x5_sRGB, - AstcBlock::B6x6 => ASTC_6x6_sRGB, - AstcBlock::B8x5 => ASTC_8x5_sRGB, - AstcBlock::B8x6 => ASTC_8x6_sRGB, - AstcBlock::B8x8 => ASTC_8x8_sRGB, - AstcBlock::B10x5 => ASTC_10x5_sRGB, - AstcBlock::B10x6 => ASTC_10x6_sRGB, - AstcBlock::B10x8 => ASTC_10x8_sRGB, - AstcBlock::B10x10 => ASTC_10x10_sRGB, - AstcBlock::B12x10 => ASTC_12x10_sRGB, - AstcBlock::B12x12 => ASTC_12x12_sRGB, + AstcBlock::B4x4 => MTL::ASTC_4x4_sRGB, + AstcBlock::B5x4 => MTL::ASTC_5x4_sRGB, + AstcBlock::B5x5 => MTL::ASTC_5x5_sRGB, + AstcBlock::B6x5 => MTL::ASTC_6x5_sRGB, + AstcBlock::B6x6 => MTL::ASTC_6x6_sRGB, + AstcBlock::B8x5 => MTL::ASTC_8x5_sRGB, + AstcBlock::B8x6 => MTL::ASTC_8x6_sRGB, + AstcBlock::B8x8 => MTL::ASTC_8x8_sRGB, + AstcBlock::B10x5 => MTL::ASTC_10x5_sRGB, + AstcBlock::B10x6 => MTL::ASTC_10x6_sRGB, + AstcBlock::B10x8 => MTL::ASTC_10x8_sRGB, + AstcBlock::B10x10 => MTL::ASTC_10x10_sRGB, + AstcBlock::B12x10 => MTL::ASTC_12x10_sRGB, + AstcBlock::B12x12 => MTL::ASTC_12x12_sRGB, }, AstcChannel::Hdr => match block { - AstcBlock::B4x4 => ASTC_4x4_HDR, - AstcBlock::B5x4 => ASTC_5x4_HDR, - AstcBlock::B5x5 => ASTC_5x5_HDR, - AstcBlock::B6x5 => ASTC_6x5_HDR, - AstcBlock::B6x6 => ASTC_6x6_HDR, - AstcBlock::B8x5 => ASTC_8x5_HDR, - AstcBlock::B8x6 => ASTC_8x6_HDR, - AstcBlock::B8x8 => ASTC_8x8_HDR, - AstcBlock::B10x5 => ASTC_10x5_HDR, - AstcBlock::B10x6 => ASTC_10x6_HDR, - AstcBlock::B10x8 => ASTC_10x8_HDR, - AstcBlock::B10x10 => ASTC_10x10_HDR, - AstcBlock::B12x10 => ASTC_12x10_HDR, - AstcBlock::B12x12 => ASTC_12x12_HDR, + AstcBlock::B4x4 => MTL::ASTC_4x4_HDR, + AstcBlock::B5x4 => MTL::ASTC_5x4_HDR, + AstcBlock::B5x5 => MTL::ASTC_5x5_HDR, + AstcBlock::B6x5 => MTL::ASTC_6x5_HDR, + AstcBlock::B6x6 => MTL::ASTC_6x6_HDR, + AstcBlock::B8x5 => MTL::ASTC_8x5_HDR, + AstcBlock::B8x6 => MTL::ASTC_8x6_HDR, + AstcBlock::B8x8 => MTL::ASTC_8x8_HDR, + AstcBlock::B10x5 => MTL::ASTC_10x5_HDR, + AstcBlock::B10x6 => MTL::ASTC_10x6_HDR, + AstcBlock::B10x8 => MTL::ASTC_10x8_HDR, + AstcBlock::B10x10 => MTL::ASTC_10x10_HDR, + AstcBlock::B12x10 => MTL::ASTC_12x10_HDR, + AstcBlock::B12x12 => MTL::ASTC_12x12_HDR, }, }, } @@ -1227,21 +1288,21 @@ impl super::PrivateCapabilities { &self, format: wgt::TextureFormat, aspects: crate::FormatAspects, - ) -> metal::MTLPixelFormat { + ) -> MTLPixelFormat { use crate::FormatAspects as Fa; - use metal::MTLPixelFormat::*; use wgt::TextureFormat as Tf; + use MTLPixelFormat as MTL; match (format, aspects) { // map combined depth-stencil format to their stencil-only format // see https://developer.apple.com/library/archive/documentation/Miscellaneous/Conceptual/MetalProgrammingGuide/WhatsNewiniOS10tvOS10andOSX1012/WhatsNewiniOS10tvOS10andOSX1012.html#//apple_ref/doc/uid/TP40014221-CH14-DontLinkElementID_77 (Tf::Depth24PlusStencil8, Fa::STENCIL) => { if self.format_depth24_stencil8 { - X24_Stencil8 + MTL::X24_Stencil8 } else { - X32_Stencil8 + MTL::X32_Stencil8 } } - (Tf::Depth32FloatStencil8, Fa::STENCIL) => X32_Stencil8, + (Tf::Depth32FloatStencil8, Fa::STENCIL) => MTL::X32_Stencil8, _ => self.map_format(format), } diff --git a/wgpu-hal/src/metal/command.rs b/wgpu-hal/src/metal/command.rs index 6f4f2e289..ebabbd4c7 100644 --- a/wgpu-hal/src/metal/command.rs +++ b/wgpu-hal/src/metal/command.rs @@ -1,10 +1,15 @@ use super::{conv, AsNative, TimestampQuerySupport}; use crate::CommandEncoder as _; -use std::{ +use alloc::{ borrow::{Cow, ToOwned as _}, - ops::Range, vec::Vec, }; +use core::ops::Range; +use metal::{ + MTLIndexType, MTLLoadAction, MTLPrimitiveType, MTLScissorRect, MTLSize, MTLStoreAction, + MTLViewport, MTLVisibilityResultMode, NSRange, +}; +use smallvec::SmallVec; // has to match `Temp::binding_sizes` const WORD_SIZE: usize = 4; @@ -15,9 +20,9 @@ impl Default for super::CommandState { blit: None, render: None, compute: None, - raw_primitive_type: metal::MTLPrimitiveType::Point, + raw_primitive_type: MTLPrimitiveType::Point, index: None, - raw_wg_size: metal::MTLSize::new(0, 0, 0), + raw_wg_size: MTLSize::new(0, 0, 0), stage_infos: Default::default(), storage_buffer_length_map: Default::default(), vertex_buffer_size_map: Default::default(), @@ -29,6 +34,10 @@ impl Default for super::CommandState { } impl super::CommandEncoder { + pub fn raw_command_buffer(&self) -> Option<&metal::CommandBuffer> { + self.raw_cmd_buf.as_ref() + } + fn enter_blit(&mut self) -> &metal::BlitCommandEncoderRef { if self.state.blit.is_none() { debug_assert!(self.state.render.is_none() && self.state.compute.is_none()); @@ -81,7 +90,7 @@ impl super::CommandEncoder { // As explained above, we need to do some write: // Conveniently, we have a buffer with every query set, that we can use for this for a dummy write, // since we know that it is going to be overwritten again on timer resolve and HAL doesn't define its state before that. - let raw_range = metal::NSRange { + let raw_range = NSRange { location: last_query.as_ref().unwrap().1 as u64 * crate::QUERY_SIZE, length: 1, }; @@ -413,7 +422,7 @@ impl crate::CommandEncoder for super::CommandEncoder { .as_ref() .unwrap() .set_visibility_result_mode( - metal::MTLVisibilityResultMode::Boolean, + MTLVisibilityResultMode::Boolean, index as u64 * crate::QUERY_SIZE, ); } @@ -427,7 +436,7 @@ impl crate::CommandEncoder for super::CommandEncoder { .render .as_ref() .unwrap() - .set_visibility_result_mode(metal::MTLVisibilityResultMode::Disabled, 0); + .set_visibility_result_mode(MTLVisibilityResultMode::Disabled, 0); } _ => {} } @@ -473,7 +482,7 @@ impl crate::CommandEncoder for super::CommandEncoder { unsafe fn reset_queries(&mut self, set: &super::QuerySet, range: Range) { let encoder = self.enter_blit(); - let raw_range = metal::NSRange { + let raw_range = NSRange { location: range.start as u64 * crate::QUERY_SIZE, length: (range.end - range.start) as u64 * crate::QUERY_SIZE, }; @@ -503,7 +512,7 @@ impl crate::CommandEncoder for super::CommandEncoder { wgt::QueryType::Timestamp => { encoder.resolve_counters( set.counter_sample_buffer.as_ref().unwrap(), - metal::NSRange::new(range.start as u64, (range.end - range.start) as u64), + NSRange::new(range.start as u64, (range.end - range.start) as u64), &buffer.raw, offset, ); @@ -517,7 +526,7 @@ impl crate::CommandEncoder for super::CommandEncoder { unsafe fn begin_render_pass( &mut self, desc: &crate::RenderPassDescriptor, - ) { + ) -> Result<(), crate::DeviceError> { self.begin_pass(); self.state.index = None; @@ -532,15 +541,18 @@ impl crate::CommandEncoder for super::CommandEncoder { if let Some(at) = at.as_ref() { let at_descriptor = descriptor.color_attachments().object_at(i as u64).unwrap(); at_descriptor.set_texture(Some(&at.target.view.raw)); + if let Some(depth_slice) = at.depth_slice { + at_descriptor.set_depth_plane(depth_slice as u64); + } if let Some(ref resolve) = at.resolve_target { //Note: the selection of levels and slices is already handled by `TextureView` at_descriptor.set_resolve_texture(Some(&resolve.view.raw)); } let load_action = if at.ops.contains(crate::AttachmentOps::LOAD) { - metal::MTLLoadAction::Load + MTLLoadAction::Load } else { at_descriptor.set_clear_color(conv::map_clear_color(&at.clear_value)); - metal::MTLLoadAction::Clear + MTLLoadAction::Clear }; let store_action = conv::map_store_action( at.ops.contains(crate::AttachmentOps::STORE), @@ -557,15 +569,15 @@ impl crate::CommandEncoder for super::CommandEncoder { at_descriptor.set_texture(Some(&at.target.view.raw)); let load_action = if at.depth_ops.contains(crate::AttachmentOps::LOAD) { - metal::MTLLoadAction::Load + MTLLoadAction::Load } else { at_descriptor.set_clear_depth(at.clear_value.0 as f64); - metal::MTLLoadAction::Clear + MTLLoadAction::Clear }; let store_action = if at.depth_ops.contains(crate::AttachmentOps::STORE) { - metal::MTLStoreAction::Store + MTLStoreAction::Store } else { - metal::MTLStoreAction::DontCare + MTLStoreAction::DontCare }; at_descriptor.set_load_action(load_action); at_descriptor.set_store_action(store_action); @@ -580,15 +592,15 @@ impl crate::CommandEncoder for super::CommandEncoder { at_descriptor.set_texture(Some(&at.target.view.raw)); let load_action = if at.stencil_ops.contains(crate::AttachmentOps::LOAD) { - metal::MTLLoadAction::Load + MTLLoadAction::Load } else { at_descriptor.set_clear_stencil(at.clear_value.1); - metal::MTLLoadAction::Clear + MTLLoadAction::Clear }; let store_action = if at.stencil_ops.contains(crate::AttachmentOps::STORE) { - metal::MTLStoreAction::Store + MTLStoreAction::Store } else { - metal::MTLStoreAction::DontCare + MTLStoreAction::DontCare }; at_descriptor.set_load_action(load_action); at_descriptor.set_store_action(store_action); @@ -642,14 +654,40 @@ impl crate::CommandEncoder for super::CommandEncoder { descriptor .set_visibility_result_buffer(Some(occlusion_query_set.raw_buffer.as_ref())) } - + // This strangely isn't mentioned in https://developer.apple.com/documentation/metal/improving-rendering-performance-with-vertex-amplification. + // The docs for [`renderTargetArrayLength`](https://developer.apple.com/documentation/metal/mtlrenderpassdescriptor/rendertargetarraylength) + // also say "The number of active layers that all attachments must have for layered rendering," implying it is only for layered rendering. + // However, when I don't set this, I get undefined behavior in nonzero layers, and all non-apple examples of vertex amplification set it. + // So this is just one of those undocumented requirements. + if let Some(mv) = desc.multiview_mask { + descriptor.set_render_target_array_length(32 - mv.leading_zeros() as u64); + } let raw = self.raw_cmd_buf.as_ref().unwrap(); let encoder = raw.new_render_command_encoder(descriptor); + if let Some(mv) = desc.multiview_mask { + // Most likely the API just wasn't thought about enough. It's not like they ever allow you + // to use enough views to overflow a 32-bit bitmask. + let mv = mv.get(); + let msb = 32 - mv.leading_zeros(); + let mut maps: SmallVec<[metal::VertexAmplificationViewMapping; 32]> = + SmallVec::new(); + for i in 0..msb { + if (mv & (1 << i)) != 0 { + maps.push(metal::VertexAmplificationViewMapping { + renderTargetArrayIndexOffset: i, + viewportArrayIndexOffset: i, + }); + } + } + encoder.set_vertex_amplification_count(mv.count_ones() as u64, Some(&maps)); + } if let Some(label) = desc.label { encoder.set_label(label); } self.state.render = Some(encoder.to_owned()); }); + + Ok(()) } unsafe fn end_render_pass(&mut self) { @@ -948,8 +986,8 @@ impl crate::CommandEncoder for super::CommandEncoder { format: wgt::IndexFormat, ) { let (stride, raw_type) = match format { - wgt::IndexFormat::Uint16 => (2, metal::MTLIndexType::UInt16), - wgt::IndexFormat::Uint32 => (4, metal::MTLIndexType::UInt32), + wgt::IndexFormat::Uint16 => (2, MTLIndexType::UInt16), + wgt::IndexFormat::Uint32 => (4, MTLIndexType::UInt32), }; self.state.index = Some(super::IndexState { buffer_ptr: AsNative::from(binding.buffer.raw.as_ref()), @@ -972,7 +1010,7 @@ impl crate::CommandEncoder for super::CommandEncoder { if buffer_size > 0 { self.state.vertex_buffer_size_map.insert( buffer_index, - std::num::NonZeroU64::new(buffer_size).unwrap(), + core::num::NonZeroU64::new(buffer_size).unwrap(), ); } else { self.state.vertex_buffer_size_map.remove(&buffer_index); @@ -997,7 +1035,7 @@ impl crate::CommandEncoder for super::CommandEncoder { depth_range.end }; let encoder = self.state.render.as_ref().unwrap(); - encoder.set_viewport(metal::MTLViewport { + encoder.set_viewport(MTLViewport { originX: rect.x as _, originY: rect.y as _, width: rect.w as _, @@ -1008,7 +1046,7 @@ impl crate::CommandEncoder for super::CommandEncoder { } unsafe fn set_scissor_rect(&mut self, rect: &crate::Rect) { //TODO: support empty scissors by modifying the viewport - let scissor = metal::MTLScissorRect { + let scissor = MTLScissorRect { x: rect.x as _, y: rect.y as _, width: rect.w as _, @@ -1296,7 +1334,7 @@ impl crate::CommandEncoder for super::CommandEncoder { unsafe fn dispatch(&mut self, count: [u32; 3]) { if count[0] > 0 && count[1] > 0 && count[2] > 0 { let encoder = self.state.compute.as_ref().unwrap(); - let raw_count = metal::MTLSize { + let raw_count = MTLSize { width: count[0] as u64, height: count[1] as u64, depth: count[2] as u64, diff --git a/wgpu-hal/src/metal/conv.rs b/wgpu-hal/src/metal/conv.rs index 350f4cbb6..260b6c15a 100644 --- a/wgpu-hal/src/metal/conv.rs +++ b/wgpu-hal/src/metal/conv.rs @@ -1,190 +1,182 @@ -pub fn map_texture_usage( - format: wgt::TextureFormat, - usage: wgt::TextureUses, -) -> metal::MTLTextureUsage { +use metal::{ + MTLBlendFactor, MTLBlendOperation, MTLBlitOption, MTLClearColor, MTLColorWriteMask, + MTLCompareFunction, MTLCullMode, MTLOrigin, MTLPrimitiveTopologyClass, MTLPrimitiveType, + MTLRenderStages, MTLResourceUsage, MTLSamplerAddressMode, MTLSamplerBorderColor, + MTLSamplerMinMagFilter, MTLSize, MTLStencilOperation, MTLStoreAction, MTLTextureType, + MTLTextureUsage, MTLVertexFormat, MTLVertexStepFunction, MTLWinding, NSRange, +}; + +pub fn map_texture_usage(format: wgt::TextureFormat, usage: wgt::TextureUses) -> MTLTextureUsage { use wgt::TextureUses as Tu; - let mut mtl_usage = metal::MTLTextureUsage::Unknown; + let mut mtl_usage = MTLTextureUsage::Unknown; mtl_usage.set( - metal::MTLTextureUsage::RenderTarget, + MTLTextureUsage::RenderTarget, usage.intersects(Tu::COLOR_TARGET | Tu::DEPTH_STENCIL_READ | Tu::DEPTH_STENCIL_WRITE), ); mtl_usage.set( - metal::MTLTextureUsage::ShaderRead, + MTLTextureUsage::ShaderRead, usage.intersects( Tu::RESOURCE | Tu::DEPTH_STENCIL_READ | Tu::STORAGE_READ_ONLY | Tu::STORAGE_READ_WRITE, ), ); mtl_usage.set( - metal::MTLTextureUsage::ShaderWrite, + MTLTextureUsage::ShaderWrite, usage.intersects(Tu::STORAGE_WRITE_ONLY | Tu::STORAGE_READ_WRITE), ); // needed for combined depth/stencil formats since we might // create a stencil-only view from them mtl_usage.set( - metal::MTLTextureUsage::PixelFormatView, + MTLTextureUsage::PixelFormatView, format.is_combined_depth_stencil_format(), ); mtl_usage.set( - metal::MTLTextureUsage::ShaderAtomic, + MTLTextureUsage::ShaderAtomic, usage.intersects(Tu::STORAGE_ATOMIC), ); mtl_usage } -pub fn map_texture_view_dimension(dim: wgt::TextureViewDimension) -> metal::MTLTextureType { - use metal::MTLTextureType::*; +pub fn map_texture_view_dimension(dim: wgt::TextureViewDimension) -> MTLTextureType { use wgt::TextureViewDimension as Tvd; + use MTLTextureType as MTL; match dim { - Tvd::D1 => D1, - Tvd::D2 => D2, - Tvd::D2Array => D2Array, - Tvd::D3 => D3, - Tvd::Cube => Cube, - Tvd::CubeArray => CubeArray, + Tvd::D1 => MTL::D1, + Tvd::D2 => MTL::D2, + Tvd::D2Array => MTL::D2Array, + Tvd::D3 => MTL::D3, + Tvd::Cube => MTL::Cube, + Tvd::CubeArray => MTL::CubeArray, } } -pub fn map_compare_function(fun: wgt::CompareFunction) -> metal::MTLCompareFunction { - use metal::MTLCompareFunction::*; +pub fn map_compare_function(fun: wgt::CompareFunction) -> MTLCompareFunction { use wgt::CompareFunction as Cf; + use MTLCompareFunction as MTL; match fun { - Cf::Never => Never, - Cf::Less => Less, - Cf::LessEqual => LessEqual, - Cf::Equal => Equal, - Cf::GreaterEqual => GreaterEqual, - Cf::Greater => Greater, - Cf::NotEqual => NotEqual, - Cf::Always => Always, + Cf::Never => MTL::Never, + Cf::Less => MTL::Less, + Cf::LessEqual => MTL::LessEqual, + Cf::Equal => MTL::Equal, + Cf::GreaterEqual => MTL::GreaterEqual, + Cf::Greater => MTL::Greater, + Cf::NotEqual => MTL::NotEqual, + Cf::Always => MTL::Always, } } -pub fn map_filter_mode(filter: wgt::FilterMode) -> metal::MTLSamplerMinMagFilter { - use metal::MTLSamplerMinMagFilter::*; +pub fn map_filter_mode(filter: wgt::FilterMode) -> MTLSamplerMinMagFilter { + use MTLSamplerMinMagFilter as MTL; match filter { - wgt::FilterMode::Nearest => Nearest, - wgt::FilterMode::Linear => Linear, + wgt::FilterMode::Nearest => MTL::Nearest, + wgt::FilterMode::Linear => MTL::Linear, } } -pub fn map_address_mode(address: wgt::AddressMode) -> metal::MTLSamplerAddressMode { - use metal::MTLSamplerAddressMode::*; +pub fn map_address_mode(address: wgt::AddressMode) -> MTLSamplerAddressMode { use wgt::AddressMode as Fm; + use MTLSamplerAddressMode as MTL; match address { - Fm::Repeat => Repeat, - Fm::MirrorRepeat => MirrorRepeat, - Fm::ClampToEdge => ClampToEdge, - Fm::ClampToBorder => ClampToBorderColor, - //Fm::MirrorClamp => MirrorClampToEdge, + Fm::Repeat => MTL::Repeat, + Fm::MirrorRepeat => MTL::MirrorRepeat, + Fm::ClampToEdge => MTL::ClampToEdge, + Fm::ClampToBorder => MTL::ClampToBorderColor, + //Fm::MirrorClamp => MTL::MirrorClampToEdge, } } -pub fn map_border_color(border_color: wgt::SamplerBorderColor) -> metal::MTLSamplerBorderColor { - use metal::MTLSamplerBorderColor::*; +pub fn map_border_color(border_color: wgt::SamplerBorderColor) -> MTLSamplerBorderColor { + use MTLSamplerBorderColor as MTL; match border_color { - wgt::SamplerBorderColor::TransparentBlack => TransparentBlack, - wgt::SamplerBorderColor::OpaqueBlack => OpaqueBlack, - wgt::SamplerBorderColor::OpaqueWhite => OpaqueWhite, + wgt::SamplerBorderColor::TransparentBlack => MTL::TransparentBlack, + wgt::SamplerBorderColor::OpaqueBlack => MTL::OpaqueBlack, + wgt::SamplerBorderColor::OpaqueWhite => MTL::OpaqueWhite, wgt::SamplerBorderColor::Zero => unreachable!(), } } pub fn map_primitive_topology( topology: wgt::PrimitiveTopology, -) -> (metal::MTLPrimitiveTopologyClass, metal::MTLPrimitiveType) { +) -> (MTLPrimitiveTopologyClass, MTLPrimitiveType) { use wgt::PrimitiveTopology as Pt; match topology { - Pt::PointList => ( - metal::MTLPrimitiveTopologyClass::Point, - metal::MTLPrimitiveType::Point, - ), - Pt::LineList => ( - metal::MTLPrimitiveTopologyClass::Line, - metal::MTLPrimitiveType::Line, - ), - Pt::LineStrip => ( - metal::MTLPrimitiveTopologyClass::Line, - metal::MTLPrimitiveType::LineStrip, - ), + Pt::PointList => (MTLPrimitiveTopologyClass::Point, MTLPrimitiveType::Point), + Pt::LineList => (MTLPrimitiveTopologyClass::Line, MTLPrimitiveType::Line), + Pt::LineStrip => (MTLPrimitiveTopologyClass::Line, MTLPrimitiveType::LineStrip), Pt::TriangleList => ( - metal::MTLPrimitiveTopologyClass::Triangle, - metal::MTLPrimitiveType::Triangle, + MTLPrimitiveTopologyClass::Triangle, + MTLPrimitiveType::Triangle, ), Pt::TriangleStrip => ( - metal::MTLPrimitiveTopologyClass::Triangle, - metal::MTLPrimitiveType::TriangleStrip, + MTLPrimitiveTopologyClass::Triangle, + MTLPrimitiveType::TriangleStrip, ), } } -pub fn map_color_write(mask: wgt::ColorWrites) -> metal::MTLColorWriteMask { - let mut raw_mask = metal::MTLColorWriteMask::empty(); +pub fn map_color_write(mask: wgt::ColorWrites) -> MTLColorWriteMask { + let mut raw_mask = MTLColorWriteMask::empty(); if mask.contains(wgt::ColorWrites::RED) { - raw_mask |= metal::MTLColorWriteMask::Red; + raw_mask |= MTLColorWriteMask::Red; } if mask.contains(wgt::ColorWrites::GREEN) { - raw_mask |= metal::MTLColorWriteMask::Green; + raw_mask |= MTLColorWriteMask::Green; } if mask.contains(wgt::ColorWrites::BLUE) { - raw_mask |= metal::MTLColorWriteMask::Blue; + raw_mask |= MTLColorWriteMask::Blue; } if mask.contains(wgt::ColorWrites::ALPHA) { - raw_mask |= metal::MTLColorWriteMask::Alpha; + raw_mask |= MTLColorWriteMask::Alpha; } raw_mask } -pub fn map_blend_factor(factor: wgt::BlendFactor) -> metal::MTLBlendFactor { - use metal::MTLBlendFactor::*; +pub fn map_blend_factor(factor: wgt::BlendFactor) -> MTLBlendFactor { use wgt::BlendFactor as Bf; + use MTLBlendFactor as MTL; match factor { - Bf::Zero => Zero, - Bf::One => One, - Bf::Src => SourceColor, - Bf::OneMinusSrc => OneMinusSourceColor, - Bf::Dst => DestinationColor, - Bf::OneMinusDst => OneMinusDestinationColor, - Bf::SrcAlpha => SourceAlpha, - Bf::OneMinusSrcAlpha => OneMinusSourceAlpha, - Bf::DstAlpha => DestinationAlpha, - Bf::OneMinusDstAlpha => OneMinusDestinationAlpha, - Bf::Constant => BlendColor, - Bf::OneMinusConstant => OneMinusBlendColor, - Bf::SrcAlphaSaturated => SourceAlphaSaturated, - Bf::Src1 => Source1Color, - Bf::OneMinusSrc1 => OneMinusSource1Color, - Bf::Src1Alpha => Source1Alpha, - Bf::OneMinusSrc1Alpha => OneMinusSource1Alpha, + Bf::Zero => MTL::Zero, + Bf::One => MTL::One, + Bf::Src => MTL::SourceColor, + Bf::OneMinusSrc => MTL::OneMinusSourceColor, + Bf::Dst => MTL::DestinationColor, + Bf::OneMinusDst => MTL::OneMinusDestinationColor, + Bf::SrcAlpha => MTL::SourceAlpha, + Bf::OneMinusSrcAlpha => MTL::OneMinusSourceAlpha, + Bf::DstAlpha => MTL::DestinationAlpha, + Bf::OneMinusDstAlpha => MTL::OneMinusDestinationAlpha, + Bf::Constant => MTL::BlendColor, + Bf::OneMinusConstant => MTL::OneMinusBlendColor, + Bf::SrcAlphaSaturated => MTL::SourceAlphaSaturated, + Bf::Src1 => MTL::Source1Color, + Bf::OneMinusSrc1 => MTL::OneMinusSource1Color, + Bf::Src1Alpha => MTL::Source1Alpha, + Bf::OneMinusSrc1Alpha => MTL::OneMinusSource1Alpha, } } -pub fn map_blend_op(operation: wgt::BlendOperation) -> metal::MTLBlendOperation { - use metal::MTLBlendOperation::*; +pub fn map_blend_op(operation: wgt::BlendOperation) -> MTLBlendOperation { use wgt::BlendOperation as Bo; + use MTLBlendOperation as MTL; match operation { - Bo::Add => Add, - Bo::Subtract => Subtract, - Bo::ReverseSubtract => ReverseSubtract, - Bo::Min => Min, - Bo::Max => Max, + Bo::Add => MTL::Add, + Bo::Subtract => MTL::Subtract, + Bo::ReverseSubtract => MTL::ReverseSubtract, + Bo::Min => MTL::Min, + Bo::Max => MTL::Max, } } pub fn map_blend_component( component: &wgt::BlendComponent, -) -> ( - metal::MTLBlendOperation, - metal::MTLBlendFactor, - metal::MTLBlendFactor, -) { +) -> (MTLBlendOperation, MTLBlendFactor, MTLBlendFactor) { ( map_blend_op(component.operation), map_blend_factor(component.src_factor), @@ -192,129 +184,129 @@ pub fn map_blend_component( ) } -pub fn map_vertex_format(format: wgt::VertexFormat) -> metal::MTLVertexFormat { - use metal::MTLVertexFormat::*; +pub fn map_vertex_format(format: wgt::VertexFormat) -> MTLVertexFormat { use wgt::VertexFormat as Vf; + use MTLVertexFormat as MTL; match format { - Vf::Unorm8 => UCharNormalized, - Vf::Snorm8 => CharNormalized, - Vf::Uint8 => UChar, - Vf::Sint8 => Char, - Vf::Unorm8x2 => UChar2Normalized, - Vf::Snorm8x2 => Char2Normalized, - Vf::Uint8x2 => UChar2, - Vf::Sint8x2 => Char2, - Vf::Unorm8x4 => UChar4Normalized, - Vf::Snorm8x4 => Char4Normalized, - Vf::Uint8x4 => UChar4, - Vf::Sint8x4 => Char4, - Vf::Unorm16 => UShortNormalized, - Vf::Snorm16 => ShortNormalized, - Vf::Uint16 => UShort, - Vf::Sint16 => Short, - Vf::Float16 => Half, - Vf::Unorm16x2 => UShort2Normalized, - Vf::Snorm16x2 => Short2Normalized, - Vf::Uint16x2 => UShort2, - Vf::Sint16x2 => Short2, - Vf::Float16x2 => Half2, - Vf::Unorm16x4 => UShort4Normalized, - Vf::Snorm16x4 => Short4Normalized, - Vf::Uint16x4 => UShort4, - Vf::Sint16x4 => Short4, - Vf::Float16x4 => Half4, - Vf::Uint32 => UInt, - Vf::Sint32 => Int, - Vf::Float32 => Float, - Vf::Uint32x2 => UInt2, - Vf::Sint32x2 => Int2, - Vf::Float32x2 => Float2, - Vf::Uint32x3 => UInt3, - Vf::Sint32x3 => Int3, - Vf::Float32x3 => Float3, - Vf::Uint32x4 => UInt4, - Vf::Sint32x4 => Int4, - Vf::Float32x4 => Float4, - Vf::Unorm10_10_10_2 => UInt1010102Normalized, - Vf::Unorm8x4Bgra => UChar4Normalized_BGRA, + Vf::Unorm8 => MTL::UCharNormalized, + Vf::Snorm8 => MTL::CharNormalized, + Vf::Uint8 => MTL::UChar, + Vf::Sint8 => MTL::Char, + Vf::Unorm8x2 => MTL::UChar2Normalized, + Vf::Snorm8x2 => MTL::Char2Normalized, + Vf::Uint8x2 => MTL::UChar2, + Vf::Sint8x2 => MTL::Char2, + Vf::Unorm8x4 => MTL::UChar4Normalized, + Vf::Snorm8x4 => MTL::Char4Normalized, + Vf::Uint8x4 => MTL::UChar4, + Vf::Sint8x4 => MTL::Char4, + Vf::Unorm16 => MTL::UShortNormalized, + Vf::Snorm16 => MTL::ShortNormalized, + Vf::Uint16 => MTL::UShort, + Vf::Sint16 => MTL::Short, + Vf::Float16 => MTL::Half, + Vf::Unorm16x2 => MTL::UShort2Normalized, + Vf::Snorm16x2 => MTL::Short2Normalized, + Vf::Uint16x2 => MTL::UShort2, + Vf::Sint16x2 => MTL::Short2, + Vf::Float16x2 => MTL::Half2, + Vf::Unorm16x4 => MTL::UShort4Normalized, + Vf::Snorm16x4 => MTL::Short4Normalized, + Vf::Uint16x4 => MTL::UShort4, + Vf::Sint16x4 => MTL::Short4, + Vf::Float16x4 => MTL::Half4, + Vf::Uint32 => MTL::UInt, + Vf::Sint32 => MTL::Int, + Vf::Float32 => MTL::Float, + Vf::Uint32x2 => MTL::UInt2, + Vf::Sint32x2 => MTL::Int2, + Vf::Float32x2 => MTL::Float2, + Vf::Uint32x3 => MTL::UInt3, + Vf::Sint32x3 => MTL::Int3, + Vf::Float32x3 => MTL::Float3, + Vf::Uint32x4 => MTL::UInt4, + Vf::Sint32x4 => MTL::Int4, + Vf::Float32x4 => MTL::Float4, + Vf::Unorm10_10_10_2 => MTL::UInt1010102Normalized, + Vf::Unorm8x4Bgra => MTL::UChar4Normalized_BGRA, Vf::Float64 | Vf::Float64x2 | Vf::Float64x3 | Vf::Float64x4 => unimplemented!(), } } -pub fn map_step_mode(mode: wgt::VertexStepMode) -> metal::MTLVertexStepFunction { +pub fn map_step_mode(mode: wgt::VertexStepMode) -> MTLVertexStepFunction { match mode { - wgt::VertexStepMode::Vertex => metal::MTLVertexStepFunction::PerVertex, - wgt::VertexStepMode::Instance => metal::MTLVertexStepFunction::PerInstance, + wgt::VertexStepMode::Vertex => MTLVertexStepFunction::PerVertex, + wgt::VertexStepMode::Instance => MTLVertexStepFunction::PerInstance, } } -pub fn map_stencil_op(op: wgt::StencilOperation) -> metal::MTLStencilOperation { - use metal::MTLStencilOperation::*; +pub fn map_stencil_op(op: wgt::StencilOperation) -> MTLStencilOperation { use wgt::StencilOperation as So; + use MTLStencilOperation as MTL; match op { - So::Keep => Keep, - So::Zero => Zero, - So::Replace => Replace, - So::IncrementClamp => IncrementClamp, - So::IncrementWrap => IncrementWrap, - So::DecrementClamp => DecrementClamp, - So::DecrementWrap => DecrementWrap, - So::Invert => Invert, + So::Keep => MTL::Keep, + So::Zero => MTL::Zero, + So::Replace => MTL::Replace, + So::IncrementClamp => MTL::IncrementClamp, + So::IncrementWrap => MTL::IncrementWrap, + So::DecrementClamp => MTL::DecrementClamp, + So::DecrementWrap => MTL::DecrementWrap, + So::Invert => MTL::Invert, } } -pub fn map_winding(winding: wgt::FrontFace) -> metal::MTLWinding { +pub fn map_winding(winding: wgt::FrontFace) -> MTLWinding { match winding { - wgt::FrontFace::Cw => metal::MTLWinding::Clockwise, - wgt::FrontFace::Ccw => metal::MTLWinding::CounterClockwise, + wgt::FrontFace::Cw => MTLWinding::Clockwise, + wgt::FrontFace::Ccw => MTLWinding::CounterClockwise, } } -pub fn map_cull_mode(face: Option) -> metal::MTLCullMode { +pub fn map_cull_mode(face: Option) -> MTLCullMode { match face { - None => metal::MTLCullMode::None, - Some(wgt::Face::Front) => metal::MTLCullMode::Front, - Some(wgt::Face::Back) => metal::MTLCullMode::Back, + None => MTLCullMode::None, + Some(wgt::Face::Front) => MTLCullMode::Front, + Some(wgt::Face::Back) => MTLCullMode::Back, } } -pub fn map_range(range: &crate::MemoryRange) -> metal::NSRange { - metal::NSRange { +pub fn map_range(range: &crate::MemoryRange) -> NSRange { + NSRange { location: range.start, length: range.end - range.start, } } -pub fn map_copy_extent(extent: &crate::CopyExtent) -> metal::MTLSize { - metal::MTLSize { +pub fn map_copy_extent(extent: &crate::CopyExtent) -> MTLSize { + MTLSize { width: extent.width as u64, height: extent.height as u64, depth: extent.depth as u64, } } -pub fn map_origin(origin: &wgt::Origin3d) -> metal::MTLOrigin { - metal::MTLOrigin { +pub fn map_origin(origin: &wgt::Origin3d) -> MTLOrigin { + MTLOrigin { x: origin.x as u64, y: origin.y as u64, z: origin.z as u64, } } -pub fn map_store_action(store: bool, resolve: bool) -> metal::MTLStoreAction { - use metal::MTLStoreAction::*; +pub fn map_store_action(store: bool, resolve: bool) -> MTLStoreAction { + use MTLStoreAction as MTL; match (store, resolve) { - (true, true) => StoreAndMultisampleResolve, - (false, true) => MultisampleResolve, - (true, false) => Store, - (false, false) => DontCare, + (true, true) => MTL::StoreAndMultisampleResolve, + (false, true) => MTL::MultisampleResolve, + (true, false) => MTL::Store, + (false, false) => MTL::DontCare, } } -pub fn map_clear_color(color: &wgt::Color) -> metal::MTLClearColor { - metal::MTLClearColor { +pub fn map_clear_color(color: &wgt::Color) -> MTLClearColor { + MTLClearColor { red: color.r, green: color.g, blue: color.b, @@ -322,45 +314,42 @@ pub fn map_clear_color(color: &wgt::Color) -> metal::MTLClearColor { } } -pub fn get_blit_option( - format: wgt::TextureFormat, - aspect: crate::FormatAspects, -) -> metal::MTLBlitOption { +pub fn get_blit_option(format: wgt::TextureFormat, aspect: crate::FormatAspects) -> MTLBlitOption { if format.is_combined_depth_stencil_format() { match aspect { - crate::FormatAspects::DEPTH => metal::MTLBlitOption::DepthFromDepthStencil, - crate::FormatAspects::STENCIL => metal::MTLBlitOption::StencilFromDepthStencil, + crate::FormatAspects::DEPTH => MTLBlitOption::DepthFromDepthStencil, + crate::FormatAspects::STENCIL => MTLBlitOption::StencilFromDepthStencil, _ => unreachable!(), } } else { - metal::MTLBlitOption::None + MTLBlitOption::None } } -pub fn map_render_stages(stage: wgt::ShaderStages) -> metal::MTLRenderStages { - let mut raw_stages = metal::MTLRenderStages::empty(); +pub fn map_render_stages(stage: wgt::ShaderStages) -> MTLRenderStages { + let mut raw_stages = MTLRenderStages::empty(); if stage.contains(wgt::ShaderStages::VERTEX) { - raw_stages |= metal::MTLRenderStages::Vertex; + raw_stages |= MTLRenderStages::Vertex; } if stage.contains(wgt::ShaderStages::FRAGMENT) { - raw_stages |= metal::MTLRenderStages::Fragment; + raw_stages |= MTLRenderStages::Fragment; } raw_stages } -pub fn map_resource_usage(ty: &wgt::BindingType) -> metal::MTLResourceUsage { +pub fn map_resource_usage(ty: &wgt::BindingType) -> MTLResourceUsage { match ty { - wgt::BindingType::Texture { .. } => metal::MTLResourceUsage::Sample, + wgt::BindingType::Texture { .. } => MTLResourceUsage::Sample, wgt::BindingType::StorageTexture { access, .. } => match access { - wgt::StorageTextureAccess::WriteOnly => metal::MTLResourceUsage::Write, - wgt::StorageTextureAccess::ReadOnly => metal::MTLResourceUsage::Read, + wgt::StorageTextureAccess::WriteOnly => MTLResourceUsage::Write, + wgt::StorageTextureAccess::ReadOnly => MTLResourceUsage::Read, wgt::StorageTextureAccess::Atomic | wgt::StorageTextureAccess::ReadWrite => { - metal::MTLResourceUsage::Read | metal::MTLResourceUsage::Write + MTLResourceUsage::Read | MTLResourceUsage::Write } }, - wgt::BindingType::Sampler(..) => metal::MTLResourceUsage::empty(), + wgt::BindingType::Sampler(..) => MTLResourceUsage::empty(), _ => unreachable!(), } } diff --git a/wgpu-hal/src/metal/device.rs b/wgpu-hal/src/metal/device.rs index 6fb172d00..915334535 100644 --- a/wgpu-hal/src/metal/device.rs +++ b/wgpu-hal/src/metal/device.rs @@ -4,18 +4,24 @@ use std::{thread, time}; use parking_lot::Mutex; -use super::conv; +use super::{conv, PassthroughShader}; use crate::auxil::map_naga_stage; +use crate::metal::ShaderModuleSource; use crate::TlasInstance; -use metal::foreign_types::ForeignType; +use metal::{ + foreign_types::ForeignType, MTLCommandBufferStatus, MTLDepthClipMode, MTLLanguageVersion, + MTLMutability, MTLPixelFormat, MTLPrimitiveTopologyClass, MTLResourceID, MTLResourceOptions, + MTLSamplerAddressMode, MTLSamplerMipFilter, MTLSize, MTLStorageMode, MTLTextureType, + MTLTriangleFillMode, MTLVertexStepFunction, NSRange, +}; type DeviceResult = Result; struct CompiledShader { library: metal::Library, function: metal::Function, - wg_size: metal::MTLSize, + wg_size: MTLSize, wg_memory_sizes: Vec, /// Bindings of WGSL `storage` globals that contain variable-sized arrays. @@ -119,171 +125,197 @@ impl super::Device { stage: &crate::ProgrammableStage, vertex_buffer_mappings: &[naga::back::msl::VertexBufferMapping], layout: &super::PipelineLayout, - primitive_class: metal::MTLPrimitiveTopologyClass, + primitive_class: MTLPrimitiveTopologyClass, naga_stage: naga::ShaderStage, ) -> Result { - let stage_bit = map_naga_stage(naga_stage); + match stage.module.source { + ShaderModuleSource::Naga(ref naga_shader) => { + let stage_bit = map_naga_stage(naga_stage); + let (module, module_info) = naga::back::pipeline_constants::process_overrides( + &naga_shader.module, + &naga_shader.info, + Some((naga_stage, stage.entry_point)), + stage.constants, + ) + .map_err(|e| { + crate::PipelineError::PipelineConstants(stage_bit, format!("MSL: {e:?}")) + })?; - let (module, module_info) = naga::back::pipeline_constants::process_overrides( - &stage.module.naga.module, - &stage.module.naga.info, - stage.constants, - ) - .map_err(|e| crate::PipelineError::PipelineConstants(stage_bit, format!("MSL: {:?}", e)))?; + let ep_resources = &layout.per_stage_map[naga_stage]; - let ep_resources = &layout.per_stage_map[naga_stage]; + let bounds_check_policy = if stage.module.bounds_checks.bounds_checks { + naga::proc::BoundsCheckPolicy::Restrict + } else { + naga::proc::BoundsCheckPolicy::Unchecked + }; - let bounds_check_policy = if stage.module.bounds_checks.bounds_checks { - naga::proc::BoundsCheckPolicy::Restrict - } else { - naga::proc::BoundsCheckPolicy::Unchecked - }; + let options = naga::back::msl::Options { + lang_version: match self.shared.private_caps.msl_version { + MTLLanguageVersion::V1_0 => (1, 0), + MTLLanguageVersion::V1_1 => (1, 1), + MTLLanguageVersion::V1_2 => (1, 2), + MTLLanguageVersion::V2_0 => (2, 0), + MTLLanguageVersion::V2_1 => (2, 1), + MTLLanguageVersion::V2_2 => (2, 2), + MTLLanguageVersion::V2_3 => (2, 3), + MTLLanguageVersion::V2_4 => (2, 4), + MTLLanguageVersion::V3_0 => (3, 0), + MTLLanguageVersion::V3_1 => (3, 1), + }, + inline_samplers: Default::default(), + spirv_cross_compatibility: false, + fake_missing_bindings: false, + per_entry_point_map: naga::back::msl::EntryPointResourceMap::from([( + stage.entry_point.to_owned(), + ep_resources.clone(), + )]), + bounds_check_policies: naga::proc::BoundsCheckPolicies { + index: bounds_check_policy, + buffer: bounds_check_policy, + image_load: bounds_check_policy, + // TODO: support bounds checks on binding arrays + binding_array: naga::proc::BoundsCheckPolicy::Unchecked, + }, + zero_initialize_workgroup_memory: stage.zero_initialize_workgroup_memory, + force_loop_bounding: stage.module.bounds_checks.force_loop_bounding, + }; - let options = naga::back::msl::Options { - lang_version: match self.shared.private_caps.msl_version { - metal::MTLLanguageVersion::V1_0 => (1, 0), - metal::MTLLanguageVersion::V1_1 => (1, 1), - metal::MTLLanguageVersion::V1_2 => (1, 2), - metal::MTLLanguageVersion::V2_0 => (2, 0), - metal::MTLLanguageVersion::V2_1 => (2, 1), - metal::MTLLanguageVersion::V2_2 => (2, 2), - metal::MTLLanguageVersion::V2_3 => (2, 3), - metal::MTLLanguageVersion::V2_4 => (2, 4), - metal::MTLLanguageVersion::V3_0 => (3, 0), - metal::MTLLanguageVersion::V3_1 => (3, 1), - }, - inline_samplers: Default::default(), - spirv_cross_compatibility: false, - fake_missing_bindings: false, - per_entry_point_map: naga::back::msl::EntryPointResourceMap::from([( - stage.entry_point.to_owned(), - ep_resources.clone(), - )]), - bounds_check_policies: naga::proc::BoundsCheckPolicies { - index: bounds_check_policy, - buffer: bounds_check_policy, - image_load: bounds_check_policy, - // TODO: support bounds checks on binding arrays - binding_array: naga::proc::BoundsCheckPolicy::Unchecked, - }, - zero_initialize_workgroup_memory: stage.zero_initialize_workgroup_memory, - force_loop_bounding: stage.module.bounds_checks.force_loop_bounding, - }; - - let pipeline_options = naga::back::msl::PipelineOptions { - allow_and_force_point_size: match primitive_class { - metal::MTLPrimitiveTopologyClass::Point => true, - _ => false, - }, - vertex_pulling_transform: true, - vertex_buffer_mappings: vertex_buffer_mappings.to_vec(), - }; - - let (source, info) = - naga::back::msl::write_string(&module, &module_info, &options, &pipeline_options) - .map_err(|e| crate::PipelineError::Linkage(stage_bit, format!("MSL: {:?}", e)))?; - - log::debug!( - "Naga generated shader for entry point '{}' and stage {:?}\n{}", - stage.entry_point, - naga_stage, - &source - ); - - let options = metal::CompileOptions::new(); - options.set_language_version(self.shared.private_caps.msl_version); - - if self.shared.private_caps.supports_preserve_invariance { - options.set_preserve_invariance(true); - } - - let library = self - .shared - .device - .lock() - .new_library_with_source(source.as_ref(), &options) - .map_err(|err| { - log::warn!("Naga generated shader:\n{}", source); - crate::PipelineError::Linkage(stage_bit, format!("Metal: {}", err)) - })?; - - let ep_index = module - .entry_points - .iter() - .position(|ep| ep.stage == naga_stage && ep.name == stage.entry_point) - .ok_or(crate::PipelineError::EntryPoint(naga_stage))?; - let ep = &module.entry_points[ep_index]; - let ep_name = info.entry_point_names[ep_index] - .as_ref() - .map_err(|e| crate::PipelineError::Linkage(stage_bit, format!("{}", e)))?; - - let wg_size = metal::MTLSize { - width: ep.workgroup_size[0] as _, - height: ep.workgroup_size[1] as _, - depth: ep.workgroup_size[2] as _, - }; - - let function = library.get_function(ep_name, None).map_err(|e| { - log::error!("get_function: {:?}", e); - crate::PipelineError::EntryPoint(naga_stage) - })?; - - // collect sizes indices, immutable buffers, and work group memory sizes - let ep_info = &module_info.get_entry_point(ep_index); - let mut wg_memory_sizes = Vec::new(); - let mut sized_bindings = Vec::new(); - let mut immutable_buffer_mask = 0; - for (var_handle, var) in module.global_variables.iter() { - match var.space { - naga::AddressSpace::WorkGroup => { - if !ep_info[var_handle].is_empty() { - let size = module.types[var.ty].inner.size(module.to_ctx()); - wg_memory_sizes.push(size); - } - } - naga::AddressSpace::Uniform | naga::AddressSpace::Storage { .. } => { - let br = match var.binding { - Some(br) => br, - None => continue, - }; - let storage_access_store = match var.space { - naga::AddressSpace::Storage { access } => { - access.contains(naga::StorageAccess::STORE) - } + let pipeline_options = naga::back::msl::PipelineOptions { + entry_point: Some((naga_stage, stage.entry_point.to_owned())), + allow_and_force_point_size: match primitive_class { + MTLPrimitiveTopologyClass::Point => true, _ => false, - }; + }, + vertex_pulling_transform: true, + vertex_buffer_mappings: vertex_buffer_mappings.to_vec(), + }; - // check for an immutable buffer - if !ep_info[var_handle].is_empty() && !storage_access_store { - let slot = ep_resources.resources[&br].buffer.unwrap(); - immutable_buffer_mask |= 1 << slot; - } + let (source, info) = naga::back::msl::write_string( + &module, + &module_info, + &options, + &pipeline_options, + ) + .map_err(|e| crate::PipelineError::Linkage(stage_bit, format!("MSL: {e:?}")))?; - let mut dynamic_array_container_ty = var.ty; - if let naga::TypeInner::Struct { ref members, .. } = module.types[var.ty].inner - { - dynamic_array_container_ty = members.last().unwrap().ty; - } - if let naga::TypeInner::Array { - size: naga::ArraySize::Dynamic, - .. - } = module.types[dynamic_array_container_ty].inner - { - sized_bindings.push(br); + log::debug!( + "Naga generated shader for entry point '{}' and stage {:?}\n{}", + stage.entry_point, + naga_stage, + &source + ); + + let options = metal::CompileOptions::new(); + options.set_language_version(self.shared.private_caps.msl_version); + + if self.shared.private_caps.supports_preserve_invariance { + options.set_preserve_invariance(true); + } + + let library = self + .shared + .device + .lock() + .new_library_with_source(source.as_ref(), &options) + .map_err(|err| { + log::warn!("Naga generated shader:\n{source}"); + crate::PipelineError::Linkage(stage_bit, format!("Metal: {err}")) + })?; + + let ep_index = module + .entry_points + .iter() + .position(|ep| ep.stage == naga_stage && ep.name == stage.entry_point) + .ok_or(crate::PipelineError::EntryPoint(naga_stage))?; + let ep = &module.entry_points[ep_index]; + let translated_ep_name = info.entry_point_names[0] + .as_ref() + .map_err(|e| crate::PipelineError::Linkage(stage_bit, format!("{e}")))?; + + let wg_size = MTLSize { + width: ep.workgroup_size[0] as _, + height: ep.workgroup_size[1] as _, + depth: ep.workgroup_size[2] as _, + }; + + let function = library + .get_function(translated_ep_name, None) + .map_err(|e| { + log::error!("get_function: {e:?}"); + crate::PipelineError::EntryPoint(naga_stage) + })?; + + // collect sizes indices, immutable buffers, and work group memory sizes + let ep_info = &module_info.get_entry_point(ep_index); + let mut wg_memory_sizes = Vec::new(); + let mut sized_bindings = Vec::new(); + let mut immutable_buffer_mask = 0; + for (var_handle, var) in module.global_variables.iter() { + match var.space { + naga::AddressSpace::WorkGroup => { + if !ep_info[var_handle].is_empty() { + let size = module.types[var.ty].inner.size(module.to_ctx()); + wg_memory_sizes.push(size); + } + } + naga::AddressSpace::Uniform | naga::AddressSpace::Storage { .. } => { + let br = match var.binding { + Some(br) => br, + None => continue, + }; + let storage_access_store = match var.space { + naga::AddressSpace::Storage { access } => { + access.contains(naga::StorageAccess::STORE) + } + _ => false, + }; + + // check for an immutable buffer + if !ep_info[var_handle].is_empty() && !storage_access_store { + let slot = ep_resources.resources[&br].buffer.unwrap(); + immutable_buffer_mask |= 1 << slot; + } + + let mut dynamic_array_container_ty = var.ty; + if let naga::TypeInner::Struct { ref members, .. } = + module.types[var.ty].inner + { + dynamic_array_container_ty = members.last().unwrap().ty; + } + if let naga::TypeInner::Array { + size: naga::ArraySize::Dynamic, + .. + } = module.types[dynamic_array_container_ty].inner + { + sized_bindings.push(br); + } + } + _ => {} } } - _ => {} - } - } - Ok(CompiledShader { - library, - function, - wg_size, - wg_memory_sizes, - sized_bindings, - immutable_buffer_mask, - }) + Ok(CompiledShader { + library, + function, + wg_size, + wg_memory_sizes, + sized_bindings, + immutable_buffer_mask, + }) + } + ShaderModuleSource::Passthrough(ref shader) => Ok(CompiledShader { + library: shader.library.clone(), + function: shader.function.clone(), + wg_size: MTLSize { + width: shader.num_workgroups.0 as u64, + height: shader.num_workgroups.1 as u64, + depth: shader.num_workgroups.2 as u64, + }, + wg_memory_sizes: vec![], + sized_bindings: vec![], + immutable_buffer_mask: 0, + }), + } } fn set_buffers_mutability( @@ -296,14 +328,14 @@ impl super::Device { buffers .object_at(slot as u64) .unwrap() - .set_mutability(metal::MTLMutability::Immutable); + .set_mutability(MTLMutability::Immutable); } } pub unsafe fn texture_from_raw( raw: metal::Texture, format: wgt::TextureFormat, - raw_type: metal::MTLTextureType, + raw_type: MTLTextureType, array_layers: u32, mip_levels: u32, copy_size: crate::CopyExtent, @@ -342,17 +374,14 @@ impl crate::Device for super::Device { let map_read = desc.usage.contains(wgt::BufferUses::MAP_READ); let map_write = desc.usage.contains(wgt::BufferUses::MAP_WRITE); - let mut options = metal::MTLResourceOptions::empty(); + let mut options = MTLResourceOptions::empty(); options |= if map_read || map_write { // `crate::MemoryFlags::PREFER_COHERENT` is ignored here - metal::MTLResourceOptions::StorageModeShared + MTLResourceOptions::StorageModeShared } else { - metal::MTLResourceOptions::StorageModePrivate + MTLResourceOptions::StorageModePrivate }; - options.set( - metal::MTLResourceOptions::CPUCacheModeWriteCombined, - map_write, - ); + options.set(MTLResourceOptions::CPUCacheModeWriteCombined, map_write); //TODO: HazardTrackingModeUntracked @@ -405,31 +434,39 @@ impl crate::Device for super::Device { let descriptor = metal::TextureDescriptor::new(); let mtl_type = match desc.dimension { - wgt::TextureDimension::D1 => metal::MTLTextureType::D1, + wgt::TextureDimension::D1 => MTLTextureType::D1, wgt::TextureDimension::D2 => { if desc.sample_count > 1 { descriptor.set_sample_count(desc.sample_count as u64); - metal::MTLTextureType::D2Multisample + MTLTextureType::D2Multisample } else if desc.size.depth_or_array_layers > 1 { descriptor.set_array_length(desc.size.depth_or_array_layers as u64); - metal::MTLTextureType::D2Array + MTLTextureType::D2Array } else { - metal::MTLTextureType::D2 + MTLTextureType::D2 } } wgt::TextureDimension::D3 => { descriptor.set_depth(desc.size.depth_or_array_layers as u64); - metal::MTLTextureType::D3 + MTLTextureType::D3 } }; + let mtl_storage_mode = if desc.usage.contains(wgt::TextureUses::TRANSIENT) + && self.shared.private_caps.supports_memoryless_storage + { + MTLStorageMode::Memoryless + } else { + MTLStorageMode::Private + }; + descriptor.set_texture_type(mtl_type); descriptor.set_width(desc.size.width as u64); descriptor.set_height(desc.size.height as u64); descriptor.set_mipmap_level_count(desc.mip_level_count as u64); descriptor.set_pixel_format(mtl_format); descriptor.set_usage(conv::map_texture_usage(desc.format, desc.usage)); - descriptor.set_storage_mode(metal::MTLStorageMode::Private); + descriptor.set_storage_mode(mtl_storage_mode); let raw = self.shared.device.lock().new_texture(&descriptor); if raw.as_ptr().is_null() { @@ -465,7 +502,7 @@ impl crate::Device for super::Device { texture: &super::Texture, desc: &crate::TextureViewDescriptor, ) -> DeviceResult { - let raw_type = if texture.raw_type == metal::MTLTextureType::D2Multisample { + let raw_type = if texture.raw_type == MTLTextureType::D2Multisample { texture.raw_type } else { conv::map_texture_view_dimension(desc.dimension) @@ -502,11 +539,11 @@ impl crate::Device for super::Device { let raw = texture.raw.new_texture_view_from_slice( raw_format, raw_type, - metal::NSRange { + NSRange { location: desc.range.base_mip_level as _, length: mip_level_count as _, }, - metal::NSRange { + NSRange { location: desc.range.base_array_layer as _, length: array_layer_count as _, }, @@ -537,11 +574,11 @@ impl crate::Device for super::Device { descriptor.set_min_filter(conv::map_filter_mode(desc.min_filter)); descriptor.set_mag_filter(conv::map_filter_mode(desc.mag_filter)); descriptor.set_mip_filter(match desc.mipmap_filter { - wgt::FilterMode::Nearest if desc.lod_clamp == (0.0..0.0) => { - metal::MTLSamplerMipFilter::NotMipmapped + wgt::MipmapFilterMode::Nearest if desc.lod_clamp == (0.0..0.0) => { + MTLSamplerMipFilter::NotMipmapped } - wgt::FilterMode::Nearest => metal::MTLSamplerMipFilter::Nearest, - wgt::FilterMode::Linear => metal::MTLSamplerMipFilter::Linear, + wgt::MipmapFilterMode::Nearest => MTLSamplerMipFilter::Nearest, + wgt::MipmapFilterMode::Linear => MTLSamplerMipFilter::Linear, }); let [s, t, r] = desc.address_modes; @@ -562,15 +599,15 @@ impl crate::Device for super::Device { if let Some(border_color) = desc.border_color { if let wgt::SamplerBorderColor::Zero = border_color { if s == wgt::AddressMode::ClampToBorder { - descriptor.set_address_mode_s(metal::MTLSamplerAddressMode::ClampToZero); + descriptor.set_address_mode_s(MTLSamplerAddressMode::ClampToZero); } if t == wgt::AddressMode::ClampToBorder { - descriptor.set_address_mode_t(metal::MTLSamplerAddressMode::ClampToZero); + descriptor.set_address_mode_t(MTLSamplerAddressMode::ClampToZero); } if r == wgt::AddressMode::ClampToBorder { - descriptor.set_address_mode_r(metal::MTLSamplerAddressMode::ClampToZero); + descriptor.set_address_mode_r(MTLSamplerAddressMode::ClampToZero); } } else { descriptor.set_border_color(conv::map_border_color(border_color)); @@ -736,6 +773,19 @@ impl crate::Device for super::Device { }; } wgt::BindingType::AccelerationStructure { .. } => unimplemented!(), + wgt::BindingType::ExternalTexture => { + target.external_texture = + Some(naga::back::msl::BindExternalTextureTarget { + planes: [ + info.counters.textures as _, + (info.counters.textures + 1) as _, + (info.counters.textures + 2) as _, + ], + params: info.counters.buffers as _, + }); + info.counters.textures += 3; + info.counters.buffers += 1; + } } } @@ -765,7 +815,7 @@ impl crate::Device for super::Device { || info.counters.textures > self.shared.private_caps.max_textures_per_stage || info.counters.samplers > self.shared.private_caps.max_samplers_per_stage { - log::error!("Resource limit exceeded: {:?}", info); + log::error!("Resource limit exceeded: {info:?}"); return Err(crate::DeviceError::OutOfMemory); } } @@ -831,6 +881,10 @@ impl crate::Device for super::Device { for (entry, layout) in layout_and_entry_iter { // Bindless path if layout.count.is_some() { + if !layout.visibility.contains(stage_bit) { + continue; + } + let count = entry.count; let stages = conv::map_render_stages(layout.visibility); @@ -839,12 +893,15 @@ impl crate::Device for super::Device { // Create argument buffer for this array let buffer = self.shared.device.lock().new_buffer( 8 * count as u64, - metal::MTLResourceOptions::HazardTrackingModeUntracked - | metal::MTLResourceOptions::StorageModeShared, + MTLResourceOptions::HazardTrackingModeUntracked + | MTLResourceOptions::StorageModeShared, ); - let contents: &mut [metal::MTLResourceID] = unsafe { - std::slice::from_raw_parts_mut(buffer.contents().cast(), count as usize) + let contents: &mut [MTLResourceID] = unsafe { + core::slice::from_raw_parts_mut( + buffer.contents().cast(), + count as usize, + ) }; match layout.ty { @@ -961,6 +1018,28 @@ impl crate::Device for super::Device { counter.textures += 1; } wgt::BindingType::AccelerationStructure { .. } => unimplemented!(), + wgt::BindingType::ExternalTexture => { + // We don't yet support binding arrays of external textures. + // https://github.com/gfx-rs/wgpu/issues/8027 + assert_eq!(entry.count, 1); + let external_texture = + &desc.external_textures[entry.resource_index as usize]; + bg.textures.extend( + external_texture + .planes + .iter() + .map(|plane| plane.view.as_raw()), + ); + bg.buffers.push(super::BufferResource { + ptr: external_texture.params.buffer.as_raw(), + offset: external_texture.params.offset, + dynamic_index: None, + binding_size: None, + binding_location: layout.binding, + }); + counter.textures += 3; + counter.buffers += 1; + } } } } @@ -985,12 +1064,40 @@ impl crate::Device for super::Device { match shader { crate::ShaderInput::Naga(naga) => Ok(super::ShaderModule { - naga, + source: ShaderModuleSource::Naga(naga), bounds_checks: desc.runtime_checks, }), - crate::ShaderInput::SpirV(_) => { - panic!("SPIRV_SHADER_PASSTHROUGH is not enabled for this backend") + crate::ShaderInput::Msl { + shader: source, + entry_point, + num_workgroups, + } => { + let options = metal::CompileOptions::new(); + // Obtain the locked device from shared + let device = self.shared.device.lock(); + let library = device + .new_library_with_source(source, &options) + .map_err(|e| crate::ShaderError::Compilation(format!("MSL: {e:?}")))?; + let function = library.get_function(&entry_point, None).map_err(|_| { + crate::ShaderError::Compilation(format!( + "Entry point '{entry_point}' not found" + )) + })?; + + Ok(super::ShaderModule { + source: ShaderModuleSource::Passthrough(PassthroughShader { + library, + function, + entry_point, + num_workgroups, + }), + bounds_checks: desc.runtime_checks, + }) } + crate::ShaderInput::SpirV(_) + | crate::ShaderInput::Dxil { .. } + | crate::ShaderInput::Hlsl { .. } + | crate::ShaderInput::Glsl { .. } => unreachable!(), } } @@ -1006,12 +1113,20 @@ impl crate::Device for super::Device { super::PipelineCache, >, ) -> Result { + let (desc_vertex_stage, desc_vertex_buffers) = match &desc.vertex_processor { + crate::VertexProcessor::Standard { + vertex_buffers, + vertex_stage, + } => (vertex_stage, *vertex_buffers), + crate::VertexProcessor::Mesh { .. } => unreachable!(), + }; + objc::rc::autoreleasepool(|| { let descriptor = metal::RenderPipelineDescriptor::new(); let raw_triangle_fill_mode = match desc.primitive.polygon_mode { - wgt::PolygonMode::Fill => metal::MTLTriangleFillMode::Fill, - wgt::PolygonMode::Line => metal::MTLTriangleFillMode::Lines, + wgt::PolygonMode::Fill => MTLTriangleFillMode::Fill, + wgt::PolygonMode::Line => MTLTriangleFillMode::Lines, wgt::PolygonMode::Point => panic!( "{:?} is not enabled for this backend", wgt::Features::POLYGON_MODE_POINT @@ -1024,7 +1139,7 @@ impl crate::Device for super::Device { // Vertex shader let (vs_lib, vs_info) = { let mut vertex_buffer_mappings = Vec::::new(); - for (i, vbl) in desc.vertex_buffers.iter().enumerate() { + for (i, vbl) in desc_vertex_buffers.iter().enumerate() { let mut attributes = Vec::::new(); for attribute in vbl.attributes.iter() { attributes.push(naga::back::msl::AttributeMapping { @@ -1047,13 +1162,21 @@ impl crate::Device for super::Device { .try_into() .unwrap() }, - indexed_by_vertex: (vbl.step_mode == wgt::VertexStepMode::Vertex {}), + step_mode: match (vbl.array_stride == 0, vbl.step_mode) { + (true, _) => naga::back::msl::VertexBufferStepMode::Constant, + (false, wgt::VertexStepMode::Vertex) => { + naga::back::msl::VertexBufferStepMode::ByVertex + } + (false, wgt::VertexStepMode::Instance) => { + naga::back::msl::VertexBufferStepMode::ByInstance + } + }, attributes, }); } let vs = self.load_shader( - &desc.vertex_stage, + desc_vertex_stage, &vertex_buffer_mappings, desc.layout, primitive_class, @@ -1110,8 +1233,7 @@ impl crate::Device for super::Device { // TODO: This is a workaround for what appears to be a Metal validation bug // A pixel format is required even though no attachments are provided if desc.color_targets.is_empty() && desc.depth_stencil.is_none() { - descriptor - .set_depth_attachment_pixel_format(metal::MTLPixelFormat::Depth32Float); + descriptor.set_depth_attachment_pixel_format(MTLPixelFormat::Depth32Float); } (None, None) } @@ -1122,7 +1244,7 @@ impl crate::Device for super::Device { let ct = if let Some(color_target) = ct.as_ref() { color_target } else { - at_descriptor.set_pixel_format(metal::MTLPixelFormat::Invalid); + at_descriptor.set_pixel_format(MTLPixelFormat::Invalid); continue; }; @@ -1167,12 +1289,12 @@ impl crate::Device for super::Device { None => None, }; - if desc.layout.total_counters.vs.buffers + (desc.vertex_buffers.len() as u32) + if desc.layout.total_counters.vs.buffers + (desc_vertex_buffers.len() as u32) > self.shared.private_caps.max_vertex_buffers { let msg = format!( "pipeline needs too many buffers in the vertex stage: {} vertex and {} layout", - desc.vertex_buffers.len(), + desc_vertex_buffers.len(), desc.layout.total_counters.vs.buffers ); return Err(crate::PipelineError::Linkage( @@ -1181,9 +1303,9 @@ impl crate::Device for super::Device { )); } - if !desc.vertex_buffers.is_empty() { + if !desc_vertex_buffers.is_empty() { let vertex_descriptor = metal::VertexDescriptor::new(); - for (i, vb) in desc.vertex_buffers.iter().enumerate() { + for (i, vb) in desc_vertex_buffers.iter().enumerate() { let buffer_index = self.shared.private_caps.max_vertex_buffers as u64 - 1 - i as u64; let buffer_desc = vertex_descriptor.layouts().object_at(buffer_index).unwrap(); @@ -1199,7 +1321,7 @@ impl crate::Device for super::Device { .max() .unwrap_or(0); buffer_desc.set_stride(wgt::math::align_to(stride, 4)); - buffer_desc.set_step_function(metal::MTLVertexStepFunction::Constant); + buffer_desc.set_step_function(MTLVertexStepFunction::Constant); buffer_desc.set_step_rate(0); } else { buffer_desc.set_stride(vb.array_stride); @@ -1231,6 +1353,10 @@ impl crate::Device for super::Device { descriptor.set_label(name); } + if let Some(mv) = desc.multiview_mask { + descriptor.set_max_vertex_amplification_count(mv.get().count_ones() as u64); + } + let raw = self .shared .device @@ -1239,7 +1365,7 @@ impl crate::Device for super::Device { .map_err(|e| { crate::PipelineError::Linkage( wgt::ShaderStages::VERTEX | wgt::ShaderStages::FRAGMENT, - format!("new_render_pipeline_state: {:?}", e), + format!("new_render_pipeline_state: {e:?}"), ) })?; @@ -1257,9 +1383,9 @@ impl crate::Device for super::Device { raw_cull_mode: conv::map_cull_mode(desc.primitive.cull_mode), raw_depth_clip_mode: if self.features.contains(wgt::Features::DEPTH_CLIP_CONTROL) { Some(if desc.primitive.unclipped_depth { - metal::MTLDepthClipMode::Clamp + MTLDepthClipMode::Clamp } else { - metal::MTLDepthClipMode::Clip + MTLDepthClipMode::Clip }) } else { None @@ -1269,17 +1395,6 @@ impl crate::Device for super::Device { }) } - unsafe fn create_mesh_pipeline( - &self, - _desc: &crate::MeshPipelineDescriptor< - ::PipelineLayout, - ::ShaderModule, - ::PipelineCache, - >, - ) -> Result<::RenderPipeline, crate::PipelineError> { - unreachable!() - } - unsafe fn destroy_render_pipeline(&self, _pipeline: super::RenderPipeline) { self.counters.render_pipelines.sub(1); } @@ -1295,13 +1410,30 @@ impl crate::Device for super::Device { objc::rc::autoreleasepool(|| { let descriptor = metal::ComputePipelineDescriptor::new(); - let cs = self.load_shader( - &desc.stage, - &[], - desc.layout, - metal::MTLPrimitiveTopologyClass::Unspecified, - naga::ShaderStage::Compute, - )?; + let module = desc.stage.module; + let cs = if let ShaderModuleSource::Passthrough(desc) = &module.source { + CompiledShader { + library: desc.library.clone(), + function: desc.function.clone(), + wg_size: MTLSize::new( + desc.num_workgroups.0 as u64, + desc.num_workgroups.1 as u64, + desc.num_workgroups.2 as u64, + ), + wg_memory_sizes: vec![], + sized_bindings: vec![], + immutable_buffer_mask: 0, + } + } else { + self.load_shader( + &desc.stage, + &[], + desc.layout, + MTLPrimitiveTopologyClass::Unspecified, + naga::ShaderStage::Compute, + )? + }; + descriptor.set_compute_function(Some(&cs.function)); if self.shared.private_caps.supports_mutability { @@ -1330,7 +1462,7 @@ impl crate::Device for super::Device { .map_err(|e| { crate::PipelineError::Linkage( wgt::ShaderStages::COMPUTE, - format!("new_compute_pipeline_state: {:?}", e), + format!("new_compute_pipeline_state: {e:?}"), ) })?; @@ -1366,7 +1498,7 @@ impl crate::Device for super::Device { match desc.ty { wgt::QueryType::Occlusion => { let size = desc.count as u64 * crate::QUERY_SIZE; - let options = metal::MTLResourceOptions::empty(); + let options = MTLResourceOptions::empty(); //TODO: HazardTrackingModeUntracked let raw_buffer = self.shared.device.lock().new_buffer(size, options); if let Some(label) = desc.label { @@ -1381,11 +1513,10 @@ impl crate::Device for super::Device { wgt::QueryType::Timestamp => { let size = desc.count as u64 * crate::QUERY_SIZE; let device = self.shared.device.lock(); - let destination_buffer = - device.new_buffer(size, metal::MTLResourceOptions::empty()); + let destination_buffer = device.new_buffer(size, MTLResourceOptions::empty()); let csb_desc = metal::CounterSampleBufferDescriptor::new(); - csb_desc.set_storage_mode(metal::MTLStorageMode::Shared); + csb_desc.set_storage_mode(MTLStorageMode::Shared); csb_desc.set_sample_count(desc.count as _); if let Some(label) = desc.label { csb_desc.set_label(label); @@ -1397,7 +1528,7 @@ impl crate::Device for super::Device { Some(counter) => counter, None => { log::error!("Failed to obtain timestamp counter set."); - return Err(crate::DeviceError::ResourceCreationFailed); + return Err(crate::DeviceError::Unexpected); } }; csb_desc.set_counter_set(timestamp_counter); @@ -1406,8 +1537,8 @@ impl crate::Device for super::Device { match device.new_counter_sample_buffer_with_descriptor(&csb_desc) { Ok(buffer) => buffer, Err(err) => { - log::error!("Failed to create counter sample buffer: {:?}", err); - return Err(crate::DeviceError::ResourceCreationFailed); + log::error!("Failed to create counter sample buffer: {err:?}"); + return Err(crate::DeviceError::Unexpected); } }; @@ -1451,7 +1582,7 @@ impl crate::Device for super::Device { unsafe fn get_fence_value(&self, fence: &super::Fence) -> DeviceResult { let mut max_value = fence.completed_value.load(atomic::Ordering::Acquire); for &(value, ref cmd_buf) in fence.pending_command_buffers.iter() { - if cmd_buf.status() == metal::MTLCommandBufferStatus::Completed { + if cmd_buf.status() == MTLCommandBufferStatus::Completed { max_value = value; } } @@ -1461,7 +1592,7 @@ impl crate::Device for super::Device { &self, fence: &super::Fence, wait_value: crate::FenceValue, - timeout_ms: u32, + timeout: Option, ) -> DeviceResult { if wait_value <= fence.completed_value.load(atomic::Ordering::Acquire) { return Ok(true); @@ -1474,24 +1605,26 @@ impl crate::Device for super::Device { { Some((_, cmd_buf)) => cmd_buf, None => { - log::error!("No active command buffers for fence value {}", wait_value); + log::error!("No active command buffers for fence value {wait_value}"); return Err(crate::DeviceError::Lost); } }; let start = time::Instant::now(); loop { - if let metal::MTLCommandBufferStatus::Completed = cmd_buf.status() { + if let MTLCommandBufferStatus::Completed = cmd_buf.status() { return Ok(true); } - if start.elapsed().as_millis() >= timeout_ms as u128 { - return Ok(false); + if let Some(timeout) = timeout { + if start.elapsed() >= timeout { + return Ok(false); + } } - thread::sleep(time::Duration::from_millis(1)); + thread::sleep(core::time::Duration::from_millis(1)); } } - unsafe fn start_capture(&self) -> bool { + unsafe fn start_graphics_debugger_capture(&self) -> bool { if !self.shared.private_caps.supports_capture_manager { return false; } @@ -1503,7 +1636,8 @@ impl crate::Device for super::Device { default_capture_scope.begin_scope(); true } - unsafe fn stop_capture(&self) { + + unsafe fn stop_graphics_debugger_capture(&self) { let shared_capture_manager = metal::CaptureManager::shared(); if let Some(default_capture_scope) = shared_capture_manager.default_capture_scope() { default_capture_scope.end_scope(); @@ -1546,4 +1680,10 @@ impl crate::Device for super::Device { fn get_internal_counters(&self) -> wgt::HalCounters { self.counters.as_ref().clone() } + + fn check_if_oom(&self) -> Result<(), crate::DeviceError> { + // TODO: see https://github.com/gfx-rs/wgpu/issues/7460 + + Ok(()) + } } diff --git a/wgpu-hal/src/metal/mod.rs b/wgpu-hal/src/metal/mod.rs index bcec1c95e..e23246a6a 100644 --- a/wgpu-hal/src/metal/mod.rs +++ b/wgpu-hal/src/metal/mod.rs @@ -13,8 +13,6 @@ end of the VS buffer table. !*/ -#![allow(clippy::std_instead_of_alloc, clippy::std_instead_of_core)] - // `MTLFeatureSet` is superseded by `MTLGpuFamily`. // However, `MTLGpuFamily` is only supported starting MacOS 10.15, whereas our minimum target is MacOS 10.13, // See https://github.com/gpuweb/gpuweb/issues/1069 for minimum spec. @@ -28,20 +26,18 @@ mod layer_observer; mod surface; mod time; -use std::{ - borrow::ToOwned as _, - fmt, iter, ops, - ptr::NonNull, - string::String, - sync::{atomic, Arc}, - thread, - vec::Vec, -}; +use alloc::{borrow::ToOwned as _, string::String, sync::Arc, vec::Vec}; +use core::{fmt, iter, ops, ptr::NonNull, sync::atomic}; use arrayvec::ArrayVec; use bitflags::bitflags; use hashbrown::HashMap; -use metal::foreign_types::ForeignTypeRef as _; +use metal::{ + foreign_types::ForeignTypeRef as _, MTLArgumentBuffersTier, MTLBuffer, MTLCommandBufferStatus, + MTLCullMode, MTLDepthClipMode, MTLIndexType, MTLLanguageVersion, MTLPrimitiveType, + MTLReadWriteTextureTier, MTLRenderStages, MTLResource, MTLResourceUsage, MTLSamplerState, + MTLSize, MTLTexture, MTLTextureType, MTLTriangleFillMode, MTLWinding, +}; use naga::FastHashMap; use parking_lot::{Mutex, RwLock}; @@ -51,6 +47,8 @@ pub struct Api; type ResourceIndex = u32; impl crate::Api for Api { + const VARIANT: wgt::Backend = wgt::Backend::Metal; + type Instance = Instance; type Surface = Surface; type Adapter = Adapter; @@ -158,9 +156,11 @@ impl crate::Instance for Instance { vendor: 0, device: 0, device_type: shared.private_caps.device_type(), + device_pci_bus_id: String::new(), driver: String::new(), driver_info: String::new(), backend: wgt::Backend::Metal, + transient_saves_memory: shared.private_caps.supports_memoryless_storage, }, features: shared.private_caps.features(), capabilities: shared.private_caps.capabilities(), @@ -200,14 +200,14 @@ bitflags!( #[derive(Clone, Debug)] struct PrivateCapabilities { family_check: bool, - msl_version: metal::MTLLanguageVersion, + msl_version: MTLLanguageVersion, fragment_rw_storage: bool, - read_write_texture_tier: metal::MTLReadWriteTextureTier, + read_write_texture_tier: MTLReadWriteTextureTier, msaa_desktop: bool, msaa_apple3: bool, msaa_apple7: bool, resource_heaps: bool, - argument_buffers: metal::MTLArgumentBuffersTier, + argument_buffers: MTLArgumentBuffersTier, shared_textures: bool, mutable_comparison_samplers: bool, sampler_clamp_to_border: bool, @@ -230,6 +230,7 @@ struct PrivateCapabilities { format_eac_etc: bool, format_astc: bool, format_astc_hdr: bool, + format_astc_3d: bool, format_any8_unorm_srgb_all: bool, format_any8_unorm_srgb_no_write: bool, format_any8_snorm_all: bool, @@ -301,6 +302,9 @@ struct PrivateCapabilities { int64_atomics: bool, float_atomics: bool, supports_shared_event: bool, + supported_vertex_amplification_factor: u32, + shader_barycentrics: bool, + supports_memoryless_storage: bool, } #[derive(Clone, Debug)] @@ -312,11 +316,19 @@ struct PrivateDisabilities { broken_layered_clear_image: bool, } -#[derive(Debug, Default)] +#[derive(Debug)] struct Settings { retain_command_buffer_references: bool, } +impl Default for Settings { + fn default() -> Self { + Self { + retain_command_buffer_references: true, + } + } +} + struct AdapterShared { device: Mutex, disabilities: PrivateDisabilities, @@ -331,7 +343,7 @@ unsafe impl Sync for AdapterShared {} impl AdapterShared { fn new(device: metal::Device) -> Self { let private_caps = PrivateCapabilities::new(&device); - log::debug!("{:#?}", private_caps); + log::debug!("{private_caps:#?}"); Self { disabilities: PrivateDisabilities::new(&device), @@ -378,7 +390,6 @@ pub struct Surface { render_layer: Mutex, swapchain_format: RwLock>, extent: RwLock, - main_thread_id: thread::ThreadId, // Useful for UI-intensive applications that are sensitive to // window resizing. pub present_with_transaction: bool, @@ -396,13 +407,13 @@ pub struct SurfaceTexture { impl crate::DynSurfaceTexture for SurfaceTexture {} -impl std::borrow::Borrow for SurfaceTexture { +impl core::borrow::Borrow for SurfaceTexture { fn borrow(&self) -> &Texture { &self.texture } } -impl std::borrow::Borrow for SurfaceTexture { +impl core::borrow::Borrow for SurfaceTexture { fn borrow(&self) -> &dyn crate::DynTexture { &self.texture } @@ -525,7 +536,7 @@ impl crate::BufferBinding<'_, Buffer> { pub struct Texture { raw: metal::Texture, format: wgt::TextureFormat, - raw_type: metal::MTLTextureType, + raw_type: MTLTextureType, array_layers: u32, mip_levels: u32, copy_size: crate::CopyExtent, @@ -676,10 +687,10 @@ trait AsNative { fn as_native(&self) -> &Self::Native; } -type ResourcePtr = NonNull; -type BufferPtr = NonNull; -type TexturePtr = NonNull; -type SamplerPtr = NonNull; +type ResourcePtr = NonNull; +type BufferPtr = NonNull; +type TexturePtr = NonNull; +type SamplerPtr = NonNull; impl AsNative for ResourcePtr { type Native = metal::ResourceRef; @@ -750,16 +761,16 @@ struct BufferResource { #[derive(Debug)] struct UseResourceInfo { - uses: metal::MTLResourceUsage, - stages: metal::MTLRenderStages, + uses: MTLResourceUsage, + stages: MTLRenderStages, visible_in_compute: bool, } impl Default for UseResourceInfo { fn default() -> Self { Self { - uses: metal::MTLResourceUsage::empty(), - stages: metal::MTLRenderStages::empty(), + uses: MTLResourceUsage::empty(), + stages: MTLRenderStages::empty(), visible_in_compute: false, } } @@ -781,9 +792,23 @@ impl crate::DynBindGroup for BindGroup {} unsafe impl Send for BindGroup {} unsafe impl Sync for BindGroup {} +#[derive(Debug)] +pub enum ShaderModuleSource { + Naga(crate::NagaShader), + Passthrough(PassthroughShader), +} + +#[derive(Debug)] +pub struct PassthroughShader { + pub library: metal::Library, + pub function: metal::Function, + pub entry_point: String, + pub num_workgroups: (u32, u32, u32), +} + #[derive(Debug)] pub struct ShaderModule { - naga: crate::NagaShader, + source: ShaderModuleSource, bounds_checks: wgt::ShaderRuntimeChecks, } @@ -835,11 +860,11 @@ pub struct RenderPipeline { fs_lib: Option, vs_info: PipelineStageInfo, fs_info: Option, - raw_primitive_type: metal::MTLPrimitiveType, - raw_triangle_fill_mode: metal::MTLTriangleFillMode, - raw_front_winding: metal::MTLWinding, - raw_cull_mode: metal::MTLCullMode, - raw_depth_clip_mode: Option, + raw_primitive_type: MTLPrimitiveType, + raw_triangle_fill_mode: MTLTriangleFillMode, + raw_front_winding: MTLWinding, + raw_cull_mode: MTLCullMode, + raw_depth_clip_mode: Option, depth_stencil: Option<(metal::DepthStencilState, wgt::DepthBiasState)>, } @@ -854,7 +879,7 @@ pub struct ComputePipeline { #[allow(dead_code)] cs_lib: metal::Library, cs_info: PipelineStageInfo, - work_group_size: metal::MTLSize, + work_group_size: MTLSize, work_group_memory_sizes: Vec, } @@ -893,7 +918,7 @@ impl Fence { fn get_latest(&self) -> crate::FenceValue { let mut max_value = self.completed_value.load(atomic::Ordering::Acquire); for &(value, ref cmd_buf) in self.pending_command_buffers.iter() { - if cmd_buf.status() == metal::MTLCommandBufferStatus::Completed { + if cmd_buf.status() == MTLCommandBufferStatus::Completed { max_value = value; } } @@ -915,7 +940,7 @@ struct IndexState { buffer_ptr: BufferPtr, offset: wgt::BufferAddress, stride: wgt::BufferAddress, - raw_type: metal::MTLIndexType, + raw_type: MTLIndexType, } #[derive(Default)] @@ -927,9 +952,9 @@ struct CommandState { blit: Option, render: Option, compute: Option, - raw_primitive_type: metal::MTLPrimitiveType, + raw_primitive_type: MTLPrimitiveType, index: Option, - raw_wg_size: metal::MTLSize, + raw_wg_size: MTLSize, stage_infos: MultiStageData, /// Sizes of currently bound [`wgt::BufferBindingType::Storage`] buffers. diff --git a/wgpu-hal/src/metal/surface.rs b/wgpu-hal/src/metal/surface.rs index 29dbc19b0..2a705cd79 100644 --- a/wgpu-hal/src/metal/surface.rs +++ b/wgpu-hal/src/metal/surface.rs @@ -1,15 +1,14 @@ #![allow(clippy::let_unit_value)] // `let () =` being used to constrain result type -use std::borrow::ToOwned as _; -use std::mem::ManuallyDrop; -use std::ptr::NonNull; -use std::thread; +use alloc::borrow::ToOwned as _; +use core::mem::ManuallyDrop; +use core::ptr::NonNull; use core_graphics_types::{ base::CGFloat, geometry::{CGRect, CGSize}, }; -use metal::foreign_types::ForeignType; +use metal::{foreign_types::ForeignType, MTLTextureType}; use objc::{ class, msg_send, rc::{autoreleasepool, StrongPtr}, @@ -29,7 +28,6 @@ impl super::Surface { render_layer: Mutex::new(layer), swapchain_format: RwLock::new(None), extent: RwLock::new(wgt::Extent3d::default()), - main_thread_id: thread::current().id(), present_with_transaction: false, } } @@ -109,6 +107,13 @@ impl super::Surface { } } + /// Gets the current dimensions of the `Surface`. + /// + /// This function is safe to call off of the main thread. However, note that + /// `bounds` and `contentsScale` may be modified by the main thread while + /// this function is running, possibly resulting in the two values being out + /// of sync. This is sound, as these properties are accessed atomically. + /// See: pub(super) fn dimensions(&self) -> wgt::Extent3d { let (size, scale): (CGSize, CGFloat) = unsafe { let render_layer_borrow = self.render_layer.lock(); @@ -134,7 +139,7 @@ impl crate::Surface for super::Surface { device: &super::Device, config: &crate::SurfaceConfiguration, ) -> Result<(), crate::SurfaceError> { - log::debug!("build swapchain {:?}", config); + log::debug!("build swapchain {config:?}"); let caps = &device.shared.private_caps; *self.swapchain_format.write() = Some(config.format); @@ -186,7 +191,7 @@ impl crate::Surface for super::Surface { unsafe fn acquire_texture( &self, - _timeout_ms: Option, //TODO + _timeout_ms: Option, //TODO _fence: &super::Fence, ) -> Result>, crate::SurfaceError> { let render_layer = self.render_layer.lock(); @@ -205,7 +210,7 @@ impl crate::Surface for super::Surface { texture: super::Texture { raw: texture, format: swapchain_format, - raw_type: metal::MTLTextureType::D2, + raw_type: MTLTextureType::D2, array_layers: 1, mip_levels: 1, copy_size: crate::CopyExtent { diff --git a/wgpu-hal/src/noop/buffer.rs b/wgpu-hal/src/noop/buffer.rs index 6e9572ef8..9b8ab17a1 100644 --- a/wgpu-hal/src/noop/buffer.rs +++ b/wgpu-hal/src/noop/buffer.rs @@ -1,6 +1,14 @@ -use alloc::{sync::Arc, vec::Vec}; +use alloc::vec::Vec; use core::{cell::UnsafeCell, ops::Range, ptr}; +cfg_if::cfg_if! { + if #[cfg(supports_ptr_atomics)] { + use alloc::sync::Arc; + } else if #[cfg(feature = "portable-atomic")] { + use portable_atomic_util::Arc; + } +} + #[derive(Clone, Debug)] pub struct Buffer { /// This data is potentially accessed mutably in arbitrary non-overlapping slices, diff --git a/wgpu-hal/src/noop/command.rs b/wgpu-hal/src/noop/command.rs index 36b5c9216..f188566d9 100644 --- a/wgpu-hal/src/noop/command.rs +++ b/wgpu-hal/src/noop/command.rs @@ -146,7 +146,11 @@ impl crate::CommandEncoder for CommandBuffer { // render - unsafe fn begin_render_pass(&mut self, desc: &crate::RenderPassDescriptor) { + unsafe fn begin_render_pass( + &mut self, + desc: &crate::RenderPassDescriptor, + ) -> DeviceResult<()> { + Ok(()) } unsafe fn end_render_pass(&mut self) {} diff --git a/wgpu-hal/src/noop/mod.rs b/wgpu-hal/src/noop/mod.rs index f5f985392..b6c110df8 100644 --- a/wgpu-hal/src/noop/mod.rs +++ b/wgpu-hal/src/noop/mod.rs @@ -31,6 +31,8 @@ pub struct Fence { type DeviceResult = Result; impl crate::Api for Api { + const VARIANT: wgt::Backend = wgt::Backend::Noop; + type Instance = Context; type Surface = Context; type Adapter = Context; @@ -95,6 +97,7 @@ impl crate::Instance for Context { }, name: _, flags: _, + memory_budget_thresholds: _, } = *desc; if enable { Ok(Context) @@ -117,22 +120,36 @@ impl crate::Instance for Context { ) -> Vec> { vec![crate::ExposedAdapter { adapter: Context, - info: wgt::AdapterInfo { - name: String::from("noop wgpu backend"), - vendor: 0, - device: 0, - device_type: wgt::DeviceType::Cpu, - driver: String::from("wgpu"), - driver_info: String::new(), - backend: wgt::Backend::Noop, - }, + info: adapter_info(), features: wgt::Features::all(), capabilities: CAPABILITIES, }] } } -const CAPABILITIES: crate::Capabilities = { +/// Returns the adapter info for the noop backend. +/// +/// This is used in the test harness to construct info about +/// the noop backend adapter without actually initializing wgpu. +pub fn adapter_info() -> wgt::AdapterInfo { + wgt::AdapterInfo { + name: String::from("noop wgpu backend"), + vendor: 0, + device: 0, + device_type: wgt::DeviceType::Cpu, + device_pci_bus_id: String::new(), + driver: String::from("wgpu"), + driver_info: String::new(), + backend: wgt::Backend::Noop, + transient_saves_memory: false, + } +} + +/// The capabilities of the noop backend. +/// +/// This is used in the test harness to construct capabilities +/// of the noop backend without actually initializing wgpu. +pub const CAPABILITIES: crate::Capabilities = { /// Guaranteed to be no bigger than isize::MAX which is the maximum size of an allocation, /// except on 16-bit platforms which we certainly don’t fit in. const ALLOC_MAX_U32: u32 = i32::MAX as u32; @@ -176,6 +193,18 @@ const CAPABILITIES: crate::Capabilities = { max_subgroup_size: ALLOC_MAX_U32, max_push_constant_size: ALLOC_MAX_U32, max_non_sampler_bindings: ALLOC_MAX_U32, + + max_task_workgroup_total_count: ALLOC_MAX_U32, + max_task_workgroups_per_dimension: ALLOC_MAX_U32, + max_mesh_multiview_view_count: ALLOC_MAX_U32, + max_mesh_output_layers: ALLOC_MAX_U32, + + max_blas_primitive_count: ALLOC_MAX_U32, + max_blas_geometry_count: ALLOC_MAX_U32, + max_tlas_instance_count: ALLOC_MAX_U32, + max_acceleration_structures_per_shader_stage: ALLOC_MAX_U32, + + max_multiview_view_count: ALLOC_MAX_U32, }, alignments: crate::Alignments { // All maximally permissive @@ -368,16 +397,6 @@ impl crate::Device for Context { ) -> Result { Ok(Resource) } - unsafe fn create_mesh_pipeline( - &self, - desc: &crate::MeshPipelineDescriptor< - ::PipelineLayout, - ::ShaderModule, - ::PipelineCache, - >, - ) -> Result<::RenderPipeline, crate::PipelineError> { - Ok(Resource) - } unsafe fn destroy_render_pipeline(&self, pipeline: Resource) {} unsafe fn create_compute_pipeline( &self, @@ -414,7 +433,7 @@ impl crate::Device for Context { &self, fence: &Fence, value: crate::FenceValue, - timeout_ms: u32, + timeout: Option, ) -> DeviceResult { // The relevant commands must have already been submitted, and noop-backend commands are // executed synchronously, so there is no waiting — either it is already done, @@ -426,10 +445,10 @@ impl crate::Device for Context { Ok(true) } - unsafe fn start_capture(&self) -> bool { + unsafe fn start_graphics_debugger_capture(&self) -> bool { false } - unsafe fn stop_capture(&self) {} + unsafe fn stop_graphics_debugger_capture(&self) {} unsafe fn create_acceleration_structure( &self, desc: &crate::AccelerationStructureDescriptor, @@ -457,4 +476,8 @@ impl crate::Device for Context { fn get_internal_counters(&self) -> wgt::HalCounters { Default::default() } + + fn check_if_oom(&self) -> DeviceResult<()> { + Ok(()) + } } diff --git a/wgpu-hal/src/validation_canary.rs b/wgpu-hal/src/validation_canary.rs new file mode 100644 index 000000000..37e417548 --- /dev/null +++ b/wgpu-hal/src/validation_canary.rs @@ -0,0 +1,39 @@ +use alloc::{string::String, vec::Vec}; + +use parking_lot::Mutex; + +/// Stores the text of any validation errors that have occurred since +/// the last call to `get_and_reset`. +/// +/// Each value is a validation error and a message associated with it, +/// or `None` if the error has no message from the api. +/// +/// This is used for internal wgpu testing only and _must not_ be used +/// as a way to check for errors. +/// +/// This works as a static because `cargo nextest` runs all of our +/// tests in separate processes, so each test gets its own canary. +/// +/// This prevents the issue of one validation error terminating the +/// entire process. +pub static VALIDATION_CANARY: ValidationCanary = ValidationCanary { + inner: Mutex::new(Vec::new()), +}; + +/// Flag for internal testing. +pub struct ValidationCanary { + inner: Mutex>, +} + +impl ValidationCanary { + #[allow(dead_code)] // in some configurations this function is dead + pub(crate) fn add(&self, msg: String) { + self.inner.lock().push(msg); + } + + /// Returns any API validation errors that have occurred in this process + /// since the last call to this function. + pub fn get_and_reset(&self) -> Vec { + self.inner.lock().drain(..).collect() + } +} diff --git a/wgpu-hal/src/vulkan/adapter.rs b/wgpu-hal/src/vulkan/adapter.rs index a43840127..dbd61694f 100644 --- a/wgpu-hal/src/vulkan/adapter.rs +++ b/wgpu-hal/src/vulkan/adapter.rs @@ -1,9 +1,12 @@ -use std::{borrow::ToOwned as _, collections::BTreeMap, ffi::CStr, sync::Arc, vec::Vec}; +use alloc::{borrow::ToOwned as _, boxed::Box, collections::BTreeMap, sync::Arc, vec::Vec}; +use core::{ffi::CStr, marker::PhantomData}; -use ash::{amd, ext, google, khr, vk}; +use ash::{ext, google, khr, vk}; use parking_lot::Mutex; -use super::conv; +use crate::vulkan::semaphore_list::SemaphoreList; + +use super::semaphore_list::SemaphoreListMode; fn depth_stencil_required_flags() -> vk::FormatFeatureFlags { vk::FormatFeatureFlags::SAMPLED_IMAGE | vk::FormatFeatureFlags::DEPTH_STENCIL_ATTACHMENT @@ -16,7 +19,7 @@ const INDEXING_FEATURES: wgt::Features = wgt::Features::TEXTURE_BINDING_ARRAY .union(wgt::Features::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING) .union(wgt::Features::UNIFORM_BUFFER_BINDING_ARRAYS) .union(wgt::Features::PARTIALLY_BOUND_BINDING_ARRAY); - +#[expect(rustdoc::private_intra_doc_links)] /// Features supported by a [`vk::PhysicalDevice`] and its extensions. /// /// This is used in two phases: @@ -43,9 +46,6 @@ pub struct PhysicalDeviceFeatures { pub(super) descriptor_indexing: Option>, - /// Features provided by `VK_KHR_imageless_framebuffer`, promoted to Vulkan 1.2. - imageless_framebuffer: Option>, - /// Features provided by `VK_KHR_timeline_semaphore`, promoted to Vulkan 1.2 timeline_semaphore: Option>, @@ -64,13 +64,11 @@ pub struct PhysicalDeviceFeatures { /// Features provided by `VK_EXT_texture_compression_astc_hdr`, promoted to Vulkan 1.3. astc_hdr: Option>, - /// Features provided by `VK_KHR_shader_float16_int8` (promoted to Vulkan - /// 1.2) and `VK_KHR_16bit_storage` (promoted to Vulkan 1.1). We use these - /// features together, or not at all. - shader_float16: Option<( - vk::PhysicalDeviceShaderFloat16Int8Features<'static>, - vk::PhysicalDevice16BitStorageFeatures<'static>, - )>, + /// Features provided by `VK_KHR_shader_float16_int8`, promoted to Vulkan 1.2 + shader_float16_int8: Option>, + + /// Features provided by `VK_KHR_16bit_storage`, promoted to Vulkan 1.1 + _16bit_storage: Option>, /// Features provided by `VK_KHR_acceleration_structure`. acceleration_structure: Option>, @@ -78,17 +76,17 @@ pub struct PhysicalDeviceFeatures { /// Features provided by `VK_KHR_buffer_device_address`, promoted to Vulkan 1.2. /// /// We only use this feature for - /// [`Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE`], which requires + /// [`Features::EXPERIMENTAL_RAY_QUERY`], which requires /// `VK_KHR_acceleration_structure`, which depends on /// `VK_KHR_buffer_device_address`, so [`Instance::expose_adapter`] only /// bothers to check if `VK_KHR_acceleration_structure` is available, /// leaving this `None`. /// /// However, we do populate this when creating a device if - /// [`Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE`] is requested. + /// [`Features::EXPERIMENTAL_RAY_QUERY`] is requested. /// /// [`Instance::expose_adapter`]: super::Instance::expose_adapter - /// [`Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE`]: wgt::Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE + /// [`Features::EXPERIMENTAL_RAY_QUERY`]: wgt::Features::EXPERIMENTAL_RAY_QUERY buffer_device_address: Option>, /// Features provided by `VK_KHR_ray_query`, @@ -125,9 +123,20 @@ pub struct PhysicalDeviceFeatures { /// Features proved by `VK_EXT_mesh_shader` mesh_shader: Option>, + + /// Features provided by `VK_KHR_shader_integer_dot_product`, promoted to Vulkan 1.3. + shader_integer_dot_product: + Option>, + + /// Features provided by `VK_KHR_fragment_shader_barycentric` + shader_barycentrics: Option>, } impl PhysicalDeviceFeatures { + pub fn get_core(&self) -> vk::PhysicalDeviceFeatures { + self.core + } + /// Add the members of `self` into `info.enabled_features` and its `p_next` chain. pub fn add_to_device_create<'a>( &'a mut self, @@ -137,9 +146,6 @@ impl PhysicalDeviceFeatures { if let Some(ref mut feature) = self.descriptor_indexing { info = info.push_next(feature); } - if let Some(ref mut feature) = self.imageless_framebuffer { - info = info.push_next(feature); - } if let Some(ref mut feature) = self.timeline_semaphore { info = info.push_next(feature); } @@ -155,9 +161,11 @@ impl PhysicalDeviceFeatures { if let Some(ref mut feature) = self.astc_hdr { info = info.push_next(feature); } - if let Some((ref mut f16_i8_feature, ref mut _16bit_feature)) = self.shader_float16 { - info = info.push_next(f16_i8_feature); - info = info.push_next(_16bit_feature); + if let Some(ref mut feature) = self.shader_float16_int8 { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self._16bit_storage { + info = info.push_next(feature); } if let Some(ref mut feature) = self.zero_initialize_workgroup_memory { info = info.push_next(feature); @@ -192,9 +200,22 @@ impl PhysicalDeviceFeatures { if let Some(ref mut feature) = self.mesh_shader { info = info.push_next(feature); } + if let Some(ref mut feature) = self.shader_integer_dot_product { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.shader_barycentrics { + info = info.push_next(feature); + } info } + fn supports_storage_input_output_16(&self) -> bool { + self._16bit_storage + .as_ref() + .map(|features| features.storage_input_output16 != 0) + .unwrap_or(false) + } + /// Create a `PhysicalDeviceFeatures` that can be used to create a logical /// device. /// @@ -223,7 +244,7 @@ impl PhysicalDeviceFeatures { /// [`Adapter::required_device_extensions`]: super::Adapter::required_device_extensions fn from_extensions_and_requested_features( phd_capabilities: &PhysicalDeviceProperties, - _phd_features: &PhysicalDeviceFeatures, + phd_features: &PhysicalDeviceFeatures, enabled_extensions: &[&'static CStr], requested_features: wgt::Features, downlevel_flags: wgt::DownlevelFlags, @@ -256,9 +277,7 @@ impl PhysicalDeviceFeatures { requested_features.contains(wgt::Features::INDIRECT_FIRST_INSTANCE), ) //.dual_src_blend(requested_features.contains(wgt::Features::DUAL_SRC_BLENDING)) - .multi_draw_indirect( - requested_features.contains(wgt::Features::MULTI_DRAW_INDIRECT), - ) + .multi_draw_indirect(phd_features.core.multi_draw_indirect != 0) .fill_mode_non_solid(requested_features.intersects( wgt::Features::POLYGON_MODE_LINE | wgt::Features::POLYGON_MODE_POINT, )) @@ -305,7 +324,7 @@ impl PhysicalDeviceFeatures { | wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY, )) //.shader_storage_image_array_dynamic_indexing( - //.shader_clip_distance(requested_features.contains(wgt::Features::SHADER_CLIP_DISTANCE)) + .shader_clip_distance(requested_features.contains(wgt::Features::CLIP_DISTANCES)) //.shader_cull_distance(requested_features.contains(wgt::Features::SHADER_CULL_DISTANCE)) .shader_float64(requested_features.contains(wgt::Features::SHADER_F64)) .shader_int64(requested_features.contains(wgt::Features::SHADER_INT64)) @@ -328,16 +347,6 @@ impl PhysicalDeviceFeatures { } else { None }, - imageless_framebuffer: if device_api_version >= vk::API_VERSION_1_2 - || enabled_extensions.contains(&khr::imageless_framebuffer::NAME) - { - Some( - vk::PhysicalDeviceImagelessFramebufferFeaturesKHR::default() - .imageless_framebuffer(private_caps.imageless_framebuffers), - ) - } else { - None - }, timeline_semaphore: if device_api_version >= vk::API_VERSION_1_2 || enabled_extensions.contains(&khr::timeline_semaphore::NAME) { @@ -394,14 +403,21 @@ impl PhysicalDeviceFeatures { } else { None }, - shader_float16: if requested_features.contains(wgt::Features::SHADER_F16) { - Some(( - vk::PhysicalDeviceShaderFloat16Int8Features::default().shader_float16(true), + shader_float16_int8: match requested_features.contains(wgt::Features::SHADER_F16) { + shader_float16 if shader_float16 || private_caps.shader_int8 => Some( + vk::PhysicalDeviceShaderFloat16Int8Features::default() + .shader_float16(shader_float16) + .shader_int8(private_caps.shader_int8), + ), + _ => None, + }, + _16bit_storage: if requested_features.contains(wgt::Features::SHADER_F16) { + Some( vk::PhysicalDevice16BitStorageFeatures::default() .storage_buffer16_bit_access(true) - .storage_input_output16(true) + .storage_input_output16(phd_features.supports_storage_input_output_16()) .uniform_and_storage_buffer16_bit_access(true), - )) + ) } else { None }, @@ -514,6 +530,27 @@ impl PhysicalDeviceFeatures { } else { None }, + shader_integer_dot_product: if device_api_version >= vk::API_VERSION_1_3 + || enabled_extensions.contains(&khr::shader_integer_dot_product::NAME) + { + Some( + vk::PhysicalDeviceShaderIntegerDotProductFeaturesKHR::default() + .shader_integer_dot_product(private_caps.shader_integer_dot_product), + ) + } else { + None + }, + shader_barycentrics: if enabled_extensions + .contains(&khr::fragment_shader_barycentric::NAME) + { + let needed = requested_features.intersects(wgt::Features::SHADER_BARYCENTRICS); + Some( + vk::PhysicalDeviceFragmentShaderBarycentricFeaturesKHR::default() + .fragment_shader_barycentric(needed), + ) + } else { + None + }, } } @@ -533,7 +570,6 @@ impl PhysicalDeviceFeatures { ) -> (wgt::Features, wgt::DownlevelFlags) { use wgt::{DownlevelFlags as Df, Features as F}; let mut features = F::empty() - | F::SPIRV_SHADER_PASSTHROUGH | F::MAPPABLE_PRIMARY_BUFFERS | F::PUSH_CONSTANTS | F::ADDRESS_MODE_CLAMP_TO_BORDER @@ -544,7 +580,9 @@ impl PhysicalDeviceFeatures { | F::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES | F::CLEAR_TEXTURE | F::PIPELINE_CACHE - | F::TEXTURE_ATOMIC; + | F::SHADER_EARLY_DEPTH_TEST + | F::TEXTURE_ATOMIC + | F::EXPERIMENTAL_PASSTHROUGH_SHADERS; let mut dl_flags = Df::COMPUTE_SHADERS | Df::BASE_VERTEX @@ -560,7 +598,7 @@ impl PhysicalDeviceFeatures { | Df::VIEW_FORMATS | Df::UNRESTRICTED_EXTERNAL_TEXTURE_COPIES | Df::NONBLOCKING_QUERY_RESOLVE - | Df::VERTEX_AND_INSTANCE_INDEX_RESPECTS_RESPECTIVE_FIRST_VALUE_IN_INDIRECT_DRAW; + | Df::SHADER_F16_IN_F32; dl_flags.set( Df::SURFACE_VIEW_FORMATS, @@ -585,7 +623,6 @@ impl PhysicalDeviceFeatures { self.core.draw_indirect_first_instance != 0, ); //if self.core.dual_src_blend != 0 - features.set(F::MULTI_DRAW_INDIRECT, self.core.multi_draw_indirect != 0); features.set(F::POLYGON_MODE_LINE, self.core.fill_mode_non_solid != 0); features.set(F::POLYGON_MODE_POINT, self.core.fill_mode_non_solid != 0); //if self.core.depth_bounds != 0 { @@ -648,6 +685,13 @@ impl PhysicalDeviceFeatures { ); } + if let Some(ref shader_barycentrics) = self.shader_barycentrics { + features.set( + F::SHADER_BARYCENTRICS, + shader_barycentrics.fragment_shader_barycentric != 0, + ); + } + //if caps.supports_extension(khr::sampler_mirror_clamp_to_edge::NAME) { //if caps.supports_extension(ext::sampler_filter_minmax::NAME) { features.set( @@ -699,9 +743,11 @@ impl PhysicalDeviceFeatures { features.set(F::DEPTH_CLIP_CONTROL, self.core.depth_clamp != 0); features.set(F::DUAL_SOURCE_BLENDING, self.core.dual_src_blend != 0); + features.set(F::CLIP_DISTANCES, self.core.shader_clip_distance != 0); if let Some(ref multiview) = self.multiview { features.set(F::MULTIVIEW, multiview.multiview != 0); + features.set(F::SELECTIVE_MULTIVIEW, multiview.multiview != 0); } features.set( @@ -716,13 +762,22 @@ impl PhysicalDeviceFeatures { ); } - if let Some((ref f16_i8, ref bit16)) = self.shader_float16 { + if self.core.texture_compression_astc_ldr != 0 { + features.set( + F::TEXTURE_COMPRESSION_ASTC_SLICED_3D, + supports_astc_3d(instance, phd), + ); + } + + if let (Some(ref f16_i8), Some(ref bit16)) = (self.shader_float16_int8, self._16bit_storage) + { + // Note `storage_input_output16` is not required, we polyfill `f16` I/O using `f32` + // types when this capability is not available features.set( F::SHADER_F16, f16_i8.shader_float16 != 0 && bit16.storage_buffer16_bit_access != 0 - && bit16.uniform_and_storage_buffer16_bit_access != 0 - && bit16.storage_input_output16 != 0, + && bit16.uniform_and_storage_buffer16_bit_access != 0, ); } @@ -735,7 +790,8 @@ impl PhysicalDeviceFeatures { | vk::SubgroupFeatureFlags::ARITHMETIC | vk::SubgroupFeatureFlags::BALLOT | vk::SubgroupFeatureFlags::SHUFFLE - | vk::SubgroupFeatureFlags::SHUFFLE_RELATIVE, + | vk::SubgroupFeatureFlags::SHUFFLE_RELATIVE + | vk::SubgroupFeatureFlags::QUAD, ) { features.set( @@ -779,16 +835,17 @@ impl PhysicalDeviceFeatures { features.set(F::DEPTH32FLOAT_STENCIL8, texture_d32_s8); - features.set( - F::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE, - caps.supports_extension(khr::deferred_host_operations::NAME) - && caps.supports_extension(khr::acceleration_structure::NAME) - && caps.supports_extension(khr::buffer_device_address::NAME), - ); + let supports_acceleration_structures = caps + .supports_extension(khr::deferred_host_operations::NAME) + && caps.supports_extension(khr::acceleration_structure::NAME) + && caps.supports_extension(khr::buffer_device_address::NAME); features.set( - F::EXPERIMENTAL_RAY_QUERY, - caps.supports_extension(khr::ray_query::NAME), + F::EXPERIMENTAL_RAY_QUERY + // Although this doesn't really require ray queries, it does not make sense to be enabled if acceleration structures + // aren't enabled. + | F::EXTENDED_ACCELERATION_STRUCTURE_VERTEX_FORMATS, + supports_acceleration_structures && caps.supports_extension(khr::ray_query::NAME), ); let rg11b10ufloat_renderable = supports_format( @@ -829,6 +886,24 @@ impl PhysicalDeviceFeatures { ); } + if let Some(ref _sampler_ycbcr_conversion) = self.sampler_ycbcr_conversion { + features.set( + F::TEXTURE_FORMAT_P010, + supports_format( + instance, + phd, + vk::Format::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16, + vk::ImageTiling::OPTIMAL, + vk::FormatFeatureFlags::SAMPLED_IMAGE + | vk::FormatFeatureFlags::TRANSFER_SRC + | vk::FormatFeatureFlags::TRANSFER_DST, + ) && !caps + .driver + .map(|driver| driver.driver_id == vk::DriverId::MOLTENVK) + .unwrap_or_default(), + ); + } + features.set( F::VULKAN_GOOGLE_DISPLAY_TIMING, caps.supports_extension(google::display_timing::NAME), @@ -911,7 +986,14 @@ pub struct PhysicalDeviceProperties { /// Additional `vk::PhysicalDevice` properties from the /// `VK_EXT_mesh_shader` extension. - _mesh_shader: Option>, + mesh_shader: Option>, + + /// Additional `vk::PhysicalDevice` properties from the + /// `VK_KHR_multiview` extension. + multiview: Option>, + + /// `VK_EXT_pci_bus_info` extension. + pci_bus_info: Option>, /// The device API version. /// @@ -943,13 +1025,8 @@ impl PhysicalDeviceProperties { extensions.push(khr::swapchain::NAME); if self.device_api_version < vk::API_VERSION_1_1 { - // Require either `VK_KHR_maintenance1` or `VK_AMD_negative_viewport_height` - if self.supports_extension(khr::maintenance1::NAME) { - extensions.push(khr::maintenance1::NAME); - } else { - // `VK_AMD_negative_viewport_height` is obsoleted by `VK_KHR_maintenance1` and must not be enabled alongside it - extensions.push(amd::negative_viewport_height::NAME); - } + // Require `VK_KHR_maintenance1` + extensions.push(khr::maintenance1::NAME); // Optional `VK_KHR_maintenance2` if self.supports_extension(khr::maintenance2::NAME) { @@ -973,6 +1050,15 @@ impl PhysicalDeviceProperties { if requested_features.contains(wgt::Features::TEXTURE_FORMAT_NV12) { extensions.push(khr::sampler_ycbcr_conversion::NAME); } + + // Require `VK_KHR_16bit_storage` if the feature `SHADER_F16` was requested + if requested_features.contains(wgt::Features::SHADER_F16) { + // - Feature `SHADER_F16` also requires `VK_KHR_shader_float16_int8`, but we always + // require that anyway (if it is available) below. + // - `VK_KHR_16bit_storage` requires `VK_KHR_storage_buffer_storage_class`, however + // we require that one already. + extensions.push(khr::_16bit_storage::NAME); + } } if self.device_api_version < vk::API_VERSION_1_2 { @@ -981,15 +1067,6 @@ impl PhysicalDeviceProperties { extensions.push(khr::image_format_list::NAME); } - // Optional `VK_KHR_imageless_framebuffer` - if self.supports_extension(khr::imageless_framebuffer::NAME) { - extensions.push(khr::imageless_framebuffer::NAME); - // Require `VK_KHR_maintenance2` due to it being a dependency - if self.device_api_version < vk::API_VERSION_1_1 { - extensions.push(khr::maintenance2::NAME); - } - } - // Optional `VK_KHR_driver_properties` if self.supports_extension(khr::driver_properties::NAME) { extensions.push(khr::driver_properties::NAME); @@ -1005,13 +1082,13 @@ impl PhysicalDeviceProperties { extensions.push(ext::descriptor_indexing::NAME); } - // Require `VK_KHR_shader_float16_int8` and `VK_KHR_16bit_storage` if the associated feature was requested - if requested_features.contains(wgt::Features::SHADER_F16) { + // Always require `VK_KHR_shader_float16_int8` if available as it enables + // Int8 optimizations. Also require it even if it's not available but + // requested so that we get a corresponding error message. + if requested_features.contains(wgt::Features::SHADER_F16) + || self.supports_extension(khr::shader_float16_int8::NAME) + { extensions.push(khr::shader_float16_int8::NAME); - // `VK_KHR_16bit_storage` requires `VK_KHR_storage_buffer_storage_class`, however we require that one already - if self.device_api_version < vk::API_VERSION_1_1 { - extensions.push(khr::_16bit_storage::NAME); - } } if requested_features.intersects(wgt::Features::EXPERIMENTAL_MESH_SHADER) { @@ -1036,6 +1113,11 @@ impl PhysicalDeviceProperties { if requested_features.intersects(wgt::Features::EXPERIMENTAL_MESH_SHADER) { extensions.push(khr::maintenance4::NAME); } + + // Optional `VK_KHR_shader_integer_dot_product` + if self.supports_extension(khr::shader_integer_dot_product::NAME) { + extensions.push(khr::shader_integer_dot_product::NAME); + } } // Optional `VK_KHR_swapchain_mutable_format` @@ -1063,6 +1145,13 @@ impl PhysicalDeviceProperties { extensions.push(ext::external_memory_dma_buf::NAME); } + // Optional `VK_EXT_memory_budget` + if self.supports_extension(ext::memory_budget::NAME) { + extensions.push(ext::memory_budget::NAME); + } else { + log::warn!("VK_EXT_memory_budget is not available.") + } + // Require `VK_KHR_draw_indirect_count` if the associated feature was requested // Even though Vulkan 1.2 has promoted the extension to core, we must require the extension to avoid // large amounts of spaghetti involved with using PhysicalDeviceVulkan12Features. @@ -1070,17 +1159,11 @@ impl PhysicalDeviceProperties { extensions.push(khr::draw_indirect_count::NAME); } - // Require `VK_KHR_deferred_host_operations`, `VK_KHR_acceleration_structure` and `VK_KHR_buffer_device_address` if the feature `RAY_TRACING` was requested - if requested_features - .contains(wgt::Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE) - { + // Require `VK_KHR_deferred_host_operations`, `VK_KHR_acceleration_structure` `VK_KHR_buffer_device_address` (for acceleration structures) and`VK_KHR_ray_query` if `EXPERIMENTAL_RAY_QUERY` was requested + if requested_features.contains(wgt::Features::EXPERIMENTAL_RAY_QUERY) { extensions.push(khr::deferred_host_operations::NAME); extensions.push(khr::acceleration_structure::NAME); extensions.push(khr::buffer_device_address::NAME); - } - - // Require `VK_KHR_ray_query` if the associated feature was requested - if requested_features.contains(wgt::Features::EXPERIMENTAL_RAY_QUERY) { extensions.push(khr::ray_query::NAME); } @@ -1128,6 +1211,11 @@ impl PhysicalDeviceProperties { extensions.push(ext::mesh_shader::NAME); } + // Require `VK_KHR_fragment_shader_barycentric` if the associated feature was requested + if requested_features.intersects(wgt::Features::SHADER_BARYCENTRICS) { + extensions.push(khr::fragment_shader_barycentric::NAME); + } + extensions } @@ -1138,14 +1226,29 @@ impl PhysicalDeviceProperties { let max_compute_workgroups_per_dimension = limits.max_compute_work_group_count[0] .min(limits.max_compute_work_group_count[1]) .min(limits.max_compute_work_group_count[2]); + let ( + max_task_workgroup_total_count, + max_task_workgroups_per_dimension, + max_mesh_multiview_view_count, + max_mesh_output_layers, + ) = match self.mesh_shader { + Some(m) => ( + m.max_task_work_group_total_count, + m.max_task_work_group_count.into_iter().min().unwrap(), + m.max_mesh_multiview_view_count, + m.max_mesh_output_layers, + ), + None => (0, 0, 0, 0), + }; - // Prevent very large buffers on mesa and most android devices. + // Prevent very large buffers on mesa and most android devices, and in all cases + // don't risk confusing JS by exceeding the range of a double. let is_nvidia = self.properties.vendor_id == crate::auxil::db::nvidia::VENDOR; let max_buffer_size = if (cfg!(target_os = "linux") || cfg!(target_os = "android")) && !is_nvidia { i32::MAX as u64 } else { - u64::MAX + 1u64 << 52 }; let mut max_binding_array_elements = 0; @@ -1176,6 +1279,23 @@ impl PhysicalDeviceProperties { let max_color_attachment_bytes_per_sample = limits.max_color_attachments * wgt::TextureFormat::MAX_TARGET_PIXEL_BYTE_COST; + let mut max_blas_geometry_count = 0; + let mut max_blas_primitive_count = 0; + let mut max_tlas_instance_count = 0; + let mut max_acceleration_structures_per_shader_stage = 0; + if let Some(properties) = self.acceleration_structure { + max_blas_geometry_count = properties.max_geometry_count as u32; + max_blas_primitive_count = properties.max_primitive_count as u32; + max_tlas_instance_count = properties.max_instance_count as u32; + max_acceleration_structures_per_shader_stage = + properties.max_per_stage_descriptor_acceleration_structures; + } + + let max_multiview_view_count = self + .multiview + .map(|a| a.max_multiview_view_count.min(32)) + .unwrap_or(0); + wgt::Limits { max_texture_dimension_1d: limits.max_image_dimension1_d, max_texture_dimension_2d: limits.max_image_dimension2_d, @@ -1233,6 +1353,18 @@ impl PhysicalDeviceProperties { max_compute_workgroups_per_dimension, max_buffer_size, max_non_sampler_bindings: u32::MAX, + + max_task_workgroup_total_count, + max_task_workgroups_per_dimension, + max_mesh_multiview_view_count, + max_mesh_output_layers, + + max_blas_primitive_count, + max_blas_geometry_count, + max_tlas_instance_count, + max_acceleration_structures_per_shader_stage, + + max_multiview_view_count, } } @@ -1291,6 +1423,9 @@ impl super::InstanceShared { capabilities.properties = unsafe { self.raw.get_physical_device_properties(phd) }; capabilities.device_api_version = capabilities.properties.api_version; + let supports_multiview = capabilities.device_api_version >= vk::API_VERSION_1_1 + || capabilities.supports_extension(khr::multiview::NAME); + if let Some(ref get_device_properties) = self.get_physical_device_properties { // Get these now to avoid borrowing conflicts later let supports_maintenance3 = capabilities.device_api_version >= vk::API_VERSION_1_1 @@ -1305,6 +1440,8 @@ impl super::InstanceShared { >= vk::API_VERSION_1_3 || capabilities.supports_extension(ext::subgroup_size_control::NAME); let supports_robustness2 = capabilities.supports_extension(ext::robustness2::NAME); + let supports_pci_bus_info = + capabilities.supports_extension(ext::pci_bus_info::NAME); let supports_acceleration_structure = capabilities.supports_extension(khr::acceleration_structure::NAME); @@ -1361,13 +1498,27 @@ impl super::InstanceShared { properties2 = properties2.push_next(next); } + if supports_pci_bus_info { + let next = capabilities + .pci_bus_info + .insert(vk::PhysicalDevicePCIBusInfoPropertiesEXT::default()); + properties2 = properties2.push_next(next); + } + if supports_mesh_shader { let next = capabilities - ._mesh_shader + .mesh_shader .insert(vk::PhysicalDeviceMeshShaderPropertiesEXT::default()); properties2 = properties2.push_next(next); } + if supports_multiview { + let next = capabilities + .multiview + .insert(vk::PhysicalDeviceMultiviewProperties::default()); + properties2 = properties2.push_next(next); + } + unsafe { get_device_properties.get_physical_device_properties2(phd, &mut properties2) }; @@ -1418,15 +1569,6 @@ impl super::InstanceShared { features2 = features2.push_next(next); } - // `VK_KHR_imageless_framebuffer` is promoted to 1.2, but has no - // changes, so we can keep using the extension unconditionally. - if capabilities.supports_extension(khr::imageless_framebuffer::NAME) { - let next = features - .imageless_framebuffer - .insert(vk::PhysicalDeviceImagelessFramebufferFeaturesKHR::default()); - features2 = features2.push_next(next); - } - // `VK_KHR_timeline_semaphore` is promoted to 1.2, but has no // changes, so we can keep using the extension unconditionally. if capabilities.supports_extension(khr::timeline_semaphore::NAME) { @@ -1477,15 +1619,22 @@ impl super::InstanceShared { .insert(vk::PhysicalDeviceTextureCompressionASTCHDRFeaturesEXT::default()); features2 = features2.push_next(next); } - if capabilities.supports_extension(khr::shader_float16_int8::NAME) - && capabilities.supports_extension(khr::_16bit_storage::NAME) + + // `VK_KHR_shader_float16_int8` is promoted to 1.2 + if capabilities.device_api_version >= vk::API_VERSION_1_2 + || capabilities.supports_extension(khr::shader_float16_int8::NAME) { - let next = features.shader_float16.insert(( - vk::PhysicalDeviceShaderFloat16Int8FeaturesKHR::default(), - vk::PhysicalDevice16BitStorageFeaturesKHR::default(), - )); - features2 = features2.push_next(&mut next.0); - features2 = features2.push_next(&mut next.1); + let next = features + .shader_float16_int8 + .insert(vk::PhysicalDeviceShaderFloat16Int8FeaturesKHR::default()); + features2 = features2.push_next(next); + } + + if capabilities.supports_extension(khr::_16bit_storage::NAME) { + let next = features + ._16bit_storage + .insert(vk::PhysicalDevice16BitStorageFeaturesKHR::default()); + features2 = features2.push_next(next); } if capabilities.supports_extension(khr::acceleration_structure::NAME) { let next = features @@ -1528,6 +1677,23 @@ impl super::InstanceShared { features2 = features2.push_next(next); } + // `VK_KHR_shader_integer_dot_product` is promoted to 1.3 + if capabilities.device_api_version >= vk::API_VERSION_1_3 + || capabilities.supports_extension(khr::shader_integer_dot_product::NAME) + { + let next = features + .shader_integer_dot_product + .insert(vk::PhysicalDeviceShaderIntegerDotProductFeatures::default()); + features2 = features2.push_next(next); + } + + if capabilities.supports_extension(khr::fragment_shader_barycentric::NAME) { + let next = features + .shader_barycentrics + .insert(vk::PhysicalDeviceFragmentShaderBarycentricFeaturesKHR::default()); + features2 = features2.push_next(next); + } + unsafe { get_device_properties.get_physical_device_features2(phd, &mut features2) }; features2.features } else { @@ -1547,6 +1713,16 @@ impl super::Instance { let (phd_capabilities, phd_features) = self.shared.inspect(phd); + let mem_properties = { + profiling::scope!("vkGetPhysicalDeviceMemoryProperties"); + unsafe { self.shared.raw.get_physical_device_memory_properties(phd) } + }; + let memory_types = &mem_properties.memory_types_as_slice(); + let supports_lazily_allocated = memory_types.iter().any(|mem| { + mem.property_flags + .contains(vk::MemoryPropertyFlags::LAZILY_ALLOCATED) + }); + let info = wgt::AdapterInfo { name: { phd_capabilities @@ -1567,6 +1743,16 @@ impl super::Instance { vk::PhysicalDeviceType::CPU => wgt::DeviceType::Cpu, _ => wgt::DeviceType::Other, }, + device_pci_bus_id: phd_capabilities + .pci_bus_info + .filter(|info| info.pci_bus != 0 || info.pci_device != 0) + .map(|info| { + format!( + "{:04x}:{:02x}:{:02x}.{}", + info.pci_domain, info.pci_bus, info.pci_device, info.pci_function + ) + }) + .unwrap_or_default(), driver: { phd_capabilities .driver @@ -1586,8 +1772,9 @@ impl super::Instance { .to_owned() }, backend: wgt::Backend::Vulkan, + transient_saves_memory: supports_lazily_allocated, }; - let (available_features, downlevel_flags) = + let (available_features, mut downlevel_flags) = phd_features.to_wgpu(&self.shared.raw, phd, &phd_capabilities); let mut workarounds = super::Workarounds::empty(); { @@ -1603,6 +1790,15 @@ impl super::Instance { ); }; + if info.driver == "llvmpipe" { + // The `F16_IN_F32` instructions do not normally require native `F16` support, but on + // llvmpipe, they do. + downlevel_flags.set( + wgt::DownlevelFlags::SHADER_F16_IN_F32, + available_features.contains(wgt::Features::SHADER_F16), + ); + } + if let Some(driver) = phd_capabilities.driver { if driver.conformance_version.major == 0 { if driver.driver_id == vk::DriverId::MOLTENVK { @@ -1631,12 +1827,11 @@ impl super::Instance { ); return None; } - if !phd_capabilities.supports_extension(amd::negative_viewport_height::NAME) - && !phd_capabilities.supports_extension(khr::maintenance1::NAME) + if !phd_capabilities.supports_extension(khr::maintenance1::NAME) && phd_capabilities.device_api_version < vk::API_VERSION_1_1 { log::warn!( - "viewport Y-flip is not supported, hiding adapter: {}", + "VK_KHR_maintenance1 is not supported, hiding adapter: {}", info.name ); return None; @@ -1649,19 +1844,11 @@ impl super::Instance { }; let queue_flags = queue_families.first()?.queue_flags; if !queue_flags.contains(vk::QueueFlags::GRAPHICS) { - log::warn!("The first queue only exposes {:?}", queue_flags); + log::warn!("The first queue only exposes {queue_flags:?}"); return None; } let private_caps = super::PrivateCapabilities { - flip_y_requires_shift: phd_capabilities.device_api_version >= vk::API_VERSION_1_1 - || phd_capabilities.supports_extension(khr::maintenance1::NAME), - imageless_framebuffers: match phd_features.imageless_framebuffer { - Some(features) => features.imageless_framebuffer == vk::TRUE, - None => phd_features - .imageless_framebuffer - .is_some_and(|ext| ext.imageless_framebuffer != 0), - }, image_view_usage: phd_capabilities.device_api_version >= vk::API_VERSION_1_1 || phd_capabilities.supports_extension(khr::maintenance2::NAME), timeline_semaphores: match phd_features.timeline_semaphore { @@ -1691,6 +1878,7 @@ impl super::Instance { vk::ImageTiling::OPTIMAL, depth_stencil_required_flags(), ), + multi_draw_indirect: phd_features.core.multi_draw_indirect != 0, non_coherent_map_mask: phd_capabilities.properties.limits.non_coherent_atom_size - 1, can_present: true, //TODO: make configurable @@ -1720,6 +1908,16 @@ impl super::Instance { .properties .limits .max_sampler_allocation_count, + shader_integer_dot_product: phd_features + .shader_integer_dot_product + .is_some_and(|ext| ext.shader_integer_dot_product != 0), + shader_int8: phd_features + .shader_float16_int8 + .is_some_and(|features| features.shader_int8 != 0), + multiview_instance_index_limit: phd_capabilities + .multiview + .map(|a| a.max_multiview_instance_index) + .unwrap_or(0), }; let capabilities = crate::Capabilities { limits: phd_capabilities.to_wgpu_limits(), @@ -1761,6 +1959,10 @@ impl super::Adapter { self.raw } + pub fn get_physical_device_features(&self) -> &PhysicalDeviceFeatures { + &self.phd_features + } + pub fn physical_device_capabilities(&self) -> &PhysicalDeviceProperties { &self.phd_capabilities } @@ -1779,10 +1981,10 @@ impl super::Adapter { }); if !unsupported_extensions.is_empty() { - log::warn!("Missing extensions: {:?}", unsupported_extensions); + log::warn!("Missing extensions: {unsupported_extensions:?}"); } - log::debug!("Supported extensions: {:?}", supported_extensions); + log::debug!("Supported extensions: {supported_extensions:?}"); supported_extensions } @@ -1850,8 +2052,6 @@ impl super::Adapter { } }); - let swapchain_fn = khr::swapchain::Device::new(&self.instance.raw, &raw_device); - // Note that VK_EXT_debug_utils is an instance extension (enabled at the instance // level) but contains a few functions that can be loaded directly on the Device for a // dispatch-table-less pointer. @@ -1949,6 +2149,7 @@ impl super::Adapter { capabilities.push(spv::Capability::GroupNonUniformBallot); capabilities.push(spv::Capability::GroupNonUniformShuffle); capabilities.push(spv::Capability::GroupNonUniformShuffleRelative); + capabilities.push(spv::Capability::GroupNonUniformQuad); } if features.intersects( @@ -1990,6 +2191,14 @@ impl super::Adapter { capabilities.push(spv::Capability::AtomicFloat32AddEXT); } + if features.contains(wgt::Features::CLIP_DISTANCES) { + capabilities.push(spv::Capability::ClipDistance); + } + + if features.intersects(wgt::Features::SHADER_BARYCENTRICS) { + capabilities.push(spv::Capability::FragmentBarycentricKHR); + } + let mut flags = spv::WriterFlags::empty(); flags.set( spv::WriterFlags::DEBUG, @@ -2012,13 +2221,31 @@ impl super::Adapter { if features.contains(wgt::Features::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN) { capabilities.push(spv::Capability::RayQueryPositionFetchKHR) } + if features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER) { + capabilities.push(spv::Capability::MeshShadingEXT); + } + if self.private_caps.shader_integer_dot_product { + // See . + capabilities.extend(&[ + spv::Capability::DotProductInputAllKHR, + spv::Capability::DotProductInput4x8BitKHR, + spv::Capability::DotProductInput4x8BitPackedKHR, + spv::Capability::DotProductKHR, + ]); + } + if self.private_caps.shader_int8 { + // See . + capabilities.extend(&[spv::Capability::Int8]); + } spv::Options { - lang_version: if features - .intersects(wgt::Features::SUBGROUP | wgt::Features::SUBGROUP_VERTEX) - { - (1, 3) - } else { - (1, 0) + lang_version: match self.phd_capabilities.device_api_version { + // Use maximum supported SPIR-V version according to + // . + vk::API_VERSION_1_0..vk::API_VERSION_1_1 => (1, 0), + vk::API_VERSION_1_1..vk::API_VERSION_1_2 => (1, 3), + vk::API_VERSION_1_2..vk::API_VERSION_1_3 => (1, 5), + vk::API_VERSION_1_3.. => (1, 6), + _ => unreachable!(), }, flags, capabilities: Some(capabilities.iter().cloned().collect()), @@ -2046,6 +2273,9 @@ impl super::Adapter { spv::ZeroInitializeWorkgroupMemoryMode::Polyfill }, force_loop_bounding: true, + use_storage_input_output_16: features.contains(wgt::Features::SHADER_F16) + && self.phd_features.supports_storage_input_output_16(), + fake_missing_bindings: false, // We need to build this separately for each invocation, so just default it out here binding_map: BTreeMap::default(), debug_info: None, @@ -2095,22 +2325,23 @@ impl super::Adapter { features, workarounds: self.workarounds, render_passes: Mutex::new(Default::default()), - framebuffers: Mutex::new(Default::default()), sampler_cache: Mutex::new(super::sampler::SamplerCache::new( self.private_caps.maximum_samplers, )), memory_allocations_counter: Default::default(), + + texture_identity_factory: super::ResourceIdentityFactory::new(), + texture_view_identity_factory: super::ResourceIdentityFactory::new(), }); let relay_semaphores = super::RelaySemaphores::new(&shared)?; let queue = super::Queue { raw: raw_queue, - swapchain_fn, device: Arc::clone(&shared), family_index, relay_semaphores: Mutex::new(relay_semaphores), - signal_semaphores: Mutex::new((Vec::new(), Vec::new())), + signal_semaphores: Mutex::new(SemaphoreList::new(SemaphoreListMode::Signal)), }; let mem_allocator = { @@ -2219,25 +2450,37 @@ impl super::Adapter { pub fn texture_format_as_raw(&self, texture_format: wgt::TextureFormat) -> vk::Format { self.private_caps.map_texture_format(texture_format) } -} -impl crate::Adapter for super::Adapter { - type A = super::Api; - - unsafe fn open( + /// # Safety: + /// - Same as `open` plus + /// - The callback may not change anything that the device does not support. + /// - The callback may not remove features. + pub unsafe fn open_with_callback<'a>( &self, features: wgt::Features, - _limits: &wgt::Limits, memory_hints: &wgt::MemoryHints, + callback: Option>>, ) -> Result, crate::DeviceError> { - let enabled_extensions = self.required_device_extensions(features); + let mut enabled_extensions = self.required_device_extensions(features); let mut enabled_phd_features = self.physical_device_features(&enabled_extensions, features); let family_index = 0; //TODO let family_info = vk::DeviceQueueCreateInfo::default() .queue_family_index(family_index) .queue_priorities(&[1.0]); - let family_infos = [family_info]; + let mut family_infos = Vec::from([family_info]); + + let mut pre_info = vk::DeviceCreateInfo::default(); + + if let Some(callback) = callback { + callback(super::CreateDeviceCallbackArgs { + extensions: &mut enabled_extensions, + device_features: &mut enabled_phd_features, + queue_create_infos: &mut family_infos, + create_info: &mut pre_info, + _phantom: PhantomData, + }) + } let str_pointers = enabled_extensions .iter() @@ -2247,7 +2490,7 @@ impl crate::Adapter for super::Adapter { }) .collect::>(); - let pre_info = vk::DeviceCreateInfo::default() + let pre_info = pre_info .queue_create_infos(&family_infos) .enabled_extension_names(&str_pointers); let info = enabled_phd_features.add_to_device_create(pre_info); @@ -2283,6 +2526,19 @@ impl crate::Adapter for super::Adapter { ) } } +} + +impl crate::Adapter for super::Adapter { + type A = super::Api; + + unsafe fn open( + &self, + features: wgt::Features, + _limits: &wgt::Limits, + memory_hints: &wgt::MemoryHints, + ) -> Result, crate::DeviceError> { + unsafe { self.open_with_callback(features, memory_hints, None) } + } unsafe fn texture_format_capabilities( &self, @@ -2407,113 +2663,7 @@ impl crate::Adapter for super::Adapter { &self, surface: &super::Surface, ) -> Option { - if !self.private_caps.can_present { - return None; - } - let queue_family_index = 0; //TODO - { - profiling::scope!("vkGetPhysicalDeviceSurfaceSupportKHR"); - match unsafe { - surface.functor.get_physical_device_surface_support( - self.raw, - queue_family_index, - surface.raw, - ) - } { - Ok(true) => (), - Ok(false) => return None, - Err(e) => { - log::error!("get_physical_device_surface_support: {}", e); - return None; - } - } - } - - let caps = { - profiling::scope!("vkGetPhysicalDeviceSurfaceCapabilitiesKHR"); - match unsafe { - surface - .functor - .get_physical_device_surface_capabilities(self.raw, surface.raw) - } { - Ok(caps) => caps, - Err(e) => { - log::error!("get_physical_device_surface_capabilities: {}", e); - return None; - } - } - }; - - // If image count is 0, the support number of images is unlimited. - let max_image_count = if caps.max_image_count == 0 { - !0 - } else { - caps.max_image_count - }; - - // `0xFFFFFFFF` indicates that the extent depends on the created swapchain. - let current_extent = if caps.current_extent.width != !0 && caps.current_extent.height != !0 - { - Some(wgt::Extent3d { - width: caps.current_extent.width, - height: caps.current_extent.height, - depth_or_array_layers: 1, - }) - } else { - None - }; - - let raw_present_modes = { - profiling::scope!("vkGetPhysicalDeviceSurfacePresentModesKHR"); - match unsafe { - surface - .functor - .get_physical_device_surface_present_modes(self.raw, surface.raw) - } { - Ok(present_modes) => present_modes, - Err(e) => { - log::error!("get_physical_device_surface_present_modes: {}", e); - // Per definition of `SurfaceCapabilities`, there must be at least one present mode. - return None; - } - } - }; - - let raw_surface_formats = { - profiling::scope!("vkGetPhysicalDeviceSurfaceFormatsKHR"); - match unsafe { - surface - .functor - .get_physical_device_surface_formats(self.raw, surface.raw) - } { - Ok(formats) => formats, - Err(e) => { - log::error!("get_physical_device_surface_formats: {}", e); - // Per definition of `SurfaceCapabilities`, there must be at least one present format. - return None; - } - } - }; - - let formats = raw_surface_formats - .into_iter() - .filter_map(conv::map_vk_surface_formats) - .collect(); - Some(crate::SurfaceCapabilities { - formats, - // TODO: Right now we're always trunkating the swap chain - // (presumably - we're actually setting the min image count which isn't necessarily the swap chain size) - // Instead, we should use extensions when available to wait in present. - // See https://github.com/gfx-rs/wgpu/issues/2869 - maximum_frame_latency: (caps.min_image_count - 1)..=(max_image_count - 1), // Note this can't underflow since both `min_image_count` is at least one and we already patched `max_image_count`. - current_extent, - usage: conv::map_vk_image_usage(caps.supported_usage_flags), - present_modes: raw_present_modes - .into_iter() - .flat_map(conv::map_vk_present_mode) - .collect(), - composite_alpha_modes: conv::map_vk_composite_alpha(caps.supported_composite_alpha), - }) + surface.inner.surface_capabilities(self) } unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp { @@ -2600,6 +2750,60 @@ fn supports_format( } } +fn supports_astc_3d(instance: &ash::Instance, phd: vk::PhysicalDevice) -> bool { + let mut supports = true; + + let astc_formats = [ + vk::Format::ASTC_4X4_UNORM_BLOCK, + vk::Format::ASTC_4X4_SRGB_BLOCK, + vk::Format::ASTC_5X4_UNORM_BLOCK, + vk::Format::ASTC_5X4_SRGB_BLOCK, + vk::Format::ASTC_5X5_UNORM_BLOCK, + vk::Format::ASTC_5X5_SRGB_BLOCK, + vk::Format::ASTC_6X5_UNORM_BLOCK, + vk::Format::ASTC_6X5_SRGB_BLOCK, + vk::Format::ASTC_6X6_UNORM_BLOCK, + vk::Format::ASTC_6X6_SRGB_BLOCK, + vk::Format::ASTC_8X5_UNORM_BLOCK, + vk::Format::ASTC_8X5_SRGB_BLOCK, + vk::Format::ASTC_8X6_UNORM_BLOCK, + vk::Format::ASTC_8X6_SRGB_BLOCK, + vk::Format::ASTC_8X8_UNORM_BLOCK, + vk::Format::ASTC_8X8_SRGB_BLOCK, + vk::Format::ASTC_10X5_UNORM_BLOCK, + vk::Format::ASTC_10X5_SRGB_BLOCK, + vk::Format::ASTC_10X6_UNORM_BLOCK, + vk::Format::ASTC_10X6_SRGB_BLOCK, + vk::Format::ASTC_10X8_UNORM_BLOCK, + vk::Format::ASTC_10X8_SRGB_BLOCK, + vk::Format::ASTC_10X10_UNORM_BLOCK, + vk::Format::ASTC_10X10_SRGB_BLOCK, + vk::Format::ASTC_12X10_UNORM_BLOCK, + vk::Format::ASTC_12X10_SRGB_BLOCK, + vk::Format::ASTC_12X12_UNORM_BLOCK, + vk::Format::ASTC_12X12_SRGB_BLOCK, + ]; + + for &format in &astc_formats { + let result = unsafe { + instance.get_physical_device_image_format_properties( + phd, + format, + vk::ImageType::TYPE_3D, + vk::ImageTiling::OPTIMAL, + vk::ImageUsageFlags::SAMPLED, + vk::ImageCreateFlags::empty(), + ) + }; + if result.is_err() { + supports = false; + break; + } + } + + supports +} + fn supports_bgra8unorm_storage( instance: &ash::Instance, phd: vk::PhysicalDevice, diff --git a/wgpu-hal/src/vulkan/command.rs b/wgpu-hal/src/vulkan/command.rs index 2d2798fb6..16ba1e320 100644 --- a/wgpu-hal/src/vulkan/command.rs +++ b/wgpu-hal/src/vulkan/command.rs @@ -1,9 +1,8 @@ use super::conv; - use arrayvec::ArrayVec; use ash::vk; - -use std::{mem, ops::Range}; +use core::{mem, ops::Range}; +use hashbrown::hash_map::Entry; const ALLOCATION_GRANULARITY: u32 = 16; const DST_IMAGE_LAYOUT: vk::ImageLayout = vk::ImageLayout::TRANSFER_DST_OPTIMAL; @@ -52,6 +51,69 @@ impl super::CommandEncoder { } } } + + fn make_framebuffer( + &mut self, + key: super::FramebufferKey, + ) -> Result { + Ok(match self.framebuffers.entry(key) { + Entry::Occupied(e) => *e.get(), + Entry::Vacant(e) => { + let super::FramebufferKey { + raw_pass, + ref attachment_views, + attachment_identities: _, + extent, + } = *e.key(); + + let vk_info = vk::FramebufferCreateInfo::default() + .render_pass(raw_pass) + .width(extent.width) + .height(extent.height) + .layers(extent.depth_or_array_layers) + .attachments(attachment_views); + + let raw = unsafe { self.device.raw.create_framebuffer(&vk_info, None).unwrap() }; + *e.insert(raw) + } + }) + } + + fn make_temp_texture_view( + &mut self, + key: super::TempTextureViewKey, + ) -> Result { + Ok(match self.temp_texture_views.entry(key) { + Entry::Occupied(e) => *e.get(), + Entry::Vacant(e) => { + let super::TempTextureViewKey { + texture, + texture_identity: _, + format, + mip_level, + depth_slice, + } = *e.key(); + + let vk_info = vk::ImageViewCreateInfo::default() + .image(texture) + .view_type(vk::ImageViewType::TYPE_2D) + .format(format) + .subresource_range(vk::ImageSubresourceRange { + aspect_mask: vk::ImageAspectFlags::COLOR, + base_mip_level: mip_level, + level_count: 1, + base_array_layer: depth_slice, + layer_count: 1, + }); + let raw = unsafe { self.device.raw.create_image_view(&vk_info, None) } + .map_err(super::map_host_device_oom_and_ioca_err)?; + + let identity = self.device.texture_view_identity_factory.next(); + + *e.insert(super::IdentifiedTextureView { raw, identity }) + } + }) + } } impl crate::CommandEncoder for super::CommandEncoder { @@ -118,6 +180,10 @@ impl crate::CommandEncoder for super::CommandEncoder { self.free .extend(cmd_bufs.into_iter().map(|cmd_buf| cmd_buf.raw)); self.free.append(&mut self.discarded); + // Delete framebuffers from the framebuffer cache + for (_, framebuffer) in self.framebuffers.drain() { + unsafe { self.device.raw.destroy_framebuffer(framebuffer, None) }; + } let _ = unsafe { self.device .raw @@ -564,7 +630,7 @@ impl crate::CommandEncoder for super::CommandEncoder { .first_vertex(triangles.first_vertex); } else { range = range - .primitive_count(triangles.vertex_count) + .primitive_count(triangles.vertex_count / 3) .first_vertex(triangles.first_vertex); } @@ -711,46 +777,53 @@ impl crate::CommandEncoder for super::CommandEncoder { unsafe fn begin_render_pass( &mut self, desc: &crate::RenderPassDescriptor, - ) { + ) -> Result<(), crate::DeviceError> { let mut vk_clear_values = ArrayVec::::new(); - let mut vk_image_views = ArrayVec::::new(); - let mut rp_key = super::RenderPassKey::default(); - let mut fb_key = super::FramebufferKey { - attachments: ArrayVec::default(), - extent: desc.extent, + let mut rp_key = super::RenderPassKey { + colors: ArrayVec::default(), + depth_stencil: None, sample_count: desc.sample_count, + multiview_mask: desc.multiview_mask, + }; + let mut fb_key = super::FramebufferKey { + raw_pass: vk::RenderPass::null(), + attachment_views: ArrayVec::default(), + attachment_identities: ArrayVec::default(), + extent: desc.extent, }; - let caps = &self.device.private_caps; for cat in desc.color_attachments { if let Some(cat) = cat.as_ref() { + let color_view = if cat.target.view.dimension == wgt::TextureViewDimension::D3 { + let key = super::TempTextureViewKey { + texture: cat.target.view.raw_texture, + texture_identity: cat.target.view.texture_identity, + format: cat.target.view.raw_format, + mip_level: cat.target.view.base_mip_level, + depth_slice: cat.depth_slice.unwrap(), + }; + self.make_temp_texture_view(key)? + } else { + cat.target.view.identified_raw_view() + }; + vk_clear_values.push(vk::ClearValue { color: unsafe { cat.make_vk_clear_color() }, }); - vk_image_views.push(cat.target.view.raw); let color = super::ColorAttachmentKey { - base: cat.target.make_attachment_key(cat.ops, caps), - resolve: cat.resolve_target.as_ref().map(|target| { - target.make_attachment_key(crate::AttachmentOps::STORE, caps) - }), + base: cat.target.make_attachment_key(cat.ops), + resolve: cat + .resolve_target + .as_ref() + .map(|target| target.make_attachment_key(crate::AttachmentOps::STORE)), }; rp_key.colors.push(Some(color)); - fb_key.attachments.push(cat.target.view.attachment.clone()); + fb_key.push_view(color_view); if let Some(ref at) = cat.resolve_target { vk_clear_values.push(unsafe { mem::zeroed() }); - vk_image_views.push(at.view.raw); - fb_key.attachments.push(at.view.attachment.clone()); - } - - // Assert this attachment is valid for the detected multiview, as a sanity check - // The driver crash for this is really bad on AMD, so the check is worth it - if let Some(multiview) = desc.multiview { - assert_eq!(cat.target.view.layers, multiview); - if let Some(ref resolve_target) = cat.resolve_target { - assert_eq!(resolve_target.view.layers, multiview); - } + fb_key.push_view(at.view.identified_raw_view()); } } else { rp_key.colors.push(None); @@ -763,21 +836,12 @@ impl crate::CommandEncoder for super::CommandEncoder { stencil: ds.clear_value.1, }, }); - vk_image_views.push(ds.target.view.raw); rp_key.depth_stencil = Some(super::DepthStencilAttachmentKey { - base: ds.target.make_attachment_key(ds.depth_ops, caps), + base: ds.target.make_attachment_key(ds.depth_ops), stencil_ops: ds.stencil_ops, }); - fb_key.attachments.push(ds.target.view.attachment.clone()); - - // Assert this attachment is valid for the detected multiview, as a sanity check - // The driver crash for this is really bad on AMD, so the check is worth it - if let Some(multiview) = desc.multiview { - assert_eq!(ds.target.view.layers, multiview); - } + fb_key.push_view(ds.target.view.identified_raw_view()); } - rp_key.sample_count = fb_key.sample_count; - rp_key.multiview = desc.multiview; let render_area = vk::Rect2D { offset: vk::Offset2D { x: 0, y: 0 }, @@ -788,11 +852,7 @@ impl crate::CommandEncoder for super::CommandEncoder { }; let vk_viewports = [vk::Viewport { x: 0.0, - y: if self.device.private_caps.flip_y_requires_shift { - desc.extent.height as f32 - } else { - 0.0 - }, + y: desc.extent.height as f32, width: desc.extent.width as f32, height: -(desc.extent.height as f32), min_depth: 0.0, @@ -800,24 +860,14 @@ impl crate::CommandEncoder for super::CommandEncoder { }]; let raw_pass = self.device.make_render_pass(rp_key).unwrap(); - let raw_framebuffer = self - .device - .make_framebuffer(fb_key, raw_pass, desc.label) - .unwrap(); + fb_key.raw_pass = raw_pass; + let raw_framebuffer = self.make_framebuffer(fb_key).unwrap(); - let mut vk_info = vk::RenderPassBeginInfo::default() + let vk_info = vk::RenderPassBeginInfo::default() .render_pass(raw_pass) .render_area(render_area) .clear_values(&vk_clear_values) .framebuffer(raw_framebuffer); - let mut vk_attachment_info = if caps.imageless_framebuffers { - Some(vk::RenderPassAttachmentBeginInfo::default().attachments(&vk_image_views)) - } else { - None - }; - if let Some(attachment_info) = vk_attachment_info.as_mut() { - vk_info = vk_info.push_next(attachment_info); - } if let Some(label) = desc.label { unsafe { self.begin_debug_marker(label) }; @@ -851,6 +901,8 @@ impl crate::CommandEncoder for super::CommandEncoder { }; self.bind_point = vk::PipelineBindPoint::GRAPHICS; + + Ok(()) } unsafe fn end_render_pass(&mut self) { unsafe { @@ -927,6 +979,7 @@ impl crate::CommandEncoder for super::CommandEncoder { unsafe fn set_render_pipeline(&mut self, pipeline: &super::RenderPipeline) { unsafe { + self.current_pipeline_is_multiview = pipeline.is_multiview; self.device.raw.cmd_bind_pipeline( self.active, vk::PipelineBindPoint::GRAPHICS, @@ -965,11 +1018,7 @@ impl crate::CommandEncoder for super::CommandEncoder { unsafe fn set_viewport(&mut self, rect: &crate::Rect, depth_range: Range) { let vk_viewports = [vk::Viewport { x: rect.x, - y: if self.device.private_caps.flip_y_requires_shift { - rect.y + rect.h - } else { - rect.y - }, + y: rect.y + rect.h, width: rect.w, height: -rect.h, // flip Y min_depth: depth_range.start, @@ -1018,6 +1067,12 @@ impl crate::CommandEncoder for super::CommandEncoder { first_instance: u32, instance_count: u32, ) { + if self.current_pipeline_is_multiview + && (first_instance as u64 + instance_count as u64 - 1) + > self.device.private_caps.multiview_instance_index_limit as u64 + { + panic!("This vulkan device is affected by [#8333](https://github.com/gfx-rs/wgpu/issues/8333)"); + } unsafe { self.device.raw.cmd_draw( self.active, @@ -1036,6 +1091,12 @@ impl crate::CommandEncoder for super::CommandEncoder { first_instance: u32, instance_count: u32, ) { + if self.current_pipeline_is_multiview + && (first_instance as u64 + instance_count as u64 - 1) + > self.device.private_caps.multiview_instance_index_limit as u64 + { + panic!("This vulkan device is affected by [#8333](https://github.com/gfx-rs/wgpu/issues/8333)"); + } unsafe { self.device.raw.cmd_draw_indexed( self.active, @@ -1083,15 +1144,29 @@ impl crate::CommandEncoder for super::CommandEncoder { offset: wgt::BufferAddress, draw_count: u32, ) { - unsafe { - self.device.raw.cmd_draw_indexed_indirect( - self.active, - buffer.raw, - offset, - draw_count, - size_of::() as u32, - ) - }; + if draw_count >= 1 && self.device.private_caps.multi_draw_indirect { + unsafe { + self.device.raw.cmd_draw_indexed_indirect( + self.active, + buffer.raw, + offset, + draw_count, + size_of::() as u32, + ) + }; + } else { + for _ in 0..draw_count { + unsafe { + self.device.raw.cmd_draw_indexed_indirect( + self.active, + buffer.raw, + offset, + 1, + size_of::() as u32, + ) + }; + } + } } unsafe fn draw_mesh_tasks_indirect( &mut self, @@ -1277,7 +1352,7 @@ impl crate::CommandEncoder for super::CommandEncoder { self.active, &vk::CopyAccelerationStructureInfoKHR { s_type: vk::StructureType::COPY_ACCELERATION_STRUCTURE_INFO_KHR, - p_next: std::ptr::null(), + p_next: core::ptr::null(), src: src.raw, dst: dst.raw, mode, diff --git a/wgpu-hal/src/vulkan/conv.rs b/wgpu-hal/src/vulkan/conv.rs index e1d5cb30e..fbad9b577 100644 --- a/wgpu-hal/src/vulkan/conv.rs +++ b/wgpu-hal/src/vulkan/conv.rs @@ -1,4 +1,4 @@ -use std::vec::Vec; +use alloc::vec::Vec; use ash::vk; @@ -78,6 +78,7 @@ impl super::PrivateCapabilities { } Tf::Depth16Unorm => F::D16_UNORM, Tf::NV12 => F::G8_B8R8_2PLANE_420_UNORM, + Tf::P010 => F::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16, Tf::Rgb9e5Ufloat => F::E5B9G9R9_UFLOAT_PACK32, Tf::Bc1RgbaUnorm => F::BC1_RGBA_UNORM_BLOCK, Tf::Bc1RgbaUnormSrgb => F::BC1_RGBA_SRGB_BLOCK, @@ -160,7 +161,8 @@ impl super::PrivateCapabilities { pub fn map_vk_surface_formats(sf: vk::SurfaceFormatKHR) -> Option { use ash::vk::Format as F; use wgt::TextureFormat as Tf; - // List we care about pulled from https://vulkan.gpuinfo.org/listsurfaceformats.php + // List we care about pulled from https://vulkan.gpuinfo.org/listsurfaceformats.php. + // Device::create_swapchain() hardcodes linear scRGB for fp16, non-linear sRGB otherwise. Some(match sf.color_space { vk::ColorSpaceKHR::SRGB_NONLINEAR => match sf.format { F::B8G8R8A8_UNORM => Tf::Bgra8Unorm, @@ -168,13 +170,13 @@ pub fn map_vk_surface_formats(sf: vk::SurfaceFormatKHR) -> Option Tf::Rgba8Snorm, F::R8G8B8A8_UNORM => Tf::Rgba8Unorm, F::R8G8B8A8_SRGB => Tf::Rgba8UnormSrgb, + F::R16G16B16A16_SNORM => Tf::Rgba16Snorm, + F::R16G16B16A16_UNORM => Tf::Rgba16Unorm, + F::A2B10G10R10_UNORM_PACK32 => Tf::Rgb10a2Unorm, _ => return None, }, vk::ColorSpaceKHR::EXTENDED_SRGB_LINEAR_EXT => match sf.format { F::R16G16B16A16_SFLOAT => Tf::Rgba16Float, - F::R16G16B16A16_SNORM => Tf::Rgba16Snorm, - F::R16G16B16A16_UNORM => Tf::Rgba16Unorm, - F::A2B10G10R10_UNORM_PACK32 => Tf::Rgb10a2Unorm, _ => return None, }, _ => return None, @@ -182,14 +184,10 @@ pub fn map_vk_surface_formats(sf: vk::SurfaceFormatKHR) -> Option { - pub(super) fn make_attachment_key( - &self, - ops: crate::AttachmentOps, - caps: &super::PrivateCapabilities, - ) -> super::AttachmentKey { + pub(super) fn make_attachment_key(&self, ops: crate::AttachmentOps) -> super::AttachmentKey { super::AttachmentKey { - format: caps.map_texture_format(self.view.attachment.view_format), - layout: derive_image_layout(self.usage, self.view.attachment.view_format), + format: self.view.raw_format, + layout: derive_image_layout(self.usage, self.view.format), ops, } } @@ -198,14 +196,7 @@ impl crate::Attachment<'_, super::TextureView> { impl crate::ColorAttachment<'_, super::TextureView> { pub(super) unsafe fn make_vk_clear_color(&self) -> vk::ClearColorValue { let cv = &self.clear_value; - match self - .target - .view - .attachment - .view_format - .sample_type(None, None) - .unwrap() - { + match self.target.view.format.sample_type(None, None).unwrap() { wgt::TextureSampleType::Float { .. } => vk::ClearColorValue { float32: [cv.r as f32, cv.g as f32, cv.b as f32, cv.a as f32], }, @@ -269,6 +260,9 @@ pub fn map_texture_usage(usage: wgt::TextureUses) -> vk::ImageUsageFlags { ) { flags |= vk::ImageUsageFlags::STORAGE; } + if usage.contains(wgt::TextureUses::TRANSIENT) { + flags |= vk::ImageUsageFlags::TRANSIENT_ATTACHMENT; + } flags } @@ -358,6 +352,9 @@ pub fn map_vk_image_usage(usage: vk::ImageUsageFlags) -> wgt::TextureUses { | wgt::TextureUses::STORAGE_READ_WRITE | wgt::TextureUses::STORAGE_ATOMIC; } + if usage.contains(vk::ImageUsageFlags::TRANSIENT_ATTACHMENT) { + bits |= wgt::TextureUses::TRANSIENT; + } bits } @@ -479,17 +476,25 @@ pub fn map_present_mode(mode: wgt::PresentMode) -> vk::PresentModeKHR { } pub fn map_vk_present_mode(mode: vk::PresentModeKHR) -> Option { - if mode == vk::PresentModeKHR::IMMEDIATE { - Some(wgt::PresentMode::Immediate) - } else if mode == vk::PresentModeKHR::MAILBOX { - Some(wgt::PresentMode::Mailbox) - } else if mode == vk::PresentModeKHR::FIFO { - Some(wgt::PresentMode::Fifo) - } else if mode == vk::PresentModeKHR::FIFO_RELAXED { - Some(wgt::PresentMode::FifoRelaxed) - } else { - log::warn!("Unrecognized present mode {:?}", mode); - None + // Not exposed in Ash yet. + const FIFO_LATEST_READY: vk::PresentModeKHR = vk::PresentModeKHR::from_raw(1_000_361_000); + + // See https://registry.khronos.org/vulkan/specs/latest/man/html/VkPresentModeKHR.html + match mode { + vk::PresentModeKHR::IMMEDIATE => Some(wgt::PresentMode::Immediate), + vk::PresentModeKHR::MAILBOX => Some(wgt::PresentMode::Mailbox), + vk::PresentModeKHR::FIFO => Some(wgt::PresentMode::Fifo), + vk::PresentModeKHR::FIFO_RELAXED => Some(wgt::PresentMode::FifoRelaxed), + + // Modes that aren't exposed yet. + vk::PresentModeKHR::SHARED_DEMAND_REFRESH => None, + vk::PresentModeKHR::SHARED_CONTINUOUS_REFRESH => None, + FIFO_LATEST_READY => None, + + _ => { + log::debug!("Unrecognized present mode {mode:?}"); + None + } } } @@ -615,7 +620,8 @@ pub fn map_buffer_usage_to_barrier( ) { stages |= vk::PipelineStageFlags::ACCELERATION_STRUCTURE_BUILD_KHR; access |= vk::AccessFlags::ACCELERATION_STRUCTURE_READ_KHR - | vk::AccessFlags::ACCELERATION_STRUCTURE_WRITE_KHR; + | vk::AccessFlags::ACCELERATION_STRUCTURE_WRITE_KHR + | vk::AccessFlags::SHADER_READ; } if usage.contains(wgt::BufferUses::ACCELERATION_STRUCTURE_QUERY) { stages |= vk::PipelineStageFlags::TRANSFER; @@ -697,10 +703,10 @@ pub fn map_filter_mode(mode: wgt::FilterMode) -> vk::Filter { } } -pub fn map_mip_filter_mode(mode: wgt::FilterMode) -> vk::SamplerMipmapMode { +pub fn map_mip_filter_mode(mode: wgt::MipmapFilterMode) -> vk::SamplerMipmapMode { match mode { - wgt::FilterMode::Nearest => vk::SamplerMipmapMode::NEAREST, - wgt::FilterMode::Linear => vk::SamplerMipmapMode::LINEAR, + wgt::MipmapFilterMode::Nearest => vk::SamplerMipmapMode::NEAREST, + wgt::MipmapFilterMode::Linear => vk::SamplerMipmapMode::LINEAR, } } @@ -749,6 +755,12 @@ pub fn map_shader_stage(stage: wgt::ShaderStages) -> vk::ShaderStageFlags { if stage.contains(wgt::ShaderStages::COMPUTE) { flags |= vk::ShaderStageFlags::COMPUTE; } + if stage.contains(wgt::ShaderStages::TASK) { + flags |= vk::ShaderStageFlags::TASK_EXT; + } + if stage.contains(wgt::ShaderStages::MESH) { + flags |= vk::ShaderStageFlags::MESH_EXT; + } flags } @@ -774,6 +786,7 @@ pub fn map_binding_type(ty: wgt::BindingType) -> vk::DescriptorType { wgt::BindingType::AccelerationStructure { .. } => { vk::DescriptorType::ACCELERATION_STRUCTURE_KHR } + wgt::BindingType::ExternalTexture => unimplemented!(), } } diff --git a/wgpu-hal/src/vulkan/device.rs b/wgpu-hal/src/vulkan/device.rs index c00792de9..d1288612b 100644 --- a/wgpu-hal/src/vulkan/device.rs +++ b/wgpu-hal/src/vulkan/device.rs @@ -1,16 +1,14 @@ -use std::{ - borrow::{Cow, ToOwned as _}, - collections::BTreeMap, - ffi::{CStr, CString}, +use alloc::{borrow::ToOwned as _, collections::BTreeMap, ffi::CString, sync::Arc, vec::Vec}; +use core::{ + ffi::CStr, mem::{self, MaybeUninit}, num::NonZeroU32, ptr, - sync::Arc, - vec::Vec, + time::Duration, }; use arrayvec::ArrayVec; -use ash::{khr, vk}; +use ash::{ext, vk}; use hashbrown::hash_map::Entry; use parking_lot::Mutex; @@ -24,7 +22,17 @@ impl super::DeviceShared { /// /// # Safety /// - /// It must be valid to set `object`'s debug name + /// This method inherits the safety contract from [`vkSetDebugUtilsObjectName`]. In particular: + /// + /// - `object` must be a valid handle for one of the following: + /// - An instance-level object from the same instance as this device. + /// - A physical-device-level object that descends from the same physical device as this + /// device. + /// - A device-level object that descends from this device. + /// - `object` must be externally synchronized—only the calling thread should access it during + /// this call. + /// + /// [`vkSetDebugUtilsObjectName`]: https://registry.khronos.org/vulkan/specs/latest/man/html/vkSetDebugUtilsObjectNameEXT.html pub(super) unsafe fn set_object_name(&self, object: impl vk::Handle, name: &str) { let Some(extension) = self.extension_fns.debug_utils.as_ref() else { return; @@ -49,7 +57,7 @@ impl super::DeviceShared { .as_bytes() .iter() .cloned() - .chain(std::iter::once(0)) + .chain(core::iter::once(0)) .collect(); &buffer_vec }; @@ -72,76 +80,106 @@ impl super::DeviceShared { Ok(match self.render_passes.lock().entry(key) { Entry::Occupied(e) => *e.get(), Entry::Vacant(e) => { + let super::RenderPassKey { + ref colors, + ref depth_stencil, + sample_count, + multiview_mask, + } = *e.key(); + let mut vk_attachments = Vec::new(); - let mut color_refs = Vec::with_capacity(e.key().colors.len()); + let mut color_refs = Vec::with_capacity(colors.len()); let mut resolve_refs = Vec::with_capacity(color_refs.capacity()); let mut ds_ref = None; - let samples = vk::SampleCountFlags::from_raw(e.key().sample_count); + let samples = vk::SampleCountFlags::from_raw(sample_count); let unused = vk::AttachmentReference { attachment: vk::ATTACHMENT_UNUSED, layout: vk::ImageLayout::UNDEFINED, }; - for cat in e.key().colors.iter() { - let (color_ref, resolve_ref) = if let Some(cat) = cat.as_ref() { - let color_ref = vk::AttachmentReference { - attachment: vk_attachments.len() as u32, - layout: cat.base.layout, - }; - vk_attachments.push({ - let (load_op, store_op) = conv::map_attachment_ops(cat.base.ops); - vk::AttachmentDescription::default() - .format(cat.base.format) - .samples(samples) - .load_op(load_op) - .store_op(store_op) - .initial_layout(cat.base.layout) - .final_layout(cat.base.layout) - }); - let resolve_ref = if let Some(ref rat) = cat.resolve { - let (load_op, store_op) = conv::map_attachment_ops(rat.ops); - let vk_attachment = vk::AttachmentDescription::default() - .format(rat.format) - .samples(vk::SampleCountFlags::TYPE_1) - .load_op(load_op) - .store_op(store_op) - .initial_layout(rat.layout) - .final_layout(rat.layout); - vk_attachments.push(vk_attachment); + for cat in colors.iter() { + let (color_ref, resolve_ref) = + if let Some(super::ColorAttachmentKey { base, resolve }) = cat { + let super::AttachmentKey { + format, + layout, + ops, + } = *base; - vk::AttachmentReference { - attachment: vk_attachments.len() as u32 - 1, - layout: rat.layout, - } + let color_ref = vk::AttachmentReference { + attachment: vk_attachments.len() as u32, + layout, + }; + vk_attachments.push({ + let (load_op, store_op) = conv::map_attachment_ops(ops); + vk::AttachmentDescription::default() + .format(format) + .samples(samples) + .load_op(load_op) + .store_op(store_op) + .initial_layout(layout) + .final_layout(layout) + }); + let resolve_ref = if let Some(rat) = resolve { + let super::AttachmentKey { + format, + layout, + ops, + } = *rat; + + let (load_op, store_op) = conv::map_attachment_ops(ops); + let vk_attachment = vk::AttachmentDescription::default() + .format(format) + .samples(vk::SampleCountFlags::TYPE_1) + .load_op(load_op) + .store_op(store_op) + .initial_layout(layout) + .final_layout(layout); + vk_attachments.push(vk_attachment); + + vk::AttachmentReference { + attachment: vk_attachments.len() as u32 - 1, + layout, + } + } else { + unused + }; + + (color_ref, resolve_ref) } else { - unused + (unused, unused) }; - (color_ref, resolve_ref) - } else { - (unused, unused) - }; - color_refs.push(color_ref); resolve_refs.push(resolve_ref); } - if let Some(ref ds) = e.key().depth_stencil { + if let Some(ds) = depth_stencil { + let super::DepthStencilAttachmentKey { + ref base, + stencil_ops, + } = *ds; + + let super::AttachmentKey { + format, + layout, + ops, + } = *base; + ds_ref = Some(vk::AttachmentReference { attachment: vk_attachments.len() as u32, - layout: ds.base.layout, + layout, }); - let (load_op, store_op) = conv::map_attachment_ops(ds.base.ops); - let (stencil_load_op, stencil_store_op) = - conv::map_attachment_ops(ds.stencil_ops); + let (load_op, store_op) = conv::map_attachment_ops(ops); + let (stencil_load_op, stencil_store_op) = conv::map_attachment_ops(stencil_ops); let vk_attachment = vk::AttachmentDescription::default() - .format(ds.base.format) + .format(format) .samples(samples) .load_op(load_op) .store_op(store_op) .stencil_load_op(stencil_load_op) .stencil_store_op(stencil_store_op) - .initial_layout(ds.base.layout) - .final_layout(ds.base.layout); + .initial_layout(layout) + .final_layout(layout); vk_attachments.push(vk_attachment); } @@ -171,15 +209,8 @@ impl super::DeviceShared { let mut multiview_info; let mask; - if let Some(multiview) = e.key().multiview { - // Sanity checks, better to panic here than cause a driver crash - assert!(multiview.get() <= 8); - assert!(multiview.get() > 1); - - // Right now we enable all bits on the view masks and correlation masks. - // This means we're rendering to all views in the subpass, and that all views - // can be rendered concurrently. - mask = [(1 << multiview.get()) - 1]; + if let Some(multiview_mask) = multiview_mask { + mask = [multiview_mask.get()]; // On Vulkan 1.1 or later, this is an alias for core functionality multiview_info = vk::RenderPassMultiviewCreateInfoKHR::default() @@ -199,90 +230,11 @@ impl super::DeviceShared { }) } - pub fn make_framebuffer( - &self, - key: super::FramebufferKey, - raw_pass: vk::RenderPass, - pass_label: crate::Label, - ) -> Result { - Ok(match self.framebuffers.lock().entry(key) { - Entry::Occupied(e) => *e.get(), - Entry::Vacant(e) => { - let vk_views = e - .key() - .attachments - .iter() - .map(|at| at.raw) - .collect::>(); - let vk_view_formats = e - .key() - .attachments - .iter() - .map(|at| self.private_caps.map_texture_format(at.view_format)) - .collect::>(); - let vk_view_formats_list = e - .key() - .attachments - .iter() - .map(|at| at.raw_view_formats.clone()) - .collect::>(); - - let vk_image_infos = e - .key() - .attachments - .iter() - .enumerate() - .map(|(i, at)| { - let mut info = vk::FramebufferAttachmentImageInfo::default() - .usage(conv::map_texture_usage(at.view_usage)) - .flags(at.raw_image_flags) - .width(e.key().extent.width) - .height(e.key().extent.height) - .layer_count(e.key().extent.depth_or_array_layers); - // https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkRenderPassBeginInfo.html#VUID-VkRenderPassBeginInfo-framebuffer-03214 - if vk_view_formats_list[i].is_empty() { - info = info.view_formats(&vk_view_formats[i..i + 1]); - } else { - info = info.view_formats(&vk_view_formats_list[i]); - }; - info - }) - .collect::>(); - - let mut vk_attachment_info = vk::FramebufferAttachmentsCreateInfo::default() - .attachment_image_infos(&vk_image_infos); - let mut vk_info = vk::FramebufferCreateInfo::default() - .render_pass(raw_pass) - .width(e.key().extent.width) - .height(e.key().extent.height) - .layers(e.key().extent.depth_or_array_layers); - - if self.private_caps.imageless_framebuffers { - //TODO: https://github.com/MaikKlein/ash/issues/450 - vk_info = vk_info - .flags(vk::FramebufferCreateFlags::IMAGELESS_KHR) - .push_next(&mut vk_attachment_info); - vk_info.attachment_count = e.key().attachments.len() as u32; - } else { - vk_info = vk_info.attachments(&vk_views); - } - - *e.insert(unsafe { - let raw = self.raw.create_framebuffer(&vk_info, None).unwrap(); - if let Some(label) = pass_label { - self.set_object_name(raw, label); - } - raw - }) - } - }) - } - fn make_memory_ranges<'a, I: 'a + Iterator>( &self, buffer: &'a super::Buffer, ranges: I, - ) -> Option> { + ) -> Option>> { let block = buffer.block.as_ref()?.lock(); let mask = self.private_caps.non_coherent_map_mask; Some(ranges.map(move |range| { @@ -530,124 +482,6 @@ struct CompiledStage { } impl super::Device { - pub(super) unsafe fn create_swapchain( - &self, - surface: &super::Surface, - config: &crate::SurfaceConfiguration, - provided_old_swapchain: Option, - ) -> Result { - profiling::scope!("Device::create_swapchain"); - let functor = khr::swapchain::Device::new(&surface.instance.raw, &self.shared.raw); - - let old_swapchain = match provided_old_swapchain { - Some(osc) => osc.raw, - None => vk::SwapchainKHR::null(), - }; - - let color_space = if config.format == wgt::TextureFormat::Rgba16Float { - // Enable wide color gamut mode - // Vulkan swapchain for Android only supports DISPLAY_P3_NONLINEAR_EXT and EXTENDED_SRGB_LINEAR_EXT - vk::ColorSpaceKHR::EXTENDED_SRGB_LINEAR_EXT - } else { - vk::ColorSpaceKHR::SRGB_NONLINEAR - }; - - let original_format = self.shared.private_caps.map_texture_format(config.format); - let mut raw_flags = vk::SwapchainCreateFlagsKHR::empty(); - let mut raw_view_formats: Vec = vec![]; - let mut wgt_view_formats = vec![]; - if !config.view_formats.is_empty() { - raw_flags |= vk::SwapchainCreateFlagsKHR::MUTABLE_FORMAT; - raw_view_formats = config - .view_formats - .iter() - .map(|f| self.shared.private_caps.map_texture_format(*f)) - .collect(); - raw_view_formats.push(original_format); - - wgt_view_formats.clone_from(&config.view_formats); - wgt_view_formats.push(config.format); - } - - let mut info = vk::SwapchainCreateInfoKHR::default() - .flags(raw_flags) - .surface(surface.raw) - .min_image_count(config.maximum_frame_latency + 1) // TODO: https://github.com/gfx-rs/wgpu/issues/2869 - .image_format(original_format) - .image_color_space(color_space) - .image_extent(vk::Extent2D { - width: config.extent.width, - height: config.extent.height, - }) - .image_array_layers(config.extent.depth_or_array_layers) - .image_usage(conv::map_texture_usage(config.usage)) - .image_sharing_mode(vk::SharingMode::EXCLUSIVE) - .pre_transform(vk::SurfaceTransformFlagsKHR::IDENTITY) - .composite_alpha(conv::map_composite_alpha_mode(config.composite_alpha_mode)) - .present_mode(conv::map_present_mode(config.present_mode)) - .clipped(true) - .old_swapchain(old_swapchain); - - let mut format_list_info = vk::ImageFormatListCreateInfo::default(); - if !raw_view_formats.is_empty() { - format_list_info = format_list_info.view_formats(&raw_view_formats); - info = info.push_next(&mut format_list_info); - } - - let result = { - profiling::scope!("vkCreateSwapchainKHR"); - unsafe { functor.create_swapchain(&info, None) } - }; - - // doing this before bailing out with error - if old_swapchain != vk::SwapchainKHR::null() { - unsafe { functor.destroy_swapchain(old_swapchain, None) } - } - - let raw = match result { - Ok(swapchain) => swapchain, - Err(error) => { - return Err(match error { - vk::Result::ERROR_SURFACE_LOST_KHR - | vk::Result::ERROR_INITIALIZATION_FAILED => crate::SurfaceError::Lost, - vk::Result::ERROR_NATIVE_WINDOW_IN_USE_KHR => { - crate::SurfaceError::Other("Native window is in use") - } - // We don't use VK_EXT_image_compression_control - // VK_ERROR_COMPRESSION_EXHAUSTED_EXT - other => super::map_host_device_oom_and_lost_err(other).into(), - }); - } - }; - - let images = - unsafe { functor.get_swapchain_images(raw) }.map_err(super::map_host_device_oom_err)?; - - // NOTE: It's important that we define at least images.len() wait - // semaphores, since we prospectively need to provide the call to - // acquire the next image with an unsignaled semaphore. - let surface_semaphores = (0..=images.len()) - .map(|_| { - super::SwapchainImageSemaphores::new(&self.shared) - .map(Mutex::new) - .map(Arc::new) - }) - .collect::, _>>()?; - - Ok(super::Swapchain { - raw, - raw_flags, - functor, - device: Arc::clone(&self.shared), - images, - config: config.clone(), - view_formats: wgt_view_formats, - surface_semaphores, - next_semaphore_index: 0, - next_present_time: None, - }) - } - /// # Safety /// /// - `vk_image` must be created respecting `desc` @@ -655,6 +489,7 @@ impl super::Device { /// `drop_callback` is [`Some`], `vk_image` must be valid until the callback is called. /// - If the `ImageCreateFlags` does not contain `MUTABLE_FORMAT`, the `view_formats` of `desc` must be empty. pub unsafe fn texture_from_raw( + &self, vk_image: vk::Image, desc: &crate::TextureDescriptor, drop_callback: Option, @@ -676,6 +511,8 @@ impl super::Device { raw_flags |= vk::ImageCreateFlags::MUTABLE_FORMAT; } + let identity = self.shared.texture_identity_factory.next(); + let drop_guard = crate::DropGuard::from_option(drop_callback); super::Texture { @@ -683,15 +520,12 @@ impl super::Device { drop_guard, external_memory: None, block: None, - usage: desc.usage, format: desc.format, - raw_flags: vk::ImageCreateFlags::empty(), copy_size: desc.copy_extent(), - view_formats, + identity, } } - #[cfg(windows)] fn find_memory_type_index( &self, type_bits_req: u32, @@ -725,17 +559,19 @@ impl super::Device { let copy_size = desc.copy_extent(); let mut raw_flags = vk::ImageCreateFlags::empty(); + if desc.dimension == wgt::TextureDimension::D3 + && desc.usage.contains(wgt::TextureUses::COLOR_TARGET) + { + raw_flags |= vk::ImageCreateFlags::TYPE_2D_ARRAY_COMPATIBLE; + } if desc.is_cube_compatible() { raw_flags |= vk::ImageCreateFlags::CUBE_COMPATIBLE; } let original_format = self.shared.private_caps.map_texture_format(desc.format); let mut vk_view_formats = vec![]; - let mut wgt_view_formats = vec![]; if !desc.view_formats.is_empty() { raw_flags |= vk::ImageCreateFlags::MUTABLE_FORMAT; - wgt_view_formats.clone_from(&desc.view_formats); - wgt_view_formats.push(desc.format); if self.shared.private_caps.image_format_list { vk_view_formats = desc @@ -747,7 +583,8 @@ impl super::Device { } } if desc.format.is_multi_planar_format() { - raw_flags |= vk::ImageCreateFlags::MUTABLE_FORMAT; + raw_flags |= + vk::ImageCreateFlags::MUTABLE_FORMAT | vk::ImageCreateFlags::EXTENDED_USAGE; } let mut vk_info = vk::ImageCreateInfo::default() @@ -779,14 +616,22 @@ impl super::Device { // VK_ERROR_COMPRESSION_EXHAUSTED_EXT super::map_host_device_oom_and_ioca_err(err) } - let req = unsafe { self.shared.raw.get_image_memory_requirements(raw) }; + let mut req = unsafe { self.shared.raw.get_image_memory_requirements(raw) }; + + if desc.usage.contains(wgt::TextureUses::TRANSIENT) { + let mem_type_index = self.find_memory_type_index( + req.memory_type_bits, + vk::MemoryPropertyFlags::LAZILY_ALLOCATED, + ); + if let Some(mem_type_index) = mem_type_index { + req.memory_type_bits = 1 << mem_type_index; + } + } Ok(ImageWithoutMemory { raw, requirements: req, copy_size, - view_formats: wgt_view_formats, - raw_flags, }) } @@ -807,7 +652,7 @@ impl super::Device { .contains(wgt::Features::VULKAN_EXTERNAL_MEMORY_WIN32) { log::error!("Vulkan driver does not support VK_KHR_external_memory_win32"); - return Err(crate::DeviceError::ResourceCreationFailed); + return Err(crate::DeviceError::Unexpected); } let mut external_memory_image_info = vk::ExternalMemoryImageCreateInfo::default() @@ -816,16 +661,26 @@ impl super::Device { let image = self.create_image_without_memory(desc, Some(&mut external_memory_image_info))?; + // Some external memory types require dedicated allocation + // https://docs.vulkan.org/guide/latest/extensions/external.html#_importing_memory + let mut dedicated_allocate_info = + vk::MemoryDedicatedAllocateInfo::default().image(image.raw); + let mut import_memory_info = vk::ImportMemoryWin32HandleInfoKHR::default() .handle_type(vk::ExternalMemoryHandleTypeFlags::D3D11_TEXTURE) .handle(d3d11_shared_handle.0 as _); + // TODO: We should use `push_next` instead, but currently ash does not provide this method for the `ImportMemoryWin32HandleInfoKHR` type. + #[allow(clippy::unnecessary_mut_passed)] + { + import_memory_info.p_next = <*const _>::cast(&mut dedicated_allocate_info); + } let mem_type_index = self .find_memory_type_index( image.requirements.memory_type_bits, vk::MemoryPropertyFlags::DEVICE_LOCAL, ) - .ok_or(crate::DeviceError::ResourceCreationFailed)?; + .ok_or(crate::DeviceError::Unexpected)?; let memory_allocate_info = vk::MemoryAllocateInfo::default() .allocation_size(image.requirements.size) @@ -841,6 +696,8 @@ impl super::Device { unsafe { self.shared.set_object_name(image.raw, label) }; } + let identity = self.shared.texture_identity_factory.next(); + self.counters.textures.add(1); Ok(super::Texture { @@ -848,28 +705,16 @@ impl super::Device { drop_guard: None, external_memory: Some(memory), block: None, - usage: desc.usage, format: desc.format, - raw_flags: image.raw_flags, copy_size: image.copy_size, - view_formats: image.view_formats, + identity, }) } - /// # Safety - /// - /// - `vk_buffer`'s memory must be managed by the caller - /// - Externally imported buffers can't be mapped by `wgpu` - pub unsafe fn buffer_from_raw(vk_buffer: vk::Buffer) -> super::Buffer { - super::Buffer { - raw: vk_buffer, - block: None, - } - } - fn create_shader_module_impl( &self, spv: &[u32], + label: &crate::Label<'_>, ) -> Result { let vk_info = vk::ShaderModuleCreateInfo::default() .flags(vk::ShaderModuleCreateFlags::empty()) @@ -887,6 +732,11 @@ impl super::Device { // VK_ERROR_INVALID_SHADER_NV super::map_host_device_oom_err(err) } + + if let Some(label) = label { + unsafe { self.shared.set_object_name(raw, label) }; + } + Ok(raw) } @@ -933,7 +783,7 @@ impl super::Device { if let Some(ref debug) = naga_shader.debug_source { temp_options.debug_info = Some(naga::back::spv::DebugInfo { source_code: &debug.source_code, - file_name: debug.file_name.as_ref().as_ref(), + file_name: debug.file_name.as_ref(), language: naga::back::spv::SourceLanguage::WGSL, }) } @@ -950,6 +800,7 @@ impl super::Device { let (module, info) = naga::back::pipeline_constants::process_overrides( &naga_shader.module, &naga_shader.info, + Some((naga_stage, stage.entry_point)), stage.constants, ) .map_err(|e| { @@ -961,7 +812,7 @@ impl super::Device { naga::back::spv::write_vec(&module, &info, options, Some(&pipeline_options)) } .map_err(|e| crate::PipelineError::Linkage(stage_flags, format!("{e}")))?; - self.create_shader_module_impl(&spv)? + self.create_shader_module_impl(&spv, &None)? } }; @@ -1021,6 +872,97 @@ impl super::Device { pub fn shared_instance(&self) -> &super::InstanceShared { &self.shared.instance } + + fn error_if_would_oom_on_resource_allocation( + &self, + needs_host_access: bool, + size: u64, + ) -> Result<(), crate::DeviceError> { + let Some(threshold) = self + .shared + .instance + .memory_budget_thresholds + .for_resource_creation + else { + return Ok(()); + }; + + if !self + .shared + .enabled_extensions + .contains(&ext::memory_budget::NAME) + { + return Ok(()); + } + + let get_physical_device_properties = self + .shared + .instance + .get_physical_device_properties + .as_ref() + .unwrap(); + + let mut memory_budget_properties = vk::PhysicalDeviceMemoryBudgetPropertiesEXT::default(); + + let mut memory_properties = + vk::PhysicalDeviceMemoryProperties2::default().push_next(&mut memory_budget_properties); + + unsafe { + get_physical_device_properties.get_physical_device_memory_properties2( + self.shared.physical_device, + &mut memory_properties, + ); + } + + let mut host_visible_heaps = [false; vk::MAX_MEMORY_HEAPS]; + let mut device_local_heaps = [false; vk::MAX_MEMORY_HEAPS]; + + let memory_properties = memory_properties.memory_properties; + + for i in 0..memory_properties.memory_type_count { + let memory_type = memory_properties.memory_types[i as usize]; + let flags = memory_type.property_flags; + + if flags.intersects( + vk::MemoryPropertyFlags::LAZILY_ALLOCATED | vk::MemoryPropertyFlags::PROTECTED, + ) { + continue; // not used by gpu-alloc + } + + if flags.contains(vk::MemoryPropertyFlags::HOST_VISIBLE) { + host_visible_heaps[memory_type.heap_index as usize] = true; + } + + if flags.contains(vk::MemoryPropertyFlags::DEVICE_LOCAL) { + device_local_heaps[memory_type.heap_index as usize] = true; + } + } + + let heaps = if needs_host_access { + host_visible_heaps + } else { + device_local_heaps + }; + + // NOTE: We might end up checking multiple heaps since gpu-alloc doesn't have a way + // for us to query the heap the resource will end up on. But this is unlikely, + // there is usually only one heap on integrated GPUs and two on dedicated GPUs. + + for (i, check) in heaps.iter().enumerate() { + if !check { + continue; + } + + let heap_usage = memory_budget_properties.heap_usage[i]; + let heap_budget = memory_budget_properties.heap_budget[i]; + + if heap_usage + size >= heap_budget / 100 * threshold as u64 { + return Err(crate::DeviceError::OutOfMemory); + } + } + + Ok(()) + } } impl crate::Device for super::Device { @@ -1066,6 +1008,13 @@ impl crate::Device for super::Device { desc.memory_flags.contains(crate::MemoryFlags::TRANSIENT), ); + let needs_host_access = alloc_usage.contains(gpu_alloc::UsageFlags::HOST_ACCESS); + + self.error_if_would_oom_on_resource_allocation(needs_host_access, req.size) + .inspect_err(|_| { + unsafe { self.shared.raw.destroy_buffer(raw, None) }; + })?; + let alignment_mask = req.alignment - 1; let block = unsafe { @@ -1077,15 +1026,21 @@ impl crate::Device for super::Device { usage: alloc_usage, memory_types: req.memory_type_bits & self.valid_ash_memory_types, }, - )? - }; + ) + } + .inspect_err(|_| { + unsafe { self.shared.raw.destroy_buffer(raw, None) }; + })?; unsafe { self.shared .raw .bind_buffer_memory(raw, *block.memory(), block.offset()) - .map_err(super::map_host_device_oom_and_ioca_err)? - }; + } + .map_err(super::map_host_device_oom_and_ioca_err) + .inspect_err(|_| { + unsafe { self.shared.raw.destroy_buffer(raw, None) }; + })?; if let Some(label) = desc.label { unsafe { self.shared.set_object_name(raw, label) }; @@ -1096,7 +1051,7 @@ impl crate::Device for super::Device { Ok(super::Buffer { raw, - block: Some(Mutex::new(block)), + block: Some(Mutex::new(super::BufferMemoryBacking::Managed(block))), }) } unsafe fn destroy_buffer(&self, buffer: super::Buffer) { @@ -1104,7 +1059,14 @@ impl crate::Device for super::Device { if let Some(block) = buffer.block { let block = block.into_inner(); self.counters.buffer_memory.sub(block.size() as isize); - unsafe { self.mem_allocator.lock().dealloc(&*self.shared, block) }; + match block { + super::BufferMemoryBacking::Managed(block) => unsafe { + self.mem_allocator.lock().dealloc(&*self.shared, block) + }, + super::BufferMemoryBacking::VulkanMemory { memory, .. } => unsafe { + self.shared.raw.free_memory(memory, None); + }, + } } self.counters.buffers.sub(1); @@ -1122,18 +1084,27 @@ impl crate::Device for super::Device { if let Some(ref block) = buffer.block { let size = range.end - range.start; let mut block = block.lock(); - let ptr = unsafe { block.map(&*self.shared, range.start, size as usize)? }; - let is_coherent = block - .props() - .contains(gpu_alloc::MemoryPropertyFlags::HOST_COHERENT); - Ok(crate::BufferMapping { ptr, is_coherent }) + if let super::BufferMemoryBacking::Managed(ref mut block) = *block { + let ptr = unsafe { block.map(&*self.shared, range.start, size as usize)? }; + let is_coherent = block + .props() + .contains(gpu_alloc::MemoryPropertyFlags::HOST_COHERENT); + Ok(crate::BufferMapping { ptr, is_coherent }) + } else { + crate::hal_usage_error("tried to map externally created buffer") + } } else { crate::hal_usage_error("tried to map external buffer") } } unsafe fn unmap_buffer(&self, buffer: &super::Buffer) { if let Some(ref block) = buffer.block { - unsafe { block.lock().unmap(&*self.shared) }; + match &mut *block.lock() { + super::BufferMemoryBacking::Managed(block) => unsafe { block.unmap(&*self.shared) }, + super::BufferMemoryBacking::VulkanMemory { .. } => { + crate::hal_usage_error("tried to unmap externally created buffer") + } + }; } else { crate::hal_usage_error("tried to unmap external buffer") } @@ -1176,6 +1147,11 @@ impl crate::Device for super::Device { ) -> Result { let image = self.create_image_without_memory(desc, None)?; + self.error_if_would_oom_on_resource_allocation(false, image.requirements.size) + .inspect_err(|_| { + unsafe { self.shared.raw.destroy_image(image.raw, None) }; + })?; + let block = unsafe { self.mem_allocator.lock().alloc( &*self.shared, @@ -1185,8 +1161,11 @@ impl crate::Device for super::Device { usage: gpu_alloc::UsageFlags::FAST_DEVICE_ACCESS, memory_types: image.requirements.memory_type_bits & self.valid_ash_memory_types, }, - )? - }; + ) + } + .inspect_err(|_| { + unsafe { self.shared.raw.destroy_image(image.raw, None) }; + })?; self.counters.texture_memory.add(block.size() as isize); @@ -1194,13 +1173,18 @@ impl crate::Device for super::Device { self.shared .raw .bind_image_memory(image.raw, *block.memory(), block.offset()) - .map_err(super::map_host_device_oom_err)? - }; + } + .map_err(super::map_host_device_oom_err) + .inspect_err(|_| { + unsafe { self.shared.raw.destroy_image(image.raw, None) }; + })?; if let Some(label) = desc.label { unsafe { self.shared.set_object_name(image.raw, label) }; } + let identity = self.shared.texture_identity_factory.next(); + self.counters.textures.add(1); Ok(super::Texture { @@ -1208,11 +1192,9 @@ impl crate::Device for super::Device { drop_guard: None, external_memory: None, block: Some(block), - usage: desc.usage, format: desc.format, - raw_flags: image.raw_flags, copy_size: image.copy_size, - view_formats: image.view_formats, + identity, }) } unsafe fn destroy_texture(&self, texture: super::Texture) { @@ -1241,24 +1223,22 @@ impl crate::Device for super::Device { desc: &crate::TextureViewDescriptor, ) -> Result { let subresource_range = conv::map_subresource_range(&desc.range, texture.format); + let raw_format = self.shared.private_caps.map_texture_format(desc.format); let mut vk_info = vk::ImageViewCreateInfo::default() .flags(vk::ImageViewCreateFlags::empty()) .image(texture.raw) .view_type(conv::map_view_dimension(desc.dimension)) - .format(self.shared.private_caps.map_texture_format(desc.format)) + .format(raw_format) .subresource_range(subresource_range); let layers = NonZeroU32::new(subresource_range.layer_count).expect("Unexpected zero layer count"); let mut image_view_info; - let view_usage = if self.shared.private_caps.image_view_usage && !desc.usage.is_empty() { + if self.shared.private_caps.image_view_usage && !desc.usage.is_empty() { image_view_info = vk::ImageViewUsageCreateInfo::default().usage(conv::map_texture_usage(desc.usage)); vk_info = vk_info.push_next(&mut image_view_info); - desc.usage - } else { - texture.usage - }; + } let raw = unsafe { self.shared.raw.create_image_view(&vk_info, None) } .map_err(super::map_host_device_oom_and_ioca_err)?; @@ -1267,40 +1247,23 @@ impl crate::Device for super::Device { unsafe { self.shared.set_object_name(raw, label) }; } - let attachment = super::FramebufferAttachment { - raw: if self.shared.private_caps.imageless_framebuffers { - vk::ImageView::null() - } else { - raw - }, - raw_image_flags: texture.raw_flags, - view_usage, - view_format: desc.format, - raw_view_formats: texture - .view_formats - .iter() - .map(|tf| self.shared.private_caps.map_texture_format(*tf)) - .collect(), - }; + let identity = self.shared.texture_view_identity_factory.next(); self.counters.texture_views.add(1); Ok(super::TextureView { + raw_texture: texture.raw, raw, - layers, - attachment, + _layers: layers, + format: desc.format, + raw_format, + base_mip_level: desc.range.base_mip_level, + dimension: desc.dimension, + texture_identity: texture.identity, + view_identity: identity, }) } unsafe fn destroy_texture_view(&self, view: super::TextureView) { - if !self.shared.private_caps.imageless_framebuffers { - let mut fbuf_lock = self.shared.framebuffers.lock(); - for (key, &raw_fbuf) in fbuf_lock.iter() { - if key.attachments.iter().any(|at| at.raw == view.raw) { - unsafe { self.shared.raw.destroy_framebuffer(raw_fbuf, None) }; - } - } - fbuf_lock.retain(|key, _| !key.attachments.iter().any(|at| at.raw == view.raw)); - } unsafe { self.shared.raw.destroy_image_view(view.raw, None) }; self.counters.texture_views.sub(1); @@ -1339,19 +1302,21 @@ impl crate::Device for super::Device { create_info = create_info.border_color(conv::map_border_color(color)); } - let raw = self - .shared - .sampler_cache - .lock() - .create_sampler(&self.shared.raw, create_info)?; + let mut sampler_cache_guard = self.shared.sampler_cache.lock(); + + let raw = sampler_cache_guard.create_sampler(&self.shared.raw, create_info)?; // Note: Cached samplers will just continually overwrite the label // // https://github.com/gfx-rs/wgpu/issues/6867 if let Some(label) = desc.label { + // SAFETY: we are holding a lock on the sampler cache, + // so we can only be setting the name from one thread. unsafe { self.shared.set_object_name(raw, label) }; } + drop(sampler_cache_guard); + self.counters.samplers.add(1); Ok(super::Sampler { raw, create_info }) @@ -1393,7 +1358,10 @@ impl crate::Device for super::Device { discarded: Vec::new(), rpass_debug_marker_active: false, end_of_pass_timer_query: None, + framebuffers: Default::default(), + temp_texture_views: Default::default(), counters: Arc::clone(&self.counters), + current_pipeline_is_multiview: false, }) } @@ -1401,20 +1369,55 @@ impl crate::Device for super::Device { &self, desc: &crate::BindGroupLayoutDescriptor, ) -> Result { + // Iterate through the entries and accumulate our Vulkan + // DescriptorSetLayoutBindings and DescriptorBindingFlags, as well as + // our binding map and our descriptor counts. + // Note: not bothering with on stack arrays here as it's low frequency + let mut vk_bindings = Vec::new(); + let mut binding_flags = Vec::new(); + let mut binding_map = Vec::new(); + let mut next_binding = 0; + let mut contains_binding_arrays = false; let mut desc_count = gpu_descriptor::DescriptorTotalCount::default(); - let mut types = Vec::new(); for entry in desc.entries { + if entry.count.is_some() { + contains_binding_arrays = true; + } + + let partially_bound = desc + .flags + .contains(crate::BindGroupLayoutFlags::PARTIALLY_BOUND); + let mut flags = vk::DescriptorBindingFlags::empty(); + if partially_bound && entry.count.is_some() { + flags |= vk::DescriptorBindingFlags::PARTIALLY_BOUND; + } + if entry.count.is_some() { + flags |= vk::DescriptorBindingFlags::UPDATE_AFTER_BIND; + } + let count = entry.count.map_or(1, |c| c.get()); - if entry.binding as usize >= types.len() { - types.resize( - entry.binding as usize + 1, - (vk::DescriptorType::INPUT_ATTACHMENT, 0), - ); + match entry.ty { + wgt::BindingType::ExternalTexture => unimplemented!(), + _ => { + vk_bindings.push(vk::DescriptorSetLayoutBinding { + binding: next_binding, + descriptor_type: conv::map_binding_type(entry.ty), + descriptor_count: count, + stage_flags: conv::map_shader_stage(entry.visibility), + p_immutable_samplers: ptr::null(), + _marker: Default::default(), + }); + binding_flags.push(flags); + binding_map.push(( + entry.binding, + super::BindingInfo { + binding: next_binding, + binding_array_size: entry.count, + }, + )); + next_binding += 1; + } } - types[entry.binding as usize] = ( - conv::map_binding_type(entry.ty), - entry.count.map_or(1, |c| c.get()), - ); match entry.ty { wgt::BindingType::Buffer { @@ -1449,62 +1452,20 @@ impl crate::Device for super::Device { wgt::BindingType::AccelerationStructure { .. } => { desc_count.acceleration_structure += count; } + wgt::BindingType::ExternalTexture => unimplemented!(), } } - //Note: not bothering with on stack array here as it's low frequency - let vk_bindings = desc - .entries - .iter() - .map(|entry| vk::DescriptorSetLayoutBinding { - binding: entry.binding, - descriptor_type: types[entry.binding as usize].0, - descriptor_count: types[entry.binding as usize].1, - stage_flags: conv::map_shader_stage(entry.visibility), - p_immutable_samplers: ptr::null(), - _marker: Default::default(), - }) - .collect::>(); - - let binding_arrays: Vec<_> = desc - .entries - .iter() - .enumerate() - .filter_map(|(idx, entry)| entry.count.map(|count| (idx as u32, count))) - .collect(); - let vk_info = vk::DescriptorSetLayoutCreateInfo::default() .bindings(&vk_bindings) - .flags(if !binding_arrays.is_empty() { + .flags(if contains_binding_arrays { vk::DescriptorSetLayoutCreateFlags::UPDATE_AFTER_BIND_POOL } else { vk::DescriptorSetLayoutCreateFlags::empty() }); - let partially_bound = desc - .flags - .contains(crate::BindGroupLayoutFlags::PARTIALLY_BOUND); - - let binding_flag_vec = desc - .entries - .iter() - .map(|entry| { - let mut flags = vk::DescriptorBindingFlags::empty(); - - if partially_bound && entry.count.is_some() { - flags |= vk::DescriptorBindingFlags::PARTIALLY_BOUND; - } - - if entry.count.is_some() { - flags |= vk::DescriptorBindingFlags::UPDATE_AFTER_BIND; - } - - flags - }) - .collect::>(); - - let mut binding_flag_info = vk::DescriptorSetLayoutBindingFlagsCreateInfo::default() - .binding_flags(&binding_flag_vec); + let mut binding_flag_info = + vk::DescriptorSetLayoutBindingFlagsCreateInfo::default().binding_flags(&binding_flags); let vk_info = vk_info.push_next(&mut binding_flag_info); @@ -1524,8 +1485,9 @@ impl crate::Device for super::Device { Ok(super::BindGroupLayout { raw, desc_count, - types: types.into_boxed_slice(), - binding_arrays, + entries: desc.entries.into(), + binding_map, + contains_binding_arrays, }) } unsafe fn destroy_bind_group_layout(&self, bg_layout: super::BindGroupLayout) { @@ -1577,27 +1539,25 @@ impl crate::Device for super::Device { unsafe { self.shared.set_object_name(raw, label) }; } - let mut binding_arrays = BTreeMap::new(); + let mut binding_map = BTreeMap::new(); for (group, &layout) in desc.bind_group_layouts.iter().enumerate() { - for &(binding, binding_array_size) in &layout.binding_arrays { - binding_arrays.insert( + for &(binding, binding_info) in &layout.binding_map { + binding_map.insert( naga::ResourceBinding { group: group as u32, binding, }, naga::back::spv::BindingInfo { - binding_array_size: Some(binding_array_size.get()), + descriptor_set: group as u32, + binding: binding_info.binding, + binding_array_size: binding_info.binding_array_size.map(NonZeroU32::get), }, ); } } self.counters.pipeline_layouts.add(1); - - Ok(super::PipelineLayout { - raw, - binding_arrays, - }) + Ok(super::PipelineLayout { raw, binding_map }) } unsafe fn destroy_pipeline_layout(&self, pipeline_layout: super::PipelineLayout) { unsafe { @@ -1619,9 +1579,7 @@ impl crate::Device for super::Device { super::AccelerationStructure, >, ) -> Result { - let contains_binding_arrays = !desc.layout.binding_arrays.is_empty(); - - let desc_set_layout_flags = if contains_binding_arrays { + let desc_set_layout_flags = if desc.layout.contains_binding_arrays { gpu_descriptor::DescriptorSetLayoutCreateFlags::UPDATE_AFTER_BIND } else { gpu_descriptor::DescriptorSetLayoutCreateFlags::empty() @@ -1707,18 +1665,22 @@ impl crate::Device for super::Device { Vec::with_capacity(desc.acceleration_structures.len()); let mut raw_acceleration_structures = ExtendStack::from_vec_capacity(&mut raw_acceleration_structures); - for entry in desc.entries { - let (ty, size) = desc.layout.types[entry.binding as usize]; - if size == 0 { - continue; // empty slot - } - let mut write = vk::WriteDescriptorSet::default() - .dst_set(*set.raw()) - .dst_binding(entry.binding) - .descriptor_type(ty); - write = match ty { - vk::DescriptorType::SAMPLER => { + let layout_and_entry_iter = desc.entries.iter().map(|entry| { + let layout = desc + .layout + .entries + .iter() + .find(|layout_entry| layout_entry.binding == entry.binding) + .expect("internal error: no layout entry found with binding slot"); + (layout, entry) + }); + let mut next_binding = 0; + for (layout, entry) in layout_and_entry_iter { + let write = vk::WriteDescriptorSet::default().dst_set(*set.raw()); + + match layout.ty { + wgt::BindingType::Sampler(_) => { let start = entry.resource_index; let end = start + entry.count; let local_image_infos; @@ -1726,30 +1688,37 @@ impl crate::Device for super::Device { image_infos.extend(desc.samplers[start as usize..end as usize].iter().map( |sampler| vk::DescriptorImageInfo::default().sampler(sampler.raw), )); - write.image_info(local_image_infos) + writes.push( + write + .dst_binding(next_binding) + .descriptor_type(conv::map_binding_type(layout.ty)) + .image_info(local_image_infos), + ); + next_binding += 1; } - vk::DescriptorType::SAMPLED_IMAGE | vk::DescriptorType::STORAGE_IMAGE => { + wgt::BindingType::Texture { .. } | wgt::BindingType::StorageTexture { .. } => { let start = entry.resource_index; let end = start + entry.count; let local_image_infos; (image_infos, local_image_infos) = image_infos.extend(desc.textures[start as usize..end as usize].iter().map( |binding| { - let layout = conv::derive_image_layout( - binding.usage, - binding.view.attachment.view_format, - ); + let layout = + conv::derive_image_layout(binding.usage, binding.view.format); vk::DescriptorImageInfo::default() .image_view(binding.view.raw) .image_layout(layout) }, )); - write.image_info(local_image_infos) + writes.push( + write + .dst_binding(next_binding) + .descriptor_type(conv::map_binding_type(layout.ty)) + .image_info(local_image_infos), + ); + next_binding += 1; } - vk::DescriptorType::UNIFORM_BUFFER - | vk::DescriptorType::UNIFORM_BUFFER_DYNAMIC - | vk::DescriptorType::STORAGE_BUFFER - | vk::DescriptorType::STORAGE_BUFFER_DYNAMIC => { + wgt::BindingType::Buffer { .. } => { let start = entry.resource_index; let end = start + entry.count; let local_buffer_infos; @@ -1764,9 +1733,15 @@ impl crate::Device for super::Device { ) }, )); - write.buffer_info(local_buffer_infos) + writes.push( + write + .dst_binding(next_binding) + .descriptor_type(conv::map_binding_type(layout.ty)) + .buffer_info(local_buffer_infos), + ); + next_binding += 1; } - vk::DescriptorType::ACCELERATION_STRUCTURE_KHR => { + wgt::BindingType::AccelerationStructure { .. } => { let start = entry.resource_index; let end = start + entry.count; @@ -1789,14 +1764,17 @@ impl crate::Device for super::Device { .acceleration_structures(local_raw_acceleration_structures), ); - write - .descriptor_count(entry.count) - .push_next(local_acceleration_structure_infos) + writes.push( + write + .dst_binding(next_binding) + .descriptor_type(conv::map_binding_type(layout.ty)) + .descriptor_count(entry.count) + .push_next(local_acceleration_structure_infos), + ); + next_binding += 1; } - _ => unreachable!(), - }; - - writes.push(write); + wgt::BindingType::ExternalTexture => unimplemented!(), + } } unsafe { self.shared.raw.update_descriptor_sets(&writes, &[]) }; @@ -1821,19 +1799,20 @@ impl crate::Device for super::Device { desc: &crate::ShaderModuleDescriptor, shader: crate::ShaderInput, ) -> Result { - let spv = match shader { - crate::ShaderInput::Naga(naga_shader) => { + let shader_module = match shader { + crate::ShaderInput::Naga(naga_shader) if self .shared .workarounds .contains(super::Workarounds::SEPARATE_ENTRY_POINTS) - || !naga_shader.module.overrides.is_empty() - { - return Ok(super::ShaderModule::Intermediate { - naga_shader, - runtime_checks: desc.runtime_checks, - }); + || !naga_shader.module.overrides.is_empty() => + { + super::ShaderModule::Intermediate { + naga_shader, + runtime_checks: desc.runtime_checks, } + } + crate::ShaderInput::Naga(naga_shader) => { let mut naga_options = self.naga_options.clone(); naga_options.debug_info = naga_shader @@ -1841,7 +1820,7 @@ impl crate::Device for super::Device { .as_ref() .map(|d| naga::back::spv::DebugInfo { source_code: d.source_code.as_ref(), - file_name: d.file_name.as_ref().as_ref(), + file_name: d.file_name.as_ref(), language: naga::back::spv::SourceLanguage::WGSL, }); if !desc.runtime_checks.bounds_checks { @@ -1852,28 +1831,27 @@ impl crate::Device for super::Device { binding_array: naga::proc::BoundsCheckPolicy::Unchecked, }; } - Cow::Owned( - naga::back::spv::write_vec( - &naga_shader.module, - &naga_shader.info, - &naga_options, - None, - ) - .map_err(|e| crate::ShaderError::Compilation(format!("{e}")))?, + let spv = naga::back::spv::write_vec( + &naga_shader.module, + &naga_shader.info, + &naga_options, + None, ) + .map_err(|e| crate::ShaderError::Compilation(format!("{e}")))?; + super::ShaderModule::Raw(self.create_shader_module_impl(&spv, &desc.label)?) } - crate::ShaderInput::SpirV(spv) => Cow::Borrowed(spv), + crate::ShaderInput::SpirV(data) => { + super::ShaderModule::Raw(self.create_shader_module_impl(data, &desc.label)?) + } + crate::ShaderInput::Msl { .. } + | crate::ShaderInput::Dxil { .. } + | crate::ShaderInput::Hlsl { .. } + | crate::ShaderInput::Glsl { .. } => unreachable!(), }; - let raw = self.create_shader_module_impl(&spv)?; - - if let Some(label) = desc.label { - unsafe { self.shared.set_object_name(raw, label) }; - } - self.counters.shader_modules.add(1); - Ok(super::ShaderModule::Raw(raw)) + Ok(shader_module) } unsafe fn destroy_shader_module(&self, module: super::ShaderModule) { @@ -1903,29 +1881,36 @@ impl crate::Device for super::Device { ]; let mut compatible_rp_key = super::RenderPassKey { sample_count: desc.multisample.count, - multiview: desc.multiview, + multiview_mask: desc.multiview_mask, ..Default::default() }; let mut stages = ArrayVec::<_, { crate::MAX_CONCURRENT_SHADER_STAGES }>::new(); - let mut vertex_buffers = Vec::with_capacity(desc.vertex_buffers.len()); + let mut vertex_buffers = Vec::new(); let mut vertex_attributes = Vec::new(); - for (i, vb) in desc.vertex_buffers.iter().enumerate() { - vertex_buffers.push(vk::VertexInputBindingDescription { - binding: i as u32, - stride: vb.array_stride as u32, - input_rate: match vb.step_mode { - wgt::VertexStepMode::Vertex => vk::VertexInputRate::VERTEX, - wgt::VertexStepMode::Instance => vk::VertexInputRate::INSTANCE, - }, - }); - for at in vb.attributes { - vertex_attributes.push(vk::VertexInputAttributeDescription { - location: at.shader_location, + if let crate::VertexProcessor::Standard { + vertex_buffers: desc_vertex_buffers, + vertex_stage: _, + } = &desc.vertex_processor + { + vertex_buffers = Vec::with_capacity(desc_vertex_buffers.len()); + for (i, vb) in desc_vertex_buffers.iter().enumerate() { + vertex_buffers.push(vk::VertexInputBindingDescription { binding: i as u32, - format: conv::map_vertex_format(at.format), - offset: at.offset as u32, + stride: vb.array_stride as u32, + input_rate: match vb.step_mode { + wgt::VertexStepMode::Vertex => vk::VertexInputRate::VERTEX, + wgt::VertexStepMode::Instance => vk::VertexInputRate::INSTANCE, + }, }); + for at in vb.attributes { + vertex_attributes.push(vk::VertexInputAttributeDescription { + location: at.shader_location, + binding: i as u32, + format: conv::map_vertex_format(at.format), + offset: at.offset as u32, + }); + } } } @@ -1937,18 +1922,47 @@ impl crate::Device for super::Device { .topology(conv::map_topology(desc.primitive.topology)) .primitive_restart_enable(desc.primitive.strip_index_format.is_some()); - let compiled_vs = self.compile_stage( - &desc.vertex_stage, - naga::ShaderStage::Vertex, - &desc.layout.binding_arrays, - )?; - stages.push(compiled_vs.create_info); + let mut compiled_vs = None; + let mut compiled_ms = None; + let mut compiled_ts = None; + match &desc.vertex_processor { + crate::VertexProcessor::Standard { + vertex_buffers: _, + vertex_stage, + } => { + compiled_vs = Some(self.compile_stage( + vertex_stage, + naga::ShaderStage::Vertex, + &desc.layout.binding_map, + )?); + stages.push(compiled_vs.as_ref().unwrap().create_info); + } + crate::VertexProcessor::Mesh { + task_stage, + mesh_stage, + } => { + if let Some(t) = task_stage.as_ref() { + compiled_ts = Some(self.compile_stage( + t, + naga::ShaderStage::Task, + &desc.layout.binding_map, + )?); + stages.push(compiled_ts.as_ref().unwrap().create_info); + } + compiled_ms = Some(self.compile_stage( + mesh_stage, + naga::ShaderStage::Mesh, + &desc.layout.binding_map, + )?); + stages.push(compiled_ms.as_ref().unwrap().create_info); + } + } let compiled_fs = match desc.fragment_stage { Some(ref stage) => { let compiled = self.compile_stage( stage, naga::ShaderStage::Fragment, - &desc.layout.binding_arrays, + &desc.layout.binding_map, )?; stages.push(compiled.create_info); Some(compiled) @@ -2105,228 +2119,13 @@ impl crate::Device for super::Device { unsafe { self.shared.set_object_name(raw, label) }; } - if let Some(raw_module) = compiled_vs.temp_raw_module { - unsafe { self.shared.raw.destroy_shader_module(raw_module, None) }; - } if let Some(CompiledStage { temp_raw_module: Some(raw_module), .. - }) = compiled_fs + }) = compiled_vs { unsafe { self.shared.raw.destroy_shader_module(raw_module, None) }; } - - self.counters.render_pipelines.add(1); - - Ok(super::RenderPipeline { raw }) - } - unsafe fn create_mesh_pipeline( - &self, - desc: &crate::MeshPipelineDescriptor< - ::PipelineLayout, - ::ShaderModule, - ::PipelineCache, - >, - ) -> Result<::RenderPipeline, crate::PipelineError> { - let dynamic_states = [ - vk::DynamicState::VIEWPORT, - vk::DynamicState::SCISSOR, - vk::DynamicState::BLEND_CONSTANTS, - vk::DynamicState::STENCIL_REFERENCE, - ]; - let mut compatible_rp_key = super::RenderPassKey { - sample_count: desc.multisample.count, - multiview: desc.multiview, - ..Default::default() - }; - let mut stages = ArrayVec::<_, { crate::MAX_CONCURRENT_SHADER_STAGES }>::new(); - - let vk_input_assembly = vk::PipelineInputAssemblyStateCreateInfo::default() - .topology(conv::map_topology(desc.primitive.topology)) - .primitive_restart_enable(desc.primitive.strip_index_format.is_some()); - - let compiled_ts = match desc.task_stage { - Some(ref stage) => { - let mut compiled = self.compile_stage( - stage, - naga::ShaderStage::Task, - &desc.layout.binding_arrays, - )?; - compiled.create_info.stage = vk::ShaderStageFlags::TASK_EXT; - stages.push(compiled.create_info); - Some(compiled) - } - None => None, - }; - - let mut compiled_ms = self.compile_stage( - &desc.mesh_stage, - naga::ShaderStage::Mesh, - &desc.layout.binding_arrays, - )?; - compiled_ms.create_info.stage = vk::ShaderStageFlags::MESH_EXT; - stages.push(compiled_ms.create_info); - let compiled_fs = match desc.fragment_stage { - Some(ref stage) => { - let compiled = self.compile_stage( - stage, - naga::ShaderStage::Fragment, - &desc.layout.binding_arrays, - )?; - stages.push(compiled.create_info); - Some(compiled) - } - None => None, - }; - - let mut vk_rasterization = vk::PipelineRasterizationStateCreateInfo::default() - .polygon_mode(conv::map_polygon_mode(desc.primitive.polygon_mode)) - .front_face(conv::map_front_face(desc.primitive.front_face)) - .line_width(1.0) - .depth_clamp_enable(desc.primitive.unclipped_depth); - if let Some(face) = desc.primitive.cull_mode { - vk_rasterization = vk_rasterization.cull_mode(conv::map_cull_face(face)) - } - let mut vk_rasterization_conservative_state = - vk::PipelineRasterizationConservativeStateCreateInfoEXT::default() - .conservative_rasterization_mode( - vk::ConservativeRasterizationModeEXT::OVERESTIMATE, - ); - if desc.primitive.conservative { - vk_rasterization = vk_rasterization.push_next(&mut vk_rasterization_conservative_state); - } - - let mut vk_depth_stencil = vk::PipelineDepthStencilStateCreateInfo::default(); - if let Some(ref ds) = desc.depth_stencil { - let vk_format = self.shared.private_caps.map_texture_format(ds.format); - let vk_layout = if ds.is_read_only(desc.primitive.cull_mode) { - vk::ImageLayout::DEPTH_STENCIL_READ_ONLY_OPTIMAL - } else { - vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL - }; - compatible_rp_key.depth_stencil = Some(super::DepthStencilAttachmentKey { - base: super::AttachmentKey::compatible(vk_format, vk_layout), - stencil_ops: crate::AttachmentOps::all(), - }); - - if ds.is_depth_enabled() { - vk_depth_stencil = vk_depth_stencil - .depth_test_enable(true) - .depth_write_enable(ds.depth_write_enabled) - .depth_compare_op(conv::map_comparison(ds.depth_compare)); - } - if ds.stencil.is_enabled() { - let s = &ds.stencil; - let front = conv::map_stencil_face(&s.front, s.read_mask, s.write_mask); - let back = conv::map_stencil_face(&s.back, s.read_mask, s.write_mask); - vk_depth_stencil = vk_depth_stencil - .stencil_test_enable(true) - .front(front) - .back(back); - } - - if ds.bias.is_enabled() { - vk_rasterization = vk_rasterization - .depth_bias_enable(true) - .depth_bias_constant_factor(ds.bias.constant as f32) - .depth_bias_clamp(ds.bias.clamp) - .depth_bias_slope_factor(ds.bias.slope_scale); - } - } - - let vk_viewport = vk::PipelineViewportStateCreateInfo::default() - .flags(vk::PipelineViewportStateCreateFlags::empty()) - .scissor_count(1) - .viewport_count(1); - - let vk_sample_mask = [ - desc.multisample.mask as u32, - (desc.multisample.mask >> 32) as u32, - ]; - let vk_multisample = vk::PipelineMultisampleStateCreateInfo::default() - .rasterization_samples(vk::SampleCountFlags::from_raw(desc.multisample.count)) - .alpha_to_coverage_enable(desc.multisample.alpha_to_coverage_enabled) - .sample_mask(&vk_sample_mask); - - let mut vk_attachments = Vec::with_capacity(desc.color_targets.len()); - for cat in desc.color_targets { - let (key, attarchment) = if let Some(cat) = cat.as_ref() { - let mut vk_attachment = vk::PipelineColorBlendAttachmentState::default() - .color_write_mask(vk::ColorComponentFlags::from_raw(cat.write_mask.bits())); - if let Some(ref blend) = cat.blend { - let (color_op, color_src, color_dst) = conv::map_blend_component(&blend.color); - let (alpha_op, alpha_src, alpha_dst) = conv::map_blend_component(&blend.alpha); - vk_attachment = vk_attachment - .blend_enable(true) - .color_blend_op(color_op) - .src_color_blend_factor(color_src) - .dst_color_blend_factor(color_dst) - .alpha_blend_op(alpha_op) - .src_alpha_blend_factor(alpha_src) - .dst_alpha_blend_factor(alpha_dst); - } - - let vk_format = self.shared.private_caps.map_texture_format(cat.format); - ( - Some(super::ColorAttachmentKey { - base: super::AttachmentKey::compatible( - vk_format, - vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL, - ), - resolve: None, - }), - vk_attachment, - ) - } else { - (None, vk::PipelineColorBlendAttachmentState::default()) - }; - - compatible_rp_key.colors.push(key); - vk_attachments.push(attarchment); - } - - let vk_color_blend = - vk::PipelineColorBlendStateCreateInfo::default().attachments(&vk_attachments); - - let vk_dynamic_state = - vk::PipelineDynamicStateCreateInfo::default().dynamic_states(&dynamic_states); - - let raw_pass = self.shared.make_render_pass(compatible_rp_key)?; - - let vk_infos = [{ - vk::GraphicsPipelineCreateInfo::default() - .layout(desc.layout.raw) - .stages(&stages) - .input_assembly_state(&vk_input_assembly) - .rasterization_state(&vk_rasterization) - .viewport_state(&vk_viewport) - .multisample_state(&vk_multisample) - .depth_stencil_state(&vk_depth_stencil) - .color_blend_state(&vk_color_blend) - .dynamic_state(&vk_dynamic_state) - .render_pass(raw_pass) - }]; - - let pipeline_cache = desc - .cache - .map(|it| it.raw) - .unwrap_or(vk::PipelineCache::null()); - - let mut raw_vec = { - profiling::scope!("vkCreateGraphicsPipelines"); - unsafe { - self.shared - .raw - .create_graphics_pipelines(pipeline_cache, &vk_infos, None) - .map_err(|(_, e)| super::map_pipeline_err(e)) - }? - }; - - let raw = raw_vec.pop().unwrap(); - if let Some(label) = desc.label { - unsafe { self.shared.set_object_name(raw, label) }; - } - // NOTE: this could leak shaders in case of an error. if let Some(CompiledStage { temp_raw_module: Some(raw_module), .. @@ -2334,7 +2133,11 @@ impl crate::Device for super::Device { { unsafe { self.shared.raw.destroy_shader_module(raw_module, None) }; } - if let Some(raw_module) = compiled_ms.temp_raw_module { + if let Some(CompiledStage { + temp_raw_module: Some(raw_module), + .. + }) = compiled_ms + { unsafe { self.shared.raw.destroy_shader_module(raw_module, None) }; } if let Some(CompiledStage { @@ -2347,7 +2150,10 @@ impl crate::Device for super::Device { self.counters.render_pipelines.add(1); - Ok(super::RenderPipeline { raw }) + Ok(super::RenderPipeline { + raw, + is_multiview: desc.multiview_mask.is_some(), + }) } unsafe fn destroy_render_pipeline(&self, pipeline: super::RenderPipeline) { @@ -2367,7 +2173,7 @@ impl crate::Device for super::Device { let compiled = self.compile_stage( &desc.stage, naga::ShaderStage::Compute, - &desc.layout.binding_arrays, + &desc.layout.binding_map, )?; let vk_infos = [{ @@ -2435,6 +2241,10 @@ impl crate::Device for super::Device { &self, desc: &wgt::QuerySetDescriptor, ) -> Result { + // Assume each query is 256 bytes. + // On an AMD W6800 with driver version 32.0.12030.9, occlusion queries are 256. + self.error_if_would_oom_on_resource_allocation(true, desc.count as u64 * 256)?; + let (vk_type, pipeline_statistics) = match desc.ty { wgt::QueryType::Occlusion => ( vk::QueryType::OCCLUSION, @@ -2525,13 +2335,16 @@ impl crate::Device for super::Device { &self, fence: &super::Fence, wait_value: crate::FenceValue, - timeout_ms: u32, + timeout: Option, ) -> Result { - let timeout_ns = timeout_ms as u64 * super::MILLIS_TO_NANOS; + let timeout_ns = timeout + .unwrap_or(Duration::MAX) + .as_nanos() + .min(u64::MAX as _) as u64; self.shared.wait_for_fence(fence, wait_value, timeout_ns) } - unsafe fn start_capture(&self) -> bool { + unsafe fn start_graphics_debugger_capture(&self) -> bool { #[cfg(feature = "renderdoc")] { // Renderdoc requires us to give us the pointer that vkInstance _points to_. @@ -2546,7 +2359,7 @@ impl crate::Device for super::Device { #[cfg(not(feature = "renderdoc"))] false } - unsafe fn stop_capture(&self) { + unsafe fn stop_graphics_debugger_capture(&self) { #[cfg(feature = "renderdoc")] { // Renderdoc requires us to give us the pointer that vkInstance _points to_. @@ -2646,7 +2459,7 @@ impl crate::Device for super::Device { triangle_data.index_type(conv::map_index_format(indices.format)); indices.count / 3 } else { - triangles.vertex_count + triangles.vertex_count / 3 }; let geometry = vk::AccelerationStructureGeometryKHR::default() @@ -2764,20 +2577,34 @@ impl crate::Device for super::Device { .map_err(super::map_host_device_oom_and_ioca_err)?; let req = self.shared.raw.get_buffer_memory_requirements(raw_buffer); - let block = self.mem_allocator.lock().alloc( - &*self.shared, - gpu_alloc::Request { - size: req.size, - align_mask: req.alignment - 1, - usage: gpu_alloc::UsageFlags::FAST_DEVICE_ACCESS, - memory_types: req.memory_type_bits & self.valid_ash_memory_types, - }, - )?; + self.error_if_would_oom_on_resource_allocation(false, req.size) + .inspect_err(|_| { + self.shared.raw.destroy_buffer(raw_buffer, None); + })?; + + let block = self + .mem_allocator + .lock() + .alloc( + &*self.shared, + gpu_alloc::Request { + size: req.size, + align_mask: req.alignment - 1, + usage: gpu_alloc::UsageFlags::FAST_DEVICE_ACCESS, + memory_types: req.memory_type_bits & self.valid_ash_memory_types, + }, + ) + .inspect_err(|_| { + self.shared.raw.destroy_buffer(raw_buffer, None); + })?; self.shared .raw .bind_buffer_memory(raw_buffer, *block.memory(), block.offset()) - .map_err(super::map_host_device_oom_and_ioca_err)?; + .map_err(super::map_host_device_oom_and_ioca_err) + .inspect_err(|_| { + self.shared.raw.destroy_buffer(raw_buffer, None); + })?; if let Some(label) = desc.label { self.shared.set_object_name(raw_buffer, label); @@ -2792,7 +2619,10 @@ impl crate::Device for super::Device { let raw_acceleration_structure = ray_tracing_functions .acceleration_structure .create_acceleration_structure(&vk_info, None) - .map_err(super::map_host_oom_and_ioca_err)?; + .map_err(super::map_host_oom_and_ioca_err) + .inspect_err(|_| { + self.shared.raw.destroy_buffer(raw_buffer, None); + })?; if let Some(label) = desc.label { self.shared @@ -2808,7 +2638,13 @@ impl crate::Device for super::Device { .shared .raw .create_query_pool(&vk_info, None) - .map_err(super::map_host_oom_and_ioca_err)?; + .map_err(super::map_host_device_oom_err) + .inspect_err(|_| { + ray_tracing_functions + .acceleration_structure + .destroy_acceleration_structure(raw_acceleration_structure, None); + self.shared.raw.destroy_buffer(raw_buffer, None); + })?; Some(raw) } else { None @@ -2869,14 +2705,73 @@ impl crate::Device for super::Device { }; bytemuck::bytes_of(&temp).to_vec() } + + fn check_if_oom(&self) -> Result<(), crate::DeviceError> { + let Some(threshold) = self + .shared + .instance + .memory_budget_thresholds + .for_device_loss + else { + return Ok(()); + }; + + if !self + .shared + .enabled_extensions + .contains(&ext::memory_budget::NAME) + { + return Ok(()); + } + + let get_physical_device_properties = self + .shared + .instance + .get_physical_device_properties + .as_ref() + .unwrap(); + + let mut memory_budget_properties = vk::PhysicalDeviceMemoryBudgetPropertiesEXT::default(); + + let mut memory_properties = + vk::PhysicalDeviceMemoryProperties2::default().push_next(&mut memory_budget_properties); + + unsafe { + get_physical_device_properties.get_physical_device_memory_properties2( + self.shared.physical_device, + &mut memory_properties, + ); + } + + let memory_properties = memory_properties.memory_properties; + + for i in 0..memory_properties.memory_heap_count { + let heap_usage = memory_budget_properties.heap_usage[i as usize]; + let heap_budget = memory_budget_properties.heap_budget[i as usize]; + + if heap_usage >= heap_budget / 100 * threshold as u64 { + return Err(crate::DeviceError::OutOfMemory); + } + } + + Ok(()) + } } impl super::DeviceShared { - pub(super) fn new_binary_semaphore(&self) -> Result { + pub(super) fn new_binary_semaphore( + &self, + name: &str, + ) -> Result { unsafe { - self.raw + let semaphore = self + .raw .create_semaphore(&vk::SemaphoreCreateInfo::default(), None) - .map_err(super::map_host_device_oom_err) + .map_err(super::map_host_device_oom_err)?; + + self.set_object_name(semaphore, name); + + Ok(semaphore) } } @@ -2978,6 +2873,4 @@ struct ImageWithoutMemory { raw: vk::Image, requirements: vk::MemoryRequirements, copy_size: crate::CopyExtent, - view_formats: Vec, - raw_flags: vk::ImageCreateFlags, } diff --git a/wgpu-hal/src/vulkan/drm.rs b/wgpu-hal/src/vulkan/drm.rs index ec62a8f25..807260e33 100644 --- a/wgpu-hal/src/vulkan/drm.rs +++ b/wgpu-hal/src/vulkan/drm.rs @@ -1,10 +1,19 @@ #![cfg(all(unix, not(target_vendor = "apple"), not(target_family = "wasm")))] +use alloc::{string::ToString, vec::Vec}; use core::mem::MaybeUninit; -use std::{string::ToString, vec::Vec}; use ash::{ext, khr, vk}; +macro_rules! to_u64 { + ($expr:expr) => {{ + #[allow(trivial_numeric_casts)] + let expr = $expr as u64; + assert!(size_of_val(&expr) <= size_of::()); + expr + }}; +} + impl super::Instance { /// Creates a new surface from the given drm configuration. /// @@ -45,7 +54,7 @@ impl super::Instance { let raw_devices = match unsafe { self.shared.raw.enumerate_physical_devices() } { Ok(devices) => devices, Err(err) => { - log::error!("enumerate_adapters: {}", err); + log::error!("enumerate_adapters: {err}"); Vec::new() } }; @@ -77,12 +86,18 @@ impl super::Instance { let render_devid = libc::makedev(drm_props.render_major as _, drm_props.render_minor as _); - // Various platforms use different widths between `dev_t` and `c_int`, so just - // force-convert to `u64` to keep things portable. + // On most platforms, both `*_devid`s and `st_rdev` are `dev_t`s (which is generally + // observed to be an unsigned integral type no greater than 64 bits). However, on some + // platforms, there divergences from this pattern: + // + // - `armv7-linux-androideabi`: `dev_t` is `c_ulong`, and `*_devid`s are `dev_t`, but + // `st_rdev` is `c_ulonglong`. So, we can't just do a `==` comparison. + // - OpenBSD has `dev_t` on both sides, but is `i32` (N.B., unsigned). Therefore, we + // can't just use `u64::from`. #[allow(clippy::useless_conversion)] if [primary_devid, render_devid] - .map(u64::from) - .contains(&drm_stat.st_rdev) + .map(|devid| to_u64!(devid)) + .contains(&to_u64!(drm_stat.st_rdev)) { physical_device = Some(device) } diff --git a/wgpu-hal/src/vulkan/instance.rs b/wgpu-hal/src/vulkan/instance.rs index 2997b6061..6225371b0 100644 --- a/wgpu-hal/src/vulkan/instance.rs +++ b/wgpu-hal/src/vulkan/instance.rs @@ -1,14 +1,12 @@ -use std::{ - borrow::ToOwned as _, - boxed::Box, - ffi::{c_void, CStr, CString}, +use alloc::{borrow::ToOwned as _, boxed::Box, ffi::CString, string::String, sync::Arc, vec::Vec}; +use core::{ + ffi::{c_void, CStr}, + marker::PhantomData, + mem::ManuallyDrop, slice, str::FromStr, - string::{String, ToString as _}, - sync::Arc, - thread, - vec::Vec, }; +use std::thread; use arrayvec::ArrayVec; use ash::{ext, khr, vk}; @@ -20,7 +18,7 @@ unsafe extern "system" fn debug_utils_messenger_callback( callback_data_ptr: *const vk::DebugUtilsMessengerCallbackDataEXT, user_data: *mut c_void, ) -> vk::Bool32 { - use std::borrow::Cow; + use alloc::borrow::Cow; if thread::panicking() { return vk::FALSE; @@ -73,6 +71,15 @@ unsafe extern "system" fn debug_utils_messenger_callback( return vk::FALSE; } + // Silence Vulkan Validation error "VUID-StandaloneSpirv-None-10684". + // + // This is a bug. To prevent massive noise in the tests, lets suppress it for now. + // https://github.com/gfx-rs/wgpu/issues/7696 + const VUID_STANDALONESPIRV_NONE_10684: i32 = 0xb210f7c2_u32 as i32; + if cd.message_id_number == VUID_STANDALONESPIRV_NONE_10684 { + return vk::FALSE; + } + let level = match message_severity { vk::DebugUtilsMessageSeverityFlagsEXT::VERBOSE => log::Level::Debug, vk::DebugUtilsMessageSeverityFlagsEXT::INFO => log::Level::Info, @@ -142,7 +149,10 @@ unsafe extern "system" fn debug_utils_messenger_callback( }); } + #[cfg(feature = "validation_canary")] if cfg!(debug_assertions) && level == log::Level::Error { + use alloc::string::ToString as _; + // Set canary and continue crate::VALIDATION_CANARY.add(message.to_string()); } @@ -161,37 +171,6 @@ impl super::DebugUtilsCreateInfo { } } -impl super::Swapchain { - /// # Safety - /// - /// - The device must have been made idle before calling this function. - unsafe fn release_resources(mut self, device: &ash::Device) -> Self { - profiling::scope!("Swapchain::release_resources"); - { - profiling::scope!("vkDeviceWaitIdle"); - // We need to also wait until all presentation work is done. Because there is no way to portably wait until - // the presentation work is done, we are forced to wait until the device is idle. - let _ = unsafe { - device - .device_wait_idle() - .map_err(super::map_host_device_oom_and_lost_err) - }; - }; - - // We cannot take this by value, as the function returns `self`. - for semaphore in self.surface_semaphores.drain(..) { - let arc_removed = Arc::into_inner(semaphore).expect( - "Trying to destroy a SurfaceSemaphores that is still in use by a SurfaceTexture", - ); - let mutex_removed = arc_removed.into_inner(); - - unsafe { mutex_removed.destroy(device) }; - } - - self - } -} - impl super::InstanceShared { pub fn entry(&self) -> &ash::Entry { &self.entry @@ -347,10 +326,11 @@ impl super::Instance { debug_utils_create_info: Option, extensions: Vec<&'static CStr>, flags: wgt::InstanceFlags, + memory_budget_thresholds: wgt::MemoryBudgetThresholds, has_nv_optimus: bool, drop_callback: Option, ) -> Result { - log::debug!("Instance version: 0x{:x}", instance_api_version); + log::debug!("Instance version: 0x{instance_api_version:x}"); let debug_utils = if let Some(debug_utils_create_info) = debug_utils_create_info { if extensions.contains(&ext::debug_utils::NAME) { @@ -397,6 +377,7 @@ impl super::Instance { extensions, drop_guard, flags, + memory_budget_thresholds, debug_utils, get_physical_device_properties, entry, @@ -537,7 +518,7 @@ impl super::Instance { #[cfg(metal)] fn create_surface_from_view( &self, - view: std::ptr::NonNull, + view: core::ptr::NonNull, ) -> Result { if !self.shared.extensions.contains(&ext::metal_surface::NAME) { return Err(crate::InstanceError::new(String::from( @@ -567,35 +548,27 @@ impl super::Instance { &self, surface: vk::SurfaceKHR, ) -> super::Surface { - let functor = khr::surface::Instance::new(&self.shared.entry, &self.shared.raw); + let native_surface = + crate::vulkan::swapchain::NativeSurface::from_vk_surface_khr(self, surface); + super::Surface { - raw: surface, - functor, - instance: Arc::clone(&self.shared), + inner: ManuallyDrop::new(Box::new(native_surface)), swapchain: RwLock::new(None), } } -} -impl Drop for super::InstanceShared { - fn drop(&mut self) { - unsafe { - // Keep du alive since destroy_instance may also log - let _du = self.debug_utils.take().inspect(|du| { - du.extension - .destroy_debug_utils_messenger(du.messenger, None); - }); - if self.drop_guard.is_none() { - self.raw.destroy_instance(None); - } - } - } -} - -impl crate::Instance for super::Instance { - type A = super::Api; - - unsafe fn init(desc: &crate::InstanceDescriptor) -> Result { + /// `Instance::init` but with a callback. + /// If you want to add extensions, add the to the `Vec<'static CStr>` not the create info, otherwise + /// it will be overwritten + /// + /// # Safety: + /// Same as `init` but additionally + /// - Callback must not remove features. + /// - Callback must not change anything to what the instance does not support. + pub unsafe fn init_with_callback( + desc: &crate::InstanceDescriptor, + callback: Option>, + ) -> Result { profiling::scope!("Init Vulkan Backend"); let entry = unsafe { @@ -644,14 +617,24 @@ impl crate::Instance for super::Instance { }, ); - let extensions = Self::desired_extensions(&entry, instance_api_version, desc.flags)?; + let mut extensions = Self::desired_extensions(&entry, instance_api_version, desc.flags)?; + let mut create_info = vk::InstanceCreateInfo::default(); + + if let Some(callback) = callback { + callback(super::CreateInstanceCallbackArgs { + extensions: &mut extensions, + create_info: &mut create_info, + entry: &entry, + _phantom: PhantomData, + }); + } let instance_layers = { profiling::scope!("vkEnumerateInstanceLayerProperties"); unsafe { entry.enumerate_instance_layer_properties() } }; let instance_layers = instance_layers.map_err(|e| { - log::debug!("enumerate_instance_layer_properties: {:?}", e); + log::debug!("enumerate_instance_layer_properties: {e:?}"); crate::InstanceError::with_source( String::from("enumerate_instance_layer_properties() failed"), e, @@ -804,7 +787,7 @@ impl crate::Instance for super::Instance { }) .collect::>(); - let mut create_info = vk::InstanceCreateInfo::default() + create_info = create_info .flags(flags) .application_info(&app_info) .enabled_layer_names(&str_pointers[..layers.len()]) @@ -860,11 +843,35 @@ impl crate::Instance for super::Instance { debug_utils, extensions, desc.flags, + desc.memory_budget_thresholds, has_nv_optimus, None, ) } } +} + +impl Drop for super::InstanceShared { + fn drop(&mut self) { + unsafe { + // Keep du alive since destroy_instance may also log + let _du = self.debug_utils.take().inspect(|du| { + du.extension + .destroy_debug_utils_messenger(du.messenger, None); + }); + if self.drop_guard.is_none() { + self.raw.destroy_instance(None); + } + } + } +} + +impl crate::Instance for super::Instance { + type A = super::Api; + + unsafe fn init(desc: &crate::InstanceDescriptor) -> Result { + unsafe { Self::init_with_callback(desc, None) } + } unsafe fn create_surface( &self, @@ -925,7 +932,7 @@ impl crate::Instance for super::Instance { let raw_devices = match unsafe { self.shared.raw.enumerate_physical_devices() } { Ok(devices) => devices, Err(err) => { - log::error!("enumerate_adapters: {}", err); + log::error!("enumerate_adapters: {err}"); Vec::new() } }; @@ -979,7 +986,7 @@ impl crate::Instance for super::Instance { impl Drop for super::Surface { fn drop(&mut self) { - unsafe { self.functor.destroy_surface(self.raw, None) }; + unsafe { ManuallyDrop::take(&mut self.inner).delete_surface() }; } } @@ -993,149 +1000,45 @@ impl crate::Surface for super::Surface { ) -> Result<(), crate::SurfaceError> { // SAFETY: `configure`'s contract guarantees there are no resources derived from the swapchain in use. let mut swap_chain = self.swapchain.write(); - let old = swap_chain - .take() - .map(|sc| unsafe { sc.release_resources(&device.shared.raw) }); - let swapchain = unsafe { device.create_swapchain(self, config, old)? }; + let mut old = swap_chain.take(); + if let Some(ref mut old) = old { + unsafe { old.release_resources(device) }; + } + + let swapchain = unsafe { self.inner.create_swapchain(device, config, old)? }; *swap_chain = Some(swapchain); Ok(()) } unsafe fn unconfigure(&self, device: &super::Device) { - if let Some(sc) = self.swapchain.write().take() { + if let Some(mut sc) = self.swapchain.write().take() { // SAFETY: `unconfigure`'s contract guarantees there are no resources derived from the swapchain in use. - let swapchain = unsafe { sc.release_resources(&device.shared.raw) }; - unsafe { swapchain.functor.destroy_swapchain(swapchain.raw, None) }; + unsafe { sc.release_resources(device) }; + unsafe { sc.delete_swapchain() }; } } unsafe fn acquire_texture( &self, - timeout: Option, + timeout: Option, fence: &super::Fence, ) -> Result>, crate::SurfaceError> { let mut swapchain = self.swapchain.write(); let swapchain = swapchain.as_mut().unwrap(); - let mut timeout_ns = match timeout { - Some(duration) => duration.as_nanos() as u64, - None => u64::MAX, - }; - - // AcquireNextImageKHR on Android (prior to Android 11) doesn't support timeouts - // and will also log verbose warnings if tying to use a timeout. - // - // Android 10 implementation for reference: - // https://android.googlesource.com/platform/frameworks/native/+/refs/tags/android-mainline-10.0.0_r13/vulkan/libvulkan/swapchain.cpp#1426 - // Android 11 implementation for reference: - // https://android.googlesource.com/platform/frameworks/native/+/refs/tags/android-mainline-11.0.0_r45/vulkan/libvulkan/swapchain.cpp#1438 - // - // Android 11 corresponds to an SDK_INT/ro.build.version.sdk of 30 - if cfg!(target_os = "android") && self.instance.android_sdk_version < 30 { - timeout_ns = u64::MAX; - } - - let swapchain_semaphores_arc = swapchain.get_surface_semaphores(); - // Nothing should be using this, so we don't block, but panic if we fail to lock. - let locked_swapchain_semaphores = swapchain_semaphores_arc - .try_lock() - .expect("Failed to lock a SwapchainSemaphores."); - - // Wait for all commands writing to the previously acquired image to - // complete. - // - // Almost all the steps in the usual acquire-draw-present flow are - // asynchronous: they get something started on the presentation engine - // or the GPU, but on the CPU, control returns immediately. Without some - // sort of intervention, the CPU could crank out frames much faster than - // the presentation engine can display them. - // - // This is the intervention: if any submissions drew on this image, and - // thus waited for `locked_swapchain_semaphores.acquire`, wait for all - // of them to finish, thus ensuring that it's okay to pass `acquire` to - // `vkAcquireNextImageKHR` again. - swapchain.device.wait_for_fence( - fence, - locked_swapchain_semaphores.previously_used_submission_index, - timeout_ns, - )?; - - // will block if no image is available - let (index, suboptimal) = match unsafe { - profiling::scope!("vkAcquireNextImageKHR"); - swapchain.functor.acquire_next_image( - swapchain.raw, - timeout_ns, - locked_swapchain_semaphores.acquire, - vk::Fence::null(), - ) - } { - // We treat `VK_SUBOPTIMAL_KHR` as `VK_SUCCESS` on Android. - // See the comment in `Queue::present`. - #[cfg(target_os = "android")] - Ok((index, _)) => (index, false), - #[cfg(not(target_os = "android"))] - Ok(pair) => pair, - Err(error) => { - return match error { - vk::Result::TIMEOUT => Ok(None), - vk::Result::NOT_READY | vk::Result::ERROR_OUT_OF_DATE_KHR => { - Err(crate::SurfaceError::Outdated) - } - vk::Result::ERROR_SURFACE_LOST_KHR => Err(crate::SurfaceError::Lost), - // We don't use VK_EXT_full_screen_exclusive - // VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT - other => Err(super::map_host_device_oom_and_lost_err(other).into()), - }; - } - }; - - drop(locked_swapchain_semaphores); - // We only advance the surface semaphores if we successfully acquired an image, otherwise - // we should try to re-acquire using the same semaphores. - swapchain.advance_surface_semaphores(); - - // special case for Intel Vulkan returning bizarre values (ugh) - if swapchain.device.vendor_id == crate::auxil::db::intel::VENDOR && index > 0x100 { - return Err(crate::SurfaceError::Outdated); - } - - // https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkRenderPassBeginInfo.html#VUID-VkRenderPassBeginInfo-framebuffer-03209 - let raw_flags = if swapchain - .raw_flags - .contains(vk::SwapchainCreateFlagsKHR::MUTABLE_FORMAT) - { - vk::ImageCreateFlags::MUTABLE_FORMAT | vk::ImageCreateFlags::EXTENDED_USAGE - } else { - vk::ImageCreateFlags::empty() - }; - - let texture = super::SurfaceTexture { - index, - texture: super::Texture { - raw: swapchain.images[index as usize], - drop_guard: None, - block: None, - external_memory: None, - usage: swapchain.config.usage, - format: swapchain.config.format, - raw_flags, - copy_size: crate::CopyExtent { - width: swapchain.config.extent.width, - height: swapchain.config.extent.height, - depth: 1, - }, - view_formats: swapchain.view_formats.clone(), - }, - surface_semaphores: swapchain_semaphores_arc, - }; - Ok(Some(crate::AcquiredSurfaceTexture { - texture, - suboptimal, - })) + unsafe { swapchain.acquire(timeout, fence) } } - unsafe fn discard_texture(&self, _texture: super::SurfaceTexture) {} + unsafe fn discard_texture(&self, texture: super::SurfaceTexture) { + unsafe { + self.swapchain + .write() + .as_mut() + .unwrap() + .discard_texture(texture) + .unwrap() + }; + } } diff --git a/wgpu-hal/src/vulkan/mod.rs b/wgpu-hal/src/vulkan/mod.rs index 4ba4a6c3d..115c6eb20 100644 --- a/wgpu-hal/src/vulkan/mod.rs +++ b/wgpu-hal/src/vulkan/mod.rs @@ -24,25 +24,26 @@ Otherwise, we manage a pool of `VkFence` objects behind each `hal::Fence`. !*/ -#![allow(clippy::std_instead_of_alloc, clippy::std_instead_of_core)] - mod adapter; mod command; -mod conv; +pub mod conv; mod device; mod drm; mod instance; mod sampler; +mod semaphore_list; +mod swapchain; -use std::{ +pub use adapter::PhysicalDeviceFeatures; + +use alloc::{boxed::Box, ffi::CString, sync::Arc, vec::Vec}; +use core::{ borrow::Borrow, - boxed::Box, - ffi::{CStr, CString}, - fmt, mem, + ffi::CStr, + fmt, + marker::PhantomData, + mem::{self, ManuallyDrop}, num::NonZeroU32, - ops::DerefMut, - sync::Arc, - vec::Vec, }; use arrayvec::ArrayVec; @@ -54,13 +55,18 @@ use parking_lot::{Mutex, RwLock}; use naga::FastHashMap; use wgt::InternalCounter; -const MILLIS_TO_NANOS: u64 = 1_000_000; +use semaphore_list::SemaphoreList; + +use crate::vulkan::semaphore_list::{SemaphoreListMode, SemaphoreType}; + const MAX_TOTAL_ATTACHMENTS: usize = crate::MAX_COLOR_ATTACHMENTS * 2 + 1; #[derive(Clone, Debug)] pub struct Api; impl crate::Api for Api { + const VARIANT: wgt::Backend = wgt::Backend::Vulkan; + type Instance = Instance; type Surface = Surface; type Adapter = Adapter; @@ -160,8 +166,8 @@ pub struct DebugUtilsMessengerUserData { pub struct InstanceShared { raw: ash::Instance, extensions: Vec<&'static CStr>, - drop_guard: Option, flags: wgt::InstanceFlags, + memory_budget_thresholds: wgt::MemoryBudgetThresholds, debug_utils: Option, get_physical_device_properties: Option, entry: ash::Entry, @@ -174,231 +180,46 @@ pub struct InstanceShared { /// It is associated with a `VkInstance` and its children, /// except for a `VkPhysicalDevice` and its children. instance_api_version: u32, + + // The `drop_guard` field must be the last field of this struct so it is dropped last. + // Do not add new fields after it. + drop_guard: Option, } pub struct Instance { shared: Arc, } -/// The semaphores needed to use one image in a swapchain. -#[derive(Debug)] -struct SwapchainImageSemaphores { - /// A semaphore that is signaled when this image is safe for us to modify. - /// - /// When [`vkAcquireNextImageKHR`] returns the index of the next swapchain - /// image that we should use, that image may actually still be in use by the - /// presentation engine, and is not yet safe to modify. However, that - /// function does accept a semaphore that it will signal when the image is - /// indeed safe to begin messing with. - /// - /// This semaphore is: - /// - /// - waited for by the first queue submission to operate on this image - /// since it was acquired, and - /// - /// - signaled by [`vkAcquireNextImageKHR`] when the acquired image is ready - /// for us to use. - /// - /// [`vkAcquireNextImageKHR`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkAcquireNextImageKHR - acquire: vk::Semaphore, - - /// True if the next command submission operating on this image should wait - /// for [`acquire`]. - /// - /// We must wait for `acquire` before drawing to this swapchain image, but - /// because `wgpu-hal` queue submissions are always strongly ordered, only - /// the first submission that works with a swapchain image actually needs to - /// wait. We set this flag when this image is acquired, and clear it the - /// first time it's passed to [`Queue::submit`] as a surface texture. - /// - /// [`acquire`]: SwapchainImageSemaphores::acquire - /// [`Queue::submit`]: crate::Queue::submit - should_wait_for_acquire: bool, - - /// A pool of semaphores for ordering presentation after drawing. - /// - /// The first [`present_index`] semaphores in this vector are: - /// - /// - all waited on by the call to [`vkQueuePresentKHR`] that presents this - /// image, and - /// - /// - each signaled by some [`vkQueueSubmit`] queue submission that draws to - /// this image, when the submission finishes execution. - /// - /// This vector accumulates one semaphore per submission that writes to this - /// image. This is awkward, but hard to avoid: [`vkQueuePresentKHR`] - /// requires a semaphore to order it with respect to drawing commands, and - /// we can't attach new completion semaphores to a command submission after - /// it's been submitted. This means that, at submission time, we must create - /// the semaphore we might need if the caller's next action is to enqueue a - /// presentation of this image. - /// - /// An alternative strategy would be for presentation to enqueue an empty - /// submit, ordered relative to other submits in the usual way, and - /// signaling a single presentation semaphore. But we suspect that submits - /// are usually expensive enough, and semaphores usually cheap enough, that - /// performance-sensitive users will avoid making many submits, so that the - /// cost of accumulated semaphores will usually be less than the cost of an - /// additional submit. - /// - /// Only the first [`present_index`] semaphores in the vector are actually - /// going to be signalled by submitted commands, and need to be waited for - /// by the next present call. Any semaphores beyond that index were created - /// for prior presents and are simply being retained for recycling. - /// - /// [`present_index`]: SwapchainImageSemaphores::present_index - /// [`vkQueuePresentKHR`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkQueuePresentKHR - /// [`vkQueueSubmit`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkQueueSubmit - present: Vec, - - /// The number of semaphores in [`present`] to be signalled for this submission. - /// - /// [`present`]: SwapchainImageSemaphores::present - present_index: usize, - - /// The fence value of the last command submission that wrote to this image. - /// - /// The next time we try to acquire this image, we'll block until - /// this submission finishes, proving that [`acquire`] is ready to - /// pass to `vkAcquireNextImageKHR` again. - /// - /// [`acquire`]: SwapchainImageSemaphores::acquire - previously_used_submission_index: crate::FenceValue, -} - -impl SwapchainImageSemaphores { - fn new(device: &DeviceShared) -> Result { - Ok(Self { - acquire: device.new_binary_semaphore()?, - should_wait_for_acquire: true, - present: Vec::new(), - present_index: 0, - previously_used_submission_index: 0, - }) - } - - fn set_used_fence_value(&mut self, value: crate::FenceValue) { - self.previously_used_submission_index = value; - } - - /// Return the semaphore that commands drawing to this image should wait for, if any. - /// - /// This only returns `Some` once per acquisition; see - /// [`SwapchainImageSemaphores::should_wait_for_acquire`] for details. - fn get_acquire_wait_semaphore(&mut self) -> Option { - if self.should_wait_for_acquire { - self.should_wait_for_acquire = false; - Some(self.acquire) - } else { - None - } - } - - /// Return a semaphore that a submission that writes to this image should - /// signal when it's done. - /// - /// See [`SwapchainImageSemaphores::present`] for details. - fn get_submit_signal_semaphore( - &mut self, - device: &DeviceShared, - ) -> Result { - // Try to recycle a semaphore we created for a previous presentation. - let sem = match self.present.get(self.present_index) { - Some(sem) => *sem, - None => { - let sem = device.new_binary_semaphore()?; - self.present.push(sem); - sem - } - }; - - self.present_index += 1; - - Ok(sem) - } - - /// Return the semaphores that a presentation of this image should wait on. - /// - /// Return a slice of semaphores that the call to [`vkQueueSubmit`] that - /// ends this image's acquisition should wait for. See - /// [`SwapchainImageSemaphores::present`] for details. - /// - /// Reset `self` to be ready for the next acquisition cycle. - /// - /// [`vkQueueSubmit`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkQueueSubmit - fn get_present_wait_semaphores(&mut self) -> &[vk::Semaphore] { - let old_index = self.present_index; - - // Since this marks the end of this acquire/draw/present cycle, take the - // opportunity to reset `self` in preparation for the next acquisition. - self.present_index = 0; - self.should_wait_for_acquire = true; - - &self.present[0..old_index] - } - - unsafe fn destroy(&self, device: &ash::Device) { - unsafe { - device.destroy_semaphore(self.acquire, None); - for sem in &self.present { - device.destroy_semaphore(*sem, None); - } - } - } -} - -struct Swapchain { - raw: vk::SwapchainKHR, - raw_flags: vk::SwapchainCreateFlagsKHR, - functor: khr::swapchain::Device, - device: Arc, - images: Vec, - config: crate::SurfaceConfiguration, - view_formats: Vec, - /// One wait semaphore per swapchain image. This will be associated with the - /// surface texture, and later collected during submission. - /// - /// We need this to be `Arc>` because we need to be able to pass this - /// data into the surface texture, so submit/present can use it. - surface_semaphores: Vec>>, - /// The index of the next semaphore to use. Ideally we would use the same - /// index as the image index, but we need to specify the semaphore as an argument - /// to the acquire_next_image function which is what tells us which image to use. - next_semaphore_index: usize, - /// The present timing information which will be set in the next call to [`present()`](crate::Queue::present()). - /// - /// # Safety - /// - /// This must only be set if [`wgt::Features::VULKAN_GOOGLE_DISPLAY_TIMING`] is enabled, and - /// so the VK_GOOGLE_display_timing extension is present. - next_present_time: Option, -} - -impl Swapchain { - fn advance_surface_semaphores(&mut self) { - let semaphore_count = self.surface_semaphores.len(); - self.next_semaphore_index = (self.next_semaphore_index + 1) % semaphore_count; - } - - fn get_surface_semaphores(&self) -> Arc> { - self.surface_semaphores[self.next_semaphore_index].clone() - } -} - pub struct Surface { - raw: vk::SurfaceKHR, - functor: khr::surface::Instance, - instance: Arc, - swapchain: RwLock>, + inner: ManuallyDrop>, + swapchain: RwLock>>, } impl Surface { + /// Returns the raw Vulkan surface handle. + /// + /// Returns `None` if the surface is a DXGI surface. + pub unsafe fn raw_native_handle(&self) -> Option { + Some( + self.inner + .as_any() + .downcast_ref::()? + .as_raw(), + ) + } + /// Get the raw Vulkan swapchain associated with this surface. /// - /// Returns [`None`] if the surface is not configured. - pub fn raw_swapchain(&self) -> Option { + /// Returns [`None`] if the surface is not configured or if the swapchain + /// is a DXGI swapchain. + pub fn raw_native_swapchain(&self) -> Option { let read = self.swapchain.read(); - read.as_ref().map(|it| it.raw) + Some( + read.as_ref()? + .as_any() + .downcast_ref::()? + .as_raw(), + ) } /// Set the present timing information which will be used for the next [presentation](crate::Queue::present()) of this surface, @@ -414,28 +235,20 @@ impl Surface { /// # Panics /// /// - If the surface hasn't been configured. + /// - If the surface has been configured for a DXGI swapchain. /// - If the device doesn't [support present timing](wgt::Features::VULKAN_GOOGLE_DISPLAY_TIMING). /// /// [VK_GOOGLE_display_timing]: https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_GOOGLE_display_timing.html #[track_caller] pub fn set_next_present_time(&self, present_timing: vk::PresentTimeGOOGLE) { let mut swapchain = self.swapchain.write(); - let swapchain = swapchain + swapchain .as_mut() - .expect("Surface should have been configured"); - let features = wgt::Features::VULKAN_GOOGLE_DISPLAY_TIMING; - if swapchain.device.features.contains(features) { - swapchain.next_present_time = Some(present_timing); - } else { - // Ideally we'd use something like `device.required_features` here, but that's in `wgpu-core`, which we are a dependency of - panic!( - concat!( - "Tried to set display timing properties ", - "without the corresponding feature ({:?}) enabled." - ), - features - ); - } + .expect("Surface should have been configured") + .as_any_mut() + .downcast_mut::() + .expect("Surface should have a native Vulkan swapchain") + .set_next_present_time(present_timing); } } @@ -443,7 +256,7 @@ impl Surface { pub struct SurfaceTexture { index: u32, texture: Texture, - surface_semaphores: Arc>, + metadata: Box, } impl crate::DynSurfaceTexture for SurfaceTexture {} @@ -466,7 +279,7 @@ pub struct Adapter { //queue_families: Vec, known_memory_flags: vk::MemoryPropertyFlags, phd_capabilities: adapter::PhysicalDeviceProperties, - phd_features: adapter::PhysicalDeviceFeatures, + phd_features: PhysicalDeviceFeatures, downlevel_flags: wgt::DownlevelFlags, private_caps: PrivateCapabilities, workarounds: Workarounds, @@ -497,11 +310,6 @@ struct RayTracingDeviceExtensionFunctions { /// device geometry, but affect the code paths taken internally. #[derive(Clone, Debug)] struct PrivateCapabilities { - /// Y-flipping is implemented with either `VK_AMD_negative_viewport_height` or `VK_KHR_maintenance1`/1.1+. The AMD extension for negative viewport height does not require a Y shift. - /// - /// This flag is `true` if the device has `VK_KHR_maintenance1`/1.1+ and `false` otherwise (i.e. in the case of `VK_AMD_negative_viewport_height`). - flip_y_requires_shift: bool, - imageless_framebuffers: bool, image_view_usage: bool, timeline_semaphores: bool, texture_d24: bool, @@ -510,6 +318,7 @@ struct PrivateCapabilities { /// Ability to present contents to any screen. Only needed to work around broken platform configurations. can_present: bool, non_coherent_map_mask: wgt::BufferAddress, + multi_draw_indirect: bool, /// True if this adapter advertises the [`robustBufferAccess`][vrba] feature. /// @@ -544,6 +353,40 @@ struct PrivateCapabilities { zero_initialize_workgroup_memory: bool, image_format_list: bool, maximum_samplers: u32, + + /// True if this adapter supports the [`VK_KHR_shader_integer_dot_product`] extension + /// (promoted to Vulkan 1.3). + /// + /// This is used to generate optimized code for WGSL's `dot4{I, U}8Packed`. + /// + /// [`VK_KHR_shader_integer_dot_product`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_shader_integer_dot_product.html + shader_integer_dot_product: bool, + + /// True if this adapter supports 8-bit integers provided by the + /// [`VK_KHR_shader_float16_int8`] extension (promoted to Vulkan 1.2). + /// + /// Allows shaders to declare the "Int8" capability. Note, however, that this + /// feature alone allows the use of 8-bit integers "only in the `Private`, + /// `Workgroup` (for non-Block variables), and `Function` storage classes" + /// ([see spec]). To use 8-bit integers in the interface storage classes (e.g., + /// `StorageBuffer`), you also need to enable the corresponding feature in + /// `VkPhysicalDevice8BitStorageFeatures` and declare the corresponding SPIR-V + /// capability (e.g., `StorageBuffer8BitAccess`). + /// + /// [`VK_KHR_shader_float16_int8`]: https://registry.khronos.org/vulkan/specs/latest/man/html/VK_KHR_shader_float16_int8.html + /// [see spec]: https://registry.khronos.org/vulkan/specs/latest/man/html/VkPhysicalDeviceShaderFloat16Int8Features.html#extension-features-shaderInt8 + shader_int8: bool, + + /// This is done to panic before undefined behavior, and is imperfect. + /// Basically, to allow implementations to emulate mv using instancing, if you + /// want to draw `n` instances to VR, you must draw `2n` instances, but you + /// can never draw more than `u32::MAX` instances. Therefore, when drawing + /// multiview on some vulkan implementations, it might restrict the instance + /// count, which isn't usually a thing in webgpu. We don't expose this limit + /// because its strange, i.e. only occurs on certain vulkan implementations + /// if you are drawing more than 128 million instances. We still want to avoid + /// undefined behavior in this situation, so we panic if the limit is violated. + multiview_instance_index_limit: u32, } bitflags::bitflags!( @@ -615,24 +458,7 @@ struct RenderPassKey { colors: ArrayVec, { crate::MAX_COLOR_ATTACHMENTS }>, depth_stencil: Option, sample_count: u32, - multiview: Option, -} - -#[derive(Clone, Debug, Eq, Hash, PartialEq)] -struct FramebufferAttachment { - /// Can be NULL if the framebuffer is image-less - raw: vk::ImageView, - raw_image_flags: vk::ImageCreateFlags, - view_usage: wgt::TextureUses, - view_format: wgt::TextureFormat, - raw_view_formats: Vec, -} - -#[derive(Clone, Eq, Hash, PartialEq)] -struct FramebufferKey { - attachments: ArrayVec, - extent: wgt::Extent3d, - sample_count: u32, + multiview_mask: Option, } struct DeviceShared { @@ -640,7 +466,6 @@ struct DeviceShared { family_index: u32, queue_index: u32, raw_queue: vk::Queue, - drop_guard: Option, instance: Arc, physical_device: vk::PhysicalDevice, enabled_extensions: Vec<&'static CStr>, @@ -652,9 +477,20 @@ struct DeviceShared { workarounds: Workarounds, features: wgt::Features, render_passes: Mutex>, - framebuffers: Mutex>, sampler_cache: Mutex, memory_allocations_counter: InternalCounter, + + /// Because we have cached framebuffers which are not deleted from until + /// the device is destroyed, if the implementation of vulkan re-uses handles + /// we need some way to differentiate between the old handle and the new handle. + /// This factory allows us to have a dedicated identity value for each texture. + texture_identity_factory: ResourceIdentityFactory, + /// As above, for texture views. + texture_view_identity_factory: ResourceIdentityFactory, + + // The `drop_guard` field must be the last field of this struct so it is dropped last. + // Do not add new fields after it. + drop_guard: Option, } impl Drop for DeviceShared { @@ -662,9 +498,6 @@ impl Drop for DeviceShared { for &raw in self.render_passes.lock().values() { unsafe { self.raw.destroy_render_pass(raw, None) }; } - for &raw in self.framebuffers.lock().values() { - unsafe { self.raw.destroy_framebuffer(raw, None) }; - } if self.drop_guard.is_none() { unsafe { self.raw.destroy_device(None) }; } @@ -728,7 +561,7 @@ impl RelaySemaphores { fn new(device: &DeviceShared) -> Result { Ok(Self { wait: None, - signal: device.new_binary_semaphore()?, + signal: device.new_binary_semaphore("RelaySemaphores: 1")?, }) } @@ -743,7 +576,7 @@ impl RelaySemaphores { // The second submission should wait on `old.signal`, and then // signal a new semaphore which we'll create now. self.wait = Some(old.signal); - self.signal = device.new_binary_semaphore()?; + self.signal = device.new_binary_semaphore("RelaySemaphores: 2")?; } Some(ref mut wait) => { // What this submission signals, the next should wait. @@ -767,11 +600,10 @@ impl RelaySemaphores { pub struct Queue { raw: vk::Queue, - swapchain_fn: khr::swapchain::Device, device: Arc, family_index: u32, relay_semaphores: Mutex, - signal_semaphores: Mutex<(Vec, Vec)>, + signal_semaphores: Mutex, } impl Queue { @@ -785,11 +617,70 @@ impl Drop for Queue { unsafe { self.relay_semaphores.lock().destroy(&self.device.raw) }; } } - +#[derive(Debug)] +enum BufferMemoryBacking { + Managed(gpu_alloc::MemoryBlock), + VulkanMemory { + memory: vk::DeviceMemory, + offset: u64, + size: u64, + }, +} +impl BufferMemoryBacking { + fn memory(&self) -> &vk::DeviceMemory { + match self { + Self::Managed(m) => m.memory(), + Self::VulkanMemory { memory, .. } => memory, + } + } + fn offset(&self) -> u64 { + match self { + Self::Managed(m) => m.offset(), + Self::VulkanMemory { offset, .. } => *offset, + } + } + fn size(&self) -> u64 { + match self { + Self::Managed(m) => m.size(), + Self::VulkanMemory { size, .. } => *size, + } + } +} #[derive(Debug)] pub struct Buffer { raw: vk::Buffer, - block: Option>>, + block: Option>, +} +impl Buffer { + /// # Safety + /// + /// - `vk_buffer`'s memory must be managed by the caller + /// - Externally imported buffers can't be mapped by `wgpu` + pub unsafe fn from_raw(vk_buffer: vk::Buffer) -> Self { + Self { + raw: vk_buffer, + block: None, + } + } + /// # Safety + /// - We will use this buffer and the buffer's backing memory range as if we have exclusive ownership over it, until the wgpu resource is dropped and the wgpu-hal object is cleaned up + /// - Externally imported buffers can't be mapped by `wgpu` + /// - `offset` and `size` must be valid with the allocation of `memory` + pub unsafe fn from_raw_managed( + vk_buffer: vk::Buffer, + memory: vk::DeviceMemory, + offset: u64, + size: u64, + ) -> Self { + Self { + raw: vk_buffer, + block: Some(Mutex::new(BufferMemoryBacking::VulkanMemory { + memory, + offset, + size, + })), + } + } } impl crate::DynBuffer for Buffer {} @@ -807,14 +698,15 @@ impl crate::DynAccelerationStructure for AccelerationStructure {} #[derive(Debug)] pub struct Texture { raw: vk::Image, - drop_guard: Option, external_memory: Option, block: Option>, - usage: wgt::TextureUses, format: wgt::TextureFormat, - raw_flags: vk::ImageCreateFlags, copy_size: crate::CopyExtent, - view_formats: Vec, + identity: ResourceIdentity, + + // The `drop_guard` field must be the last field of this struct so it is dropped last. + // Do not add new fields after it. + drop_guard: Option, } impl crate::DynTexture for Texture {} @@ -826,13 +718,26 @@ impl Texture { pub unsafe fn raw_handle(&self) -> vk::Image { self.raw } + + /// # Safety + /// + /// - The external memory must not be manually freed + pub unsafe fn external_memory(&self) -> Option { + self.external_memory + } } #[derive(Debug)] pub struct TextureView { + raw_texture: vk::Image, raw: vk::ImageView, - layers: NonZeroU32, - attachment: FramebufferAttachment, + _layers: NonZeroU32, + format: wgt::TextureFormat, + raw_format: vk::Format, + base_mip_level: u32, + dimension: wgt::TextureViewDimension, + texture_identity: ResourceIdentity, + view_identity: ResourceIdentity, } impl crate::DynTextureView for TextureView {} @@ -844,6 +749,14 @@ impl TextureView { pub unsafe fn raw_handle(&self) -> vk::ImageView { self.raw } + + /// Returns the raw texture view, along with its identity. + fn identified_raw_view(&self) -> IdentifiedTextureView { + IdentifiedTextureView { + raw: self.raw, + identity: self.view_identity, + } + } } #[derive(Debug)] @@ -854,13 +767,25 @@ pub struct Sampler { impl crate::DynSampler for Sampler {} +/// Information about a binding within a specific BindGroupLayout / BindGroup. +/// This will be used to construct a [`naga::back::spv::BindingInfo`], where +/// the descriptor set value will be taken from the index of the group. +#[derive(Copy, Clone, Debug)] +struct BindingInfo { + binding: u32, + binding_array_size: Option, +} + #[derive(Debug)] pub struct BindGroupLayout { raw: vk::DescriptorSetLayout, desc_count: gpu_descriptor::DescriptorTotalCount, - types: Box<[(vk::DescriptorType, u32)]>, - /// Map of binding index to size, - binding_arrays: Vec<(u32, NonZeroU32)>, + /// Sorted list of entries. + entries: Box<[wgt::BindGroupLayoutEntry]>, + /// Map of original binding index to remapped binding index and optional + /// array size. + binding_map: Vec<(u32, BindingInfo)>, + contains_binding_arrays: bool, } impl crate::DynBindGroupLayout for BindGroupLayout {} @@ -868,7 +793,7 @@ impl crate::DynBindGroupLayout for BindGroupLayout {} #[derive(Debug)] pub struct PipelineLayout { raw: vk::PipelineLayout, - binding_arrays: naga::back::spv::BindingMap, + binding_map: naga::back::spv::BindingMap, } impl crate::DynPipelineLayout for PipelineLayout {} @@ -903,6 +828,102 @@ impl Temp { } } +/// Generates unique IDs for each resource of type `T`. +/// +/// Because vk handles are not permanently unique, this +/// provides a way to generate unique IDs for each resource. +struct ResourceIdentityFactory { + #[cfg(not(target_has_atomic = "64"))] + next_id: Mutex, + #[cfg(target_has_atomic = "64")] + next_id: core::sync::atomic::AtomicU64, + _phantom: PhantomData, +} + +impl ResourceIdentityFactory { + fn new() -> Self { + Self { + #[cfg(not(target_has_atomic = "64"))] + next_id: Mutex::new(0), + #[cfg(target_has_atomic = "64")] + next_id: core::sync::atomic::AtomicU64::new(0), + _phantom: PhantomData, + } + } + + /// Returns a new unique ID for a resource of type `T`. + fn next(&self) -> ResourceIdentity { + #[cfg(not(target_has_atomic = "64"))] + { + let mut next_id = self.next_id.lock(); + let id = *next_id; + *next_id += 1; + ResourceIdentity { + id, + _phantom: PhantomData, + } + } + + #[cfg(target_has_atomic = "64")] + ResourceIdentity { + id: self + .next_id + .fetch_add(1, core::sync::atomic::Ordering::Relaxed), + _phantom: PhantomData, + } + } +} + +/// A unique identifier for a resource of type `T`. +/// +/// This is used as a hashable key for resources, which +/// is permanently unique through the lifetime of the program. +#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq)] +struct ResourceIdentity { + id: u64, + _phantom: PhantomData, +} + +#[derive(Clone, Eq, Hash, PartialEq)] +struct FramebufferKey { + raw_pass: vk::RenderPass, + /// Because this is used as a key in a hash map, we need to include the identity + /// so that this hashes differently, even if the ImageView handles are the same + /// between different views. + attachment_identities: ArrayVec, { MAX_TOTAL_ATTACHMENTS }>, + /// While this is redundant for calculating the hash, we need access to an array + /// of all the raw ImageViews when we are creating the actual framebuffer, + /// so we store this here. + attachment_views: ArrayVec, + extent: wgt::Extent3d, +} + +impl FramebufferKey { + fn push_view(&mut self, view: IdentifiedTextureView) { + self.attachment_identities.push(view.identity); + self.attachment_views.push(view.raw); + } +} + +/// A texture view paired with its identity. +#[derive(Copy, Clone)] +struct IdentifiedTextureView { + raw: vk::ImageView, + identity: ResourceIdentity, +} + +#[derive(Clone, Eq, Hash, PartialEq)] +struct TempTextureViewKey { + texture: vk::Image, + /// As this is used in a hashmap, we need to + /// include the identity so that this hashes differently, + /// even if the Image handles are the same between different images. + texture_identity: ResourceIdentity, + format: vk::Format, + mip_level: u32, + depth_slice: u32, +} + pub struct CommandEncoder { raw: vk::CommandPool, device: Arc, @@ -939,7 +960,12 @@ pub struct CommandEncoder { /// the given pool & location. end_of_pass_timer_query: Option<(vk::QueryPool, u32)>, + framebuffers: FastHashMap, + temp_texture_views: FastHashMap, + counters: Arc, + + current_pipeline_is_multiview: bool, } impl Drop for CommandEncoder { @@ -960,6 +986,15 @@ impl Drop for CommandEncoder { // fields. self.device.raw.destroy_command_pool(self.raw, None); } + + for (_, fb) in self.framebuffers.drain() { + unsafe { self.device.raw.destroy_framebuffer(fb, None) }; + } + + for (_, view) in self.temp_texture_views.drain() { + unsafe { self.device.raw.destroy_image_view(view.raw, None) }; + } + self.counters.command_encoders.sub(1); } } @@ -1003,6 +1038,7 @@ impl crate::DynShaderModule for ShaderModule {} #[derive(Debug)] pub struct RenderPipeline { raw: vk::Pipeline, + is_multiview: bool, } impl crate::DynRenderPipeline for RenderPipeline {} @@ -1184,19 +1220,18 @@ impl crate::Queue for Queue { ) -> Result<(), crate::DeviceError> { let mut fence_raw = vk::Fence::null(); - let mut wait_stage_masks = Vec::new(); - let mut wait_semaphores = Vec::new(); - let mut signal_semaphores = Vec::new(); - let mut signal_values = Vec::new(); + let mut wait_semaphores = SemaphoreList::new(SemaphoreListMode::Wait); + let mut signal_semaphores = SemaphoreList::new(SemaphoreListMode::Signal); // Double check that the same swapchain image isn't being given to us multiple times, // as that will deadlock when we try to lock them all. debug_assert!( { let mut check = HashSet::with_capacity(surface_textures.len()); - // We compare the Arcs by pointer, as Eq isn't well defined for SurfaceSemaphores. + // We compare the Box by pointer, as Eq isn't well defined for SurfaceSemaphores. for st in surface_textures { - check.insert(Arc::as_ptr(&st.surface_semaphores)); + let ptr: *const () = <*const _>::cast(&*st.metadata); + check.insert(ptr as usize); } check.len() == surface_textures.len() }, @@ -1205,38 +1240,28 @@ impl crate::Queue for Queue { let locked_swapchain_semaphores = surface_textures .iter() - .map(|st| { - st.surface_semaphores - .try_lock() - .expect("Failed to lock surface semaphore.") - }) + .map(|st| st.metadata.get_semaphore_guard()) .collect::>(); - for mut swapchain_semaphore in locked_swapchain_semaphores { - swapchain_semaphore.set_used_fence_value(signal_value); + for mut semaphores in locked_swapchain_semaphores { + semaphores.set_used_fence_value(signal_value); // If we're the first submission to operate on this image, wait on // its acquire semaphore, to make sure the presentation engine is // done with it. - if let Some(sem) = swapchain_semaphore.get_acquire_wait_semaphore() { - wait_stage_masks.push(vk::PipelineStageFlags::TOP_OF_PIPE); - wait_semaphores.push(sem); + if let Some(sem) = semaphores.get_acquire_wait_semaphore() { + wait_semaphores.push_wait(sem, vk::PipelineStageFlags::TOP_OF_PIPE); } // Get a semaphore to signal when we're done writing to this surface // image. Presentation of this image will wait for this. - let signal_semaphore = swapchain_semaphore.get_submit_signal_semaphore(&self.device)?; - signal_semaphores.push(signal_semaphore); - signal_values.push(!0); + let signal_semaphore = semaphores.get_submit_signal_semaphore(&self.device)?; + signal_semaphores.push_signal(signal_semaphore); } - let mut guards = self.signal_semaphores.lock(); - let (ref mut pending_signal_semaphores, ref mut pending_signal_semaphore_values) = - guards.deref_mut(); - assert!(pending_signal_semaphores.len() == pending_signal_semaphore_values.len()); - if !pending_signal_semaphores.is_empty() { - signal_semaphores.append(pending_signal_semaphores); - signal_values.append(pending_signal_semaphore_values); + let mut guard = self.signal_semaphores.lock(); + if !guard.is_empty() { + signal_semaphores.append(&mut guard); } // In order for submissions to be strictly ordered, we encode a dependency between each submission @@ -1244,19 +1269,19 @@ impl crate::Queue for Queue { let semaphore_state = self.relay_semaphores.lock().advance(&self.device)?; if let Some(sem) = semaphore_state.wait { - wait_stage_masks.push(vk::PipelineStageFlags::TOP_OF_PIPE); - wait_semaphores.push(sem); + wait_semaphores.push_wait( + SemaphoreType::Binary(sem), + vk::PipelineStageFlags::TOP_OF_PIPE, + ); } - signal_semaphores.push(semaphore_state.signal); - signal_values.push(!0); + signal_semaphores.push_signal(SemaphoreType::Binary(semaphore_state.signal)); // We need to signal our wgpu::Fence if we have one, this adds it to the signal list. signal_fence.maintain(&self.device.raw)?; match *signal_fence { Fence::TimelineSemaphore(raw) => { - signal_semaphores.push(raw); - signal_values.push(signal_value); + signal_semaphores.push_signal(SemaphoreType::Timeline(raw, signal_value)); } Fence::FencePool { ref mut active, @@ -1282,19 +1307,13 @@ impl crate::Queue for Queue { .collect::>(); let mut vk_info = vk::SubmitInfo::default().command_buffers(&vk_cmd_buffers); - - vk_info = vk_info - .wait_semaphores(&wait_semaphores) - .wait_dst_stage_mask(&wait_stage_masks) - .signal_semaphores(&signal_semaphores); - - let mut vk_timeline_info; - - if self.device.private_caps.timeline_semaphores { - vk_timeline_info = - vk::TimelineSemaphoreSubmitInfo::default().signal_semaphore_values(&signal_values); - vk_info = vk_info.push_next(&mut vk_timeline_info); - } + let mut vk_timeline_info = mem::MaybeUninit::uninit(); + vk_info = SemaphoreList::add_to_submit( + &mut wait_semaphores, + &mut signal_semaphores, + vk_info, + &mut vk_timeline_info, + ); profiling::scope!("vkQueueSubmit"); unsafe { @@ -1312,54 +1331,8 @@ impl crate::Queue for Queue { texture: SurfaceTexture, ) -> Result<(), crate::SurfaceError> { let mut swapchain = surface.swapchain.write(); - let ssc = swapchain.as_mut().unwrap(); - let mut swapchain_semaphores = texture.surface_semaphores.lock(); - let swapchains = [ssc.raw]; - let image_indices = [texture.index]; - let vk_info = vk::PresentInfoKHR::default() - .swapchains(&swapchains) - .image_indices(&image_indices) - .wait_semaphores(swapchain_semaphores.get_present_wait_semaphores()); - - let mut display_timing; - let present_times; - let vk_info = if let Some(present_time) = ssc.next_present_time.take() { - debug_assert!( - ssc.device - .features - .contains(wgt::Features::VULKAN_GOOGLE_DISPLAY_TIMING), - "`next_present_time` should only be set if `VULKAN_GOOGLE_DISPLAY_TIMING` is enabled" - ); - present_times = [present_time]; - display_timing = vk::PresentTimesInfoGOOGLE::default().times(&present_times); - // SAFETY: We know that VK_GOOGLE_display_timing is present because of the safety contract on `next_present_time`. - vk_info.push_next(&mut display_timing) - } else { - vk_info - }; - - let suboptimal = { - profiling::scope!("vkQueuePresentKHR"); - unsafe { self.swapchain_fn.queue_present(self.raw, &vk_info) }.map_err(|error| { - match error { - vk::Result::ERROR_OUT_OF_DATE_KHR => crate::SurfaceError::Outdated, - vk::Result::ERROR_SURFACE_LOST_KHR => crate::SurfaceError::Lost, - // We don't use VK_EXT_full_screen_exclusive - // VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT - _ => map_host_device_oom_and_lost_err(error).into(), - } - })? - }; - if suboptimal { - // We treat `VK_SUBOPTIMAL_KHR` as `VK_SUCCESS` on Android. - // On Android 10+, libvulkan's `vkQueuePresentKHR` implementation returns `VK_SUBOPTIMAL_KHR` if not doing pre-rotation - // (i.e `VkSwapchainCreateInfoKHR::preTransform` not being equal to the current device orientation). - // This is always the case when the device orientation is anything other than the identity one, as we unconditionally use `VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR`. - #[cfg(not(target_os = "android"))] - log::warn!("Suboptimal present of frame {}", texture.index); - } - Ok(()) + unsafe { swapchain.as_mut().unwrap().present(self, texture) } } unsafe fn get_timestamp_period(&self) -> f32 { @@ -1373,10 +1346,12 @@ impl Queue { } pub fn add_signal_semaphore(&self, semaphore: vk::Semaphore, semaphore_value: Option) { - let mut guards = self.signal_semaphores.lock(); - let (ref mut semaphores, ref mut semaphore_values) = guards.deref_mut(); - semaphores.push(semaphore); - semaphore_values.push(semaphore_value.unwrap_or(!0)); + let mut guard = self.signal_semaphores.lock(); + if let Some(value) = semaphore_value { + guard.push_signal(SemaphoreType::Timeline(semaphore, value)); + } else { + guard.push_signal(SemaphoreType::Binary(semaphore)); + } } } @@ -1470,13 +1445,8 @@ fn get_unexpected_err(_err: vk::Result) -> crate::DeviceError { crate::DeviceError::Unexpected } -/// Returns [`crate::DeviceError::OutOfMemory`] or panics if the `oom_panic` -/// feature flag is enabled. +/// Returns [`crate::DeviceError::OutOfMemory`]. fn get_oom_err(_err: vk::Result) -> crate::DeviceError { - #[cfg(feature = "oom_panic")] - panic!("Out of memory ({_err:?})"); - - #[allow(unreachable_code)] crate::DeviceError::OutOfMemory } @@ -1498,3 +1468,65 @@ struct RawTlasInstance { shader_binding_table_record_offset_and_flags: u32, acceleration_structure_reference: u64, } + +/// Arguments to the [`CreateDeviceCallback`]. +pub struct CreateDeviceCallbackArgs<'arg, 'pnext, 'this> +where + 'this: 'pnext, +{ + /// The extensions to enable for the device. You must not remove anything from this list, + /// but you may add to it. + pub extensions: &'arg mut Vec<&'static CStr>, + /// The physical device features to enable. You may enable features, but must not disable any. + pub device_features: &'arg mut PhysicalDeviceFeatures, + /// The queue create infos for the device. You may add or modify queue create infos as needed. + pub queue_create_infos: &'arg mut Vec>, + /// The create info for the device. You may add or modify things in the pnext chain, but + /// do not turn features off. Additionally, do not add things to the list of extensions, + /// or to the feature set, as all changes to that member will be overwritten. + pub create_info: &'arg mut vk::DeviceCreateInfo<'pnext>, + /// We need to have `'this` in the struct, so we can declare that all lifetimes coming from + /// captures in the closure will live longer (and hence satisfy) `'pnext`. However, we + /// don't actually directly use `'this` + _phantom: PhantomData<&'this ()>, +} + +/// Callback to allow changing the vulkan device creation parameters. +/// +/// # Safety: +/// - If you want to add extensions, add the to the `Vec<'static CStr>` not the create info, +/// as the create info value will be overwritten. +/// - Callback must not remove features. +/// - Callback must not change anything to what the instance does not support. +pub type CreateDeviceCallback<'this> = + dyn for<'arg, 'pnext> FnOnce(CreateDeviceCallbackArgs<'arg, 'pnext, 'this>) + 'this; + +/// Arguments to the [`CreateInstanceCallback`]. +pub struct CreateInstanceCallbackArgs<'arg, 'pnext, 'this> +where + 'this: 'pnext, +{ + /// The extensions to enable for the instance. You must not remove anything from this list, + /// but you may add to it. + pub extensions: &'arg mut Vec<&'static CStr>, + /// The create info for the instance. You may add or modify things in the pnext chain, but + /// do not turn features off. Additionally, do not add things to the list of extensions, + /// all changes to that member will be overwritten. + pub create_info: &'arg mut vk::InstanceCreateInfo<'pnext>, + /// Vulkan entry point. + pub entry: &'arg ash::Entry, + /// We need to have `'this` in the struct, so we can declare that all lifetimes coming from + /// captures in the closure will live longer (and hence satisfy) `'pnext`. However, we + /// don't actually directly use `'this` + _phantom: PhantomData<&'this ()>, +} + +/// Callback to allow changing the vulkan instance creation parameters. +/// +/// # Safety: +/// - If you want to add extensions, add the to the `Vec<'static CStr>` not the create info, +/// as the create info value will be overwritten. +/// - Callback must not remove features. +/// - Callback must not change anything to what the instance does not support. +pub type CreateInstanceCallback<'this> = + dyn for<'arg, 'pnext> FnOnce(CreateInstanceCallbackArgs<'arg, 'pnext, 'this>) + 'this; diff --git a/wgpu-hal/src/vulkan/sampler.rs b/wgpu-hal/src/vulkan/sampler.rs index 5fd32c33d..b99341d21 100644 --- a/wgpu-hal/src/vulkan/sampler.rs +++ b/wgpu-hal/src/vulkan/sampler.rs @@ -39,8 +39,8 @@ impl PartialEq for HashableSamplerCreateInfo { impl Eq for HashableSamplerCreateInfo {} -impl std::hash::Hash for HashableSamplerCreateInfo { - fn hash(&self, state: &mut H) { +impl core::hash::Hash for HashableSamplerCreateInfo { + fn hash(&self, state: &mut H) { self.0.flags.hash(state); self.0.mag_filter.hash(state); self.0.min_filter.hash(state); diff --git a/wgpu-hal/src/vulkan/semaphore_list.rs b/wgpu-hal/src/vulkan/semaphore_list.rs new file mode 100644 index 000000000..91e031008 --- /dev/null +++ b/wgpu-hal/src/vulkan/semaphore_list.rs @@ -0,0 +1,195 @@ +//! Definition of the [`SemaphoreList`] type. + +use alloc::vec::Vec; +use ash::vk; +use core::mem::MaybeUninit; + +#[derive(Debug, PartialEq)] +pub enum SemaphoreListMode { + Wait, + Signal, +} + +/// A list of Vulkan semaphores to wait for or signal. +/// +/// This represents a list of binary or timeline semaphores, together +/// with values for the timeline semaphores, and stage masks, if these +/// are used for waiting. +/// +/// This type ensures that the array of semaphores to be signaled +/// stays aligned with the array of values for timeline semaphores +/// appearing in that list. The [`add_to_submit`] method prepares the +/// `vkQueueSubmit` arguments appropriately for whatever semaphores we +/// actually have. +/// +/// [`add_to_submit`]: SemaphoreList::add_to_submit +#[derive(Debug)] +pub struct SemaphoreList { + /// Mode of the semaphore list. Used for validation. + mode: SemaphoreListMode, + + /// Semaphores to use. + /// + /// This can be a mix of binary and timeline semaphores. + semaphores: Vec, + + /// Values for the timeline semaphores. + /// + /// If no timeline semaphores are present in [`semaphores`], this + /// is empty. If any timeline semaphores are present, then this + /// has the same length as [`semaphores`], with dummy !0 values + /// in the elements corresponding to binary semaphores, since + /// Vulkan ignores these. + /// + /// [`semaphores`]: Self::semaphores + values: Vec, + + /// Stage masks for wait semaphores. + /// + /// This is only used if `mode` is `Wait`. + pub stage_masks: Vec, +} + +impl SemaphoreList { + pub fn new(mode: SemaphoreListMode) -> Self { + Self { + mode, + semaphores: Vec::new(), + values: Vec::new(), + stage_masks: Vec::new(), + } + } + + pub fn is_empty(&self) -> bool { + self.semaphores.is_empty() + } + + /// Add this list to the semaphores to be signalled by a `vkQueueSubmit` call. + /// + /// - Set `submit_info`'s `pSignalSemaphores` list to this list's + /// semaphores. + /// + /// - If this list contains any timeline semaphores, then initialize + /// `timeline_info`, set its `pSignalSemaphoreValues` to this + /// list's values, and add it to `submit_info`s extension chain. + /// + /// Return the revised `submit_info` value. + pub fn add_to_submit<'info, 'semaphores: 'info>( + wait_semaphores: &'semaphores mut Self, + signal_semaphores: &'semaphores mut Self, + submit_info: vk::SubmitInfo<'info>, + timeline_info: &'info mut MaybeUninit>, + ) -> vk::SubmitInfo<'info> { + wait_semaphores.check(); + signal_semaphores.check(); + + assert!(matches!(wait_semaphores.mode, SemaphoreListMode::Wait)); + assert!(matches!(signal_semaphores.mode, SemaphoreListMode::Signal)); + + let timeline_info = timeline_info.write(vk::TimelineSemaphoreSubmitInfo::default()); + + let mut uses_timeline = false; + + if !wait_semaphores.values.is_empty() { + *timeline_info = timeline_info.wait_semaphore_values(&wait_semaphores.values); + uses_timeline = true; + } + + if !signal_semaphores.values.is_empty() { + *timeline_info = timeline_info.signal_semaphore_values(&signal_semaphores.values); + uses_timeline = true; + } + + let mut submit_info = submit_info + .wait_semaphores(&wait_semaphores.semaphores) + .wait_dst_stage_mask(&wait_semaphores.stage_masks) + .signal_semaphores(&signal_semaphores.semaphores); + + if uses_timeline { + submit_info = submit_info.push_next(timeline_info); + } + + submit_info + } + + /// Add a semaphore to be signaled. Panics if this is a list of semaphores to wait. + pub fn push_signal(&mut self, semaphore: SemaphoreType) { + assert!(matches!(self.mode, SemaphoreListMode::Signal)); + self.push_inner(semaphore); + } + + /// Add a semaphore to be waited for. Panics if this is a list of semaphores to signal. + pub fn push_wait(&mut self, semaphore: SemaphoreType, stage: vk::PipelineStageFlags) { + assert!(matches!(self.mode, SemaphoreListMode::Wait)); + + self.stage_masks.push(stage); + self.push_inner(semaphore); + } + + fn push_inner(&mut self, semaphore: SemaphoreType) { + match semaphore { + SemaphoreType::Binary(semaphore) => { + self.semaphores.push(semaphore); + // Push a dummy value if necessary. + if !self.values.is_empty() { + self.values.push(!0); + } + } + SemaphoreType::Timeline(semaphore, value) => { + // We may be the first timeline semaphore, ensure that the values + // array is filled with dummy values for existing binary semaphores. + self.pad_values(); + self.semaphores.push(semaphore); + self.values.push(value); + } + } + + self.check(); + } + + /// Append `other` to `self`, leaving `other` empty. + pub fn append(&mut self, other: &mut Self) { + assert_eq!(self.mode, other.mode); + + // If we're about to receive values, ensure we're aligned first. + if !other.values.is_empty() { + self.pad_values(); + } + self.semaphores.append(&mut other.semaphores); + self.values.append(&mut other.values); + // If we had values, but `other` did not, re-align. + if !self.values.is_empty() { + self.pad_values(); + } + self.stage_masks.append(&mut other.stage_masks); + self.check(); + } + + /// Pad `self.values` with dummy values for binary semaphores, + /// in preparation for adding a timeline semaphore value. + /// + /// This is a no-op if we already have values. + fn pad_values(&mut self) { + self.values.resize(self.semaphores.len(), !0); + } + + #[track_caller] + fn check(&self) { + debug_assert!(self.values.is_empty() || self.values.len() == self.semaphores.len()); + match self.mode { + SemaphoreListMode::Wait => { + debug_assert!( + self.stage_masks.is_empty() || self.stage_masks.len() == self.semaphores.len() + ); + } + SemaphoreListMode::Signal => { + debug_assert!(self.stage_masks.is_empty()); + } + } + } +} + +pub enum SemaphoreType { + Binary(vk::Semaphore), + Timeline(vk::Semaphore, u64), +} diff --git a/wgpu-hal/src/vulkan/swapchain/mod.rs b/wgpu-hal/src/vulkan/swapchain/mod.rs new file mode 100644 index 000000000..8019f292d --- /dev/null +++ b/wgpu-hal/src/vulkan/swapchain/mod.rs @@ -0,0 +1,107 @@ +use alloc::boxed::Box; +use core::{any::Any, fmt::Debug, time::Duration}; + +use crate::vulkan::{semaphore_list::SemaphoreType, DeviceShared}; + +pub(super) use native::*; + +mod native; + +pub(super) trait Surface: Send + Sync + 'static { + /// Deletes the surface and associated resources. + /// + /// The surface must not be in use when it is deleted. + unsafe fn delete_surface(self: Box); + + /// Returns the surface capabilities for the given adapter. + /// + /// Returns `None` if the surface is not compatible with the adapter. + fn surface_capabilities(&self, adapter: &super::Adapter) -> Option; + + /// Creates a swapchain for the surface with the given configuration. + /// + /// If this is not the first swapchain created for the surface, the old swapchain + /// must be provided. [`Swapchain::release_resources`] must be called on the old swapchain + /// before calling this method. + unsafe fn create_swapchain( + &self, + device: &super::Device, + config: &crate::SurfaceConfiguration, + provided_old_swapchain: Option>, + ) -> Result, crate::SurfaceError>; + + /// Allows downcasting to the concrete type. + fn as_any(&self) -> &dyn Any; +} + +pub(super) trait Swapchain: Send + Sync + 'static { + /// Releases all resources associated with the swapchain, without + /// destroying the swapchain itself. Must be called before calling + /// either [`Surface::create_swapchain`] or [`Swapchain::delete_swapchain`]. + /// + /// The swapchain must not be in use when this is called. + unsafe fn release_resources(&mut self, device: &super::Device); + + /// Deletes the swapchain. + /// + /// The swapchain must not be in use when it is deleted and + /// [`Swapchain::release_resources`] must have been called first. + unsafe fn delete_swapchain(self: Box); + + /// Acquires the next available surface texture for rendering. + /// + /// `timeout` specifies the maximum time to wait for an image to become available. + /// If `None` is specified, this function will wait indefinitely. + /// + /// Returns `Ok(None)` if the timeout elapsed before an image became available. + unsafe fn acquire( + &mut self, + timeout: Option, + fence: &super::Fence, + ) -> Result>, crate::SurfaceError>; + + /// Tries to discard the acquired texture without presenting it. + /// + /// In practice, this doesn't really work in the current implementations. + unsafe fn discard_texture( + &mut self, + texture: super::SurfaceTexture, + ) -> Result<(), crate::SurfaceError>; + + /// Presents the given surface texture using the queue. + unsafe fn present( + &mut self, + queue: &super::Queue, + texture: crate::vulkan::SurfaceTexture, + ) -> Result<(), crate::SurfaceError>; + + /// Allows downcasting to the concrete type. + fn as_any(&self) -> &dyn Any; + + /// Allows downcasting to the concrete type mutably. + fn as_any_mut(&mut self) -> &mut dyn Any; +} + +/// Swapchain specific metadata associated with a surface texture. +pub(super) trait SurfaceTextureMetadata: Debug + Send + Sync + 'static { + /// Returns a guard which can yield the semaphores needed for submission using this swapchain texture. + fn get_semaphore_guard(&self) -> Box; + + /// Allows downcasting to the concrete type. + fn as_any(&self) -> &dyn Any; +} + +/// Guard type for managing swapchain submission semaphores. +pub(super) trait SwapchainSubmissionSemaphoreGuard { + /// Sets the Fence value for this submission. + fn set_used_fence_value(&mut self, value: u64); + + /// Gets semaphores to wait on before doing GPU work for this swapchain texture. + fn get_acquire_wait_semaphore(&mut self) -> Option; + + /// Gets the semaphore to signal when GPU work for this swapchain texture is complete. + fn get_submit_signal_semaphore( + &mut self, + device: &DeviceShared, + ) -> Result; +} diff --git a/wgpu-hal/src/vulkan/swapchain/native.rs b/wgpu-hal/src/vulkan/swapchain/native.rs new file mode 100644 index 000000000..ac8c07cd1 --- /dev/null +++ b/wgpu-hal/src/vulkan/swapchain/native.rs @@ -0,0 +1,904 @@ +//! Vulkan Surface and Swapchain implementation using native Vulkan surfaces. + +use alloc::{boxed::Box, sync::Arc, vec::Vec}; +use core::any::Any; + +use ash::{khr, vk}; +use parking_lot::{Mutex, MutexGuard}; + +use crate::vulkan::{ + conv, map_host_device_oom_and_lost_err, + semaphore_list::SemaphoreType, + swapchain::{Surface, SurfaceTextureMetadata, Swapchain, SwapchainSubmissionSemaphoreGuard}, + DeviceShared, InstanceShared, +}; + +pub(crate) struct NativeSurface { + raw: vk::SurfaceKHR, + functor: khr::surface::Instance, + instance: Arc, +} + +impl NativeSurface { + pub fn from_vk_surface_khr(instance: &crate::vulkan::Instance, raw: vk::SurfaceKHR) -> Self { + let functor = khr::surface::Instance::new(&instance.shared.entry, &instance.shared.raw); + Self { + raw, + functor, + instance: Arc::clone(&instance.shared), + } + } + + pub fn as_raw(&self) -> vk::SurfaceKHR { + self.raw + } +} + +impl Surface for NativeSurface { + unsafe fn delete_surface(self: Box) { + unsafe { + self.functor.destroy_surface(self.raw, None); + } + } + + fn surface_capabilities( + &self, + adapter: &crate::vulkan::Adapter, + ) -> Option { + if !adapter.private_caps.can_present { + return None; + } + let queue_family_index = 0; //TODO + { + profiling::scope!("vkGetPhysicalDeviceSurfaceSupportKHR"); + match unsafe { + self.functor.get_physical_device_surface_support( + adapter.raw, + queue_family_index, + self.raw, + ) + } { + Ok(true) => (), + Ok(false) => return None, + Err(e) => { + log::error!("get_physical_device_surface_support: {e}"); + return None; + } + } + } + + let caps = { + profiling::scope!("vkGetPhysicalDeviceSurfaceCapabilitiesKHR"); + match unsafe { + self.functor + .get_physical_device_surface_capabilities(adapter.raw, self.raw) + } { + Ok(caps) => caps, + Err(e) => { + log::error!("get_physical_device_surface_capabilities: {e}"); + return None; + } + } + }; + + // If image count is 0, the support number of images is unlimited. + let max_image_count = if caps.max_image_count == 0 { + !0 + } else { + caps.max_image_count + }; + + // `0xFFFFFFFF` indicates that the extent depends on the created swapchain. + let current_extent = if caps.current_extent.width != !0 && caps.current_extent.height != !0 + { + Some(wgt::Extent3d { + width: caps.current_extent.width, + height: caps.current_extent.height, + depth_or_array_layers: 1, + }) + } else { + None + }; + + let raw_present_modes = { + profiling::scope!("vkGetPhysicalDeviceSurfacePresentModesKHR"); + match unsafe { + self.functor + .get_physical_device_surface_present_modes(adapter.raw, self.raw) + } { + Ok(present_modes) => present_modes, + Err(e) => { + log::error!("get_physical_device_surface_present_modes: {e}"); + // Per definition of `SurfaceCapabilities`, there must be at least one present mode. + return None; + } + } + }; + + let raw_surface_formats = { + profiling::scope!("vkGetPhysicalDeviceSurfaceFormatsKHR"); + match unsafe { + self.functor + .get_physical_device_surface_formats(adapter.raw, self.raw) + } { + Ok(formats) => formats, + Err(e) => { + log::error!("get_physical_device_surface_formats: {e}"); + // Per definition of `SurfaceCapabilities`, there must be at least one present format. + return None; + } + } + }; + + let formats = raw_surface_formats + .into_iter() + .filter_map(conv::map_vk_surface_formats) + .collect(); + Some(crate::SurfaceCapabilities { + formats, + // TODO: Right now we're always truncating the swap chain + // (presumably - we're actually setting the min image count which isn't necessarily the swap chain size) + // Instead, we should use extensions when available to wait in present. + // See https://github.com/gfx-rs/wgpu/issues/2869 + maximum_frame_latency: (caps.min_image_count - 1)..=(max_image_count - 1), // Note this can't underflow since both `min_image_count` is at least one and we already patched `max_image_count`. + current_extent, + usage: conv::map_vk_image_usage(caps.supported_usage_flags), + present_modes: raw_present_modes + .into_iter() + .flat_map(conv::map_vk_present_mode) + .collect(), + composite_alpha_modes: conv::map_vk_composite_alpha(caps.supported_composite_alpha), + }) + } + + unsafe fn create_swapchain( + &self, + device: &crate::vulkan::Device, + config: &crate::SurfaceConfiguration, + provided_old_swapchain: Option>, + ) -> Result, crate::SurfaceError> { + profiling::scope!("Device::create_swapchain"); + let functor = khr::swapchain::Device::new(&self.instance.raw, &device.shared.raw); + + let old_swapchain = match provided_old_swapchain { + Some(osc) => osc.as_any().downcast_ref::().unwrap().raw, + None => vk::SwapchainKHR::null(), + }; + + let color_space = if config.format == wgt::TextureFormat::Rgba16Float { + // Enable wide color gamut mode + // Vulkan swapchain for Android only supports DISPLAY_P3_NONLINEAR_EXT and EXTENDED_SRGB_LINEAR_EXT + vk::ColorSpaceKHR::EXTENDED_SRGB_LINEAR_EXT + } else { + vk::ColorSpaceKHR::SRGB_NONLINEAR + }; + + let original_format = device.shared.private_caps.map_texture_format(config.format); + let mut raw_flags = vk::SwapchainCreateFlagsKHR::empty(); + let mut raw_view_formats: Vec = vec![]; + if !config.view_formats.is_empty() { + raw_flags |= vk::SwapchainCreateFlagsKHR::MUTABLE_FORMAT; + raw_view_formats = config + .view_formats + .iter() + .map(|f| device.shared.private_caps.map_texture_format(*f)) + .collect(); + raw_view_formats.push(original_format); + } + + let mut info = vk::SwapchainCreateInfoKHR::default() + .flags(raw_flags) + .surface(self.raw) + .min_image_count(config.maximum_frame_latency + 1) // TODO: https://github.com/gfx-rs/wgpu/issues/2869 + .image_format(original_format) + .image_color_space(color_space) + .image_extent(vk::Extent2D { + width: config.extent.width, + height: config.extent.height, + }) + .image_array_layers(config.extent.depth_or_array_layers) + .image_usage(conv::map_texture_usage(config.usage)) + .image_sharing_mode(vk::SharingMode::EXCLUSIVE) + .pre_transform(vk::SurfaceTransformFlagsKHR::IDENTITY) + .composite_alpha(conv::map_composite_alpha_mode(config.composite_alpha_mode)) + .present_mode(conv::map_present_mode(config.present_mode)) + .clipped(true) + .old_swapchain(old_swapchain); + + let mut format_list_info = vk::ImageFormatListCreateInfo::default(); + if !raw_view_formats.is_empty() { + format_list_info = format_list_info.view_formats(&raw_view_formats); + info = info.push_next(&mut format_list_info); + } + + let result = { + profiling::scope!("vkCreateSwapchainKHR"); + unsafe { functor.create_swapchain(&info, None) } + }; + + // doing this before bailing out with error + if old_swapchain != vk::SwapchainKHR::null() { + unsafe { functor.destroy_swapchain(old_swapchain, None) } + } + + let raw = match result { + Ok(swapchain) => swapchain, + Err(error) => { + return Err(match error { + vk::Result::ERROR_SURFACE_LOST_KHR + | vk::Result::ERROR_INITIALIZATION_FAILED => crate::SurfaceError::Lost, + vk::Result::ERROR_NATIVE_WINDOW_IN_USE_KHR => { + crate::SurfaceError::Other("Native window is in use") + } + // We don't use VK_EXT_image_compression_control + // VK_ERROR_COMPRESSION_EXHAUSTED_EXT + other => map_host_device_oom_and_lost_err(other).into(), + }); + } + }; + + let images = unsafe { functor.get_swapchain_images(raw) } + .map_err(crate::vulkan::map_host_device_oom_err)?; + + let fence = unsafe { + device + .shared + .raw + .create_fence(&vk::FenceCreateInfo::default(), None) + .map_err(crate::vulkan::map_host_device_oom_err)? + }; + + // NOTE: It's important that we define the same number of acquire/present semaphores + // as we will need to index into them with the image index. + let acquire_semaphores = (0..images.len()) + .map(|i| { + SwapchainAcquireSemaphore::new(&device.shared, i) + .map(Mutex::new) + .map(Arc::new) + }) + .collect::, _>>()?; + + let present_semaphores = (0..images.len()) + .map(|i| Arc::new(Mutex::new(SwapchainPresentSemaphores::new(i)))) + .collect::>(); + + Ok(Box::new(NativeSwapchain { + raw, + functor, + device: Arc::clone(&device.shared), + images, + fence, + config: config.clone(), + acquire_semaphores, + next_acquire_index: 0, + present_semaphores, + next_present_time: None, + })) + } + + fn as_any(&self) -> &dyn Any { + self + } +} + +pub(crate) struct NativeSwapchain { + raw: vk::SwapchainKHR, + functor: khr::swapchain::Device, + device: Arc, + images: Vec, + /// Fence used to wait on the acquired image. + fence: vk::Fence, + config: crate::SurfaceConfiguration, + + /// Semaphores used between image acquisition and the first submission + /// that uses that image. This is indexed using [`next_acquire_index`]. + /// + /// Because we need to provide this to [`vkAcquireNextImageKHR`], we haven't + /// received the swapchain image index for the frame yet, so we cannot use + /// that to index it. + /// + /// Before we pass this to [`vkAcquireNextImageKHR`], we ensure that we wait on + /// the submission indicated by [`previously_used_submission_index`]. This ensures + /// the semaphore is no longer in use before we use it. + /// + /// [`next_acquire_index`]: NativeSwapchain::next_acquire_index + /// [`vkAcquireNextImageKHR`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkAcquireNextImageKHR + /// [`previously_used_submission_index`]: SwapchainAcquireSemaphore::previously_used_submission_index + acquire_semaphores: Vec>>, + /// The index of the next acquire semaphore to use. + /// + /// This is incremented each time we acquire a new image, and wraps around + /// to 0 when it reaches the end of [`acquire_semaphores`]. + /// + /// [`acquire_semaphores`]: NativeSwapchain::acquire_semaphores + next_acquire_index: usize, + + /// Semaphore sets used between all submissions that write to an image and + /// the presentation of that image. + /// + /// This is indexed by the swapchain image index returned by + /// [`vkAcquireNextImageKHR`]. + /// + /// We know it is safe to use these semaphores because use them + /// _after_ the acquire semaphore. Because the acquire semaphore + /// has been signaled, the previous presentation using that image + /// is known-finished, so this semaphore is no longer in use. + /// + /// [`vkAcquireNextImageKHR`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkAcquireNextImageKHR + present_semaphores: Vec>>, + + /// The present timing information which will be set in the next call to [`present()`](crate::Queue::present()). + /// + /// # Safety + /// + /// This must only be set if [`wgt::Features::VULKAN_GOOGLE_DISPLAY_TIMING`] is enabled, and + /// so the VK_GOOGLE_display_timing extension is present. + next_present_time: Option, +} + +impl Swapchain for NativeSwapchain { + unsafe fn release_resources(&mut self, device: &crate::vulkan::Device) { + profiling::scope!("Swapchain::release_resources"); + { + profiling::scope!("vkDeviceWaitIdle"); + // We need to also wait until all presentation work is done. Because there is no way to portably wait until + // the presentation work is done, we are forced to wait until the device is idle. + let _ = unsafe { + device + .shared + .raw + .device_wait_idle() + .map_err(map_host_device_oom_and_lost_err) + }; + }; + + unsafe { device.shared.raw.destroy_fence(self.fence, None) } + + // We cannot take this by value, as the function returns `self`. + for semaphore in self.acquire_semaphores.drain(..) { + let arc_removed = Arc::into_inner(semaphore).expect( + "Trying to destroy a SwapchainAcquireSemaphore that is still in use by a SurfaceTexture", + ); + let mutex_removed = arc_removed.into_inner(); + + unsafe { mutex_removed.destroy(&device.shared.raw) }; + } + + for semaphore in self.present_semaphores.drain(..) { + let arc_removed = Arc::into_inner(semaphore).expect( + "Trying to destroy a SwapchainPresentSemaphores that is still in use by a SurfaceTexture", + ); + let mutex_removed = arc_removed.into_inner(); + + unsafe { mutex_removed.destroy(&device.shared.raw) }; + } + } + + unsafe fn delete_swapchain(self: Box) { + unsafe { self.functor.destroy_swapchain(self.raw, None) }; + } + + unsafe fn acquire( + &mut self, + timeout: Option, + fence: &crate::vulkan::Fence, + ) -> Result>, crate::SurfaceError> + { + let mut timeout_ns = match timeout { + Some(duration) => duration.as_nanos() as u64, + None => u64::MAX, + }; + + // AcquireNextImageKHR on Android (prior to Android 11) doesn't support timeouts + // and will also log verbose warnings if tying to use a timeout. + // + // Android 10 implementation for reference: + // https://android.googlesource.com/platform/frameworks/native/+/refs/tags/android-mainline-10.0.0_r13/vulkan/libvulkan/swapchain.cpp#1426 + // Android 11 implementation for reference: + // https://android.googlesource.com/platform/frameworks/native/+/refs/tags/android-mainline-11.0.0_r45/vulkan/libvulkan/swapchain.cpp#1438 + // + // Android 11 corresponds to an SDK_INT/ro.build.version.sdk of 30 + if cfg!(target_os = "android") && self.device.instance.android_sdk_version < 30 { + timeout_ns = u64::MAX; + } + + let acquire_semaphore_arc = self.get_acquire_semaphore(); + // Nothing should be using this, so we don't block, but panic if we fail to lock. + let acquire_semaphore_guard = acquire_semaphore_arc + .try_lock() + .expect("Failed to lock a SwapchainSemaphores."); + + // Wait for all commands writing to the previously acquired image to + // complete. + // + // Almost all the steps in the usual acquire-draw-present flow are + // asynchronous: they get something started on the presentation engine + // or the GPU, but on the CPU, control returns immediately. Without some + // sort of intervention, the CPU could crank out frames much faster than + // the presentation engine can display them. + // + // This is the intervention: if any submissions drew on this image, and + // thus waited for `locked_swapchain_semaphores.acquire`, wait for all + // of them to finish, thus ensuring that it's okay to pass `acquire` to + // `vkAcquireNextImageKHR` again. + self.device.wait_for_fence( + fence, + acquire_semaphore_guard.previously_used_submission_index, + timeout_ns, + )?; + + // will block if no image is available + let (index, suboptimal) = match unsafe { + profiling::scope!("vkAcquireNextImageKHR"); + self.functor.acquire_next_image( + self.raw, + timeout_ns, + acquire_semaphore_guard.acquire, + self.fence, + ) + } { + // We treat `VK_SUBOPTIMAL_KHR` as `VK_SUCCESS` on Android. + // See the comment in `Queue::present`. + #[cfg(target_os = "android")] + Ok((index, _)) => (index, false), + #[cfg(not(target_os = "android"))] + Ok(pair) => pair, + Err(error) => { + return match error { + vk::Result::TIMEOUT => Ok(None), + vk::Result::NOT_READY | vk::Result::ERROR_OUT_OF_DATE_KHR => { + Err(crate::SurfaceError::Outdated) + } + vk::Result::ERROR_SURFACE_LOST_KHR => Err(crate::SurfaceError::Lost), + // We don't use VK_EXT_full_screen_exclusive + // VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT + other => Err(map_host_device_oom_and_lost_err(other).into()), + }; + } + }; + + // Wait for the image was acquired to be fully ready to be rendered too. + // + // This wait is very important on Windows to avoid bad frame pacing on + // Windows where the Vulkan driver is using a DXGI swapchain. See + // https://github.com/gfx-rs/wgpu/issues/8310 and + // https://github.com/gfx-rs/wgpu/issues/8354 for more details. + // + // On other platforms, this wait may serve to slightly decrease frame + // latency, depending on how the platform implements waiting within + // acquire. + unsafe { + self.device + .raw + .wait_for_fences(&[self.fence], false, timeout_ns) + .map_err(map_host_device_oom_and_lost_err)?; + + self.device + .raw + .reset_fences(&[self.fence]) + .map_err(map_host_device_oom_and_lost_err)?; + } + + drop(acquire_semaphore_guard); + // We only advance the surface semaphores if we successfully acquired an image, otherwise + // we should try to re-acquire using the same semaphores. + self.advance_acquire_semaphore(); + + let present_semaphore_arc = self.get_present_semaphores(index); + + // special case for Intel Vulkan returning bizarre values (ugh) + if self.device.vendor_id == crate::auxil::db::intel::VENDOR && index > 0x100 { + return Err(crate::SurfaceError::Outdated); + } + + let identity = self.device.texture_identity_factory.next(); + + let texture = crate::vulkan::SurfaceTexture { + index, + texture: crate::vulkan::Texture { + raw: self.images[index as usize], + drop_guard: None, + block: None, + external_memory: None, + format: self.config.format, + copy_size: crate::CopyExtent { + width: self.config.extent.width, + height: self.config.extent.height, + depth: 1, + }, + identity, + }, + metadata: Box::new(NativeSurfaceTextureMetadata { + acquire_semaphores: acquire_semaphore_arc, + present_semaphores: present_semaphore_arc, + }), + }; + Ok(Some(crate::AcquiredSurfaceTexture { + texture, + suboptimal, + })) + } + + unsafe fn discard_texture( + &mut self, + _texture: crate::vulkan::SurfaceTexture, + ) -> Result<(), crate::SurfaceError> { + // TODO: Current implementation no-ops + Ok(()) + } + + unsafe fn present( + &mut self, + queue: &crate::vulkan::Queue, + texture: crate::vulkan::SurfaceTexture, + ) -> Result<(), crate::SurfaceError> { + let metadata = texture + .metadata + .as_any() + .downcast_ref::() + .unwrap(); + let mut acquire_semaphore = metadata.acquire_semaphores.lock(); + let mut present_semaphores = metadata.present_semaphores.lock(); + + let wait_semaphores = present_semaphores.get_present_wait_semaphores(); + + // Reset the acquire and present semaphores internal state + // to be ready for the next frame. + // + // We do this before the actual call to present to ensure that + // even if this method errors and early outs, we have reset + // the state for next frame. + acquire_semaphore.end_semaphore_usage(); + present_semaphores.end_semaphore_usage(); + + drop(acquire_semaphore); + + let swapchains = [self.raw]; + let image_indices = [texture.index]; + let vk_info = vk::PresentInfoKHR::default() + .swapchains(&swapchains) + .image_indices(&image_indices) + .wait_semaphores(&wait_semaphores); + + let mut display_timing; + let present_times; + let vk_info = if let Some(present_time) = self.next_present_time.take() { + debug_assert!( + self.device + .features + .contains(wgt::Features::VULKAN_GOOGLE_DISPLAY_TIMING), + "`next_present_time` should only be set if `VULKAN_GOOGLE_DISPLAY_TIMING` is enabled" + ); + present_times = [present_time]; + display_timing = vk::PresentTimesInfoGOOGLE::default().times(&present_times); + // SAFETY: We know that VK_GOOGLE_display_timing is present because of the safety contract on `next_present_time`. + vk_info.push_next(&mut display_timing) + } else { + vk_info + }; + + let suboptimal = { + profiling::scope!("vkQueuePresentKHR"); + unsafe { self.functor.queue_present(queue.raw, &vk_info) }.map_err(|error| { + match error { + vk::Result::ERROR_OUT_OF_DATE_KHR => crate::SurfaceError::Outdated, + vk::Result::ERROR_SURFACE_LOST_KHR => crate::SurfaceError::Lost, + // We don't use VK_EXT_full_screen_exclusive + // VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT + _ => map_host_device_oom_and_lost_err(error).into(), + } + })? + }; + if suboptimal { + // We treat `VK_SUBOPTIMAL_KHR` as `VK_SUCCESS` on Android. + // On Android 10+, libvulkan's `vkQueuePresentKHR` implementation returns `VK_SUBOPTIMAL_KHR` if not doing pre-rotation + // (i.e `VkSwapchainCreateInfoKHR::preTransform` not being equal to the current device orientation). + // This is always the case when the device orientation is anything other than the identity one, as we unconditionally use `VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR`. + #[cfg(not(target_os = "android"))] + log::warn!("Suboptimal present of frame {}", texture.index); + } + Ok(()) + } + + fn as_any(&self) -> &dyn Any { + self + } + + fn as_any_mut(&mut self) -> &mut dyn Any { + self + } +} + +impl NativeSwapchain { + pub(crate) fn as_raw(&self) -> vk::SwapchainKHR { + self.raw + } + + pub fn set_next_present_time(&mut self, present_timing: vk::PresentTimeGOOGLE) { + let features = wgt::Features::VULKAN_GOOGLE_DISPLAY_TIMING; + if self.device.features.contains(features) { + self.next_present_time = Some(present_timing); + } else { + // Ideally we'd use something like `device.required_features` here, but that's in `wgpu-core`, which we are a dependency of + panic!( + concat!( + "Tried to set display timing properties ", + "without the corresponding feature ({:?}) enabled." + ), + features + ); + } + } + + /// Mark the current frame finished, advancing to the next acquire semaphore. + fn advance_acquire_semaphore(&mut self) { + let semaphore_count = self.acquire_semaphores.len(); + self.next_acquire_index = (self.next_acquire_index + 1) % semaphore_count; + } + + /// Get the next acquire semaphore that should be used with this swapchain. + fn get_acquire_semaphore(&self) -> Arc> { + self.acquire_semaphores[self.next_acquire_index].clone() + } + + /// Get the set of present semaphores that should be used with the given image index. + fn get_present_semaphores(&self, index: u32) -> Arc> { + self.present_semaphores[index as usize].clone() + } +} + +/// Semaphore used to acquire a swapchain image. +#[derive(Debug)] +struct SwapchainAcquireSemaphore { + /// A semaphore that is signaled when this image is safe for us to modify. + /// + /// When [`vkAcquireNextImageKHR`] returns the index of the next swapchain + /// image that we should use, that image may actually still be in use by the + /// presentation engine, and is not yet safe to modify. However, that + /// function does accept a semaphore that it will signal when the image is + /// indeed safe to begin messing with. + /// + /// This semaphore is: + /// + /// - waited for by the first queue submission to operate on this image + /// since it was acquired, and + /// + /// - signaled by [`vkAcquireNextImageKHR`] when the acquired image is ready + /// for us to use. + /// + /// [`vkAcquireNextImageKHR`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkAcquireNextImageKHR + acquire: vk::Semaphore, + + /// True if the next command submission operating on this image should wait + /// for [`acquire`]. + /// + /// We must wait for `acquire` before drawing to this swapchain image, but + /// because `wgpu-hal` queue submissions are always strongly ordered, only + /// the first submission that works with a swapchain image actually needs to + /// wait. We set this flag when this image is acquired, and clear it the + /// first time it's passed to [`Queue::submit`] as a surface texture. + /// + /// Additionally, semaphores can only be waited on once, so we need to ensure + /// that we only actually pass this semaphore to the first submission that + /// uses that image. + /// + /// [`acquire`]: SwapchainAcquireSemaphore::acquire + /// [`Queue::submit`]: crate::Queue::submit + should_wait_for_acquire: bool, + + /// The fence value of the last command submission that wrote to this image. + /// + /// The next time we try to acquire this image, we'll block until + /// this submission finishes, proving that [`acquire`] is ready to + /// pass to `vkAcquireNextImageKHR` again. + /// + /// [`acquire`]: SwapchainAcquireSemaphore::acquire + previously_used_submission_index: crate::FenceValue, +} + +impl SwapchainAcquireSemaphore { + fn new(device: &DeviceShared, index: usize) -> Result { + Ok(Self { + acquire: device + .new_binary_semaphore(&format!("SwapchainImageSemaphore: Index {index} acquire"))?, + should_wait_for_acquire: true, + previously_used_submission_index: 0, + }) + } + + /// Sets the fence value which the next acquire will wait for. This prevents + /// the semaphore from being used while the previous submission is still in flight. + fn set_used_fence_value(&mut self, value: crate::FenceValue) { + self.previously_used_submission_index = value; + } + + /// Return the semaphore that commands drawing to this image should wait for, if any. + /// + /// This only returns `Some` once per acquisition; see + /// [`SwapchainAcquireSemaphore::should_wait_for_acquire`] for details. + fn get_acquire_wait_semaphore(&mut self) -> Option { + if self.should_wait_for_acquire { + self.should_wait_for_acquire = false; + Some(self.acquire) + } else { + None + } + } + + /// Indicates the cpu-side usage of this semaphore has finished for the frame, + /// so reset internal state to be ready for the next frame. + fn end_semaphore_usage(&mut self) { + // Reset the acquire semaphore, so that the next time we acquire this + // image, we can wait for it again. + self.should_wait_for_acquire = true; + } + + unsafe fn destroy(&self, device: &ash::Device) { + unsafe { + device.destroy_semaphore(self.acquire, None); + } + } +} + +#[derive(Debug)] +struct SwapchainPresentSemaphores { + /// A pool of semaphores for ordering presentation after drawing. + /// + /// The first [`present_index`] semaphores in this vector are: + /// + /// - all waited on by the call to [`vkQueuePresentKHR`] that presents this + /// image, and + /// + /// - each signaled by some [`vkQueueSubmit`] queue submission that draws to + /// this image, when the submission finishes execution. + /// + /// This vector accumulates one semaphore per submission that writes to this + /// image. This is awkward, but hard to avoid: [`vkQueuePresentKHR`] + /// requires a semaphore to order it with respect to drawing commands, and + /// we can't attach new completion semaphores to a command submission after + /// it's been submitted. This means that, at submission time, we must create + /// the semaphore we might need if the caller's next action is to enqueue a + /// presentation of this image. + /// + /// An alternative strategy would be for presentation to enqueue an empty + /// submit, ordered relative to other submits in the usual way, and + /// signaling a single presentation semaphore. But we suspect that submits + /// are usually expensive enough, and semaphores usually cheap enough, that + /// performance-sensitive users will avoid making many submits, so that the + /// cost of accumulated semaphores will usually be less than the cost of an + /// additional submit. + /// + /// Only the first [`present_index`] semaphores in the vector are actually + /// going to be signalled by submitted commands, and need to be waited for + /// by the next present call. Any semaphores beyond that index were created + /// for prior presents and are simply being retained for recycling. + /// + /// [`present_index`]: SwapchainPresentSemaphores::present_index + /// [`vkQueuePresentKHR`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkQueuePresentKHR + /// [`vkQueueSubmit`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkQueueSubmit + present: Vec, + + /// The number of semaphores in [`present`] to be signalled for this submission. + /// + /// [`present`]: SwapchainPresentSemaphores::present + present_index: usize, + + /// Which image this semaphore set is used for. + frame_index: usize, +} + +impl SwapchainPresentSemaphores { + pub fn new(frame_index: usize) -> Self { + Self { + present: Vec::new(), + present_index: 0, + frame_index, + } + } + + /// Return the semaphore that the next submission that writes to this image should + /// signal when it's done. + /// + /// See [`SwapchainPresentSemaphores::present`] for details. + fn get_submit_signal_semaphore( + &mut self, + device: &DeviceShared, + ) -> Result { + // Try to recycle a semaphore we created for a previous presentation. + let sem = match self.present.get(self.present_index) { + Some(sem) => *sem, + None => { + let sem = device.new_binary_semaphore(&format!( + "SwapchainImageSemaphore: Image {} present semaphore {}", + self.frame_index, self.present_index + ))?; + self.present.push(sem); + sem + } + }; + + self.present_index += 1; + + Ok(sem) + } + + /// Indicates the cpu-side usage of this semaphore has finished for the frame, + /// so reset internal state to be ready for the next frame. + fn end_semaphore_usage(&mut self) { + // Reset the index to 0, so that the next time we get a semaphore, we + // start from the beginning of the list. + self.present_index = 0; + } + + /// Return the semaphores that a presentation of this image should wait on. + /// + /// Return a slice of semaphores that the call to [`vkQueueSubmit`] that + /// ends this image's acquisition should wait for. See + /// [`SwapchainPresentSemaphores::present`] for details. + /// + /// Reset `self` to be ready for the next acquisition cycle. + /// + /// [`vkQueueSubmit`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkQueueSubmit + fn get_present_wait_semaphores(&mut self) -> Vec { + self.present[0..self.present_index].to_vec() + } + + unsafe fn destroy(&self, device: &ash::Device) { + unsafe { + for sem in &self.present { + device.destroy_semaphore(*sem, None); + } + } + } +} + +#[derive(Debug)] +struct NativeSurfaceTextureMetadata { + acquire_semaphores: Arc>, + present_semaphores: Arc>, +} + +impl SurfaceTextureMetadata for NativeSurfaceTextureMetadata { + fn get_semaphore_guard(&self) -> Box { + Box::new(NativeSwapchainSubmissionSemaphoreGuard { + acquire_semaphore_guard: self + .acquire_semaphores + .try_lock() + .expect("Failed to lock surface acquire semaphore"), + present_semaphores_guard: self + .present_semaphores + .try_lock() + .expect("Failed to lock surface present semaphores"), + }) + } + + fn as_any(&self) -> &dyn Any { + self + } +} + +struct NativeSwapchainSubmissionSemaphoreGuard<'a> { + acquire_semaphore_guard: MutexGuard<'a, SwapchainAcquireSemaphore>, + present_semaphores_guard: MutexGuard<'a, SwapchainPresentSemaphores>, +} + +impl<'a> SwapchainSubmissionSemaphoreGuard for NativeSwapchainSubmissionSemaphoreGuard<'a> { + fn set_used_fence_value(&mut self, value: u64) { + self.acquire_semaphore_guard.set_used_fence_value(value); + } + + fn get_acquire_wait_semaphore(&mut self) -> Option { + self.acquire_semaphore_guard + .get_acquire_wait_semaphore() + .map(SemaphoreType::Binary) + } + + fn get_submit_signal_semaphore( + &mut self, + device: &DeviceShared, + ) -> Result { + self.present_semaphores_guard + .get_submit_signal_semaphore(device) + .map(SemaphoreType::Binary) + } +} diff --git a/wgpu-info/Cargo.toml b/wgpu-info/Cargo.toml index 56ddf860b..720e06c93 100644 --- a/wgpu-info/Cargo.toml +++ b/wgpu-info/Cargo.toml @@ -16,6 +16,7 @@ bitflags.workspace = true env_logger.workspace = true hashbrown = { workspace = true, features = ["serde"] } pico-args.workspace = true +pollster.workspace = true serde = { workspace = true, features = ["default"] } serde_json.workspace = true wgpu.workspace = true diff --git a/wgpu-info/LICENSE.APACHE b/wgpu-info/LICENSE.APACHE new file mode 100644 index 000000000..d9a10c0d8 --- /dev/null +++ b/wgpu-info/LICENSE.APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/wgpu-info/LICENSE.MIT b/wgpu-info/LICENSE.MIT new file mode 100644 index 000000000..8d02e4dbd --- /dev/null +++ b/wgpu-info/LICENSE.MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 The gfx-rs developers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/wgpu-info/src/human.rs b/wgpu-info/src/human.rs index 1c2f7a841..a58779254 100644 --- a/wgpu-info/src/human.rs +++ b/wgpu-info/src/human.rs @@ -99,6 +99,7 @@ fn print_adapter(output: &mut impl io::Write, report: &AdapterReport, idx: usize writeln!(output, "\t Name: {}", info.name)?; writeln!(output, "\t VendorID: {:#X?}", info.vendor)?; writeln!(output, "\t DeviceID: {:#X?}", info.device)?; + writeln!(output, "\t DevicePCIBusId: {}", print_empty_string(&info.device_pci_bus_id))?; writeln!(output, "\t Type: {:?}", info.device_type)?; writeln!(output, "\t Driver: {}", print_empty_string(&info.driver))?; writeln!(output, "\t DriverInfo: {}", print_empty_string(&info.driver_info))?; @@ -160,6 +161,18 @@ fn print_adapter(output: &mut impl io::Write, report: &AdapterReport, idx: usize max_subgroup_size, max_push_constant_size, max_non_sampler_bindings, + + max_task_workgroup_total_count, + max_task_workgroups_per_dimension, + max_mesh_multiview_view_count: max_mesh_multiview_count, + max_mesh_output_layers, + + max_blas_primitive_count, + max_blas_geometry_count, + max_tlas_instance_count, + max_acceleration_structures_per_shader_stage, + + max_multiview_view_count, } = limits; writeln!(output, "\t\t Max Texture Dimension 1d: {max_texture_dimension_1d}")?; writeln!(output, "\t\t Max Texture Dimension 2d: {max_texture_dimension_2d}")?; @@ -196,7 +209,18 @@ fn print_adapter(output: &mut impl io::Write, report: &AdapterReport, idx: usize writeln!(output, "\t\t Max Compute Workgroup Size Y: {max_compute_workgroup_size_y}")?; writeln!(output, "\t\t Max Compute Workgroup Size Z: {max_compute_workgroup_size_z}")?; writeln!(output, "\t\t Max Compute Workgroups Per Dimension: {max_compute_workgroups_per_dimension}")?; + + writeln!(output, "\t\t Max Task Workgroup Total Count: {max_task_workgroup_total_count}")?; + writeln!(output, "\t\t Max Task Workgroups Per Dimension: {max_task_workgroups_per_dimension}")?; + writeln!(output, "\t\t Max Mesh Multiview View Count: {max_mesh_multiview_count}")?; + writeln!(output, "\t\t Max Mesh Output Layers: {max_mesh_output_layers}")?; + writeln!(output, "\t\t Max BLAS Primitive count: {max_blas_primitive_count}")?; + writeln!(output, "\t\t Max BLAS Geometry count: {max_blas_geometry_count}")?; + writeln!(output, "\t\t Max TLAS Instance count: {max_tlas_instance_count}")?; + writeln!(output, "\t\t Max Acceleration Structures Per Shader Stage: {max_acceleration_structures_per_shader_stage}")?; + + writeln!(output, "\t\t Max Multiview View Count: {max_multiview_view_count}")?; // This one reflects more of a wgpu implementation limitations than a hardware limit // so don't show it here. let _ = max_non_sampler_bindings; diff --git a/wgpu-info/src/report.rs b/wgpu-info/src/report.rs index ed0f16914..fa0522b2b 100644 --- a/wgpu-info/src/report.rs +++ b/wgpu-info/src/report.rs @@ -25,7 +25,8 @@ impl GpuReport { desc.flags = wgpu::InstanceFlags::debugging(); desc.with_env() }); - let adapters = instance.enumerate_adapters(wgpu::Backends::all()); + + let adapters = pollster::block_on(instance.enumerate_adapters(wgpu::Backends::all())); let mut devices = Vec::with_capacity(adapters.len()); for adapter in adapters { diff --git a/wgpu-info/src/texture.rs b/wgpu-info/src/texture.rs index 64325f0e5..883a827a0 100644 --- a/wgpu-info/src/texture.rs +++ b/wgpu-info/src/texture.rs @@ -1,6 +1,6 @@ // Lets keep these on one line #[rustfmt::skip] -pub const TEXTURE_FORMAT_LIST: [wgpu::TextureFormat; 117] = [ +pub const TEXTURE_FORMAT_LIST: [wgpu::TextureFormat; 118] = [ wgpu::TextureFormat::R8Unorm, wgpu::TextureFormat::R8Snorm, wgpu::TextureFormat::R8Uint, @@ -52,6 +52,7 @@ pub const TEXTURE_FORMAT_LIST: [wgpu::TextureFormat; 117] = [ wgpu::TextureFormat::Depth32Float, wgpu::TextureFormat::Depth32FloatStencil8, wgpu::TextureFormat::NV12, + wgpu::TextureFormat::P010, wgpu::TextureFormat::Bc1RgbaUnorm, wgpu::TextureFormat::Bc1RgbaUnormSrgb, wgpu::TextureFormat::Bc2RgbaUnorm, @@ -133,6 +134,32 @@ fn test_uniqueness_in_texture_format_list() { assert_eq!(duplicated, vec![]); } +#[test] +fn test_compute_render_extent() { + for format in TEXTURE_FORMAT_LIST { + let desc = wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { + width: 1280, + height: 720, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::empty(), + view_formats: &[], + }; + + if format.is_multi_planar_format() { + let _ = desc.compute_render_extent(0, Some(0)); + } else { + let _ = desc.compute_render_extent(0, None); + } + } +} + pub fn max_texture_format_string_size() -> usize { TEXTURE_FORMAT_LIST .into_iter() diff --git a/wgpu-macros/Cargo.toml b/wgpu-macros/Cargo.toml index 97c4f3139..aea8503c1 100644 --- a/wgpu-macros/Cargo.toml +++ b/wgpu-macros/Cargo.toml @@ -16,6 +16,6 @@ publish = false proc-macro = true [dependencies] -heck = "0.5" -quote = "1" -syn = { version = "2", features = ["full"] } +heck.workspace = true +quote.workspace = true +syn = { workspace = true, features = ["full"] } diff --git a/wgpu-macros/src/lib.rs b/wgpu-macros/src/lib.rs index f8232c036..eeafca5de 100644 --- a/wgpu-macros/src/lib.rs +++ b/wgpu-macros/src/lib.rs @@ -9,29 +9,27 @@ use syn::Ident; #[proc_macro_attribute] pub fn gpu_test(_attr: TokenStream, item: TokenStream) -> TokenStream { let input_static = syn::parse_macro_input!(item as syn::ItemStatic); + let vis = input_static.vis; let expr = &input_static.expr; let ident = &input_static.ident; let ident_str = ident.to_string(); let ident_lower = ident_str.to_snake_case(); - let register_test_name = Ident::new(&format!("{ident_lower}_initializer"), ident.span()); + let register_test_name = Ident::new(&format!("{ident}"), ident.span()); let test_name_webgl = Ident::new(&format!("{ident_lower}_webgl"), ident.span()); quote! { - #[cfg(not(target_arch = "wasm32"))] - #[::wgpu_test::ctor] - fn #register_test_name() { + #[allow(non_snake_case)] + #vis fn #register_test_name() -> ::wgpu_test::GpuTestConfiguration { struct S; - ::wgpu_test::native::TEST_LIST.lock().push( - // Allow any type that can be converted to a GpuTestConfiguration - ::wgpu_test::GpuTestConfiguration::from(#expr).name_from_init_function_typename::(#ident_lower) - ) + // Allow any type that can be converted to a GpuTestConfiguration + ::wgpu_test::GpuTestConfiguration::from(#expr).name_from_init_function_typename::(#ident_lower) } #[cfg(target_arch = "wasm32")] #[wasm_bindgen_test::wasm_bindgen_test] - async fn #test_name_webgl() { + #vis async fn #test_name_webgl() { struct S; // Allow any type that can be converted to a GpuTestConfiguration diff --git a/wgpu-types/Cargo.toml b/wgpu-types/Cargo.toml index d98e8e7cb..7bb971892 100644 --- a/wgpu-types/Cargo.toml +++ b/wgpu-types/Cargo.toml @@ -1,13 +1,13 @@ [package] name = "wgpu-types" -version = "24.0.0" -authors = ["gfx-rs developers"] -edition = "2021" +version.workspace = true +authors.workspace = true +edition.workspace = true description = "Common types and utilities for wgpu, the cross-platform, safe, pure-rust graphics API" -homepage = "https://wgpu.rs/" -repository = "https://github.com/gfx-rs/wgpu" -keywords = ["graphics"] -license = "MIT OR Apache-2.0" +homepage.workspace = true +repository.workspace = true +keywords.workspace = true +license.workspace = true # Override the workspace's `rust-version` key. Firefox uses `cargo vendor` to # copy the crates it actually uses out of the workspace, so it's meaningful for @@ -37,7 +37,7 @@ alloc_instead_of_core = "warn" [features] default = ["std"] -std = ["js-sys/std", "web-sys/std", "thiserror/std"] +std = ["js-sys?/std", "web-sys?/std"] strict_asserts = [] fragile-send-sync-non-atomic-wasm = [] serde = ["dep:serde", "bitflags/serde"] @@ -45,20 +45,21 @@ serde = ["dep:serde", "bitflags/serde"] counters = [] # Enables variants of `Trace` other than `Trace::Off` trace = ["std"] +# Enable web-specific dependencies for wasm. +web = ["dep:js-sys", "dep:web-sys"] [dependencies] -bitflags = { workspace = true, features = ["serde"] } +bitflags.workspace = true bytemuck = { workspace = true, features = ["derive"] } log.workspace = true -thiserror = { workspace = true, optional = true } serde = { workspace = true, default-features = false, features = [ "alloc", "derive", ], optional = true } [target.'cfg(target_arch = "wasm32")'.dependencies] -js-sys = { workspace = true, default-features = false } -web-sys = { workspace = true, default-features = false, features = [ +js-sys = { workspace = true, optional = true, default-features = false } +web-sys = { workspace = true, optional = true, default-features = false, features = [ "ImageBitmap", "ImageData", "HtmlImageElement", diff --git a/wgpu-types/LICENSE.APACHE b/wgpu-types/LICENSE.APACHE deleted file mode 120000 index 7141cad5b..000000000 --- a/wgpu-types/LICENSE.APACHE +++ /dev/null @@ -1 +0,0 @@ -../LICENSE.APACHE \ No newline at end of file diff --git a/wgpu-types/LICENSE.APACHE b/wgpu-types/LICENSE.APACHE new file mode 100644 index 000000000..d9a10c0d8 --- /dev/null +++ b/wgpu-types/LICENSE.APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/wgpu-types/LICENSE.MIT b/wgpu-types/LICENSE.MIT deleted file mode 120000 index 6b8772d1a..000000000 --- a/wgpu-types/LICENSE.MIT +++ /dev/null @@ -1 +0,0 @@ -../LICENSE.MIT \ No newline at end of file diff --git a/wgpu-types/LICENSE.MIT b/wgpu-types/LICENSE.MIT new file mode 100644 index 000000000..8d02e4dbd --- /dev/null +++ b/wgpu-types/LICENSE.MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 The gfx-rs developers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/wgpu-types/src/error.rs b/wgpu-types/src/error.rs new file mode 100644 index 000000000..96cc7453a --- /dev/null +++ b/wgpu-types/src/error.rs @@ -0,0 +1,41 @@ +//! Shared types for WebGPU errors. See also: +//! + +/// A classification of WebGPU error for implementers of the WebGPU API to use in their own error +/// layer(s). +/// +/// Strongly correlates to the [`GPUError`] and [`GPUErrorFilter`] types in the WebGPU API, with an +/// additional [`Self::DeviceLost`] variant. +/// +/// [`GPUError`]: https://gpuweb.github.io/gpuweb/#gpuerror +/// [`GPUErrorFilter`]: https://gpuweb.github.io/gpuweb/#enumdef-gpuerrorfilter +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] +pub enum ErrorType { + /// A [`GPUInternalError`]. + /// + /// [`GPUInternalError`]: https://gpuweb.github.io/gpuweb/#gpuinternalerror + Internal, + /// A [`GPUOutOfMemoryError`]. + /// + /// [`GPUOutOfMemoryError`]: https://gpuweb.github.io/gpuweb/#gpuoutofmemoryerror + OutOfMemory, + /// A [`GPUValidationError`]. + /// + /// [`GPUValidationError`]: https://gpuweb.github.io/gpuweb/#gpuvalidationerror + Validation, + /// Indicates that device loss occurred. In JavaScript, this means the [`GPUDevice.lost`] + /// property should be `resolve`d. + /// + /// [`GPUDevice.lost`]: https://www.w3.org/TR/webgpu/#dom-gpudevice-lost + DeviceLost, +} + +/// A trait for querying the [`ErrorType`] classification of an error. +/// +/// This is intended to be used as a convenience by implementations of WebGPU to classify errors +/// returned by [`wgpu_core`](crate). +pub trait WebGpuError: core::error::Error + 'static { + /// Determine the classification of this error as a WebGPU [`ErrorType`]. + fn webgpu_error_type(&self) -> ErrorType; +} diff --git a/wgpu-types/src/features.rs b/wgpu-types/src/features.rs index b375b3c26..234d01d85 100644 --- a/wgpu-types/src/features.rs +++ b/wgpu-types/src/features.rs @@ -37,25 +37,31 @@ mod webgpu_impl { pub const WEBGPU_FEATURE_TEXTURE_COMPRESSION_ASTC: u64 = 1 << 5; #[doc(hidden)] - pub const WEBGPU_FEATURE_TIMESTAMP_QUERY: u64 = 1 << 6; + pub const WEBGPU_FEATURE_TEXTURE_COMPRESSION_ASTC_SLICED_3D: u64 = 1 << 6; #[doc(hidden)] - pub const WEBGPU_FEATURE_INDIRECT_FIRST_INSTANCE: u64 = 1 << 7; + pub const WEBGPU_FEATURE_TIMESTAMP_QUERY: u64 = 1 << 7; #[doc(hidden)] - pub const WEBGPU_FEATURE_SHADER_F16: u64 = 1 << 8; + pub const WEBGPU_FEATURE_INDIRECT_FIRST_INSTANCE: u64 = 1 << 8; #[doc(hidden)] - pub const WEBGPU_FEATURE_RG11B10UFLOAT_RENDERABLE: u64 = 1 << 9; + pub const WEBGPU_FEATURE_SHADER_F16: u64 = 1 << 9; #[doc(hidden)] - pub const WEBGPU_FEATURE_BGRA8UNORM_STORAGE: u64 = 1 << 10; + pub const WEBGPU_FEATURE_RG11B10UFLOAT_RENDERABLE: u64 = 1 << 10; #[doc(hidden)] - pub const WEBGPU_FEATURE_FLOAT32_FILTERABLE: u64 = 1 << 11; + pub const WEBGPU_FEATURE_BGRA8UNORM_STORAGE: u64 = 1 << 11; #[doc(hidden)] - pub const WEBGPU_FEATURE_DUAL_SOURCE_BLENDING: u64 = 1 << 12; + pub const WEBGPU_FEATURE_FLOAT32_FILTERABLE: u64 = 1 << 12; + + #[doc(hidden)] + pub const WEBGPU_FEATURE_DUAL_SOURCE_BLENDING: u64 = 1 << 13; + + #[doc(hidden)] + pub const WEBGPU_FEATURE_CLIP_DISTANCES: u64 = 1 << 14; } macro_rules! bitflags_array_impl { @@ -529,7 +535,11 @@ bitflags_array! { /// Features that are not guaranteed to be supported. /// - /// These are extension features supported by wgpu when targeting native. For all features see [`Features`] + /// Most of these are native-only extension features supported by wgpu only when targeting + /// native. A few are intended to align with a proposed WebGPU extension, and one + /// (`EXTERNAL_TEXTURE`) controls WebGPU-specified behavior that is not optional in the + /// standard, but that we don't want to make a [`crate::DownlevelFlags`] until the + /// implementation is more complete. For all features see [`Features`]. /// /// If you want to use a feature, you need to first verify that the adapter supports /// the feature. If the adapter does not support the feature, requesting a device with it enabled @@ -778,28 +788,11 @@ bitflags_array! { /// /// This is a native only feature. const PARTIALLY_BOUND_BINDING_ARRAY = 1 << 13; - /// Allows the user to call [`RenderPass::multi_draw_indirect`] and [`RenderPass::multi_draw_indexed_indirect`]. - /// - /// Allows multiple indirect calls to be dispatched from a single buffer. - /// - /// Natively Supported Platforms: - /// - DX12 - /// - Vulkan - /// - /// Emulated Platforms: - /// - Metal - /// - OpenGL - /// - WebGPU - /// - /// Emulation is preformed by looping over the individual indirect draw calls in the backend. This is still significantly - /// faster than enulating it yourself, as wgpu only does draw call validation once. - /// - /// [`RenderPass::multi_draw_indirect`]: ../wgpu/struct.RenderPass.html#method.multi_draw_indirect - /// [`RenderPass::multi_draw_indexed_indirect`]: ../wgpu/struct.RenderPass.html#method.multi_draw_indexed_indirect - const MULTI_DRAW_INDIRECT = 1 << 14; /// Allows the user to call [`RenderPass::multi_draw_indirect_count`] and [`RenderPass::multi_draw_indexed_indirect_count`]. /// - /// This allows the use of a buffer containing the actual number of draw calls. + /// This allows the use of a buffer containing the actual number of draw calls. This feature being present also implies + /// that all calls to [`RenderPass::multi_draw_indirect`] and [`RenderPass::multi_draw_indexed_indirect`] are not being emulated + /// with a series of `draw_indirect` calls. /// /// Supported platforms: /// - DX12 @@ -807,6 +800,8 @@ bitflags_array! { /// /// This is a native only feature. /// + /// [`RenderPass::multi_draw_indirect`]: ../wgpu/struct.RenderPass.html#method.multi_draw_indirect + /// [`RenderPass::multi_draw_indexed_indirect`]: ../wgpu/struct.RenderPass.html#method.multi_draw_indexed_indirect /// [`RenderPass::multi_draw_indirect_count`]: ../wgpu/struct.RenderPass.html#method.multi_draw_indirect_count /// [`RenderPass::multi_draw_indexed_indirect_count`]: ../wgpu/struct.RenderPass.html#method.multi_draw_indexed_indirect_count const MULTI_DRAW_INDIRECT_COUNT = 1 << 15; @@ -920,28 +915,17 @@ bitflags_array! { /// /// This is a native only feature. const CLEAR_TEXTURE = 1 << 23; - /// Enables creating shader modules from SPIR-V binary data (unsafe). - /// - /// SPIR-V data is not parsed or interpreted in any way; you can use - /// [`wgpu::make_spirv_raw!`] to check for alignment and magic number when converting from - /// raw bytes. - /// - /// Supported platforms: - /// - Vulkan, in case shader's requested capabilities and extensions agree with - /// Vulkan implementation. - /// - /// This is a native only feature. - /// - /// [`wgpu::make_spirv_raw!`]: https://docs.rs/wgpu/latest/wgpu/macro.include_spirv_raw.html - const SPIRV_SHADER_PASSTHROUGH = 1 << 24; - /// Enables multiview render passes and `builtin(view_index)` in vertex shaders. + /// Enables multiview render passes and `builtin(view_index)` in vertex/mesh shaders. /// /// Supported platforms: /// - Vulkan + /// - Metal /// - OpenGL (web only) /// + /// DX12 support is a WIP. + /// /// This is a native only feature. - const MULTIVIEW = 1 << 25; + const MULTIVIEW = 1 << 26; /// Enables using 64-bit types for vertex attributes. /// /// Requires SHADER_FLOAT64. @@ -949,7 +933,7 @@ bitflags_array! { /// Supported Platforms: N/A /// /// This is a native only feature. - const VERTEX_ATTRIBUTE_64BIT = 1 << 26; + const VERTEX_ATTRIBUTE_64BIT = 1 << 27; /// Enables image atomic fetch add, and, xor, or, min, and max for R32Uint and R32Sint textures. /// /// Supported platforms: @@ -958,7 +942,7 @@ bitflags_array! { /// - Metal (with MSL 3.1+) /// /// This is a native only feature. - const TEXTURE_ATOMIC = 1 << 27; + const TEXTURE_ATOMIC = 1 << 28; /// Allows for creation of textures of format [`TextureFormat::NV12`] /// /// Supported platforms: @@ -968,19 +952,33 @@ bitflags_array! { /// This is a native only feature. /// /// [`TextureFormat::NV12`]: super::TextureFormat::NV12 - const TEXTURE_FORMAT_NV12 = 1 << 28; - /// ***THIS IS EXPERIMENTAL:*** Features enabled by this may have - /// major bugs in them and are expected to be subject to breaking changes, suggestions - /// for the API exposed by this should be posted on [the ray-tracing issue](https://github.com/gfx-rs/wgpu/issues/1040) - /// - /// Allows for the creation of ray-tracing acceleration structures. Currently, - /// ray-tracing acceleration structures are only useful when used with [Features::EXPERIMENTAL_RAY_QUERY] + const TEXTURE_FORMAT_NV12 = 1 << 29; + /// Allows for creation of textures of format [`TextureFormat::P010`] /// /// Supported platforms: + /// - DX12 /// - Vulkan /// - /// This is a native-only feature. - const EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE = 1 << 29; + /// This is a native only feature. + /// + /// [`TextureFormat::P010`]: super::TextureFormat::P010 + const TEXTURE_FORMAT_P010 = 1 << 30; + + /// Allows for the creation and usage of `ExternalTexture`s, and bind + /// group layouts containing external texture `BindingType`s. + /// + /// Conceptually this should really be a [`crate::DownlevelFlags`] as + /// it corresponds to WebGPU's [`GPUExternalTexture`]( + /// https://www.w3.org/TR/webgpu/#gpuexternaltexture). + /// However, the implementation is currently in-progress, and until it + /// is complete we do not want applications to ignore adapters due to + /// a missing downlevel flag, when they may not require this feature at + /// all. + /// + /// Supported platforms: + /// - DX12 + /// - Metal + const EXTERNAL_TEXTURE = 1 << 31; // Shader: @@ -994,7 +992,7 @@ bitflags_array! { /// - Vulkan /// /// This is a native-only feature. - const EXPERIMENTAL_RAY_QUERY = 1 << 30; + const EXPERIMENTAL_RAY_QUERY = 1 << 32; /// Enables 64-bit floating point types in SPIR-V shaders. /// /// Note: even when supported by GPU hardware, 64-bit floating point operations are @@ -1004,14 +1002,14 @@ bitflags_array! { /// - Vulkan /// /// This is a native only feature. - const SHADER_F64 = 1 << 31; + const SHADER_F64 = 1 << 33; /// Allows shaders to use i16. Not currently supported in `naga`, only available through `spirv-passthrough`. /// /// Supported platforms: /// - Vulkan /// /// This is a native only feature. - const SHADER_I16 = 1 << 32; + const SHADER_I16 = 1 << 34; /// Enables `builtin(primitive_index)` in fragment shaders. /// /// Note: enables geometry processing for pipelines using the builtin. @@ -1025,14 +1023,35 @@ bitflags_array! { /// - OpenGL (some) /// /// This is a native only feature. - const SHADER_PRIMITIVE_INDEX = 1 << 33; + const SHADER_PRIMITIVE_INDEX = 1 << 35; /// Allows shaders to use the `early_depth_test` attribute. /// + /// The attribute is applied to the fragment shader entry point. It can be used in two + /// ways: + /// + /// 1. Force early depth/stencil tests: + /// + /// - `@early_depth_test(force)` (WGSL) + /// + /// - `layout(early_fragment_tests) in;` (GLSL) + /// + /// 2. Provide a conservative depth specifier that allows an additional early + /// depth test under certain conditions: + /// + /// - `@early_depth_test(greater_equal/less_equal/unchanged)` (WGSL) + /// + /// - `layout(depth_) out float gl_FragDepth;` (GLSL) + /// + /// See [`EarlyDepthTest`] for more details. + /// /// Supported platforms: + /// - Vulkan /// - GLES 3.1+ /// /// This is a native only feature. - const SHADER_EARLY_DEPTH_TEST = 1 << 34; + /// + /// [`EarlyDepthTest`]: https://docs.rs/naga/latest/naga/ir/enum.EarlyDepthTest.html + const SHADER_EARLY_DEPTH_TEST = 1 << 36; /// Allows shaders to use i64 and u64. /// /// Supported platforms: @@ -1041,8 +1060,9 @@ bitflags_array! { /// - Metal (with MSL 2.3+) /// /// This is a native only feature. - const SHADER_INT64 = 1 << 35; - /// Allows compute and fragment shaders to use the subgroup operation built-ins + const SHADER_INT64 = 1 << 37; + /// Allows compute and fragment shaders to use the subgroup operation + /// built-ins and perform subgroup operations (except barriers). /// /// Supported Platforms: /// - Vulkan @@ -1050,22 +1070,25 @@ bitflags_array! { /// - Metal /// /// This is a native only feature. - const SUBGROUP = 1 << 36; - /// Allows vertex shaders to use the subgroup operation built-ins + const SUBGROUP = 1 << 38; + /// Allows vertex shaders to use the subgroup operation built-ins and + /// perform subgroup operations (except barriers). /// /// Supported Platforms: /// - Vulkan /// /// This is a native only feature. - const SUBGROUP_VERTEX = 1 << 37; - /// Allows shaders to use the subgroup barrier + const SUBGROUP_VERTEX = 1 << 39; + /// Allows compute shaders to use the subgroup barrier. + /// + /// Requires [`Features::SUBGROUP`]. Without it, enables nothing. /// /// Supported Platforms: /// - Vulkan /// - Metal /// /// This is a native only feature. - const SUBGROUP_BARRIER = 1 << 38; + const SUBGROUP_BARRIER = 1 << 40; /// Allows the use of pipeline cache objects /// /// Supported platforms: @@ -1074,7 +1097,7 @@ bitflags_array! { /// Unimplemented Platforms: /// - DX12 /// - Metal - const PIPELINE_CACHE = 1 << 39; + const PIPELINE_CACHE = 1 << 41; /// Allows shaders to use i64 and u64 atomic min and max. /// /// Supported platforms: @@ -1083,7 +1106,7 @@ bitflags_array! { /// - Metal (with MSL 2.4+) /// /// This is a native only feature. - const SHADER_INT64_ATOMIC_MIN_MAX = 1 << 40; + const SHADER_INT64_ATOMIC_MIN_MAX = 1 << 42; /// Allows shaders to use all i64 and u64 atomic operations. /// /// Supported platforms: @@ -1091,7 +1114,7 @@ bitflags_array! { /// - DX12 (with SM 6.6+) /// /// This is a native only feature. - const SHADER_INT64_ATOMIC_ALL_OPS = 1 << 41; + const SHADER_INT64_ATOMIC_ALL_OPS = 1 << 43; /// Allows using the [VK_GOOGLE_display_timing] Vulkan extension. /// /// This is used for frame pacing to reduce latency, and is generally only available on Android. @@ -1107,7 +1130,7 @@ bitflags_array! { /// /// [VK_GOOGLE_display_timing]: https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_GOOGLE_display_timing.html /// [`Surface::as_hal()`]: https://docs.rs/wgpu/latest/wgpu/struct.Surface.html#method.as_hal - const VULKAN_GOOGLE_DISPLAY_TIMING = 1 << 42; + const VULKAN_GOOGLE_DISPLAY_TIMING = 1 << 44; /// Allows using the [VK_KHR_external_memory_win32] Vulkan extension. /// @@ -1117,7 +1140,7 @@ bitflags_array! { /// This is a native only feature. /// /// [VK_KHR_external_memory_win32]: https://registry.khronos.org/vulkan/specs/latest/man/html/VK_KHR_external_memory_win32.html - const VULKAN_EXTERNAL_MEMORY_WIN32 = 1 << 43; + const VULKAN_EXTERNAL_MEMORY_WIN32 = 1 << 45; /// Enables R64Uint image atomic min and max. /// @@ -1127,7 +1150,7 @@ bitflags_array! { /// - Metal (with MSL 3.1+) /// /// This is a native only feature. - const TEXTURE_INT64_ATOMIC = 1 << 44; + const TEXTURE_INT64_ATOMIC = 1 << 46; /// Allows uniform buffers to be bound as binding arrays. /// @@ -1144,7 +1167,7 @@ bitflags_array! { /// - Vulkan 1.2+ (or VK_EXT_descriptor_indexing)'s `shaderUniformBufferArrayNonUniformIndexing` feature) /// /// This is a native only feature. - const UNIFORM_BUFFER_BINDING_ARRAYS = 1 << 45; + const UNIFORM_BUFFER_BINDING_ARRAYS = 1 << 47; /// Enables mesh shaders and task shaders in mesh shader pipelines. /// @@ -1156,7 +1179,7 @@ bitflags_array! { /// - Metal /// /// This is a native only feature. - const EXPERIMENTAL_MESH_SHADER = 1 << 46; + const EXPERIMENTAL_MESH_SHADER = 1 << 48; /// ***THIS IS EXPERIMENTAL:*** Features enabled by this may have /// major bugs in them and are expected to be subject to breaking changes, suggestions @@ -1171,7 +1194,7 @@ bitflags_array! { /// This is a native only feature /// /// [`AccelerationStructureFlags::ALLOW_RAY_HIT_VERTEX_RETURN`]: super::AccelerationStructureFlags::ALLOW_RAY_HIT_VERTEX_RETURN - const EXPERIMENTAL_RAY_HIT_VERTEX_RETURN = 1 << 47; + const EXPERIMENTAL_RAY_HIT_VERTEX_RETURN = 1 << 49; /// Enables multiview in mesh shader pipelines /// @@ -1183,12 +1206,60 @@ bitflags_array! { /// - Metal /// /// This is a native only feature. - const EXPERIMENTAL_MESH_SHADER_MULTIVIEW = 1 << 48; + const EXPERIMENTAL_MESH_SHADER_MULTIVIEW = 1 << 50; + + /// Allows usage of additional vertex formats in [BlasTriangleGeometrySizeDescriptor::vertex_format] + /// + /// Supported platforms + /// - Vulkan + /// - DX12 + /// + /// [BlasTriangleGeometrySizeDescriptor::vertex_format]: super::BlasTriangleGeometrySizeDescriptor + const EXTENDED_ACCELERATION_STRUCTURE_VERTEX_FORMATS = 1 << 51; + + /// Enables creating shaders from passthrough with reflection info (unsafe) + /// + /// Allows using [`Device::create_shader_module_passthrough`]. + /// Shader code isn't parsed or interpreted in any way. It is the user's + /// responsibility to ensure the code and reflection (if passed) are correct. + /// + /// Supported platforms + /// - Vulkan + /// - DX12 + /// - Metal + /// - WebGPU + /// + /// Ideally, in the future, all platforms will be supported. For more info, see + /// [this comment](https://github.com/gfx-rs/wgpu/issues/3103#issuecomment-2833058367). + /// + /// [`Device::create_shader_module_passthrough`]: https://docs.rs/wgpu/latest/wgpu/struct.Device.html#method.create_shader_module_passthrough + const EXPERIMENTAL_PASSTHROUGH_SHADERS = 1 << 52; + + /// Enables shader barycentric coordinates. + /// + /// Supported platforms: + /// - Vulkan (with VK_KHR_fragment_shader_barycentric) + /// - DX12 (with SM 6.1+) + /// - Metal (with MSL 2.2+) + /// + /// This is a native only feature. + const SHADER_BARYCENTRICS = 1 << 53; + + /// Enables using multiview where not all texture array layers are rendered to in a single render pass/render pipeline. Making + /// use of this feature also requires enabling `Features::MULTIVIEW`. + /// + /// Supported platforms + /// - Vulkan + /// + /// DX12 will support this when it supports multiview in general. + /// + /// While metal supports this in theory, the behavior of `view_index` differs from vulkan and dx12 so the feature isn't exposed. + const SELECTIVE_MULTIVIEW = 1 << 54; } /// Features that are not guaranteed to be supported. /// - /// These are part of the webgpu standard. For all features see [`Features`] + /// These are part of the WebGPU standard. For all features, see [`Features`]. /// /// If you want to use a feature, you need to first verify that the adapter supports /// the feature. If the adapter does not support the feature, requesting a device with it enabled @@ -1285,6 +1356,9 @@ bitflags_array! { /// Support for this feature guarantees availability of [`TextureUsages::COPY_SRC | TextureUsages::COPY_DST | TextureUsages::TEXTURE_BINDING`] for ASTC formats with Unorm/UnormSrgb channel type. /// [`Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES`] may enable additional usages. /// + /// This feature does not guarantee availability of sliced 3d textures for ASTC formats. + /// If available, 3d support can be enabled by TEXTURE_COMPRESSION_ASTC_SLICED_3D feature. + /// /// Supported Platforms: /// - Vulkan on Intel /// - Mobile (some) @@ -1292,6 +1366,23 @@ bitflags_array! { /// This is a web and native feature. const TEXTURE_COMPRESSION_ASTC = WEBGPU_FEATURE_TEXTURE_COMPRESSION_ASTC; + + /// Allows the 3d dimension for textures with ASTC compressed formats. + /// + /// This feature must be used in combination with TEXTURE_COMPRESSION_ASTC to enable 3D textures with ASTC compression. + /// It does not enable the ASTC formats by itself. + /// + /// Supported Platforms: + /// - Vulkan (some) + /// - Metal on Apple3+ + /// - OpenGL/WebGL (some) + /// + /// Not Supported: + /// - DX12 + /// + /// This is a web and native feature. + const TEXTURE_COMPRESSION_ASTC_SLICED_3D = WEBGPU_FEATURE_TEXTURE_COMPRESSION_ASTC_SLICED_3D; + /// Enables use of Timestamp Queries. These queries tell the current gpu timestamp when /// all work before the query is finished. /// @@ -1401,7 +1492,18 @@ bitflags_array! { /// - Metal (with MSL 1.2+) /// - Vulkan (with dualSrcBlend) /// - DX12 + /// + /// This is a web and native feature. const DUAL_SOURCE_BLENDING = WEBGPU_FEATURE_DUAL_SOURCE_BLENDING; + + /// Allows the use of `@builtin(clip_distances)` in WGSL. + /// + /// Supported platforms: + /// - Vulkan (mainly on Desktop GPUs) + /// - GL (Desktop or `GL_EXT_clip_cull_distance`) + /// + /// This is a web and native feature. + const CLIP_DISTANCES = WEBGPU_FEATURE_CLIP_DISTANCES; } } @@ -1424,13 +1526,33 @@ impl Features { ])) } + /// Mask of all features which are experimental. + #[must_use] + pub const fn all_experimental_mask() -> Self { + Self::from_bits_truncate(FeatureBits([ + FeaturesWGPU::EXPERIMENTAL_MESH_SHADER.bits() + | FeaturesWGPU::EXPERIMENTAL_MESH_SHADER_MULTIVIEW.bits() + | FeaturesWGPU::EXPERIMENTAL_RAY_QUERY.bits() + | FeaturesWGPU::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN.bits() + | FeaturesWGPU::EXPERIMENTAL_PASSTHROUGH_SHADERS.bits(), + FeaturesWebGPU::empty().bits(), + ])) + } + /// Vertex formats allowed for creating and building BLASes #[must_use] pub fn allowed_vertex_formats_for_blas(&self) -> Vec { let mut formats = Vec::new(); - if self.contains(Self::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE) { + if self.intersects(Self::EXPERIMENTAL_RAY_QUERY) { formats.push(VertexFormat::Float32x3); } + if self.contains(Self::EXTENDED_ACCELERATION_STRUCTURE_VERTEX_FORMATS) { + formats.push(VertexFormat::Float32x2); + formats.push(VertexFormat::Float16x2); + formats.push(VertexFormat::Float16x4); + formats.push(VertexFormat::Snorm16x2); + formats.push(VertexFormat::Snorm16x4); + } formats } } @@ -1479,10 +1601,10 @@ mod tests { use alloc::format; let feature = Features::CLEAR_TEXTURE; - assert_eq!(format!("{}", feature), "CLEAR_TEXTURE"); + assert_eq!(format!("{feature}"), "CLEAR_TEXTURE"); let feature = Features::CLEAR_TEXTURE | Features::BGRA8UNORM_STORAGE; - assert_eq!(format!("{}", feature), "CLEAR_TEXTURE | BGRA8UNORM_STORAGE"); + assert_eq!(format!("{feature}"), "CLEAR_TEXTURE | BGRA8UNORM_STORAGE"); } #[test] @@ -1543,4 +1665,13 @@ mod tests { ) ); } + + #[test] + fn experimental_features_part_of_experimental_mask() { + for (name, feature) in Features::all().iter_names() { + let prefixed_with_experimental = name.starts_with("EXPERIMENTAL_"); + let in_experimental_mask = Features::all_experimental_mask().contains(feature); + assert_eq!(in_experimental_mask, prefixed_with_experimental); + } + } } diff --git a/wgpu-types/src/instance.rs b/wgpu-types/src/instance.rs index 28b29d3a0..b19ce6ff9 100644 --- a/wgpu-types/src/instance.rs +++ b/wgpu-types/src/instance.rs @@ -8,26 +8,37 @@ use crate::Backends; use crate::{Backend, DownlevelFlags}; /// Options for creating an instance. -#[derive(Clone, Debug)] +/// +/// If you want to allow control of instance settings via environment variables, call either +/// [`InstanceDescriptor::from_env_or_default()`] or [`InstanceDescriptor::with_env()`]. Each type +/// within this descriptor has its own equivalent methods, so you can select which options you want +/// to expose to influence from the environment. +#[derive(Clone, Debug, Default)] pub struct InstanceDescriptor { - /// Which `Backends` to enable. + /// Which [`Backends`] to enable. + /// + /// [`Backends::BROWSER_WEBGPU`] has an additional effect: + /// If it is set and a [`navigator.gpu`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/gpu) + /// object is present, this instance will *only* be able to create WebGPU adapters. + /// + /// ⚠️ On some browsers this check is insufficient to determine whether WebGPU is supported, + /// as the browser may define the `navigator.gpu` object, but be unable to create any WebGPU adapters. + /// For targeting _both_ WebGPU & WebGL, it is recommended to use [`crate::util::new_instance_with_webgpu_detection`](../wgpu/util/fn.new_instance_with_webgpu_detection.html). + /// + /// If you instead want to force use of WebGL, either disable the `webgpu` compile-time feature + /// or don't include the [`Backends::BROWSER_WEBGPU`] flag in this field. + /// If it is set and WebGPU support is *not* detected, the instance will use `wgpu-core` + /// to create adapters, meaning that if the `webgl` feature is enabled, it is able to create + /// a WebGL adapter. pub backends: Backends, /// Flags to tune the behavior of the instance. pub flags: InstanceFlags, - /// Options the control the behavior of various backends. + /// Memory budget thresholds used by some backends. + pub memory_budget_thresholds: MemoryBudgetThresholds, + /// Options the control the behavior of specific backends. pub backend_options: BackendOptions, } -impl Default for InstanceDescriptor { - fn default() -> Self { - Self { - backends: Backends::all(), - flags: InstanceFlags::default(), - backend_options: BackendOptions::default(), - } - } -} - impl InstanceDescriptor { /// Choose instance options entirely from environment variables. /// @@ -48,6 +59,7 @@ impl InstanceDescriptor { Self { backends, flags, + memory_budget_thresholds: MemoryBudgetThresholds::default(), backend_options, } } @@ -66,9 +78,29 @@ bitflags::bitflags! { /// /// When `Self::from_env()` is used takes value from `WGPU_DEBUG` environment variable. const DEBUG = 1 << 0; - /// Enable validation, if possible. + /// Enable validation in the backend API, if possible: /// - /// When `Self::from_env()` is used takes value from `WGPU_VALIDATION` environment variable. + /// - On the Direct3D `dx12` backend, this calls [`ID3D12Debug::EnableDebugLayer`][dx12]. + /// + /// - On the Vulkan backend, this enables the [Vulkan Validation Layer][vvl]. + /// + /// - On the `gles` backend driving Windows OpenGL, this enables [debug + /// output][gl:do], effectively calling `glEnable(GL_DEBUG_OUTPUT)`. + /// + /// - On non-Windows `gles` backends, this calls + /// [`eglDebugMessageControlKHR`][gl:dm] to enable all debugging messages. + /// If the GLES implementation is ANGLE running on Vulkan, this also + /// enables the Vulkan validation layers by setting + /// [`EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED`][gl:av]. + /// + /// When `Self::from_env()` is used, this bit is set if the `WGPU_VALIDATION` + /// environment variable has any value but "0". + /// + /// [dx12]: https://learn.microsoft.com/en-us/windows/win32/api/d3d12sdklayers/nf-d3d12sdklayers-id3d12debug-enabledebuglayer + /// [vvl]: https://github.com/KhronosGroup/Vulkan-ValidationLayers + /// [gl:dm]: https://registry.khronos.org/EGL/extensions/KHR/EGL_KHR_debug.txt + /// [gl:do]: https://www.khronos.org/opengl/wiki/Debug_Output + /// [gl:av]: https://chromium.googlesource.com/angle/angle/+/HEAD/extensions/EGL_ANGLE_platform_angle.txt const VALIDATION = 1 << 1; /// Don't pass labels to wgpu-hal. /// @@ -101,8 +133,40 @@ bitflags::bitflags! { /// Validate indirect buffer content prior to issuing indirect draws/dispatches. /// + /// This validation will transform indirect calls into no-ops if they are not valid: + /// + /// - When calling `dispatch_workgroups_indirect`, all 3 indirect arguments encoded in the buffer + /// must be less than the `max_compute_workgroups_per_dimension` device limit. + /// - When calling `draw_indirect`/`draw_indexed_indirect`/`multi_draw_indirect`/`multi_draw_indexed_indirect`: + /// - If `Features::INDIRECT_FIRST_INSTANCE` is not enabled on the device, the `first_instance` indirect argument must be 0. + /// - The `first_instance` & `instance_count` indirect arguments must form a range that fits within all bound vertex buffers with `step_mode` set to `Instance`. + /// - When calling `draw_indirect`/`multi_draw_indirect`: + /// - The `first_vertex` & `vertex_count` indirect arguments must form a range that fits within all bound vertex buffers with `step_mode` set to `Vertex`. + /// - When calling `draw_indexed_indirect`/`multi_draw_indexed_indirect`: + /// - The `first_index` & `index_count` indirect arguments must form a range that fits within the bound index buffer. + /// + /// __Behavior is undefined if this validation is disabled and the rules above are not satisfied.__ + /// + /// Disabling this will also cause the following built-ins to not report the right values on the D3D12 backend: + /// + /// - the 3 components of `@builtin(num_workgroups)` will be 0 + /// - the value of `@builtin(vertex_index)` will not take into account the value of the `first_vertex`/`base_vertex` argument present in the indirect buffer + /// - the value of `@builtin(instance_index)` will not take into account the value of the `first_instance` argument present in the indirect buffer + /// /// When `Self::from_env()` is used takes value from `WGPU_VALIDATION_INDIRECT_CALL` environment variable. const VALIDATION_INDIRECT_CALL = 1 << 5; + + /// Enable automatic timestamp normalization. This means that in [`CommandEncoder::resolve_query_set`][rqs], + /// the timestamps will automatically be normalized to be in nanoseconds instead of the raw timestamp values. + /// + /// This is disabled by default because it introduces a compute shader into the resolution of query sets. + /// + /// This can be useful for users that need to read timestamps on the gpu, as the normalization + /// can be a hassle to do manually. When this is enabled, the timestamp period returned by the queue + /// will always be `1.0`. + /// + /// [rqs]: ../wgpu/struct.CommandEncoder.html#method.resolve_query_set + const AUTOMATIC_TIMESTAMP_NORMALIZATION = 1 << 6; } } @@ -193,6 +257,24 @@ impl InstanceFlags { } } +/// Memory budget thresholds used by backends to try to avoid high memory pressure situations. +/// +/// Currently only the D3D12 and (optionally) Vulkan backends support these options. +#[derive(Default, Clone, Debug, Copy)] +pub struct MemoryBudgetThresholds { + /// Threshold at which texture, buffer, query set and acceleration structure creation will start to return OOM errors. + /// This is a percent of the memory budget reported by native APIs. + /// + /// If not specified, resource creation might still return OOM errors. + pub for_resource_creation: Option, + + /// Threshold at which devices will become lost due to memory pressure. + /// This is a percent of the memory budget reported by native APIs. + /// + /// If not specified, devices might still become lost due to memory pressure. + pub for_device_loss: Option, +} + /// Options that are passed to a given backend. /// /// Part of [`InstanceDescriptor`]. @@ -277,6 +359,10 @@ impl GlBackendOptions { pub struct Dx12BackendOptions { /// Which DX12 shader compiler to use. pub shader_compiler: Dx12Compiler, + /// Presentation system to use. + pub presentation_system: Dx12SwapchainKind, + /// Whether to wait for the latency waitable object before acquiring the next swapchain image. + pub latency_waitable_object: Dx12UseFrameLatencyWaitableObject, } impl Dx12BackendOptions { @@ -286,8 +372,13 @@ impl Dx12BackendOptions { #[must_use] pub fn from_env_or_default() -> Self { let compiler = Dx12Compiler::from_env().unwrap_or_default(); + let presentation_system = Dx12SwapchainKind::from_env().unwrap_or_default(); + let latency_waitable_object = + Dx12UseFrameLatencyWaitableObject::from_env().unwrap_or_default(); Self { shader_compiler: compiler, + presentation_system, + latency_waitable_object, } } @@ -297,7 +388,13 @@ impl Dx12BackendOptions { #[must_use] pub fn with_env(self) -> Self { let shader_compiler = self.shader_compiler.with_env(); - Self { shader_compiler } + let presentation_system = self.presentation_system.with_env(); + let latency_waitable_object = self.latency_waitable_object.with_env(); + Self { + shader_compiler, + presentation_system, + latency_waitable_object, + } } } @@ -347,6 +444,58 @@ impl NoopBackendOptions { } } +#[derive(Clone, Debug, Default, Copy, PartialEq, Eq)] +/// Selects which kind of swapchain to use on DX12. +pub enum Dx12SwapchainKind { + /// Use a DXGI swapchain made directly from the window's HWND. + /// + /// This does not support transparency but has better support from developer tooling from RenderDoc. + #[default] + DxgiFromHwnd, + /// Use a DXGI swapchain made from a DirectComposition visual made automatically from the window's HWND. + /// + /// This creates a single [`IDCompositionVisual`] over the entire window that is used by the `Surface`. + /// If a user wants to manage the composition tree themselves, they should create their own device and + /// composition, and pass the relevant visual down via [`SurfaceTargetUnsafe::CompositionVisual`][CV]. + /// + /// This supports transparent windows, but does not have support from RenderDoc. + /// + /// [`IDCompositionVisual`]: https://learn.microsoft.com/en-us/windows/win32/api/dcomp/nn-dcomp-idcompositionvisual + /// [CV]: ../wgpu/struct.SurfaceTargetUnsafe.html#variant.CompositionVisual + DxgiFromVisual, +} + +impl Dx12SwapchainKind { + /// Choose which presentation system to use from the environment variable `WGPU_DX12_PRESENTATION_SYSTEM`. + /// + /// Valid values, case insensitive: + /// - `DxgiFromVisual` or `Visual` + /// - `DxgiFromHwnd` or `Hwnd` for [`Self::DxgiFromHwnd`] + #[must_use] + pub fn from_env() -> Option { + let value = crate::env::var("WGPU_DX12_PRESENTATION_SYSTEM") + .as_deref()? + .to_lowercase(); + match value.as_str() { + "dxgifromvisual" | "visual" => Some(Self::DxgiFromVisual), + "dxgifromhwnd" | "hwnd" => Some(Self::DxgiFromHwnd), + _ => None, + } + } + + /// Takes the given presentation system, modifies it based on the `WGPU_DX12_PRESENTATION_SYSTEM` environment variable, and returns the result. + /// + /// See [`from_env`](Self::from_env) for more information. + #[must_use] + pub fn with_env(self) -> Self { + if let Some(presentation_system) = Self::from_env() { + presentation_system + } else { + self + } + } +} + /// DXC shader model. #[derive(Clone, Debug)] #[allow(missing_docs)] @@ -362,9 +511,6 @@ pub enum DxcShaderModel { } /// Selects which DX12 shader compiler to use. -/// -/// If the `DynamicDxc` option is selected, but `dxcompiler.dll` and `dxil.dll` files aren't found, -/// then this will fall back to the Fxc compiler at runtime and log an error. #[derive(Clone, Debug, Default)] pub enum Dx12Compiler { /// The Fxc compiler (default) is old, slow and unmaintained. @@ -374,17 +520,15 @@ pub enum Dx12Compiler { Fxc, /// The Dxc compiler is new, fast and maintained. /// - /// However, it requires both `dxcompiler.dll` and `dxil.dll` to be shipped with the application. + /// However, it requires `dxcompiler.dll` to be shipped with the application. /// These files can be downloaded from . /// - /// Minimum supported version: [v1.5.2010](https://github.com/microsoft/DirectXShaderCompiler/releases/tag/v1.5.2010) + /// Minimum supported version: [v1.8.2502](https://github.com/microsoft/DirectXShaderCompiler/releases/tag/v1.8.2502) /// /// It also requires WDDM 2.1 (Windows 10 version 1607). DynamicDxc { /// Path to `dxcompiler.dll`. dxc_path: String, - /// Path to `dxil.dll`. - dxil_path: String, /// Maximum shader model the given dll supports. max_shader_model: DxcShaderModel, }, @@ -398,12 +542,11 @@ pub enum Dx12Compiler { impl Dx12Compiler { /// Helper function to construct a `DynamicDxc` variant with default paths. /// - /// The dll must support at least shader model 6.5. + /// The dll must support at least shader model 6.8. pub fn default_dynamic_dxc() -> Self { Self::DynamicDxc { dxc_path: String::from("dxcompiler.dll"), - dxil_path: String::from("dxil.dll"), - max_shader_model: DxcShaderModel::V6_5, + max_shader_model: DxcShaderModel::V6_7, // should be 6.8 but the variant is missing } } @@ -439,6 +582,54 @@ impl Dx12Compiler { } } +/// Whether and how to use a waitable handle obtained from `GetFrameLatencyWaitableObject`. +#[derive(Clone, Debug, Default)] +pub enum Dx12UseFrameLatencyWaitableObject { + /// Do not obtain a waitable handle and do not wait for it. The swapchain will + /// be created without the `DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT` flag. + None, + /// Obtain a waitable handle and wait for it before acquiring the next swapchain image. + #[default] + Wait, + /// Create the swapchain with the `DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT` flag and + /// obtain a waitable handle, but do not wait for it before acquiring the next swapchain image. + /// This is useful if the application wants to wait for the waitable object itself. + DontWait, +} + +impl Dx12UseFrameLatencyWaitableObject { + /// Choose whether to use a frame latency waitable object from the environment variable `WGPU_DX12_USE_FRAME_LATENCY_WAITABLE_OBJECT`. + /// + /// Valid values, case insensitive: + /// - `None` + /// - `Wait` + /// - `DontWait` + #[must_use] + pub fn from_env() -> Option { + let value = crate::env::var("WGPU_DX12_USE_FRAME_LATENCY_WAITABLE_OBJECT") + .as_deref()? + .to_lowercase(); + match value.as_str() { + "none" => Some(Self::None), + "wait" => Some(Self::Wait), + "dontwait" => Some(Self::DontWait), + _ => None, + } + } + + /// Takes the given setting, modifies it based on the `WGPU_DX12_USE_FRAME_LATENCY_WAITABLE_OBJECT` environment variable, and returns the result. + /// + /// See `from_env` for more information. + #[must_use] + pub fn with_env(self) -> Self { + if let Some(compiler) = Self::from_env() { + compiler + } else { + self + } + } +} + /// Selects which OpenGL ES 3 minor version to request. /// /// When using ANGLE as an OpenGL ES/EGL implementation, explicitly requesting `Version1` can provide a non-conformant ES 3.1 on APIs like D3D11. diff --git a/wgpu-types/src/lib.rs b/wgpu-types/src/lib.rs index b53d31871..4c02d67bf 100644 --- a/wgpu-types/src/lib.rs +++ b/wgpu-types/src/lib.rs @@ -1,7 +1,7 @@ //! This library describes the API surface of WebGPU that is agnostic of the backend. //! This API is used for targeting both Web and Native. -#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] +#![cfg_attr(docsrs, feature(doc_cfg))] #![allow( // We don't use syntax sugar where it's not necessary. clippy::match_like_matches_macro, @@ -14,13 +14,16 @@ extern crate std; extern crate alloc; +use alloc::borrow::Cow; use alloc::{string::String, vec, vec::Vec}; use core::{ + cmp::Ordering, fmt, hash::{Hash, Hasher}, mem, num::NonZeroU32, ops::Range, + time::Duration, }; use bytemuck::{Pod, Zeroable}; @@ -35,13 +38,18 @@ pub mod assertions; mod cast_utils; mod counters; mod env; +pub mod error; mod features; pub mod instance; pub mod math; +mod tokens; +mod transfers; pub use counters::*; pub use features::*; pub use instance::*; +pub use tokens::*; +pub use transfers::*; /// Integral type used for [`Buffer`] offsets and sizes. /// @@ -68,12 +76,14 @@ pub type ShaderLocation = u32; /// [dynamic bind group offsets](../wgpu/struct.RenderPass.html#method.set_bind_group). pub type DynamicOffset = u32; -/// Buffer-to-texture copies must have [`bytes_per_row`] aligned to this number. +/// Buffer-texture copies must have [`bytes_per_row`] aligned to this number. /// -/// This doesn't apply to [`Queue::write_texture`][Qwt], only to [`copy_buffer_to_texture()`]. +/// This doesn't apply to [`Queue::write_texture`][Qwt], only to [`copy_buffer_to_texture()`] +/// and [`copy_texture_to_buffer()`]. /// /// [`bytes_per_row`]: TexelCopyBufferLayout::bytes_per_row /// [`copy_buffer_to_texture()`]: ../wgpu/struct.Queue.html#method.copy_buffer_to_texture +/// [`copy_texture_to_buffer()`]: ../wgpu/struct.Queue.html#method.copy_texture_to_buffer /// [Qwt]: ../wgpu/struct.Queue.html#method.write_texture pub const COPY_BYTES_PER_ROW_ALIGNMENT: u32 = 256; @@ -93,10 +103,18 @@ pub const COPY_BUFFER_ALIGNMENT: BufferAddress = 4; /// [`get_mapped_range()`]: ../wgpu/struct.Buffer.html#method.get_mapped_range pub const MAP_ALIGNMENT: BufferAddress = 8; +/// [Vertex buffer offsets] and [strides] have to be a multiple of this number. +/// +/// [Vertex buffer offsets]: ../wgpu/util/trait.RenderEncoder.html#tymethod.set_vertex_buffer +/// [strides]: ../wgpu/struct.VertexBufferLayout.html#structfield.array_stride +pub const VERTEX_ALIGNMENT: BufferAddress = 4; + /// [Vertex buffer strides] have to be a multiple of this number. /// /// [Vertex buffer strides]: ../wgpu/struct.VertexBufferLayout.html#structfield.array_stride +#[deprecated(note = "Use `VERTEX_ALIGNMENT` instead", since = "27.0.0")] pub const VERTEX_STRIDE_ALIGNMENT: BufferAddress = 4; + /// Ranges of [writes to push constant storage] must be at least this aligned. /// /// [writes to push constant storage]: ../wgpu/struct.RenderPass.html#method.set_push_constants @@ -320,7 +338,7 @@ impl Backends { "webgpu" => Self::BROWSER_WEBGPU, "noop" => Self::NOOP, b => { - log::warn!("unknown backend string '{}'", b); + log::warn!("unknown backend string '{b}'"); continue; } } @@ -445,6 +463,73 @@ impl fmt::Display for RequestAdapterError { } } +/// Invoke a macro for each of the limits. +/// +/// The supplied macro should take two arguments. The first is a limit name, as +/// an identifier, typically used to access a member of `struct Limits`. The +/// second is `Ordering::Less` if valid values are less than the limit (the +/// common case), or `Ordering::Greater` if valid values are more than the limit +/// (for limits like alignments, which are minima instead of maxima). +macro_rules! with_limits { + ($macro_name:ident) => { + $macro_name!(max_texture_dimension_1d, Ordering::Less); + $macro_name!(max_texture_dimension_1d, Ordering::Less); + $macro_name!(max_texture_dimension_2d, Ordering::Less); + $macro_name!(max_texture_dimension_3d, Ordering::Less); + $macro_name!(max_texture_array_layers, Ordering::Less); + $macro_name!(max_bind_groups, Ordering::Less); + $macro_name!(max_bindings_per_bind_group, Ordering::Less); + $macro_name!( + max_dynamic_uniform_buffers_per_pipeline_layout, + Ordering::Less + ); + $macro_name!( + max_dynamic_storage_buffers_per_pipeline_layout, + Ordering::Less + ); + $macro_name!(max_sampled_textures_per_shader_stage, Ordering::Less); + $macro_name!(max_samplers_per_shader_stage, Ordering::Less); + $macro_name!(max_storage_buffers_per_shader_stage, Ordering::Less); + $macro_name!(max_storage_textures_per_shader_stage, Ordering::Less); + $macro_name!(max_uniform_buffers_per_shader_stage, Ordering::Less); + $macro_name!(max_binding_array_elements_per_shader_stage, Ordering::Less); + $macro_name!(max_uniform_buffer_binding_size, Ordering::Less); + $macro_name!(max_storage_buffer_binding_size, Ordering::Less); + $macro_name!(max_vertex_buffers, Ordering::Less); + $macro_name!(max_buffer_size, Ordering::Less); + $macro_name!(max_vertex_attributes, Ordering::Less); + $macro_name!(max_vertex_buffer_array_stride, Ordering::Less); + $macro_name!(min_uniform_buffer_offset_alignment, Ordering::Greater); + $macro_name!(min_storage_buffer_offset_alignment, Ordering::Greater); + $macro_name!(max_inter_stage_shader_components, Ordering::Less); + $macro_name!(max_color_attachments, Ordering::Less); + $macro_name!(max_color_attachment_bytes_per_sample, Ordering::Less); + $macro_name!(max_compute_workgroup_storage_size, Ordering::Less); + $macro_name!(max_compute_invocations_per_workgroup, Ordering::Less); + $macro_name!(max_compute_workgroup_size_x, Ordering::Less); + $macro_name!(max_compute_workgroup_size_y, Ordering::Less); + $macro_name!(max_compute_workgroup_size_z, Ordering::Less); + $macro_name!(max_compute_workgroups_per_dimension, Ordering::Less); + + $macro_name!(min_subgroup_size, Ordering::Greater); + $macro_name!(max_subgroup_size, Ordering::Less); + + $macro_name!(max_push_constant_size, Ordering::Less); + $macro_name!(max_non_sampler_bindings, Ordering::Less); + + $macro_name!(max_task_workgroup_total_count, Ordering::Less); + $macro_name!(max_task_workgroups_per_dimension, Ordering::Less); + $macro_name!(max_mesh_multiview_view_count, Ordering::Less); + $macro_name!(max_mesh_output_layers, Ordering::Less); + + $macro_name!(max_blas_primitive_count, Ordering::Less); + $macro_name!(max_blas_geometry_count, Ordering::Less); + $macro_name!(max_tlas_instance_count, Ordering::Less); + + $macro_name!(max_multiview_view_count, Ordering::Less); + }; +} + /// Represents the sets of limits an adapter/device supports. /// /// We provide three different defaults. @@ -584,9 +669,9 @@ pub struct Limits { /// Defaults to 65535. Higher is "better". pub max_compute_workgroups_per_dimension: u32, - /// Minimal number of invocations in a subgroup. Higher is "better". + /// Minimal number of invocations in a subgroup. Lower is "better". pub min_subgroup_size: u32, - /// Maximal number of invocations in a subgroup. Lower is "better". + /// Maximal number of invocations in a subgroup. Higher is "better". pub max_subgroup_size: u32, /// Amount of storage available for push constants in bytes. Defaults to 0. Higher is "better". /// Requesting more than 0 during device creation requires [`Features::PUSH_CONSTANTS`] to be enabled. @@ -603,6 +688,36 @@ pub struct Limits { /// This limit only affects the d3d12 backend. Using a large number will allow the device /// to create many bind groups at the cost of a large up-front allocation at device creation. pub max_non_sampler_bindings: u32, + + /// The maximum total value of x*y*z for a given `draw_mesh_tasks` command + pub max_task_workgroup_total_count: u32, + /// The maximum value for each dimension of a `RenderPass::draw_mesh_tasks(x, y, z)` operation. + /// Defaults to 65535. Higher is "better". + pub max_task_workgroups_per_dimension: u32, + /// The maximum number of layers that can be output from a mesh shader + pub max_mesh_output_layers: u32, + /// The maximum number of views that can be used by a mesh shader in multiview rendering + pub max_mesh_multiview_view_count: u32, + + /// The maximum number of primitive (ex: triangles, aabbs) a BLAS is allowed to have. Requesting + /// more than 0 during device creation only makes sense if [`Features::EXPERIMENTAL_RAY_QUERY`] + /// is enabled. + pub max_blas_primitive_count: u32, + /// The maximum number of geometry descriptors a BLAS is allowed to have. Requesting + /// more than 0 during device creation only makes sense if [`Features::EXPERIMENTAL_RAY_QUERY`] + /// is enabled. + pub max_blas_geometry_count: u32, + /// The maximum number of instances a TLAS is allowed to have. Requesting more than 0 during + /// device creation only makes sense if [`Features::EXPERIMENTAL_RAY_QUERY`] + /// is enabled. + pub max_tlas_instance_count: u32, + /// The maximum number of acceleration structures allowed to be used in a shader stage. + /// Requesting more than 0 during device creation only makes sense if [`Features::EXPERIMENTAL_RAY_QUERY`] + /// is enabled. + pub max_acceleration_structures_per_shader_stage: u32, + + /// The maximum number of views that can be used in multiview rendering + pub max_multiview_view_count: u32, } impl Default for Limits { @@ -612,9 +727,65 @@ impl Default for Limits { } impl Limits { - // Rust doesn't allow const in trait implementations, so we break this out - // to allow reusing these defaults in const contexts like `downlevel_defaults` - const fn defaults() -> Self { + /// These default limits are guaranteed to to work on all modern + /// backends and guaranteed to be supported by WebGPU + /// + /// Those limits are as follows: + /// ```rust + /// # use wgpu_types::Limits; + /// assert_eq!(Limits::defaults(), Limits { + /// max_texture_dimension_1d: 8192, + /// max_texture_dimension_2d: 8192, + /// max_texture_dimension_3d: 2048, + /// max_texture_array_layers: 256, + /// max_bind_groups: 4, + /// max_bindings_per_bind_group: 1000, + /// max_dynamic_uniform_buffers_per_pipeline_layout: 8, + /// max_dynamic_storage_buffers_per_pipeline_layout: 4, + /// max_sampled_textures_per_shader_stage: 16, + /// max_samplers_per_shader_stage: 16, + /// max_storage_buffers_per_shader_stage: 8, + /// max_storage_textures_per_shader_stage: 4, + /// max_uniform_buffers_per_shader_stage: 12, + /// max_binding_array_elements_per_shader_stage: 0, + /// max_binding_array_sampler_elements_per_shader_stage: 0, + /// max_uniform_buffer_binding_size: 64 << 10, // (64 KiB) + /// max_storage_buffer_binding_size: 128 << 20, // (128 MiB) + /// max_vertex_buffers: 8, + /// max_buffer_size: 256 << 20, // (256 MiB) + /// max_vertex_attributes: 16, + /// max_vertex_buffer_array_stride: 2048, + /// min_uniform_buffer_offset_alignment: 256, + /// min_storage_buffer_offset_alignment: 256, + /// max_inter_stage_shader_components: 60, + /// max_color_attachments: 8, + /// max_color_attachment_bytes_per_sample: 32, + /// max_compute_workgroup_storage_size: 16384, + /// max_compute_invocations_per_workgroup: 256, + /// max_compute_workgroup_size_x: 256, + /// max_compute_workgroup_size_y: 256, + /// max_compute_workgroup_size_z: 64, + /// max_compute_workgroups_per_dimension: 65535, + /// min_subgroup_size: 0, + /// max_subgroup_size: 0, + /// max_push_constant_size: 0, + /// max_non_sampler_bindings: 1_000_000, + /// max_task_workgroup_total_count: 0, + /// max_task_workgroups_per_dimension: 0, + /// max_mesh_multiview_view_count: 0, + /// max_mesh_output_layers: 0, + /// max_blas_primitive_count: 0, + /// max_blas_geometry_count: 0, + /// max_tlas_instance_count: 0, + /// max_acceleration_structures_per_shader_stage: 0, + /// max_multiview_view_count: 0, + /// }); + /// ``` + /// + /// Rust doesn't allow const in trait implementations, so we break this out + /// to allow reusing these defaults in const contexts + #[must_use] + pub const fn defaults() -> Self { Self { max_texture_dimension_1d: 8192, max_texture_dimension_2d: 8192, @@ -652,6 +823,18 @@ impl Limits { max_subgroup_size: 0, max_push_constant_size: 0, max_non_sampler_bindings: 1_000_000, + + max_task_workgroup_total_count: 0, + max_task_workgroups_per_dimension: 0, + max_mesh_multiview_view_count: 0, + max_mesh_output_layers: 0, + + max_blas_primitive_count: 0, + max_blas_geometry_count: 0, + max_tlas_instance_count: 0, + max_acceleration_structures_per_shader_stage: 0, + + max_multiview_view_count: 0, } } @@ -697,6 +880,18 @@ impl Limits { /// max_compute_workgroups_per_dimension: 65535, /// max_buffer_size: 256 << 20, // (256 MiB) /// max_non_sampler_bindings: 1_000_000, + /// + /// max_task_workgroup_total_count: 0, + /// max_task_workgroups_per_dimension: 0, + /// max_mesh_multiview_view_count: 0, + /// max_mesh_output_layers: 0, + /// + /// max_blas_primitive_count: 0, + /// max_blas_geometry_count: 0, + /// max_tlas_instance_count: 0, + /// max_acceleration_structures_per_shader_stage: 0, + /// + /// max_multiview_view_count: 0, /// }); /// ``` #[must_use] @@ -710,6 +905,11 @@ impl Limits { max_color_attachments: 4, // see: https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=7 max_compute_workgroup_storage_size: 16352, + + max_task_workgroups_per_dimension: 0, + max_task_workgroup_total_count: 0, + max_mesh_multiview_view_count: 0, + max_mesh_output_layers: 0, ..Self::defaults() } } @@ -757,6 +957,18 @@ impl Limits { /// max_compute_workgroups_per_dimension: 0, // + /// max_buffer_size: 256 << 20, // (256 MiB), /// max_non_sampler_bindings: 1_000_000, + /// + /// max_task_workgroup_total_count: 0, + /// max_task_workgroups_per_dimension: 0, + /// max_mesh_multiview_view_count: 0, + /// max_mesh_output_layers: 0, + /// + /// max_blas_primitive_count: 0, + /// max_blas_geometry_count: 0, + /// max_tlas_instance_count: 0, + /// max_acceleration_structures_per_shader_stage: 0, + /// + /// max_multiview_view_count: 0, /// }); /// ``` #[must_use] @@ -812,6 +1024,52 @@ impl Limits { } } + /// The minimum guaranteed limits for acceleration structures if you enable [`Features::EXPERIMENTAL_RAY_QUERY`] + #[must_use] + pub const fn using_minimum_supported_acceleration_structure_values(self) -> Self { + Self { + max_blas_geometry_count: (1 << 24) - 1, // 2^24 - 1: Vulkan's minimum + max_tlas_instance_count: (1 << 24) - 1, // 2^24 - 1: Vulkan's minimum + max_blas_primitive_count: (1 << 24) - 1, // Should be 2^28: Metal's minimum, but due to an llvmpipe bug it is 2^24 - 1 + max_acceleration_structures_per_shader_stage: 16, // Vulkan's minimum + ..self + } + } + + /// Modify the current limits to use the acceleration structure limits of `other` (`other` could + /// be the limits of the adapter). + #[must_use] + pub const fn using_acceleration_structure_values(self, other: Self) -> Self { + Self { + max_blas_geometry_count: other.max_blas_geometry_count, + max_tlas_instance_count: other.max_tlas_instance_count, + max_blas_primitive_count: other.max_blas_primitive_count, + max_acceleration_structures_per_shader_stage: other + .max_acceleration_structures_per_shader_stage, + ..self + } + } + + /// The recommended minimum limits for mesh shaders if you enable [`Features::EXPERIMENTAL_MESH_SHADER`] + /// + /// These are chosen somewhat arbitrarily. They are small enough that they should cover all physical devices, + /// but not necessarily all use cases. + #[must_use] + pub const fn using_recommended_minimum_mesh_shader_values(self) -> Self { + Self { + // Literally just made this up as 256^2 or 2^16. + // My GPU supports 2^22, and compute shaders don't have this kind of limit. + // This very likely is never a real limiter + max_task_workgroup_total_count: 65536, + max_task_workgroups_per_dimension: 256, + // llvmpipe reports 0 multiview count, which just means no multiview is allowed + max_mesh_multiview_view_count: 0, + // llvmpipe once again requires this to be 8. An RTX 3060 supports well over 1024. + max_mesh_output_layers: 8, + ..self + } + } + /// Compares every limits within self is within the limits given in `allowed`. /// /// If you need detailed information on failures, look at [`Limits::check_limits_with_fail_fn`]. @@ -838,59 +1096,61 @@ impl Limits { fatal: bool, mut fail_fn: impl FnMut(&'static str, u64, u64), ) { - use core::cmp::Ordering; - - macro_rules! compare { - ($name:ident, $ordering:ident) => { - match self.$name.cmp(&allowed.$name) { - Ordering::$ordering | Ordering::Equal => (), - _ => { - fail_fn(stringify!($name), self.$name as u64, allowed.$name as u64); - if fatal { - return; - } + macro_rules! check_with_fail_fn { + ($name:ident, $ordering:expr) => { + let invalid_ord = $ordering.reverse(); + // In the case of `min_subgroup_size`, requesting a value of + // zero means "I'm not going to use subgroups", so we have to + // special case that. If any of our minimum limits could + // meaningfully go all the way to zero, that would conflict with + // this. + if self.$name != 0 && self.$name.cmp(&allowed.$name) == invalid_ord { + fail_fn(stringify!($name), self.$name as u64, allowed.$name as u64); + if fatal { + return; } } }; } - compare!(max_texture_dimension_1d, Less); - compare!(max_texture_dimension_2d, Less); - compare!(max_texture_dimension_3d, Less); - compare!(max_texture_array_layers, Less); - compare!(max_bind_groups, Less); - compare!(max_bindings_per_bind_group, Less); - compare!(max_dynamic_uniform_buffers_per_pipeline_layout, Less); - compare!(max_dynamic_storage_buffers_per_pipeline_layout, Less); - compare!(max_sampled_textures_per_shader_stage, Less); - compare!(max_samplers_per_shader_stage, Less); - compare!(max_storage_buffers_per_shader_stage, Less); - compare!(max_storage_textures_per_shader_stage, Less); - compare!(max_uniform_buffers_per_shader_stage, Less); - compare!(max_binding_array_elements_per_shader_stage, Less); - compare!(max_uniform_buffer_binding_size, Less); - compare!(max_storage_buffer_binding_size, Less); - compare!(max_vertex_buffers, Less); - compare!(max_buffer_size, Less); - compare!(max_vertex_attributes, Less); - compare!(max_vertex_buffer_array_stride, Less); - compare!(min_uniform_buffer_offset_alignment, Greater); - compare!(min_storage_buffer_offset_alignment, Greater); - compare!(max_inter_stage_shader_components, Less); - compare!(max_color_attachments, Less); - compare!(max_color_attachment_bytes_per_sample, Less); - compare!(max_compute_workgroup_storage_size, Less); - compare!(max_compute_invocations_per_workgroup, Less); - compare!(max_compute_workgroup_size_x, Less); - compare!(max_compute_workgroup_size_y, Less); - compare!(max_compute_workgroup_size_z, Less); - compare!(max_compute_workgroups_per_dimension, Less); - if self.min_subgroup_size > 0 && self.max_subgroup_size > 0 { - compare!(min_subgroup_size, Greater); - compare!(max_subgroup_size, Less); + if self.min_subgroup_size > self.max_subgroup_size { + fail_fn( + "max_subgroup_size", + self.min_subgroup_size as u64, + allowed.min_subgroup_size as u64, + ); } - compare!(max_push_constant_size, Less); - compare!(max_non_sampler_bindings, Less); + with_limits!(check_with_fail_fn); + } + + /// For each limit in `other` that is better than the value in `self`, + /// replace the value in `self` with the value from `other`. + /// + /// A request for a limit value less than the WebGPU-specified default must + /// be ignored. This function is used to clamp such requests to the default + /// value. + /// + /// This function is not for clamping requests for values beyond the + /// supported limits. For that purpose the desired function would be + /// `or_worse_values_from` (which doesn't exist, but could be added if + /// needed). + #[must_use] + pub fn or_better_values_from(mut self, other: &Self) -> Self { + macro_rules! or_better_value_from { + ($name:ident, $ordering:expr) => { + match $ordering { + // Limits that are maximum values (most of them) + Ordering::Less => self.$name = self.$name.max(other.$name), + // Limits that are minimum values + Ordering::Greater => self.$name = self.$name.min(other.$name), + Ordering::Equal => unreachable!(), + } + }; + } + + with_limits!(or_better_value_from); + + self } } @@ -945,7 +1205,7 @@ impl DownlevelCapabilities { bitflags::bitflags! { /// Binary flags listing features that may or may not be present on downlevel adapters. /// - /// A downlevel adapter is a GPU adapter that WGPU supports, but with potentially limited + /// A downlevel adapter is a GPU adapter that wgpu supports, but with potentially limited /// features, due to the lack of hardware feature support. /// /// Flags that are **not** present for a downlevel adapter or device usually indicates @@ -1079,33 +1339,11 @@ bitflags::bitflags! { /// - GL ES / WebGL const NONBLOCKING_QUERY_RESOLVE = 1 << 22; - /// If this is true, use of `@builtin(vertex_index)` and `@builtin(instance_index)` will properly take into consideration - /// the `first_vertex` and `first_instance` parameters of indirect draw calls. + /// Allows shaders to use `quantizeToF16`, `pack2x16float`, and `unpack2x16float`, which + /// operate on `f16`-precision values stored in `f32`s. /// - /// If this is false, `@builtin(vertex_index)` and `@builtin(instance_index)` will start by counting from 0, ignoring the - /// `first_vertex` and `first_instance` parameters. - /// - /// For example, if you had a draw call like this: - /// - `first_vertex: 4,` - /// - `vertex_count: 12,` - /// - /// When this flag is present, `@builtin(vertex_index)` will start at 4 and go up to 15 (12 invocations). - /// - /// When this flag is not present, `@builtin(vertex_index)` will start at 0 and go up to 11 (12 invocations). - /// - /// This only affects the builtins in the shaders, - /// vertex buffers and instance rate vertex buffers will behave like expected with this flag disabled. - /// - /// See also [`Features::`] - /// - /// Supported By: - /// - Vulkan - /// - Metal - /// - OpenGL - /// - /// Will be implemented in the future by: - /// - DX12 ([#2471](https://github.com/gfx-rs/wgpu/issues/2471)) - const VERTEX_AND_INSTANCE_INDEX_RESPECTS_RESPECTIVE_FIRST_VALUE_IN_INDIRECT_DRAW = 1 << 23; + /// Not supported by Vulkan on Mesa when [`Features::SHADER_F16`] is absent. + const SHADER_F16_IN_F32 = 1 << 23; } } @@ -1183,12 +1421,21 @@ pub struct AdapterInfo { pub device: u32, /// Type of device pub device_type: DeviceType, + /// [`Backend`]-specific PCI bus ID of the adapter. + /// + /// * For [`Backend::Vulkan`], [`VkPhysicalDevicePCIBusInfoPropertiesEXT`] is used, + /// if available, in the form `bus:device.function`, e.g. `0000:01:00.0`. + /// + /// [`VkPhysicalDevicePCIBusInfoPropertiesEXT`]: https://registry.khronos.org/vulkan/specs/latest/man/html/VkPhysicalDevicePCIBusInfoPropertiesEXT.html + pub device_pci_bus_id: String, /// Driver name pub driver: String, /// Driver info pub driver_info: String, /// Backend used for device pub backend: Backend, + /// If true, adding [`TextureUsages::TRANSIENT`] to a texture will decrease memory usage. + pub transient_saves_memory: bool, } /// Hints to the device about the memory allocation strategy. @@ -1245,6 +1492,9 @@ pub struct DeviceDescriptor { /// Exactly the specified limits, and no better or worse, /// will be allowed in validation of API calls on the resulting device. pub required_limits: Limits, + /// Specifies whether `self.required_features` is allowed to contain experimental features. + #[cfg_attr(feature = "serde", serde(skip))] + pub experimental_features: ExperimentalFeatures, /// Hints for memory allocation strategies. pub memory_hints: MemoryHints, /// Whether API tracing for debugging is enabled, @@ -1260,6 +1510,7 @@ impl DeviceDescriptor { label: fun(&self.label), required_features: self.required_features, required_limits: self.required_limits.clone(), + experimental_features: self.experimental_features, memory_hints: self.memory_hints.clone(), trace: self.trace.clone(), } @@ -1310,9 +1561,9 @@ bitflags::bitflags! { const COMPUTE = 1 << 2; /// Binding is visible from the vertex and fragment shaders of a render pipeline. const VERTEX_FRAGMENT = Self::VERTEX.bits() | Self::FRAGMENT.bits(); - /// Binding is visible from the task shader of a mesh pipeline + /// Binding is visible from the task shader of a mesh pipeline. const TASK = 1 << 3; - /// Binding is visible from the mesh shader of a mesh pipeline + /// Binding is visible from the mesh shader of a mesh pipeline. const MESH = 1 << 4; } } @@ -2072,6 +2323,23 @@ pub enum TextureFormat { /// [`Features::TEXTURE_FORMAT_NV12`] must be enabled to use this texture format. NV12, + /// YUV 4:2:0 chroma subsampled format. + /// + /// Contains two planes: + /// - 0: Single 16 bit channel luminance, of which only the high 10 bits + /// are used. + /// - 1: Dual 16 bit channel chrominance at half width and half height, of + /// which only the high 10 bits are used. + /// + /// Valid view formats for luminance are [`TextureFormat::R16Unorm`]. + /// + /// Valid view formats for chrominance are [`TextureFormat::Rg16Unorm`]. + /// + /// Width and height must be even. + /// + /// [`Features::TEXTURE_FORMAT_P010`] must be enabled to use this texture format. + P010, + // Compressed textures usable with `TEXTURE_COMPRESSION_BC` feature. `TEXTURE_COMPRESSION_SLICED_3D` is required to use with 3D textures. /// 4x4 block compressed texture. 8 bytes per block (4 bit/px). 4 color + alpha pallet. 5 bit R + 6 bit G + 5 bit B + 1 bit alpha. /// [0, 63] ([0, 1] for alpha) converted to/from float [0, 1] in shader. @@ -2317,6 +2585,7 @@ impl<'de> Deserialize<'de> for TextureFormat { "depth24plus" => TextureFormat::Depth24Plus, "depth24plus-stencil8" => TextureFormat::Depth24PlusStencil8, "nv12" => TextureFormat::NV12, + "p010" => TextureFormat::P010, "rgb9e5ufloat" => TextureFormat::Rgb9e5Ufloat, "bc1-rgba-unorm" => TextureFormat::Bc1RgbaUnorm, "bc1-rgba-unorm-srgb" => TextureFormat::Bc1RgbaUnormSrgb, @@ -2446,6 +2715,7 @@ impl Serialize for TextureFormat { TextureFormat::Depth24Plus => "depth24plus", TextureFormat::Depth24PlusStencil8 => "depth24plus-stencil8", TextureFormat::NV12 => "nv12", + TextureFormat::P010 => "p010", TextureFormat::Rgb9e5Ufloat => "rgb9e5ufloat", TextureFormat::Bc1RgbaUnorm => "bc1-rgba-unorm", TextureFormat::Bc1RgbaUnormSrgb => "bc1-rgba-unorm-srgb", @@ -2514,8 +2784,21 @@ impl TextureAspect { _ => return None, }) } + + /// Returns the plane for a given texture aspect. + #[must_use] + pub fn to_plane(&self) -> Option { + match self { + TextureAspect::Plane0 => Some(0), + TextureAspect::Plane1 => Some(1), + TextureAspect::Plane2 => Some(2), + _ => None, + } + } } +// There are some additional texture format helpers in `wgpu-core/src/conv.rs`, +// that may need to be modified along with the ones here. impl TextureFormat { /// Returns the aspect-specific format of the original format /// @@ -2536,6 +2819,8 @@ impl TextureFormat { (Self::Depth32FloatStencil8, TextureAspect::DepthOnly) => Some(Self::Depth32Float), (Self::NV12, TextureAspect::Plane0) => Some(Self::R8Unorm), (Self::NV12, TextureAspect::Plane1) => Some(Self::Rg8Unorm), + (Self::P010, TextureAspect::Plane0) => Some(Self::R16Unorm), + (Self::P010, TextureAspect::Plane1) => Some(Self::Rg16Unorm), // views to multi-planar formats must specify the plane (format, TextureAspect::All) if !format.is_multi_planar_format() => Some(format), _ => None, @@ -2591,6 +2876,7 @@ impl TextureFormat { pub fn planes(&self) -> Option { match *self { Self::NV12 => Some(2), + Self::P010 => Some(2), _ => None, } } @@ -2628,6 +2914,7 @@ impl TextureFormat { pub fn size_multiple_requirement(&self) -> (u32, u32) { match *self { Self::NV12 => (2, 2), + Self::P010 => (2, 2), _ => self.block_dimensions(), } } @@ -2688,7 +2975,8 @@ impl TextureFormat { | Self::Depth24PlusStencil8 | Self::Depth32Float | Self::Depth32FloatStencil8 - | Self::NV12 => (1, 1), + | Self::NV12 + | Self::P010 => (1, 1), Self::Bc1RgbaUnorm | Self::Bc1RgbaUnormSrgb @@ -2747,6 +3035,13 @@ impl TextureFormat { self.required_features() == Features::TEXTURE_COMPRESSION_BC } + /// Returns `true` for ASTC compressed formats. + #[must_use] + pub fn is_astc(&self) -> bool { + self.required_features() == Features::TEXTURE_COMPRESSION_ASTC + || self.required_features() == Features::TEXTURE_COMPRESSION_ASTC_HDR + } + /// Returns the required features (if any) in order to use the texture. #[must_use] pub fn required_features(&self) -> Features { @@ -2799,6 +3094,7 @@ impl TextureFormat { Self::Depth32FloatStencil8 => Features::DEPTH32FLOAT_STENCIL8, Self::NV12 => Features::TEXTURE_FORMAT_NV12, + Self::P010 => Features::TEXTURE_FORMAT_P010, Self::R16Unorm | Self::R16Snorm @@ -2857,7 +3153,7 @@ impl TextureFormat { // Flags let basic = TextureUsages::COPY_SRC | TextureUsages::COPY_DST | TextureUsages::TEXTURE_BINDING; - let attachment = basic | TextureUsages::RENDER_ATTACHMENT; + let attachment = basic | TextureUsages::RENDER_ATTACHMENT | TextureUsages::TRANSIENT; let storage = basic | TextureUsages::STORAGE_BINDING; let binding = TextureUsages::TEXTURE_BINDING; let all_flags = attachment | storage | binding; @@ -2867,11 +3163,12 @@ impl TextureFormat { storage | binding }; let atomic = attachment | atomic_64; - let rg11b10f = if device_features.contains(Features::RG11B10UFLOAT_RENDERABLE) { - attachment - } else { - basic - }; + let (rg11b10f_f, rg11b10f_u) = + if device_features.contains(Features::RG11B10UFLOAT_RENDERABLE) { + (msaa_resolve, attachment) + } else { + (msaa, basic) + }; let (bgra8unorm_f, bgra8unorm) = if device_features.contains(Features::BGRA8UNORM_STORAGE) { ( msaa_resolve | TextureFormatFeatureFlags::STORAGE_WRITE_ONLY, @@ -2912,7 +3209,7 @@ impl TextureFormat { Self::Bgra8UnormSrgb => (msaa_resolve, attachment), Self::Rgb10a2Uint => ( msaa, attachment), Self::Rgb10a2Unorm => (msaa_resolve, attachment), - Self::Rg11b10Ufloat => ( msaa, rg11b10f), + Self::Rg11b10Ufloat => ( rg11b10f_f, rg11b10f_u), Self::R64Uint => ( s_ro_wo, atomic_64), Self::Rg32Uint => ( s_ro_wo, all_flags), Self::Rg32Sint => ( s_ro_wo, all_flags), @@ -2931,8 +3228,10 @@ impl TextureFormat { Self::Depth32Float => ( msaa, attachment), Self::Depth32FloatStencil8 => ( msaa, attachment), - // We only support sampling nv12 textures until we implement transfer plane data. + // We only support sampling nv12 and p010 textures until we + // implement transfer plane data. Self::NV12 => ( none, binding), + Self::P010 => ( none, binding), Self::R16Unorm => ( msaa | s_ro_wo, storage), Self::R16Snorm => ( msaa | s_ro_wo, storage), @@ -3062,7 +3361,7 @@ impl TextureFormat { _ => None, }, - Self::NV12 => match aspect { + Self::NV12 | Self::P010 => match aspect { Some(TextureAspect::Plane0) | Some(TextureAspect::Plane1) => { Some(unfilterable_float) } @@ -3195,6 +3494,12 @@ impl TextureFormat { _ => None, }, + Self::P010 => match aspect { + Some(TextureAspect::Plane0) => Some(2), + Some(TextureAspect::Plane1) => Some(4), + _ => None, + }, + Self::Bc1RgbaUnorm | Self::Bc1RgbaUnormSrgb | Self::Bc4RUnorm | Self::Bc4RSnorm => { Some(8) } @@ -3280,6 +3585,7 @@ impl TextureFormat { | Self::Depth32Float | Self::Depth32FloatStencil8 | Self::NV12 + | Self::P010 | Self::Rgb9e5Ufloat | Self::Bc1RgbaUnorm | Self::Bc1RgbaUnormSrgb @@ -3363,6 +3669,7 @@ impl TextureFormat { | Self::Depth32Float | Self::Depth32FloatStencil8 | Self::NV12 + | Self::P010 | Self::Rgb9e5Ufloat | Self::Bc1RgbaUnorm | Self::Bc1RgbaUnormSrgb @@ -3457,7 +3764,7 @@ impl TextureFormat { _ => 2, }, - Self::NV12 => match aspect { + Self::NV12 | Self::P010 => match aspect { TextureAspect::Plane0 => 1, TextureAspect::Plane1 => 2, _ => 3, @@ -3540,6 +3847,49 @@ impl TextureFormat { pub fn is_srgb(&self) -> bool { *self != self.remove_srgb_suffix() } + + /// Returns the theoretical memory footprint of a texture with the given format and dimensions. + /// + /// Actual memory usage may greatly exceed this value due to alignment and padding. + #[must_use] + pub fn theoretical_memory_footprint(&self, size: Extent3d) -> u64 { + let (block_width, block_height) = self.block_dimensions(); + + let block_size = self.block_copy_size(None); + + let approximate_block_size = match block_size { + Some(size) => size, + None => match self { + // One f16 per pixel + Self::Depth16Unorm => 2, + // One u24 per pixel, padded to 4 bytes + Self::Depth24Plus => 4, + // One u24 per pixel, plus one u8 per pixel + Self::Depth24PlusStencil8 => 4, + // One f32 per pixel + Self::Depth32Float => 4, + // One f32 per pixel, plus one u8 per pixel, with 3 bytes intermediary padding + Self::Depth32FloatStencil8 => 8, + // One u8 per pixel + Self::Stencil8 => 1, + // Two chroma bytes per block, one luma byte per block + Self::NV12 => 3, + // Two chroma u16s and one luma u16 per block + Self::P010 => 6, + f => { + log::warn!("Memory footprint for format {f:?} is not implemented"); + 0 + } + }, + }; + + let width_blocks = size.width.div_ceil(block_width) as u64; + let height_blocks = size.height.div_ceil(block_height) as u64; + + let total_blocks = width_blocks * height_blocks * size.depth_or_array_layers as u64; + + total_blocks * approximate_block_size as u64 + } } #[test] @@ -4185,37 +4535,42 @@ pub enum PollType { /// /// On WebGPU, this has no effect. Callbacks are invoked from the /// window event loop. - WaitForSubmissionIndex(T), - /// Same as `WaitForSubmissionIndex` but waits for the most recent submission. - Wait, + Wait { + /// Submission index to wait for. + /// + /// If not specified, will wait for the most recent submission at the time of the poll. + /// By the time the method returns, more submissions may have taken place. + submission_index: Option, + + /// Max time to wait for the submission to complete. + /// + /// If not specified, will wait indefinitely (or until an error is detected). + /// If waiting for the GPU device takes this long or longer, the poll will return [`PollError::Timeout`]. + timeout: Option, + }, + /// Check the device for a single time without blocking. Poll, } impl PollType { - /// Construct a [`Self::Wait`] variant + /// Wait indefinitely until for the most recent submission to complete. + /// + /// This is a convenience function that creates a [`Self::Wait`] variant with + /// no timeout and no submission index. #[must_use] - pub fn wait() -> Self { - // This function seems a little silly, but it is useful to allow - // to be split up, as - // it has meaning in that PR. - Self::Wait - } - - /// Construct a [`Self::WaitForSubmissionIndex`] variant - #[must_use] - pub fn wait_for(submission_index: T) -> Self { - // This function seems a little silly, but it is useful to allow - // to be split up, as - // it has meaning in that PR. - Self::WaitForSubmissionIndex(submission_index) + pub const fn wait_indefinitely() -> Self { + Self::Wait { + submission_index: None, + timeout: None, + } } /// This `PollType` represents a wait of some kind. #[must_use] pub fn is_wait(&self) -> bool { match *self { - Self::WaitForSubmissionIndex(..) | Self::Wait => true, + Self::Wait { .. } => true, Self::Poll => false, } } @@ -4227,25 +4582,47 @@ impl PollType { F: FnOnce(T) -> U, { match self { - Self::WaitForSubmissionIndex(i) => PollType::WaitForSubmissionIndex(func(i)), - Self::Wait => PollType::Wait, + Self::Wait { + submission_index, + timeout, + } => PollType::Wait { + submission_index: submission_index.map(func), + timeout, + }, Self::Poll => PollType::Poll, } } } -/// Error states after a device poll +/// Error states after a device poll. #[derive(Debug)] -#[cfg_attr(feature = "std", derive(thiserror::Error))] pub enum PollError { /// The requested Wait timed out before the submission was completed. - #[cfg_attr( - feature = "std", - error("The requested Wait timed out before the submission was completed.") - )] Timeout, + /// The requested Wait was given a wrong submission index. + WrongSubmissionIndex(u64, u64), } +// This impl could be derived by `thiserror`, but by not doing so, we can reduce the number of +// dependencies this early in the dependency graph, which may improve build parallelism. +impl fmt::Display for PollError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + PollError::Timeout => { + f.write_str("The requested Wait timed out before the submission was completed.") + } + PollError::WrongSubmissionIndex(requested, successful) => write!( + f, + "Tried to wait using a submission index ({requested}) \ + that has not been returned by a successful submission \ + (last successful submission: {successful}" + ), + } + } +} + +impl core::error::Error for PollError {} + /// Status of device poll operation. #[derive(Debug, PartialEq, Eq)] pub enum PollStatus { @@ -4904,6 +5281,36 @@ impl VertexFormat { Self::Float64x4 => 32, } } + + /// Returns the size read by an acceleration structure build of the vertex format. This is + /// slightly different from [`Self::size`] because the alpha component of 4-component formats + /// are not read in an acceleration structure build, allowing for a smaller stride. + #[must_use] + pub const fn min_acceleration_structure_vertex_stride(&self) -> u64 { + match self { + Self::Float16x2 | Self::Snorm16x2 => 4, + Self::Float32x3 => 12, + Self::Float32x2 => 8, + // This is the minimum value from DirectX + // > A16 component is ignored, other data can be packed there, such as setting vertex stride to 6 bytes + // + // https://microsoft.github.io/DirectX-Specs/d3d/Raytracing.html#d3d12_raytracing_geometry_triangles_desc + // + // Vulkan does not express a minimum stride. + Self::Float16x4 | Self::Snorm16x4 => 6, + _ => unreachable!(), + } + } + + /// Returns the alignment required for `wgpu::BlasTriangleGeometry::vertex_stride` + #[must_use] + pub const fn acceleration_structure_stride_alignment(&self) -> u64 { + match self { + Self::Float16x4 | Self::Float16x2 | Self::Snorm16x4 | Self::Snorm16x2 => 2, + Self::Float32x2 | Self::Float32x3 => 4, + _ => unreachable!(), + } + } } bitflags::bitflags! { @@ -4912,6 +5319,10 @@ bitflags::bitflags! { /// The usages determine what kind of memory the buffer is allocated from and what /// actions the buffer can partake in. /// + /// Specifying only usages the application will actually perform may increase performance. + /// Additionally, on the WebGL backend, there are restrictions on [`BufferUsages::INDEX`]; + /// see [`DownlevelFlags::UNRESTRICTED_INDEX_BUFFER`] for more information. + /// /// Corresponds to [WebGPU `GPUBufferUsageFlags`]( /// https://gpuweb.github.io/gpuweb/#typedefdef-gpubufferusageflags). #[repr(transparent)] @@ -4926,7 +5337,7 @@ bitflags::bitflags! { /// may have is COPY_DST. const MAP_READ = 1 << 0; /// Allow a buffer to be mapped for writing using [`Buffer::map_async`] + [`Buffer::get_mapped_range_mut`]. - /// This does not include creating a buffer with `mapped_at_creation` set. + /// This does not include creating a buffer with [`BufferDescriptor::mapped_at_creation`] set. /// /// If [`Features::MAPPABLE_PRIMARY_BUFFERS`] feature isn't enabled, the only other usage a buffer /// may have is COPY_SRC. @@ -4958,6 +5369,8 @@ bitflags::bitflags! { bitflags::bitflags! { /// Similar to `BufferUsages`, but used only for `CommandEncoder::transition_resources`. + #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] + #[cfg_attr(feature = "serde", serde(transparent))] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub struct BufferUses: u16 { /// The argument to a read-only mapping. @@ -5008,7 +5421,8 @@ bitflags::bitflags! { } /// A buffer transition for use with `CommandEncoder::transition_resources`. -#[derive(Debug)] +#[derive(Clone, Debug)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct BufferTransition { /// The buffer to transition. pub buffer: T, @@ -5030,6 +5444,10 @@ pub struct BufferDescriptor { pub size: BufferAddress, /// Usages of a buffer. If the buffer is used in any way that isn't specified here, the operation /// will panic. + /// + /// Specifying only usages the application will actually perform may increase performance. + /// Additionally, on the WebGL backend, there are restrictions on [`BufferUsages::INDEX`]; + /// see [`DownlevelFlags::UNRESTRICTED_INDEX_BUFFER`] for more information. pub usage: BufferUsages, /// Allows a buffer to be mapped immediately after they are made. It does not have to be [`BufferUsages::MAP_READ`] or /// [`BufferUsages::MAP_WRITE`], all buffers are allowed to be mapped at creation. @@ -5240,6 +5658,8 @@ bitflags::bitflags! { /// Allows a texture to be a [`BindingType::StorageTexture`] in a bind group. const STORAGE_BINDING = 1 << 3; /// Allows a texture to be an output attachment of a render pass. + /// + /// Consider adding [`TextureUsages::TRANSIENT`] if the contents are not reused. const RENDER_ATTACHMENT = 1 << 4; // @@ -5249,12 +5669,23 @@ bitflags::bitflags! { // /// Allows a texture to be used with image atomics. Requires [`Features::TEXTURE_ATOMIC`]. const STORAGE_ATOMIC = 1 << 16; + /// Specifies the contents of this texture will not be used in another pass to potentially reduce memory usage and bandwidth. + /// + /// No-op on platforms on platforms that do not benefit from transient textures. + /// Generally mobile and Apple chips care about this. + /// + /// Incompatible with ALL other usages except [`TextureUsages::RENDER_ATTACHMENT`] and requires it. + /// + /// Requires [`StoreOp::Discard`]. + const TRANSIENT = 1 << 17; } } bitflags::bitflags! { /// Similar to `TextureUsages`, but used only for `CommandEncoder::transition_resources`. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] + #[cfg_attr(feature = "serde", serde(transparent))] pub struct TextureUses: u16 { /// The texture is in unknown state. const UNINITIALIZED = 1 << 0; @@ -5286,6 +5717,8 @@ bitflags::bitflags! { /// Image atomic enabled storage. /// cbindgen:ignore const STORAGE_ATOMIC = 1 << 11; + /// Transient texture that may not have any backing memory. Not a resource state stored in the trackers, only used for passing down usages to create_texture. + const TRANSIENT = 1 << 12; /// The combination of states that a texture may be in _at the same time_. /// cbindgen:ignore const INCLUSIVE = Self::COPY_SRC.bits() | Self::RESOURCE.bits() | Self::DEPTH_STENCIL_READ.bits(); @@ -5299,15 +5732,16 @@ bitflags::bitflags! { const ORDERED = Self::INCLUSIVE.bits() | Self::COLOR_TARGET.bits() | Self::DEPTH_STENCIL_WRITE.bits() | Self::STORAGE_READ_ONLY.bits(); /// Flag used by the wgpu-core texture tracker to say a texture is in different states for every sub-resource - const COMPLEX = 1 << 12; + const COMPLEX = 1 << 13; /// Flag used by the wgpu-core texture tracker to say that the tracker does not know the state of the sub-resource. /// This is different from UNINITIALIZED as that says the tracker does know, but the texture has not been initialized. - const UNKNOWN = 1 << 13; + const UNKNOWN = 1 << 14; } } /// A texture transition for use with `CommandEncoder::transition_resources`. -#[derive(Debug)] +#[derive(Clone, Debug)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct TextureTransition { /// The texture to transition. pub texture: T, @@ -5321,6 +5755,7 @@ pub struct TextureTransition { /// Specifies a particular set of subresources in a texture. #[derive(Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct TextureSelector { /// Range of mips to use. pub mips: Range, @@ -5391,25 +5826,40 @@ pub struct SurfaceConfiguration { /// `AutoNoVsync` will gracefully do a designed sets of fallbacks if their primary modes are /// unsupported. pub present_mode: PresentMode, - /// Desired maximum number of frames that the presentation engine should queue in advance. + /// Desired maximum number of monitor refreshes between a [`Surface::get_current_texture`] call and the + /// texture being presented to the screen. This is sometimes called "Frames in Flight". /// - /// This is a hint to the backend implementation and will always be clamped to the supported range. - /// As a consequence, either the maximum frame latency is set directly on the swap chain, - /// or waits on present are scheduled to avoid exceeding the maximum frame latency if supported, - /// or the swap chain size is set to (max-latency + 1). + /// Defaults to `2` when created via [`Surface::get_default_config`] as this is a reasonable default. /// - /// Defaults to 2 when created via `Surface::get_default_config`. + /// This is ultimately a hint to the backend implementation and will always be clamped + /// to the supported range. /// - /// Typical values range from 3 to 1, but higher values are possible: - /// * Choose 2 or higher for potentially smoother frame display, as it allows to be at least one frame - /// to be queued up. This typically avoids starving the GPU's work queue. - /// Higher values are useful for achieving a constant flow of frames to the display under varying load. - /// * Choose 1 for low latency from frame recording to frame display. - /// ⚠️ If the backend does not support waiting on present, this will cause the CPU to wait for the GPU - /// to finish all work related to the previous frame when calling `Surface::get_current_texture`, - /// causing CPU-GPU serialization (i.e. when `Surface::get_current_texture` returns, the GPU might be idle). - /// It is currently not possible to query this. See . - /// * A value of 0 is generally not supported and always clamped to a higher value. + /// Typical values are `1` to `3`, but higher values are valid, though likely to be clamped. + /// * Choose `1` to minimize latency above all else. This only gives a single monitor refresh for all of + /// the CPU and GPU work to complete. ⚠️ As a result of these short swapchains, the CPU and GPU + /// cannot run in parallel, prioritizing latency over throughput. For applications like GUIs doing + /// a small amount of GPU work each frame that need low latency, this is a reasonable choice. + /// * Choose `2` for a balance between latency and throughput. The CPU and GPU both can each use + /// a full monitor refresh to do their computations. This is a reasonable default for most applications. + /// * Choose `3` or higher to maximize throughput, sacrificing latency when the the CPU and GPU + /// are using less than a full monitor refresh each. For applications that use CPU-side pipelining + /// of frames this may be a reasonable choice. ⚠️ On 60hz displays the latency can be very noticeable. + /// + /// This maps to the backend in the following ways: + /// - Vulkan: Number of frames in the swapchain is `desired_maximum_frame_latency + 1`, + /// clamped to the supported range. + /// - DX12: Calls [`IDXGISwapChain2::SetMaximumFrameLatency(desired_maximum_frame_latency)`][SMFL]. + /// - Metal: Sets the `maximumDrawableCount` of the underlying `CAMetalLayer` to + /// `desired_maximum_frame_latency + 1`, clamped to the supported range. + /// - OpenGL: Ignored + /// + /// It also has various subtle interactions with various present modes and APIs. + /// - DX12 + Mailbox: Limits framerate to `desired_maximum_frame_latency * Monitor Hz` fps. + /// - Vulkan/Metal + Mailbox: If this is set to `2`, limits framerate to `2 * Monitor Hz` fps. `3` or higher is unlimited. + /// + /// [`Surface::get_current_texture`]: ../wgpu/struct.Surface.html#method.get_current_texture + /// [`Surface::get_default_config`]: ../wgpu/struct.Surface.html#method.get_default_config + /// [SMFL]: https://learn.microsoft.com/en-us/windows/win32/api/dxgi1_3/nf-dxgi1_3-idxgiswapchain2-setmaximumframelatency pub desired_maximum_frame_latency: u32, /// Specifies how the alpha channel of the textures should be handled during compositing. pub alpha_mode: CompositeAlphaMode, @@ -6011,10 +6461,22 @@ impl TextureDescriptor { /// /// #[must_use] - pub fn compute_render_extent(&self, mip_level: u32) -> Extent3d { + pub fn compute_render_extent(&self, mip_level: u32, plane: Option) -> Extent3d { + let width = self.size.width >> mip_level; + let height = self.size.height >> mip_level; + + let (width, height) = match (self.format, plane) { + (TextureFormat::NV12 | TextureFormat::P010, Some(0)) => (width, height), + (TextureFormat::NV12 | TextureFormat::P010, Some(1)) => (width / 2, height / 2), + _ => { + debug_assert!(!self.format.is_multi_planar_format()); + (width, height) + } + }; + Extent3d { - width: u32::max(1, self.size.width >> mip_level), - height: u32::max(1, self.size.height >> mip_level), + width, + height, depth_or_array_layers: 1, } } @@ -6031,6 +6493,168 @@ impl TextureDescriptor { } } +/// Format of an `ExternalTexture`. This indicates the number of underlying +/// planes used by the `ExternalTexture` as well as each plane's format. +#[repr(C)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum ExternalTextureFormat { + /// Single [`TextureFormat::Rgba8Unorm`] or [`TextureFormat::Bgra8Unorm`] format plane. + Rgba, + /// [`TextureFormat::R8Unorm`] Y plane, and [`TextureFormat::Rg8Unorm`] + /// interleaved CbCr plane. + Nv12, + /// Separate [`TextureFormat::R8Unorm`] Y, Cb, and Cr planes. + Yu12, +} + +/// Parameters describing a gamma encoding transfer function in the form +/// tf = { k * linear | linear < b +/// { a * pow(linear, 1/g) - (a-1) | linear >= b +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Zeroable, bytemuck::Pod)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[allow(missing_docs)] +pub struct ExternalTextureTransferFunction { + pub a: f32, + pub b: f32, + pub g: f32, + pub k: f32, +} + +impl Default for ExternalTextureTransferFunction { + fn default() -> Self { + Self { + a: 1.0, + b: 1.0, + g: 1.0, + k: 1.0, + } + } +} + +/// Describes an [`ExternalTexture`](../wgpu/struct.ExternalTexture.html). +/// +/// Note that [`width`] and [`height`] are the values that should be returned by +/// size queries in shader code; they do not necessarily match the dimensions of +/// the underlying plane texture(s). As a special case, if `(width, height)` is +/// `(0, 0)`, the actual size of the first underlying plane should be used instead. +/// +/// The size given by [`width`] and [`height`] must be consistent with +/// [`sample_transform`]: they should be the size in texels of the rectangle +/// covered by the square (0,0)..(1,1) after [`sample_transform`] has been applied +/// to it. +/// +/// [`width`]: Self::width +/// [`height`]: Self::height +/// [`sample_transform`]: Self::sample_transform +/// +/// Corresponds to [WebGPU `GPUExternalTextureDescriptor`]( +/// https://gpuweb.github.io/gpuweb/#dictdef-gpuexternaltexturedescriptor). +#[repr(C)] +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub struct ExternalTextureDescriptor { + /// Debug label of the external texture. This will show up in graphics + /// debuggers for easy identification. + pub label: L, + + /// Width of the external texture. + pub width: u32, + + /// Height of the external texture. + pub height: u32, + + /// Format of the external texture. + pub format: ExternalTextureFormat, + + /// 4x4 column-major matrix with which to convert sampled YCbCr values + /// to RGBA. + /// This is ignored when `format` is [`ExternalTextureFormat::Rgba`]. + pub yuv_conversion_matrix: [f32; 16], + + /// 3x3 column-major matrix to transform linear RGB values in the source + /// color space to linear RGB values in the destination color space. In + /// combination with [`Self::src_transfer_function`] and + /// [`Self::dst_transfer_function`] this can be used to ensure that + /// [`ImageSample`] and [`ImageLoad`] operations return values in the + /// desired destination color space rather than the source color space of + /// the underlying planes. + /// + /// [`ImageSample`]: https://docs.rs/naga/latest/naga/ir/enum.Expression.html#variant.ImageSample + /// [`ImageLoad`]: https://docs.rs/naga/latest/naga/ir/enum.Expression.html#variant.ImageLoad + pub gamut_conversion_matrix: [f32; 9], + + /// Transfer function for the source color space. The *inverse* of this + /// will be applied to decode non-linear RGB to linear RGB in the source + /// color space. + pub src_transfer_function: ExternalTextureTransferFunction, + + /// Transfer function for the destination color space. This will be applied + /// to encode linear RGB to non-linear RGB in the destination color space. + pub dst_transfer_function: ExternalTextureTransferFunction, + + /// Transform to apply to [`ImageSample`] coordinates. + /// + /// This is a 3x2 column-major matrix representing an affine transform from + /// normalized texture coordinates to the normalized coordinates that should + /// be sampled from the external texture's underlying plane(s). + /// + /// This transform may scale, translate, flip, and rotate in 90-degree + /// increments, but the result of transforming the rectangle (0,0)..(1,1) + /// must be an axis-aligned rectangle that falls within the bounds of + /// (0,0)..(1,1). + /// + /// [`ImageSample`]: https://docs.rs/naga/latest/naga/ir/enum.Expression.html#variant.ImageSample + pub sample_transform: [f32; 6], + + /// Transform to apply to [`ImageLoad`] coordinates. + /// + /// This is a 3x2 column-major matrix representing an affine transform from + /// non-normalized texel coordinates to the non-normalized coordinates of + /// the texel that should be loaded from the external texture's underlying + /// plane 0. For planes 1 and 2, if present, plane 0's coordinates are + /// scaled according to the textures' relative sizes. + /// + /// This transform may scale, translate, flip, and rotate in 90-degree + /// increments, but the result of transforming the rectangle (0,0)..([`width`], + /// [`height`]) must be an axis-aligned rectangle that falls within the bounds + /// of (0,0)..([`width`], [`height`]). + /// + /// [`ImageLoad`]: https://docs.rs/naga/latest/naga/ir/enum.Expression.html#variant.ImageLoad + /// [`width`]: Self::width + /// [`height`]: Self::height + pub load_transform: [f32; 6], +} + +impl ExternalTextureDescriptor { + /// Takes a closure and maps the label of the external texture descriptor into another. + #[must_use] + pub fn map_label(&self, fun: impl FnOnce(&L) -> K) -> ExternalTextureDescriptor { + ExternalTextureDescriptor { + label: fun(&self.label), + width: self.width, + height: self.height, + format: self.format, + yuv_conversion_matrix: self.yuv_conversion_matrix, + sample_transform: self.sample_transform, + load_transform: self.load_transform, + gamut_conversion_matrix: self.gamut_conversion_matrix, + src_transfer_function: self.src_transfer_function, + dst_transfer_function: self.dst_transfer_function, + } + } + + /// The number of underlying planes used by the external texture. + pub fn num_planes(&self) -> usize { + match self.format { + ExternalTextureFormat::Rgba => 1, + ExternalTextureFormat::Nv12 => 2, + ExternalTextureFormat::Yu12 => 3, + } + } +} + /// Describes a `Sampler`. /// /// For use with `Device::create_sampler`. @@ -6053,7 +6677,7 @@ pub struct SamplerDescriptor { /// How to filter the texture when it needs to be minified (made smaller) pub min_filter: FilterMode, /// How to filter between mip map levels - pub mipmap_filter: FilterMode, + pub mipmap_filter: MipmapFilterMode, /// Minimum level of detail (i.e. mip level) to use pub lod_min_clamp: f32, /// Maximum level of detail (i.e. mip level) to use @@ -6158,12 +6782,32 @@ pub enum AddressMode { pub enum FilterMode { /// Nearest neighbor sampling. /// - /// This creates a pixelated effect when used as a mag filter + /// This creates a pixelated effect. #[default] Nearest = 0, /// Linear Interpolation /// - /// This makes textures smooth but blurry when used as a mag filter. + /// This makes textures smooth but blurry. + Linear = 1, +} + +/// Texel mixing mode when sampling between texels. +/// +/// Corresponds to [WebGPU `GPUMipmapFilterMode`]( +/// https://gpuweb.github.io/gpuweb/#enumdef-gpumipmapfiltermode). +#[repr(C)] +#[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))] +pub enum MipmapFilterMode { + /// Nearest neighbor sampling. + /// + /// Return the value of the texel nearest to the texture coordinates. + #[default] + Nearest = 0, + /// Linear Interpolation + /// + /// Select two texels in each dimension and return a linear interpolation between their values. Linear = 1, } @@ -6306,13 +6950,6 @@ pub struct TexelCopyBufferLayout { pub rows_per_image: Option, } -/// Old name for a [`TexelCopyBufferLayout`]. -#[deprecated( - since = "24.0.0", - note = "This has been renamed to `TexelCopyBufferLayout`, and will be removed in 25.0.0." -)] -pub type ImageDataLayout = TexelCopyBufferLayout; - /// Specific type of a buffer binding. /// /// Corresponds to [WebGPU `GPUBufferBindingType`]( @@ -6706,6 +7343,20 @@ pub enum BindingType { /// If enabled requires [`Features::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN`] vertex_return: bool, }, + + /// An external texture binding. + /// + /// Example WGSL syntax: + /// ```rust,ignore + /// @group(0) @binding(0) + /// var t: texture_external; + /// ``` + /// + /// Corresponds to [WebGPU `GPUExternalTextureBindingLayout`]( + /// https://gpuweb.github.io/gpuweb/#dictdef-gpuexternaltexturebindinglayout). + /// + /// Requires [`Features::EXTERNAL_TEXTURE`] + ExternalTexture, } impl BindingType { @@ -6765,13 +7416,6 @@ pub struct TexelCopyBufferInfo { pub layout: TexelCopyBufferLayout, } -/// Old name for a [`TexelCopyBufferInfo`]. -#[deprecated( - since = "24.0.0", - note = "This has been renamed to `TexelCopyBufferInfo`, and will be removed in 25.0.0." -)] -pub type ImageCopyBuffer = TexelCopyBufferInfo; - /// View of a texture which can be used to copy to/from a buffer/texture. /// /// Corresponds to [WebGPU `GPUTexelCopyTextureInfo`]( @@ -6813,18 +7457,11 @@ impl TexelCopyTextureInfo { } } -/// Old name for a [`TexelCopyTextureInfo`]. -#[deprecated( - since = "24.0.0", - note = "This has been renamed to `TexelCopyTextureInfo`, and will be removed in 25.0.0." -)] -pub type ImageCopyTexture = TexelCopyTextureInfo; - /// View of an external texture that can be used to copy to a texture. /// /// Corresponds to [WebGPU `GPUCopyExternalImageSourceInfo`]( /// https://gpuweb.github.io/gpuweb/#dictdef-gpuimagecopyexternalimage). -#[cfg(target_arch = "wasm32")] +#[cfg(all(target_arch = "wasm32", feature = "web"))] #[derive(Clone, Debug)] pub struct CopyExternalImageSourceInfo { /// The texture to be copied from. The copy source data is captured at the moment @@ -6843,19 +7480,11 @@ pub struct CopyExternalImageSourceInfo { pub flip_y: bool, } -/// Old name for a [`CopyExternalImageSourceInfo`]. -#[deprecated( - since = "24.0.0", - note = "This has been renamed to `CopyExternalImageSourceInfo`, and will be removed in 25.0.0." -)] -#[cfg(target_arch = "wasm32")] -pub type ImageCopyExternalImage = CopyExternalImageSourceInfo; - /// Source of an external texture copy. /// /// Corresponds to the [implicit union type on WebGPU `GPUCopyExternalImageSourceInfo.source`]( /// https://gpuweb.github.io/gpuweb/#dom-gpuimagecopyexternalimage-source). -#[cfg(target_arch = "wasm32")] +#[cfg(all(target_arch = "wasm32", feature = "web"))] #[derive(Clone, Debug)] pub enum ExternalImageSource { /// Copy from a previously-decoded image bitmap. @@ -6877,7 +7506,7 @@ pub enum ExternalImageSource { VideoFrame(web_sys::VideoFrame), } -#[cfg(target_arch = "wasm32")] +#[cfg(all(target_arch = "wasm32", feature = "web"))] impl ExternalImageSource { /// Gets the pixel, not css, width of the source. pub fn width(&self) -> u32 { @@ -6908,7 +7537,7 @@ impl ExternalImageSource { } } -#[cfg(target_arch = "wasm32")] +#[cfg(all(target_arch = "wasm32", feature = "web"))] impl core::ops::Deref for ExternalImageSource { type Target = js_sys::Object; @@ -6928,12 +7557,14 @@ impl core::ops::Deref for ExternalImageSource { #[cfg(all( target_arch = "wasm32", + feature = "web", feature = "fragile-send-sync-non-atomic-wasm", not(target_feature = "atomics") ))] unsafe impl Send for ExternalImageSource {} #[cfg(all( target_arch = "wasm32", + feature = "web", feature = "fragile-send-sync-non-atomic-wasm", not(target_feature = "atomics") ))] @@ -6987,13 +7618,6 @@ impl CopyExternalImageDestInfo { } } -/// Old name for a [`CopyExternalImageDestInfo`]. -#[deprecated( - since = "24.0.0", - note = "This has been renamed to `CopyExternalImageDestInfo`, and will be removed in 25.0.0." -)] -pub type ImageCopyTextureTagged = CopyExternalImageDestInfo; - /// Subresource range within an image #[repr(C)] #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] @@ -7321,7 +7945,7 @@ pub struct ShaderRuntimeChecks { impl ShaderRuntimeChecks { /// Creates a new configuration where the shader is fully checked. #[must_use] - pub fn checked() -> Self { + pub const fn checked() -> Self { unsafe { Self::all(true) } } @@ -7332,7 +7956,7 @@ impl ShaderRuntimeChecks { /// See the documentation for the `set_*` methods for the safety requirements /// of each sub-configuration. #[must_use] - pub fn unchecked() -> Self { + pub const fn unchecked() -> Self { unsafe { Self::all(false) } } @@ -7344,7 +7968,7 @@ impl ShaderRuntimeChecks { /// See the documentation for the `set_*` methods for the safety requirements /// of each sub-configuration. #[must_use] - pub unsafe fn all(all_checks: bool) -> Self { + pub const unsafe fn all(all_checks: bool) -> Self { Self { bounds_checks: all_checks, force_loop_bounding: all_checks, @@ -7363,8 +7987,8 @@ impl Default for ShaderRuntimeChecks { /// Descriptor for all size defining attributes of a single triangle geometry inside a bottom level acceleration structure. pub struct BlasTriangleGeometrySizeDescriptor { /// Format of a vertex position, must be [`VertexFormat::Float32x3`] - /// with just [`Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE`] - /// but later features may add more formats. + /// with just [`Features::EXPERIMENTAL_RAY_QUERY`] + /// but [`Features::EXTENDED_ACCELERATION_STRUCTURE_VERTEX_FORMATS`] adds more. pub vertex_format: VertexFormat, /// Number of vertices. pub vertex_count: u32, @@ -7463,8 +8087,8 @@ bitflags::bitflags!( /// Allow for incremental updates (no change in size), currently this is unimplemented /// and will build as normal (this is fine, update vs build should be unnoticeable) const ALLOW_UPDATE = 1 << 0; - /// Allow the acceleration structure to be compacted in a copy operation, the function - /// to compact is not currently implemented. + /// Allow the acceleration structure to be compacted in a copy operation + /// (`Blas::prepare_for_compaction`, `CommandEncoder::compact_blas`). const ALLOW_COMPACTION = 1 << 1; /// Optimize for fast ray tracing performance, recommended if the geometry is unlikely /// to change (e.g. in a game: non-interactive scene geometry) @@ -7601,15 +8225,112 @@ mod send_sync { impl WasmNotSync for T {} } -/// Reason for "lose the device". +/// Corresponds to a [`GPUDeviceLostReason`]. /// -/// Corresponds to [WebGPU `GPUDeviceLostReason`](https://gpuweb.github.io/gpuweb/#enumdef-gpudevicelostreason). +/// [`GPUDeviceLostReason`]: https://www.w3.org/TR/webgpu/#enumdef-gpudevicelostreason #[repr(u8)] #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum DeviceLostReason { - /// Triggered by driver + /// The device was lost for an unspecific reason, including driver errors. Unknown = 0, - /// After `Device::destroy` + /// The device's `destroy` method was called. Destroyed = 1, } + +/// Descriptor for a shader module given by any of several sources. +/// These shaders are passed through directly to the underlying api. +/// At least one shader type that may be used by the backend must be `Some` or a panic is raised. +#[derive(Debug, Clone)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct CreateShaderModuleDescriptorPassthrough<'a, L> { + /// Entrypoint. Unused for Spir-V. + pub entry_point: String, + /// Debug label of the shader module. This will show up in graphics debuggers for easy identification. + pub label: L, + /// Number of workgroups in each dimension x, y and z. Unused for Spir-V. + pub num_workgroups: (u32, u32, u32), + /// Runtime checks that should be enabled. + pub runtime_checks: ShaderRuntimeChecks, + + /// Binary SPIR-V data, in 4-byte words. + pub spirv: Option>, + /// Shader DXIL source. + pub dxil: Option>, + /// Shader MSL source. + pub msl: Option>, + /// Shader HLSL source. + pub hlsl: Option>, + /// Shader GLSL source (currently unused). + pub glsl: Option>, + /// Shader WGSL source. + pub wgsl: Option>, +} + +// This is so people don't have to fill in fields they don't use, like num_workgroups, +// entry_point, or other shader languages they didn't compile for +impl<'a, L: Default> Default for CreateShaderModuleDescriptorPassthrough<'a, L> { + fn default() -> Self { + Self { + entry_point: "".into(), + label: Default::default(), + num_workgroups: (0, 0, 0), + runtime_checks: ShaderRuntimeChecks::unchecked(), + spirv: None, + dxil: None, + msl: None, + hlsl: None, + glsl: None, + wgsl: None, + } + } +} + +impl<'a, L> CreateShaderModuleDescriptorPassthrough<'a, L> { + /// Takes a closure and maps the label of the shader module descriptor into another. + pub fn map_label( + &self, + fun: impl FnOnce(&L) -> K, + ) -> CreateShaderModuleDescriptorPassthrough<'a, K> { + CreateShaderModuleDescriptorPassthrough { + entry_point: self.entry_point.clone(), + label: fun(&self.label), + num_workgroups: self.num_workgroups, + runtime_checks: self.runtime_checks, + spirv: self.spirv.clone(), + dxil: self.dxil.clone(), + msl: self.msl.clone(), + hlsl: self.hlsl.clone(), + glsl: self.glsl.clone(), + wgsl: self.wgsl.clone(), + } + } + + #[cfg(feature = "trace")] + /// Returns the source data for tracing purpose. + pub fn trace_data(&self) -> &[u8] { + if let Some(spirv) = &self.spirv { + bytemuck::cast_slice(spirv) + } else if let Some(msl) = &self.msl { + msl.as_bytes() + } else if let Some(dxil) = &self.dxil { + dxil + } else { + panic!("No binary data provided to `ShaderModuleDescriptorGeneric`") + } + } + + #[cfg(feature = "trace")] + /// Returns the binary file extension for tracing purpose. + pub fn trace_binary_ext(&self) -> &'static str { + if self.spirv.is_some() { + "spv" + } else if self.msl.is_some() { + "msl" + } else if self.dxil.is_some() { + "dxil" + } else { + panic!("No binary data provided to `ShaderModuleDescriptorGeneric`") + } + } +} diff --git a/wgpu-types/src/tokens.rs b/wgpu-types/src/tokens.rs new file mode 100644 index 000000000..ecf100ddb --- /dev/null +++ b/wgpu-types/src/tokens.rs @@ -0,0 +1,43 @@ +/// Token of the user agreeing to access experimental features. +#[derive(Debug, Default, Copy, Clone)] +pub struct ExperimentalFeatures { + enabled: bool, +} + +impl ExperimentalFeatures { + /// Uses of [`Features`] prefixed with "EXPERIMENTAL" are disallowed. + /// + /// [`Features`]: ../wgpu/struct.Features.html + pub const fn disabled() -> Self { + Self { enabled: false } + } + + /// Uses of [`Features`] prefixed with "EXPERIMENTAL" may result + /// in undefined behavior when used incorrectly. The exact bounds + /// of these issues varies by the feature. These instances are + /// inherently bugs in our implementation that we will eventually fix. + /// + /// By giving access to still work-in-progress APIs, users can get + /// access to newer technology sooner, and we can work with users + /// to fix bugs quicker. + /// + /// Look inside our repo at the [`api-specs`] for more information + /// on various experimental apis. + /// + /// # Safety + /// + /// - You acknowledge that there may be UB-containing bugs in these + /// apis and those may be hit by calling otherwise safe code. + /// - You agree to report any such bugs to us, if you find them. + /// + /// [`Features`]: ../wgpu/struct.Features.html + /// [`api-specs`]: https://github.com/gfx-rs/wgpu/tree/trunk/docs/api-specs + pub const unsafe fn enabled() -> Self { + Self { enabled: true } + } + + /// Returns true if the user has agreed to access experimental features. + pub const fn is_enabled(&self) -> bool { + self.enabled + } +} diff --git a/wgpu-types/src/transfers.rs b/wgpu-types/src/transfers.rs new file mode 100644 index 000000000..2e40958c1 --- /dev/null +++ b/wgpu-types/src/transfers.rs @@ -0,0 +1,465 @@ +use crate::{BufferAddress, Extent3d, TexelCopyBufferLayout, TextureAspect, TextureFormat}; + +impl TexelCopyBufferLayout { + /// Extract a variety of information about the given copy operation. + /// + /// Returns an error if the size of the copy overflows a `u64`, or if the arguments are + /// not valid in conjunction with the `bytes_per_row` or `rows_per_image` parameters in + /// `self`. + /// + /// This is public for use by `wgpu-core` and `wgpu-hal`, it is not a stable API. + /// + /// Although WebGPU requires that `bytes_per_row` and `rows_per_image` be specified in + /// cases where they apply, we are more lenient here (although it's not clear if that is + /// necessary). Our caller, `validate_linear_texture_data`, enforces this and other + /// WebGPU requirements on the copy parameters that we do not check here. + #[doc(hidden)] + #[inline(always)] + pub fn get_buffer_texture_copy_info( + &self, + format: TextureFormat, + aspect: TextureAspect, + copy_size: &Extent3d, + ) -> Result { + let copy_width = BufferAddress::from(copy_size.width); + let copy_height = BufferAddress::from(copy_size.height); + let depth_or_array_layers = BufferAddress::from(copy_size.depth_or_array_layers); + + let block_size_bytes = BufferAddress::from(format.block_copy_size(Some(aspect)).unwrap()); + let (block_width, block_height) = format.block_dimensions(); + let block_width_texels = BufferAddress::from(block_width); + let block_height_texels = BufferAddress::from(block_height); + + let width_blocks = copy_width.div_ceil(block_width_texels); + let height_blocks = copy_height.div_ceil(block_height_texels); + + // The spec calls this bytesInLastRow. + let row_bytes_dense = width_blocks * block_size_bytes; + let row_stride_bytes = match self.bytes_per_row.map(BufferAddress::from) { + Some(bytes_per_row) if bytes_per_row >= row_bytes_dense => bytes_per_row, + Some(_) => return Err(Error::InvalidBytesPerRow), + None => row_bytes_dense, + }; + + let image_rows_dense = height_blocks; + let image_stride_rows = match self.rows_per_image.map(BufferAddress::from) { + Some(rows_per_image) if rows_per_image >= image_rows_dense => rows_per_image, + Some(_) => return Err(Error::InvalidRowsPerImage), + None => image_rows_dense, + }; + + let image_bytes_dense = match image_rows_dense.checked_sub(1) { + Some(rows_minus_one) => rows_minus_one + .checked_mul(row_stride_bytes) + .ok_or(Error::ImageBytesOverflow(false))? + .checked_add(row_bytes_dense) + .ok_or(Error::ImageBytesOverflow(true))?, + None => 0, + }; + + // It is possible that `image_stride_bytes` overflows, but the actual + // copy size does not, when the copy only has a single layer and + // `image_size_bytes` is not used. We don't worry about handling this + // gracefully because WebGPU texture size limits should keep things out + // of this realm entirely. + let image_stride_bytes = row_stride_bytes + .checked_mul(image_stride_rows) + .ok_or(Error::ImageStrideOverflow)?; + + let bytes_in_copy = if depth_or_array_layers <= 1 { + depth_or_array_layers * image_bytes_dense + } else { + (depth_or_array_layers - 1) + .checked_mul(image_stride_bytes) + .ok_or(Error::ArraySizeOverflow(false))? + .checked_add(image_bytes_dense) + .ok_or(Error::ArraySizeOverflow(true))? + }; + + Ok(BufferTextureCopyInfo { + copy_width, + copy_height, + depth_or_array_layers, + + offset: self.offset, + + block_size_bytes, + block_width_texels, + block_height_texels, + + width_blocks, + height_blocks, + + row_bytes_dense, + row_stride_bytes, + + image_stride_rows, + image_stride_bytes, + + image_rows_dense, + image_bytes_dense, + + bytes_in_copy, + }) + } +} + +/// Information about a copy between a buffer and a texture. +/// +/// Mostly used for internal calculations, but useful nonetheless. +/// Generated by [`TexelCopyBufferLayout::get_buffer_texture_copy_info`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct BufferTextureCopyInfo { + /// The width of the copy region in pixels. + pub copy_width: u64, + /// The height of the copy region in pixels. + pub copy_height: u64, + /// The depth of the copy region in pixels. + pub depth_or_array_layers: u64, + + /// The offset in the buffer where the copy starts. + pub offset: u64, + + /// The size of a single texture texel block in bytes. + pub block_size_bytes: u64, + /// The number of texel in a texel block in the x direction. + pub block_width_texels: u64, + /// The number of texel in a texel block in the y direction. + pub block_height_texels: u64, + + /// The width of the copy region in blocks. + pub width_blocks: u64, + /// The height of the copy region in blocks. + pub height_blocks: u64, + + /// The number of bytes in the last row of the copy region. + pub row_bytes_dense: u64, + /// The stride in bytes between the start of one row in an image and the next row in the same image. + /// + /// This includes any padding between one row and the next row. + pub row_stride_bytes: u64, + + /// The stride in rows between the start of one image and the next image. + pub image_stride_rows: u64, + /// The stride in bytes between the start of one image and the next image. + pub image_stride_bytes: u64, + + /// The number of rows in a densely packed list of images. + /// + /// This is the number of rows in the image that are actually used for texel data, + /// and does not include any padding rows, unlike `image_stride_rows`. + pub image_rows_dense: u64, + /// The number of bytes in a densely packed list of images. + /// + /// This is the number of bytes in the image that are actually used for texel data, + /// or are used for padding between _rows_. Padding at the end of the last row and + /// between _images_ is not included. + pub image_bytes_dense: u64, + + /// The total number of bytes in the copy region. + /// + /// This includes all padding except the padding after the last row in the copy. + pub bytes_in_copy: u64, +} + +/// Errors that can occur while populating `BufferTextureCopyInfo`. +// +// We use the additional detail provided by these errors (over wgpu-core's +// `TransferError`) to improve the reliability of the tests in this module. It +// doesn't seem worth plumbing them upwards, because at the API level it +// shouldn't be possible to exceed them without exceeding the WebGPU limits on +// texture dimension. But the WebGPU limits are not currently enforced, so we +// have to do something here to protect against overflows. +// +// Even when the WebGPU limits are enforced, it may still be useful to keep the +// checks here as a failsafe if the correctness of the primary limit enforcement +// is not immediately apparent. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum BufferTextureCopyInfoError { + /// The `bytes_per_row` is too small for the texture width. + InvalidBytesPerRow, + /// The `rows_per_image` is too small for the texture height. + InvalidRowsPerImage, + /// The image stride overflows a `u64`. + ImageStrideOverflow, + /// The last-layer byte size overflows a `u64`. + /// + /// The bool value indicates whether the multiplication (false) or the + /// addition (true) overflowed. + ImageBytesOverflow(bool), + /// The total size of the copy overflows a `u64`. + /// + /// The bool value indicates whether the multiplication (false) or the + /// addition (true) overflowed. + ArraySizeOverflow(bool), +} +type Error = BufferTextureCopyInfoError; + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Clone)] + struct LTDTest { + layout: TexelCopyBufferLayout, + format: TextureFormat, + aspect: TextureAspect, + copy_size: Extent3d, + expected_result: BufferTextureCopyInfo, + // Normally a Result would be make sense, + // but since the existing tests were written to mutate + // `LTDTest.expected_result`, keeping this separate avoids a bunch of + // `unwrap`s. + expected_error: Option, + } + + impl LTDTest { + #[track_caller] + fn run(&self) { + let linear_texture_data = + self.layout + .get_buffer_texture_copy_info(self.format, self.aspect, &self.copy_size); + let expected = match self.expected_error { + Some(err) => Err(err), + None => Ok(self.expected_result), + }; + assert_eq!(linear_texture_data, expected); + } + } + + #[test] + fn linear_texture_data_1d_copy() { + let mut test = LTDTest { + layout: TexelCopyBufferLayout { + offset: 0, + bytes_per_row: None, + rows_per_image: None, + }, + format: TextureFormat::Rgba8Unorm, + aspect: TextureAspect::All, + copy_size: Extent3d { + width: 4, + height: 1, + depth_or_array_layers: 1, + }, + expected_result: BufferTextureCopyInfo { + copy_width: 4, + copy_height: 1, + depth_or_array_layers: 1, + offset: 0, + block_size_bytes: 4, + block_width_texels: 1, + block_height_texels: 1, + width_blocks: 4, + height_blocks: 1, + row_bytes_dense: 16, + row_stride_bytes: 16, + image_stride_rows: 1, + image_stride_bytes: 16, + image_rows_dense: 1, + image_bytes_dense: 16, + bytes_in_copy: 16, + }, + expected_error: None, + }; + + test.run(); + + // Changing bytes_per_row should only change the bytes_per_row, not the bytes_in_copy + // as that is only affected by the last row size. + test.layout.bytes_per_row = Some(32); + test.expected_result.row_stride_bytes = 32; + test.expected_result.image_stride_bytes = 32; + + test.run(); + + // Changing rows_per_image should only change the rows_per_image and bytes_per_image, nothing else + test.layout.rows_per_image = Some(4); + test.expected_result.image_stride_bytes = 128; // 32 * 4 + test.expected_result.image_stride_rows = 4; + + test.run(); + + // Changing the offset should change nothing. + + test.layout.offset = 4; + test.expected_result.offset = 4; + + test.run(); + } + + #[test] + fn linear_texture_data_2d_3d_copy() { + let template = LTDTest { + layout: TexelCopyBufferLayout { + offset: 0, + bytes_per_row: None, + rows_per_image: None, + }, + format: TextureFormat::Rgba8Unorm, + aspect: TextureAspect::All, + copy_size: Extent3d { + width: 7, + height: 12, + depth_or_array_layers: 1, + }, + expected_result: BufferTextureCopyInfo { + copy_width: 7, + copy_height: 12, + depth_or_array_layers: 1, + offset: 0, + block_size_bytes: 4, + block_width_texels: 1, + block_height_texels: 1, + width_blocks: 7, + height_blocks: 12, + row_bytes_dense: 4 * 7, + row_stride_bytes: 4 * 7, + image_stride_rows: 12, + image_stride_bytes: 4 * 7 * 12, + image_rows_dense: 12, + image_bytes_dense: 4 * 7 * 12, + bytes_in_copy: 4 * 7 * 12, + }, + expected_error: None, + }; + + let mut test = template.clone(); + test.run(); + + // Changing bytes_per_row changes a number of other properties. + test.layout.bytes_per_row = Some(48); + test.expected_result.row_stride_bytes = 48; + test.expected_result.image_stride_bytes = 48 * 12; + test.expected_result.image_bytes_dense = 48 * 11 + (4 * 7); + test.expected_result.bytes_in_copy = 48 * 11 + (4 * 7); + test.run(); + + // Making this a 3D copy only changes the depth_or_array_layers and the bytes_in_copy. + test.copy_size.depth_or_array_layers = 4; + test.expected_result.depth_or_array_layers = 4; + test.expected_result.bytes_in_copy = 48 * 12 * 3 + 48 * 11 + (4 * 7); // 4 layers + test.run(); + + // Changing rows_per_image + test.layout.rows_per_image = Some(20); + test.expected_result.image_stride_rows = 20; + test.expected_result.image_stride_bytes = 20 * test.expected_result.row_stride_bytes; + test.expected_result.bytes_in_copy = 48 * 20 * 3 + 48 * 11 + (4 * 7); // 4 layers + test.run(); + + // Invalid because the row stride is too small. + let mut test = template.clone(); + test.layout.bytes_per_row = Some(20); + test.expected_error = Some(Error::InvalidBytesPerRow); + test.run(); + + // Invalid because the image stride is too small. + let mut test = template.clone(); + test.layout.rows_per_image = Some(8); + test.expected_error = Some(Error::InvalidRowsPerImage); + test.run(); + + // Invalid because width * height * texel_size_bytes overflows. + let mut test = template.clone(); + test.copy_size.width = u32::MAX; + test.copy_size.height = u32::MAX; + test.expected_error = Some(Error::ImageBytesOverflow(false)); + test.run(); + + // Invalid because the addition of row_bytes_dense overflows. + // (But the product rows_minus_one * row_stride_bytes does not overflow.) + let mut test = template.clone(); + test.copy_size.width = 0x8000_0000; + test.copy_size.height = 0x8000_0000; + test.expected_error = Some(Error::ImageBytesOverflow(true)); + test.run(); + + // Invalid because image_stride_bytes overflows. + let mut test = template.clone(); + test.copy_size.width = 0x8000_0000; + test.layout.rows_per_image = Some(0x8000_0000); + test.expected_result.image_stride_rows = 0x8000_0000; + test.expected_error = Some(Error::ImageStrideOverflow); + test.run(); + + // Invalid because (layers - 1) * image_stride_bytes overflows. + let mut test = template.clone(); + test.copy_size.depth_or_array_layers = 0x8000_0000; + test.copy_size.width = 0x1_0000; + test.copy_size.height = 0x1_0000; + test.expected_error = Some(Error::ArraySizeOverflow(false)); + test.run(); + + // Invalid because the total size of the copy overflows (but the product + // (layers - 1) * image_stride_bytes does not overflow). + let mut test = template.clone(); + test.copy_size.depth_or_array_layers = 0x3fff_8001; + test.copy_size.width = 0x1_0001; + test.copy_size.height = 0x1_0001; + test.expected_error = Some(Error::ArraySizeOverflow(true)); + test.run(); + } + + #[test] + fn linear_texture_data_2d_3d_compressed_copy() { + let mut test = LTDTest { + layout: TexelCopyBufferLayout { + offset: 0, + bytes_per_row: None, + rows_per_image: None, + }, + format: TextureFormat::Bc1RgbaUnorm, + aspect: TextureAspect::All, + copy_size: Extent3d { + width: 7, + height: 13, + depth_or_array_layers: 1, + }, + expected_result: BufferTextureCopyInfo { + copy_width: 7, + copy_height: 13, + depth_or_array_layers: 1, + offset: 0, + block_size_bytes: 8, + block_width_texels: 4, + block_height_texels: 4, + width_blocks: 2, + height_blocks: 4, + row_bytes_dense: 8 * 2, // block size * width_blocks + row_stride_bytes: 8 * 2, + image_stride_rows: 4, + image_stride_bytes: 8 * 2 * 4, // block size * width_blocks * height_blocks + image_rows_dense: 4, + image_bytes_dense: 8 * 2 * 4, + bytes_in_copy: 8 * 2 * 4, + }, + expected_error: None, + }; + + test.run(); + + // Changing bytes_per_row. + test.layout.bytes_per_row = Some(48); + test.expected_result.row_stride_bytes = 48; + test.expected_result.image_stride_bytes = 48 * 4; + test.expected_result.image_bytes_dense = 48 * 3 + (8 * 2); + test.expected_result.bytes_in_copy = 48 * 3 + (8 * 2); + + test.run(); + + // Changing rows_per_image. + test.layout.rows_per_image = Some(8); + test.expected_result.image_stride_bytes = 48 * 8; + test.expected_result.image_stride_rows = 8; + + test.run(); + + // Making this a 3D copy only changes the depth_or_array_layers and the bytes_in_copy. + test.copy_size.depth_or_array_layers = 4; + test.expected_result.depth_or_array_layers = 4; + test.expected_result.bytes_in_copy = 48 * 8 * 3 + 48 * 3 + (8 * 2); // 4 layers + + test.run(); + } +} diff --git a/wgpu/Cargo.toml b/wgpu/Cargo.toml index d9f0783e5..d9b01559c 100644 --- a/wgpu/Cargo.toml +++ b/wgpu/Cargo.toml @@ -29,7 +29,16 @@ ignored = ["cfg_aliases"] [lib] [features] -default = ["dx12", "metal", "gles", "vulkan", "wgsl", "webgpu"] +default = [ + "std", + "parking_lot", + "dx12", + "metal", + "gles", + "vulkan", + "wgsl", + "webgpu", +] #! ### Backends # -------------------------------------------------------------------- @@ -48,6 +57,7 @@ gles = ["wgpu-core?/gles"] ## Enables the WebGPU backend on WebAssembly. webgpu = [ + "web", "naga?/wgsl-out", "dep:wasm-bindgen-futures", "web-sys/Document", @@ -68,7 +78,7 @@ angle = ["wgpu-core?/angle"] vulkan-portability = ["wgpu-core?/vulkan-portability"] ## Enables the GLES backend on WebAssembly only. -webgl = ["wgpu-core/webgl", "dep:wgpu-hal", "dep:smallvec"] +webgl = ["web", "wgpu-core/webgl", "dep:wgpu-hal", "dep:smallvec"] ## Enables the noop backend for testing. ## @@ -76,7 +86,7 @@ webgl = ["wgpu-core/webgl", "dep:wgpu-hal", "dep:smallvec"] ## but performs no computation. ## Because it lacks basic functionality, it is only actually used if explicitly enabled ## through `NoopBackendOptions`. -noop = ["wgpu-core/noop"] +noop = ["wgpu-core/noop", "dep:wgpu-hal", "dep:smallvec"] #! **Note:** In the documentation, if you see that an item depends on a backend, #! it means that the item is only available when that backend is enabled _and_ the backend @@ -120,8 +130,8 @@ serde = ["wgpu-core?/serde", "wgpu-types/serde"] ## Enables statically linking DXC. ## -## Normally, to use the modern DXC shader compiler with WGPU, the final application -## must be shipped alongside `dxcompiler.dll` and `dxil.dll` (which can be downloaded from [Microsoft's GitHub][dxc]). +## Normally, to use the modern DXC shader compiler with wgpu, the final application +## must be shipped alongside `dxcompiler.dll` (min v1.8.2502) (which can be downloaded from [Microsoft's GitHub][dxc]). ## This feature statically links a version of DXC so that no external binaries are required ## to compile DX12 shaders. ## @@ -148,24 +158,44 @@ fragile-send-sync-non-atomic-wasm = [ "wgpu-types/fragile-send-sync-non-atomic-wasm", ] +## Use web-specific libraries on WASM +## +## Those libraties (wasm-bindgen, web-sys, js-sys) can only be used when there is a JavaScript +## context around the WASM VM, e.g., when the WASM binary is used in a browser. +web = ["dep:wasm-bindgen", "dep:js-sys", "dep:web-sys", "wgpu-types/web"] + +## Enables use of the standard library within `wgpu` and its dependencies. +## +## This can allow for better error reporting and for improved multithreading +## support. +std = ["raw-window-handle/std", "wgpu-types/std", "wgpu-core?/std"] + +## Uses `parking_lot` as the implementation for locking primitives. +## +## This is a recommended feature for most users and should only be disabled when +## required, e.g., for `no_std` support. +## If disabled, either `std::sync::Mutex` or `core::cell::RefCell` will be used, +## based on whether `std` is enabled or not. +parking_lot = ["dep:parking_lot"] + ######################### # Standard Dependencies # ######################### [dependencies] -naga = { workspace = true, optional = true } +naga = { workspace = true, optional = true, features = ["termcolor"] } wgpu-core = { workspace = true, optional = true } wgpu-types.workspace = true # Needed for both wgpu-core and webgpu arrayvec.workspace = true bitflags.workspace = true +cfg-if.workspace = true document-features.workspace = true -hashbrown.workspace = true log.workspace = true -parking_lot.workspace = true +parking_lot = { workspace = true, optional = true } profiling.workspace = true -raw-window-handle = { workspace = true, features = ["std"] } +raw-window-handle = { workspace = true, features = ["alloc"] } static_assertions.workspace = true ######################################## @@ -192,9 +222,9 @@ smallvec.workspace = true ############### [target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))'.dependencies] # Needed for all backends -js-sys = { workspace = true, features = ["default"] } -wasm-bindgen.workspace = true -web-sys = { workspace = true, features = [ +js-sys = { workspace = true, optional = true, features = ["default"] } +wasm-bindgen = { workspace = true, optional = true } +web-sys = { workspace = true, optional = true, features = [ "HtmlCanvasElement", "OffscreenCanvas", ] } diff --git a/wgpu/LICENSE.APACHE b/wgpu/LICENSE.APACHE deleted file mode 120000 index 7141cad5b..000000000 --- a/wgpu/LICENSE.APACHE +++ /dev/null @@ -1 +0,0 @@ -../LICENSE.APACHE \ No newline at end of file diff --git a/wgpu/LICENSE.APACHE b/wgpu/LICENSE.APACHE new file mode 100644 index 000000000..d9a10c0d8 --- /dev/null +++ b/wgpu/LICENSE.APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/wgpu/LICENSE.MIT b/wgpu/LICENSE.MIT deleted file mode 120000 index 6b8772d1a..000000000 --- a/wgpu/LICENSE.MIT +++ /dev/null @@ -1 +0,0 @@ -../LICENSE.MIT \ No newline at end of file diff --git a/wgpu/LICENSE.MIT b/wgpu/LICENSE.MIT new file mode 100644 index 000000000..8d02e4dbd --- /dev/null +++ b/wgpu/LICENSE.MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 The gfx-rs developers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/wgpu/build.rs b/wgpu/build.rs index c3f78fd53..9a039c265 100644 --- a/wgpu/build.rs +++ b/wgpu/build.rs @@ -2,6 +2,7 @@ fn main() { cfg_aliases::cfg_aliases! { native: { not(target_arch = "wasm32") }, Emscripten: { all(target_arch = "wasm32", target_os = "emscripten") }, + web: { all(target_arch = "wasm32", not(Emscripten), feature = "web") }, send_sync: { any( native, @@ -15,7 +16,7 @@ fn main() { metal: { all(target_vendor = "apple", feature = "metal") }, vulkan: { any( // The `vulkan` feature enables the Vulkan backend only on "native Vulkan" platforms, i.e. Windows/Linux/Android - all(any(windows, target_os = "linux", target_os = "android"), feature = "vulkan"), + all(any(windows, target_os = "linux", target_os = "android", target_os = "freebsd"), feature = "vulkan"), // On Apple platforms, however, we require the `vulkan-portability` feature // to explicitly opt-in to Vulkan since it's meant to be used with MoltenVK. all(target_vendor = "apple", feature = "vulkan-portability") @@ -23,7 +24,7 @@ fn main() { gles: { any( // The `gles` feature enables the OpenGL/GLES backend only on "native OpenGL" platforms, i.e. Windows, Linux, Android, and Emscripten. // (Note that WebGL is also not included here!) - all(any(windows, target_os = "linux", target_os = "android", Emscripten), feature = "gles"), + all(any(windows, target_os = "linux", target_os = "android", target_os = "freebsd", Emscripten), feature = "gles"), // On Apple platforms, however, we require the `angle` feature to explicitly opt-in to OpenGL // since its meant to be used with ANGLE. all(target_vendor = "apple", feature = "angle") @@ -46,6 +47,16 @@ fn main() { // ⚠️ Keep in sync with target.cfg() definition in wgpu-hal/Cargo.toml and cfg_alias in `wgpu-hal` crate ⚠️ static_dxc: { all(target_os = "windows", feature = "static-dxc", not(target_arch = "aarch64")) }, supports_64bit_atomics: { target_has_atomic = "64" }, - custom: {any(feature = "custom")} + custom: {any(feature = "custom")}, + std: { any( + feature = "std", + // TODO: Remove this when an alternative Mutex implementation is available for `no_std`. + // send_sync requires an appropriate Mutex implementation, which is only currently + // possible with `std` enabled. + send_sync, + // Unwinding panics necessitate access to `std` to determine if a thread is panicking + panic = "unwind" + ) }, + no_std: { not(std) } } } diff --git a/wgpu/src/api/adapter.rs b/wgpu/src/api/adapter.rs index 614f43bae..16abaacf1 100644 --- a/wgpu/src/api/adapter.rs +++ b/wgpu/src/api/adapter.rs @@ -1,4 +1,6 @@ use core::future::Future; +#[cfg(wgpu_core)] +use core::ops::Deref; use crate::*; @@ -43,11 +45,6 @@ impl Adapter { /// [`Adapter`]. /// However, `wgpu` does not currently enforce this restriction. /// - /// # Arguments - /// - /// - `desc` - Description of the features and limits requested from the given device. - /// - `trace` - Can be used for API call tracing, if the feature is enabled. - /// /// # Panics /// /// - `request_device()` was already called on this `Adapter`. @@ -69,14 +66,14 @@ impl Adapter { } } - /// Create a wgpu [`Device`] and [`Queue`] from a wgpu-hal `OpenDevice` + /// Create a wgpu [`Device`] and [`Queue`] from a wgpu-hal [`hal::OpenDevice`]. /// /// # Safety /// /// - `hal_device` must be created from this adapter internal handle. - /// - `desc.features` must be a subset of `hal_device` features. + /// - `desc.features` must be a subset of `hal_device`'s supported features. #[cfg(wgpu_core)] - pub unsafe fn create_device_from_hal( + pub unsafe fn create_device_from_hal( &self, hal_device: hal::OpenDevice, desc: &DeviceDescriptor<'_>, @@ -98,39 +95,50 @@ impl Adapter { )) } - /// Apply a callback to this `Adapter`'s underlying backend adapter. + /// Get the [`wgpu_hal`] adapter from this `Adapter`. /// - /// If this `Adapter` is implemented by the backend API given by `A` (Vulkan, - /// Dx12, etc.), then apply `hal_adapter_callback` to `Some(&adapter)`, where - /// `adapter` is the underlying backend adapter type, [`A::Adapter`]. + /// Find the Api struct corresponding to the active backend in [`wgpu_hal::api`], + /// and pass that struct to the to the `A` type parameter. /// - /// If this `Adapter` uses a different backend, apply `hal_adapter_callback` - /// to `None`. + /// Returns a guard that dereferences to the type of the hal backend + /// which implements [`A::Adapter`]. /// - /// The adapter is locked for reading while `hal_adapter_callback` runs. If - /// the callback attempts to perform any `wgpu` operations that require - /// write access to the adapter, deadlock will occur. The locks are - /// automatically released when the callback returns. + /// # Types + /// + /// The returned type depends on the backend: + /// + #[doc = crate::hal_type_vulkan!("Adapter")] + #[doc = crate::hal_type_metal!("Adapter")] + #[doc = crate::hal_type_dx12!("Adapter")] + #[doc = crate::hal_type_gles!("Adapter")] + /// + /// # Errors + /// + /// This method will return None if: + /// - The adapter is not from the backend specified by `A`. + /// - The adapter is from the `webgpu` or `custom` backend. /// /// # Safety /// - /// - The raw handle passed to the callback must not be manually destroyed. + /// - The returned resource must not be destroyed unless the guard + /// is the last reference to it and it is not in use by the GPU. + /// The guard and handle may be dropped at any time however. + /// - All the safety requirements of wgpu-hal must be upheld. /// /// [`A::Adapter`]: hal::Api::Adapter #[cfg(wgpu_core)] - pub unsafe fn as_hal) -> R, R>( + pub unsafe fn as_hal( &self, - hal_adapter_callback: F, - ) -> R { - if let Some(adapter) = self.inner.as_core_opt() { - unsafe { - adapter - .context - .adapter_as_hal::(adapter, hal_adapter_callback) - } - } else { - hal_adapter_callback(None) - } + ) -> Option + WasmNotSendSync> { + let adapter = self.inner.as_core_opt()?; + + unsafe { adapter.context.adapter_as_hal::(adapter) } + } + + #[cfg(custom)] + /// Returns custom implementation of adapter (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() } #[cfg(custom)] diff --git a/wgpu/src/api/bind_group.rs b/wgpu/src/api/bind_group.rs index d9c27bdc4..8471fca53 100644 --- a/wgpu/src/api/bind_group.rs +++ b/wgpu/src/api/bind_group.rs @@ -17,6 +17,14 @@ static_assertions::assert_impl_all!(BindGroup: Send, Sync); crate::cmp::impl_eq_ord_hash_proxy!(BindGroup => .inner); +impl BindGroup { + #[cfg(custom)] + /// Returns custom implementation of BindGroup (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() + } +} + /// Resource to be bound by a [`BindGroup`] for use with a pipeline. /// /// The pipeline’s [`BindGroupLayout`] must contain a matching [`BindingType`]. @@ -73,6 +81,12 @@ pub enum BindingResource<'a> { /// built using `build_acceleration_structures` a validation error is generated otherwise this is a part of the /// safety section of `build_acceleration_structures_unsafe_tlas` and so undefined behavior occurs. AccelerationStructure(&'a Tlas), + /// Binding is backed by an external texture. + /// + /// [`Features::EXTERNAL_TEXTURE`] must be supported to use this feature. + /// + /// Corresponds to [`wgt::BindingType::ExternalTexture`]. + ExternalTexture(&'a ExternalTexture), } #[cfg(send_sync)] static_assertions::assert_impl_all!(BindingResource<'_>: Send, Sync); diff --git a/wgpu/src/api/bind_group_layout.rs b/wgpu/src/api/bind_group_layout.rs index a55921ccc..62eb7dd41 100644 --- a/wgpu/src/api/bind_group_layout.rs +++ b/wgpu/src/api/bind_group_layout.rs @@ -20,6 +20,14 @@ static_assertions::assert_impl_all!(BindGroupLayout: Send, Sync); crate::cmp::impl_eq_ord_hash_proxy!(BindGroupLayout => .inner); +impl BindGroupLayout { + #[cfg(custom)] + /// Returns custom implementation of BindGroupLayout (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() + } +} + /// Describes a [`BindGroupLayout`]. /// /// For use with [`Device::create_bind_group_layout`]. diff --git a/wgpu/src/api/blas.rs b/wgpu/src/api/blas.rs index 67798487d..5f884e164 100644 --- a/wgpu/src/api/blas.rs +++ b/wgpu/src/api/blas.rs @@ -1,6 +1,9 @@ +#[cfg(wgpu_core)] +use core::ops::Deref; + use alloc::{boxed::Box, vec::Vec}; -use wgt::WasmNotSendSync; +use wgt::{WasmNotSend, WasmNotSendSync}; use crate::dispatch; use crate::{Buffer, Label}; @@ -31,7 +34,7 @@ static_assertions::assert_impl_all!(CreateBlasDescriptor<'_>: Send, Sync); /// Safe instance for a [Tlas]. /// -/// A TlasInstance may be made invalid, if a TlasInstance is invalid, any attempt to build a [TlasPackage] containing an +/// A TlasInstance may be made invalid, if a TlasInstance is invalid, any attempt to build a [Tlas] containing an /// invalid TlasInstance will generate a validation error /// /// Each one contains: @@ -42,7 +45,6 @@ static_assertions::assert_impl_all!(CreateBlasDescriptor<'_>: Send, Sync); /// - A user accessible custom index /// /// [Tlas]: crate::Tlas -/// [TlasPackage]: crate::TlasPackage #[derive(Debug, Clone)] pub struct TlasInstance { pub(crate) blas: dispatch::DispatchBlas, @@ -100,7 +102,8 @@ pub struct BlasTriangleGeometry<'a> { pub vertex_buffer: &'a Buffer, /// Offset into the vertex buffer as a factor of the vertex stride. pub first_vertex: u32, - /// Vertex stride. + /// Vertex stride, must be greater than [`wgpu_types::VertexFormat::min_acceleration_structure_vertex_stride`] + /// of the format and must be a multiple of [`wgpu_types::VertexFormat::acceleration_structure_stride_alignment`]. pub vertex_stride: wgt::BufferAddress, /// Index buffer (optional). pub index_buffer: Option<&'a Buffer>, @@ -150,6 +153,57 @@ impl Blas { pub fn handle(&self) -> Option { self.handle } + + /// Get the [`wgpu_hal`] acceleration structure from this `Blas`. + /// + /// Find the Api struct corresponding to the active backend in [`wgpu_hal::api`], + /// and pass that struct to the to the `A` type parameter. + /// + /// Returns a guard that dereferences to the type of the hal backend + /// which implements [`A::AccelerationStructure`]. + /// + /// # Types + /// + /// The returned type depends on the backend: + /// + #[doc = crate::hal_type_vulkan!("AccelerationStructure")] + #[doc = crate::hal_type_metal!("AccelerationStructure")] + #[doc = crate::hal_type_dx12!("AccelerationStructure")] + #[doc = crate::hal_type_gles!("AccelerationStructure")] + /// + /// # Deadlocks + /// + /// - The returned guard holds a read-lock on a device-local "destruction" + /// lock, which will cause all calls to `destroy` to block until the + /// guard is released. + /// + /// # Errors + /// + /// This method will return None if: + /// - The acceleration structure is not from the backend specified by `A`. + /// - The acceleration structure is from the `webgpu` or `custom` backend. + /// + /// # Safety + /// + /// - The returned resource must not be destroyed unless the guard + /// is the last reference to it and it is not in use by the GPU. + /// The guard and handle may be dropped at any time however. + /// - All the safety requirements of wgpu-hal must be upheld. + /// + /// [`A::AccelerationStructure`]: hal::Api::AccelerationStructure + #[cfg(wgpu_core)] + pub unsafe fn as_hal( + &mut self, + ) -> Option + WasmNotSendSync> { + let blas = self.inner.as_core_opt()?; + unsafe { blas.context.blas_as_hal::(blas) } + } + + #[cfg(custom)] + /// Returns custom implementation of Blas (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() + } } /// Context version of [BlasTriangleGeometry]. @@ -185,3 +239,48 @@ pub struct ContextBlasBuildEntry<'a> { #[expect(dead_code)] pub(crate) geometries: ContextBlasGeometries<'a>, } + +/// Error occurred when trying to asynchronously prepare a blas for compaction. +#[derive(Clone, PartialEq, Eq, Debug)] +pub struct BlasAsyncError; +static_assertions::assert_impl_all!(BlasAsyncError: Send, Sync); + +impl core::fmt::Display for BlasAsyncError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!( + f, + "Error occurred when trying to asynchronously prepare a blas for compaction" + ) + } +} + +impl core::error::Error for BlasAsyncError {} + +impl Blas { + /// Asynchronously prepares this BLAS for compaction. The callback is called once all builds + /// using this BLAS are finished and the BLAS is compactable. This can be checked using + /// [`Blas::ready_for_compaction`]. Rebuilding this BLAS will reset its compacted state, and it + /// will need to be prepared again. + /// + /// ### Interaction with other functions + /// On native, `queue.submit(..)` and polling devices (that is calling `instance.poll_all` or + /// `device.poll`) with [`PollType::Poll`] may call the callback. On native, polling devices with + /// [`PollType::Wait`] (optionally with a submission index greater + /// than the last submit the BLAS was used in) will guarantee callback is called. + /// + /// [`PollType::Poll`]: wgpu_types::PollType::Poll + /// [`PollType::Wait`]: wgpu_types::PollType::Wait + pub fn prepare_compaction_async( + &self, + callback: impl FnOnce(Result<(), BlasAsyncError>) + WasmNotSend + 'static, + ) { + self.inner.prepare_compact_async(Box::new(callback)); + } + + /// Checks whether this BLAS is ready for compaction. The returned value is `true` if + /// [`Blas::prepare_compaction_async`]'s callback was called with a non-error value, otherwise + /// this is `false`. + pub fn ready_for_compaction(&self) -> bool { + self.inner.ready_for_compaction() + } +} diff --git a/wgpu/src/api/buffer.rs b/wgpu/src/api/buffer.rs index 089c743a0..afab2cf1c 100644 --- a/wgpu/src/api/buffer.rs +++ b/wgpu/src/api/buffer.rs @@ -4,16 +4,18 @@ use core::{ ops::{Bound, Deref, DerefMut, Range, RangeBounds}, }; -use parking_lot::Mutex; - +use crate::util::Mutex; use crate::*; /// Handle to a GPU-accessible buffer. /// -/// Created with [`Device::create_buffer`] or -/// [`DeviceExt::create_buffer_init`](util::DeviceExt::create_buffer_init). -/// -/// Corresponds to [WebGPU `GPUBuffer`](https://gpuweb.github.io/gpuweb/#buffer-interface). +/// A `Buffer` is a memory allocation for use by the GPU, somewhat analogous to +/// [Box]<[\[u8\]][primitive@slice]> in Rust. +/// The contents of buffers are untyped bytes; it is up to the application to +/// specify the interpretation of the bytes when the buffer is used, in ways +/// such as [`VertexBufferLayout`]. +/// A single buffer can be used to hold multiple independent pieces of data at +/// different offsets (e.g. both vertices and indices for one or more meshes). /// /// A `Buffer`'s bytes have "interior mutability": functions like /// [`Queue::write_buffer`] or [mapping] a buffer for writing only require a @@ -21,8 +23,49 @@ use crate::*; /// prevents simultaneous reads and writes of buffer contents using run-time /// checks. /// +/// Created with [`Device::create_buffer()`] or +/// [`DeviceExt::create_buffer_init()`]. +/// +/// Corresponds to [WebGPU `GPUBuffer`](https://gpuweb.github.io/gpuweb/#buffer-interface). +/// /// [mapping]: Buffer#mapping-buffers /// +/// # How to get your data into a buffer +/// +/// Every `Buffer` starts with all bytes zeroed. +/// There are many ways to load data into a `Buffer`: +/// +/// - When creating a buffer, you may set the [`mapped_at_creation`][mac] flag, +/// then write to its [`get_mapped_range_mut()`][Buffer::get_mapped_range_mut]. +/// This only works when the buffer is created and has not yet been used by +/// the GPU, but it is all you need for buffers whose contents do not change +/// after creation. +/// - You may use [`DeviceExt::create_buffer_init()`] as a convenient way to +/// do that and copy data from a `&[u8]` you provide. +/// - After creation, you may use [`Buffer::map_async()`] to map it again; +/// however, you then need to wait until the GPU is no longer using the buffer +/// before you begin writing. +/// - You may use [`CommandEncoder::copy_buffer_to_buffer()`] to copy data into +/// this buffer from another buffer. +/// - You may use [`Queue::write_buffer()`] to copy data into the buffer from a +/// `&[u8]`. This uses a temporary “staging” buffer managed by `wgpu` to hold +/// the data. +/// - [`Queue::write_buffer_with()`] allows you to write directly into temporary +/// storage instead of providing a slice you already prepared, which may +/// allow *your* code to save the allocation of a [`Vec`] or such. +/// - You may use [`util::StagingBelt`] to manage a set of temporary buffers. +/// This may be more efficient than [`Queue::write_buffer_with()`] when you +/// have many small copies to perform, but requires more steps to use, and +/// tuning of the belt buffer size. +/// - You may write your own staging buffer management customized to your +/// application, based on mapped buffers and +/// [`CommandEncoder::copy_buffer_to_buffer()`]. +/// - A GPU computation’s results can be stored in a buffer: +/// - A [compute shader][ComputePipeline] may write to a buffer bound as a +/// [storage buffer][BufferBindingType::Storage]. +/// - A render pass may render to a texture which is then copied to a buffer +/// using [`CommandEncoder::copy_texture_to_buffer()`]. +/// /// # Mapping buffers /// /// If a `Buffer` is created with the appropriate [`usage`], it can be *mapped*: @@ -173,6 +216,7 @@ use crate::*; /// [mac]: BufferDescriptor::mapped_at_creation /// [`MAP_READ`]: BufferUsages::MAP_READ /// [`MAP_WRITE`]: BufferUsages::MAP_WRITE +/// [`DeviceExt::create_buffer_init()`]: util::DeviceExt::create_buffer_init #[derive(Debug, Clone)] pub struct Buffer { pub(crate) inner: dispatch::DispatchBuffer, @@ -201,26 +245,50 @@ impl Buffer { } } - /// Returns the inner hal Buffer using a callback. The hal buffer will be `None` if the - /// backend type argument does not match with this wgpu Buffer + /// Get the [`wgpu_hal`] buffer from this `Buffer`. + /// + /// Find the Api struct corresponding to the active backend in [`wgpu_hal::api`], + /// and pass that struct to the to the `A` type parameter. + /// + /// Returns a guard that dereferences to the type of the hal backend + /// which implements [`A::Buffer`]. + /// + /// # Types + /// + /// The returned type depends on the backend: + /// + #[doc = crate::hal_type_vulkan!("Buffer")] + #[doc = crate::hal_type_metal!("Buffer")] + #[doc = crate::hal_type_dx12!("Buffer")] + #[doc = crate::hal_type_gles!("Buffer")] + /// + /// # Deadlocks + /// + /// - The returned guard holds a read-lock on a device-local "destruction" + /// lock, which will cause all calls to `destroy` to block until the + /// guard is released. + /// + /// # Errors + /// + /// This method will return None if: + /// - The buffer is not from the backend specified by `A`. + /// - The buffer is from the `webgpu` or `custom` backend. + /// - The buffer has had [`Self::destroy()`] called on it. /// /// # Safety /// - /// - The raw handle obtained from the hal Buffer must not be manually destroyed + /// - The returned resource must not be destroyed unless the guard + /// is the last reference to it and it is not in use by the GPU. + /// The guard and handle may be dropped at any time however. + /// - All the safety requirements of wgpu-hal must be upheld. + /// + /// [`A::Buffer`]: hal::Api::Buffer #[cfg(wgpu_core)] - pub unsafe fn as_hal) -> R, R>( + pub unsafe fn as_hal( &self, - hal_buffer_callback: F, - ) -> R { - if let Some(buffer) = self.inner.as_core_opt() { - unsafe { - buffer - .context - .buffer_as_hal::(buffer, hal_buffer_callback) - } - } else { - hal_buffer_callback(None) - } + ) -> Option + WasmNotSendSync> { + let buffer = self.inner.as_core_opt()?; + unsafe { buffer.context.buffer_as_hal::(buffer) } } /// Returns a [`BufferSlice`] referring to the portion of `self`'s contents @@ -240,8 +308,9 @@ impl Buffer { /// /// - If `bounds` is outside of the bounds of `self`. /// - If `bounds` has a length less than 1. + #[track_caller] pub fn slice>(&self, bounds: S) -> BufferSlice<'_> { - let (offset, size) = range_to_offset_size(bounds); + let (offset, size) = range_to_offset_size(bounds, self.size); check_buffer_bounds(self.size, offset, size); BufferSlice { buffer: self, @@ -278,20 +347,28 @@ impl Buffer { self.usage } - /// Map the buffer to host (CPU) memory, making it available for reading or writing - /// via [`get_mapped_range()`](Self::get_mapped_range). - /// It is available once the `callback` is called with an [`Ok`] response. + /// Map the buffer to host (CPU) memory, making it available for reading or writing via + /// [`get_mapped_range()`](Self::get_mapped_range). The buffer becomes accessible once the + /// `callback` is invoked with [`Ok`]. /// - /// For the callback to complete, either `queue.submit(..)`, `instance.poll_all(..)`, or `device.poll(..)` - /// must be called elsewhere in the runtime, possibly integrated into an event loop or run on a separate thread. + /// Use this when you want to map the buffer immediately. If you need to submit GPU work that + /// uses the buffer before mapping it, use `map_buffer_on_submit` on + /// [`CommandEncoder`][CEmbos], [`CommandBuffer`][CBmbos], [`RenderPass`][RPmbos], or + /// [`ComputePass`][CPmbos] to schedule the mapping after submission. This avoids extra calls to + /// [`Buffer::map_async()`] or [`BufferSlice::map_async()`] and lets you initiate mapping from a + /// more convenient place. /// - /// The callback will be called on the thread that first calls the above functions after the GPU work - /// has completed. There are no restrictions on the code you can run in the callback, however on native the - /// call to the function will not complete until the callback returns, so prefer keeping callbacks short - /// and used to set flags, send messages, etc. + /// For the callback to run, either [`queue.submit(..)`][q::s], [`instance.poll_all(..)`][i::p_a], + /// or [`device.poll(..)`][d::p] must be called elsewhere in the runtime, possibly integrated into + /// an event loop or run on a separate thread. /// - /// As long as a buffer is mapped, it is not available for use by any other commands; - /// at all times, either the GPU or the CPU has exclusive access to the contents of the buffer. + /// The callback runs on the thread that first calls one of the above functions after the GPU work + /// completes. There are no restrictions on the code you can run in the callback; however, on native + /// the polling call will not return until the callback finishes, so keep callbacks short (set flags, + /// send messages, etc.). + /// + /// While a buffer is mapped, it cannot be used by other commands; at any time, either the GPU or + /// the CPU has exclusive access to the buffer’s contents. /// /// This can also be performed using [`BufferSlice::map_async()`]. /// @@ -300,8 +377,16 @@ impl Buffer { /// - If the buffer is already mapped. /// - If the buffer’s [`BufferUsages`] do not allow the requested [`MapMode`]. /// - If `bounds` is outside of the bounds of `self`. - /// - If `bounds` has a length less than 1. - /// - If the start and end of `bounds` are not be aligned to [`MAP_ALIGNMENT`]. + /// - If `bounds` does not start at a multiple of [`MAP_ALIGNMENT`]. + /// - If `bounds` has a length that is not a multiple of 4 greater than 0. + /// + /// [CEmbos]: CommandEncoder::map_buffer_on_submit + /// [CBmbos]: CommandBuffer::map_buffer_on_submit + /// [RPmbos]: RenderPass::map_buffer_on_submit + /// [CPmbos]: ComputePass::map_buffer_on_submit + /// [q::s]: Queue::submit + /// [i::p_a]: Instance::poll_all + /// [d::p]: Device::poll pub fn map_async>( &self, mode: MapMode, @@ -324,43 +409,17 @@ impl Buffer { /// # Panics /// /// - If `bounds` is outside of the bounds of `self`. - /// - If `bounds` has a length less than 1. - /// - If the start and end of `bounds` are not aligned to [`MAP_ALIGNMENT`]. + /// - If `bounds` does not start at a multiple of [`MAP_ALIGNMENT`]. + /// - If `bounds` has a length that is not a multiple of 4 greater than 0. /// - If the buffer to which `self` refers is not currently [mapped]. - /// - If you try to create overlapping views of a buffer, mutable or otherwise. + /// - If you try to create a view which overlaps an existing [`BufferViewMut`]. /// /// [mapped]: Buffer#mapping-buffers - pub fn get_mapped_range>(&self, bounds: S) -> BufferView<'_> { + #[track_caller] + pub fn get_mapped_range>(&self, bounds: S) -> BufferView { self.slice(bounds).get_mapped_range() } - /// Synchronously and immediately map a buffer for reading. If the buffer is not immediately mappable - /// through [`BufferDescriptor::mapped_at_creation`] or [`BufferSlice::map_async`], will fail. - /// - /// This is useful when targeting WebGPU and you want to pass mapped data directly to js. - /// Unlike `get_mapped_range` which unconditionally copies mapped data into the wasm heap, - /// this function directly hands you the ArrayBuffer that we mapped the data into in js. - /// - /// This is only available on WebGPU, on any other backends this will return `None`. - /// - /// `bounds` may be less than the bounds passed to [`Self::map_async()`], - /// and multiple views may be obtained and used simultaneously as long as they do not overlap. - /// - /// This can also be performed using [`BufferSlice::get_mapped_range_as_array_buffer()`]. - /// - /// # Panics - /// - /// - If `bounds` is outside of the bounds of `self`. - /// - If `bounds` has a length less than 1. - /// - If the start and end of `bounds` are not aligned to [`MAP_ALIGNMENT`]. - #[cfg(webgpu)] - pub fn get_mapped_range_as_array_buffer>( - &self, - bounds: S, - ) -> Option { - self.slice(bounds).get_mapped_range_as_array_buffer() - } - /// Gain write access to the bytes of a [mapped] [`Buffer`]. /// /// Returns a [`BufferViewMut`] referring to the buffer range represented by @@ -374,18 +433,22 @@ impl Buffer { /// # Panics /// /// - If `bounds` is outside of the bounds of `self`. - /// - If `bounds` has a length less than 1. - /// - If the start and end of `bounds` are not aligned to [`MAP_ALIGNMENT`]. + /// - If `bounds` does not start at a multiple of [`MAP_ALIGNMENT`]. + /// - If `bounds` has a length that is not a multiple of 4 greater than 0. /// - If the buffer to which `self` refers is not currently [mapped]. - /// - If you try to create overlapping views of a buffer, mutable or otherwise. + /// - If you try to create a view which overlaps an existing [`BufferView`] or [`BufferViewMut`]. /// /// [mapped]: Buffer#mapping-buffers - pub fn get_mapped_range_mut>( - &self, - bounds: S, - ) -> BufferViewMut<'_> { + #[track_caller] + pub fn get_mapped_range_mut>(&self, bounds: S) -> BufferViewMut { self.slice(bounds).get_mapped_range_mut() } + + #[cfg(custom)] + /// Returns custom implementation of Buffer (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() + } } /// A slice of a [`Buffer`], to be mapped, used for vertex or index data, or the like. @@ -432,7 +495,7 @@ impl Buffer { pub struct BufferSlice<'a> { pub(crate) buffer: &'a Buffer, pub(crate) offset: BufferAddress, - pub(crate) size: Option, + pub(crate) size: BufferSize, } #[cfg(send_sync)] static_assertions::assert_impl_all!(BufferSlice<'_>: Send, Sync); @@ -450,37 +513,39 @@ impl<'a> BufferSlice<'a> { /// /// - If `bounds` is outside of the bounds of `self`. /// - If `bounds` has a length less than 1. + #[track_caller] pub fn slice>(&self, bounds: S) -> BufferSlice<'a> { - let (offset, size) = range_to_offset_size(bounds); - check_buffer_bounds( - match self.size { - Some(size) => size.get(), - None => self.buffer.size(), - }, - offset, - size, - ); + let (offset, size) = range_to_offset_size(bounds, self.size.get()); + check_buffer_bounds(self.size.get(), offset, size); BufferSlice { buffer: self.buffer, offset: self.offset + offset, // check_buffer_bounds ensures this does not overflow - size: size.or(self.size), // check_buffer_bounds ensures this is essentially min() + size, // check_buffer_bounds ensures this is essentially min() } } - /// Map the buffer to host (CPU) memory, making it available for reading or writing - /// via [`get_mapped_range()`](Self::get_mapped_range). - /// It is available once the `callback` is called with an [`Ok`] response. + /// Map the buffer to host (CPU) memory, making it available for reading or writing via + /// [`get_mapped_range()`](Self::get_mapped_range). The buffer becomes accessible once the + /// `callback` is invoked with [`Ok`]. /// - /// For the callback to complete, either `queue.submit(..)`, `instance.poll_all(..)`, or `device.poll(..)` - /// must be called elsewhere in the runtime, possibly integrated into an event loop or run on a separate thread. + /// Use this when you want to map the buffer immediately. If you need to submit GPU work that + /// uses the buffer before mapping it, use `map_buffer_on_submit` on + /// [`CommandEncoder`][CEmbos], [`CommandBuffer`][CBmbos], [`RenderPass`][RPmbos], or + /// [`ComputePass`][CPmbos] to schedule the mapping after submission. This avoids extra calls to + /// [`Buffer::map_async()`] or [`BufferSlice::map_async()`] and lets you initiate mapping from a + /// more convenient place. /// - /// The callback will be called on the thread that first calls the above functions after the GPU work - /// has completed. There are no restrictions on the code you can run in the callback, however on native the - /// call to the function will not complete until the callback returns, so prefer keeping callbacks short - /// and used to set flags, send messages, etc. + /// For the callback to run, either [`queue.submit(..)`][q::s], [`instance.poll_all(..)`][i::p_a], + /// or [`device.poll(..)`][d::p] must be called elsewhere in the runtime, possibly integrated into + /// an event loop or run on a separate thread. /// - /// As long as a buffer is mapped, it is not available for use by any other commands; - /// at all times, either the GPU or the CPU has exclusive access to the contents of the buffer. + /// The callback runs on the thread that first calls one of the above functions after the GPU work + /// completes. There are no restrictions on the code you can run in the callback; however, on native + /// the polling call will not return until the callback finishes, so keep callbacks short (set flags, + /// send messages, etc.). + /// + /// While a buffer is mapped, it cannot be used by other commands; at any time, either the GPU or + /// the CPU has exclusive access to the buffer’s contents. /// /// This can also be performed using [`Buffer::map_async()`]. /// @@ -488,19 +553,25 @@ impl<'a> BufferSlice<'a> { /// /// - If the buffer is already mapped. /// - If the buffer’s [`BufferUsages`] do not allow the requested [`MapMode`]. - /// - If the endpoints of this slice are not aligned to [`MAP_ALIGNMENT`] within the buffer. + /// - If the beginning of this slice is not aligned to [`MAP_ALIGNMENT`] within the buffer. + /// - If the length of this slice is not a multiple of 4. + /// + /// [CEmbos]: CommandEncoder::map_buffer_on_submit + /// [CBmbos]: CommandBuffer::map_buffer_on_submit + /// [RPmbos]: RenderPass::map_buffer_on_submit + /// [CPmbos]: ComputePass::map_buffer_on_submit + /// [q::s]: Queue::submit + /// [i::p_a]: Instance::poll_all + /// [d::p]: Device::poll pub fn map_async( &self, mode: MapMode, callback: impl FnOnce(Result<(), BufferAsyncError>) + WasmNotSend + 'static, ) { let mut mc = self.buffer.map_context.lock(); - assert_eq!(mc.initial_range, 0..0, "Buffer is already mapped"); - let end = match self.size { - Some(s) => self.offset + s.get(), - None => mc.total_size, - }; - mc.initial_range = self.offset..end; + assert_eq!(mc.mapped_range, 0..0, "Buffer is already mapped"); + let end = self.offset + self.size.get(); + mc.mapped_range = self.offset..end; self.buffer .inner @@ -519,46 +590,28 @@ impl<'a> BufferSlice<'a> { /// /// # Panics /// - /// - If the endpoints of this slice are not aligned to [`MAP_ALIGNMENT`] within the buffer. + /// - If the beginning of this slice is not aligned to [`MAP_ALIGNMENT`] within the buffer. + /// - If the length of this slice is not a multiple of 4. /// - If the buffer to which `self` refers is not currently [mapped]. - /// - If you try to create overlapping views of a buffer, mutable or otherwise. + /// - If you try to create a view which overlaps an existing [`BufferViewMut`]. /// /// [mapped]: Buffer#mapping-buffers - pub fn get_mapped_range(&self) -> BufferView<'a> { - let end = self.buffer.map_context.lock().add(self.offset, self.size); - let range = self.buffer.inner.get_mapped_range(self.offset..end); + #[track_caller] + pub fn get_mapped_range(&self) -> BufferView { + let subrange = Subrange::new(self.offset, self.size, RangeMappingKind::Immutable); + self.buffer + .map_context + .lock() + .validate_and_add(subrange.clone()); + let range = self.buffer.inner.get_mapped_range(subrange.index); BufferView { - slice: *self, + buffer: self.buffer.clone(), + size: self.size, + offset: self.offset, inner: range, } } - /// Synchronously and immediately map a buffer for reading. If the buffer is not immediately mappable - /// through [`BufferDescriptor::mapped_at_creation`] or [`BufferSlice::map_async`], will fail. - /// - /// This is useful when targeting WebGPU and you want to pass mapped data directly to js. - /// Unlike `get_mapped_range` which unconditionally copies mapped data into the wasm heap, - /// this function directly hands you the ArrayBuffer that we mapped the data into in js. - /// - /// This is only available on WebGPU, on any other backends this will return `None`. - /// - /// Multiple views may be obtained and used simultaneously as long as they are from - /// non-overlapping slices. - /// - /// This can also be performed using [`Buffer::get_mapped_range_as_array_buffer()`]. - /// - /// # Panics - /// - /// - If the endpoints of this slice are not aligned to [`MAP_ALIGNMENT`] within the buffer. - #[cfg(webgpu)] - pub fn get_mapped_range_as_array_buffer(&self) -> Option { - let end = self.buffer.map_context.lock().add(self.offset, self.size); - - self.buffer - .inner - .get_mapped_range_as_array_buffer(self.offset..end) - } - /// Gain write access to the bytes of a [mapped] [`Buffer`]. /// /// Returns a [`BufferViewMut`] referring to the buffer range represented by @@ -571,16 +624,24 @@ impl<'a> BufferSlice<'a> { /// /// # Panics /// - /// - If the endpoints of this slice are not aligned to [`MAP_ALIGNMENT`]. + /// - If the beginning of this slice is not aligned to [`MAP_ALIGNMENT`] within the buffer. + /// - If the length of this slice is not a multiple of 4. /// - If the buffer to which `self` refers is not currently [mapped]. - /// - If you try to create overlapping views of a buffer, mutable or otherwise. + /// - If you try to create a view which overlaps an existing [`BufferView`] or [`BufferViewMut`]. /// /// [mapped]: Buffer#mapping-buffers - pub fn get_mapped_range_mut(&self) -> BufferViewMut<'a> { - let end = self.buffer.map_context.lock().add(self.offset, self.size); - let range = self.buffer.inner.get_mapped_range(self.offset..end); + #[track_caller] + pub fn get_mapped_range_mut(&self) -> BufferViewMut { + let subrange = Subrange::new(self.offset, self.size, RangeMappingKind::Mutable); + self.buffer + .map_context + .lock() + .validate_and_add(subrange.clone()); + let range = self.buffer.inner.get_mapped_range(subrange.index); BufferViewMut { - slice: *self, + buffer: self.buffer.clone(), + size: self.size, + offset: self.offset, inner: range, readable: self.buffer.usage.contains(BufferUsages::MAP_READ), } @@ -602,10 +663,7 @@ impl<'a> BufferSlice<'a> { /// Returns the size of this slice. pub fn size(&self) -> BufferSize { - self.size.unwrap_or_else(|| { - (|| BufferSize::new(self.buffer.size().checked_sub(self.offset)?))() - .expect("can't happen: slice has incorrect size for its buffer") - }) + self.size } } @@ -616,7 +674,7 @@ impl<'a> From> for crate::BufferBinding<'a> { BufferBinding { buffer: value.buffer, offset: value.offset, - size: value.size, + size: Some(value.size), } } } @@ -629,18 +687,62 @@ impl<'a> From> for crate::BindingResource<'a> { } } +fn range_overlaps(a: &Range, b: &Range) -> bool { + a.start < b.end && b.start < a.end +} + +fn range_contains(a: &Range, b: &Range) -> bool { + a.start <= b.start && a.end >= b.end +} + +#[derive(Debug, Copy, Clone)] +enum RangeMappingKind { + Mutable, + Immutable, +} + +impl RangeMappingKind { + /// Returns true if a range of this kind can touch the same bytes as a range of the other kind. + /// + /// This is Rust's Mutable XOR Shared rule. + fn allowed_concurrently_with(self, other: Self) -> bool { + matches!( + (self, other), + (RangeMappingKind::Immutable, RangeMappingKind::Immutable) + ) + } +} + +#[derive(Debug, Clone)] +struct Subrange { + index: Range, + kind: RangeMappingKind, +} + +impl Subrange { + fn new(offset: BufferAddress, size: BufferSize, kind: RangeMappingKind) -> Self { + Self { + index: offset..(offset + size.get()), + kind, + } + } +} + +impl fmt::Display for Subrange { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{}..{} ({:?})", + self.index.start, self.index.end, self.kind + ) + } +} + /// The mapped portion of a buffer, if any, and its outstanding views. /// -/// This ensures that views fall within the mapped range and don't overlap, and -/// also takes care of turning `Option` sizes into actual buffer -/// offsets. +/// This ensures that views fall within the mapped range and don't overlap. #[derive(Debug)] pub(crate) struct MapContext { - /// The overall size of the buffer. - /// - /// This is just a convenient copy of [`Buffer::size`]. - pub(crate) total_size: BufferAddress, - /// The range of the buffer that is mapped. /// /// This is `0..0` if the buffer is not mapped. This becomes non-empty when @@ -649,26 +751,31 @@ pub(crate) struct MapContext { /// *or has been requested to be* mapped.) /// /// All [`BufferView`]s and [`BufferViewMut`]s must fall within this range. - pub(crate) initial_range: Range, + mapped_range: Range, /// The ranges covered by all outstanding [`BufferView`]s and /// [`BufferViewMut`]s. These are non-overlapping, and are all contained - /// within `initial_range`. - sub_ranges: Vec>, + /// within `mapped_range`. + sub_ranges: Vec, } impl MapContext { - pub(crate) fn new(total_size: BufferAddress) -> Self { + /// Creates a new `MapContext`. + /// + /// For [`mapped_at_creation`] buffers, pass the full buffer range in the + /// `mapped_range` argument. For other buffers, pass `None`. + /// + /// [`mapped_at_creation`]: BufferDescriptor::mapped_at_creation + pub(crate) fn new(mapped_range: Option>) -> Self { Self { - total_size, - initial_range: 0..0, + mapped_range: mapped_range.unwrap_or(0..0), sub_ranges: Vec::new(), } } /// Record that the buffer is no longer mapped. fn reset(&mut self) { - self.initial_range = 0..0; + self.mapped_range = 0..0; assert!( self.sub_ranges.is_empty(), @@ -678,28 +785,38 @@ impl MapContext { /// Record that the `size` bytes of the buffer at `offset` are now viewed. /// - /// Return the byte offset within the buffer of the end of the viewed range. - /// /// # Panics /// - /// This panics if the given range overlaps with any existing range. - fn add(&mut self, offset: BufferAddress, size: Option) -> BufferAddress { - let end = match size { - Some(s) => offset + s.get(), - None => self.initial_range.end, - }; - assert!(self.initial_range.start <= offset && end <= self.initial_range.end); + /// This panics if the given range is invalid. + #[track_caller] + fn validate_and_add(&mut self, new_sub: Subrange) { + if self.mapped_range.is_empty() { + panic!("tried to call get_mapped_range(_mut) on an unmapped buffer"); + } + if !range_contains(&self.mapped_range, &new_sub.index) { + panic!( + "tried to call get_mapped_range(_mut) on a range that is not entirely mapped. \ + Attempted to get range {}, but the mapped range is {}..{}", + new_sub, self.mapped_range.start, self.mapped_range.end + ); + } + // This check is essential for avoiding undefined behavior: it is the // only thing that ensures that `&mut` references to the buffer's // contents don't alias anything else. for sub in self.sub_ranges.iter() { - assert!( - end <= sub.start || offset >= sub.end, - "Intersecting map range with {sub:?}" - ); + if range_overlaps(&sub.index, &new_sub.index) + && !sub.kind.allowed_concurrently_with(new_sub.kind) + { + panic!( + "tried to call get_mapped_range(_mut) on a range that has already \ + been mapped and would break Rust memory aliasing rules. Attempted \ + to get range {}, and the conflicting range is {}", + new_sub, sub + ); + } } - self.sub_ranges.push(offset..end); - end + self.sub_ranges.push(new_sub); } /// Record that the `size` bytes of the buffer at `offset` are no longer viewed. @@ -707,19 +824,14 @@ impl MapContext { /// # Panics /// /// This panics if the given range does not exactly match one previously - /// passed to [`add`]. - /// - /// [`add]`: MapContext::add - fn remove(&mut self, offset: BufferAddress, size: Option) { - let end = match size { - Some(s) => offset + s.get(), - None => self.initial_range.end, - }; + /// passed to [`MapContext::validate_and_add`]. + fn remove(&mut self, offset: BufferAddress, size: BufferSize) { + let end = offset + size.get(); let index = self .sub_ranges .iter() - .position(|r| *r == (offset..end)) + .position(|r| r.index == (offset..end)) .expect("unable to remove range from map context"); self.sub_ranges.swap_remove(index); } @@ -774,12 +886,25 @@ static_assertions::assert_impl_all!(MapMode: Send, Sync); /// [map]: Buffer#mapping-buffers /// [`map_async`]: BufferSlice::map_async #[derive(Debug)] -pub struct BufferView<'a> { - slice: BufferSlice<'a>, +pub struct BufferView { + // `buffer, offset, size` are similar to `BufferSlice`, except that they own the buffer. + buffer: Buffer, + offset: BufferAddress, + size: BufferSize, inner: dispatch::DispatchBufferMappedRange, } -impl core::ops::Deref for BufferView<'_> { +#[cfg(webgpu)] +impl BufferView { + /// Provides the same data as dereferencing the view, but as a `Uint8Array` in js. + /// This can be MUCH faster than dereferencing the view which copies the data into + /// the Rust / wasm heap. + pub fn as_uint8array(&self) -> &js_sys::Uint8Array { + self.inner.as_uint8array() + } +} + +impl core::ops::Deref for BufferView { type Target = [u8]; #[inline] @@ -788,7 +913,7 @@ impl core::ops::Deref for BufferView<'_> { } } -impl AsRef<[u8]> for BufferView<'_> { +impl AsRef<[u8]> for BufferView { #[inline] fn as_ref(&self) -> &[u8] { self.inner.slice() @@ -814,20 +939,23 @@ impl AsRef<[u8]> for BufferView<'_> { /// /// [map]: Buffer#mapping-buffers #[derive(Debug)] -pub struct BufferViewMut<'a> { - slice: BufferSlice<'a>, +pub struct BufferViewMut { + // `buffer, offset, size` are similar to `BufferSlice`, except that they own the buffer. + buffer: Buffer, + offset: BufferAddress, + size: BufferSize, inner: dispatch::DispatchBufferMappedRange, readable: bool, } -impl AsMut<[u8]> for BufferViewMut<'_> { +impl AsMut<[u8]> for BufferViewMut { #[inline] fn as_mut(&mut self) -> &mut [u8] { self.inner.slice_mut() } } -impl Deref for BufferViewMut<'_> { +impl Deref for BufferViewMut { type Target = [u8]; fn deref(&self) -> &Self::Target { @@ -839,125 +967,142 @@ impl Deref for BufferViewMut<'_> { } } -impl DerefMut for BufferViewMut<'_> { +impl DerefMut for BufferViewMut { fn deref_mut(&mut self) -> &mut Self::Target { self.inner.slice_mut() } } -impl Drop for BufferView<'_> { +impl Drop for BufferView { fn drop(&mut self) { - self.slice - .buffer + self.buffer .map_context .lock() - .remove(self.slice.offset, self.slice.size); + .remove(self.offset, self.size); } } -impl Drop for BufferViewMut<'_> { +impl Drop for BufferViewMut { fn drop(&mut self) { - self.slice - .buffer + self.buffer .map_context .lock() - .remove(self.slice.offset, self.slice.size); + .remove(self.offset, self.size); } } +#[track_caller] fn check_buffer_bounds( buffer_size: BufferAddress, - offset: BufferAddress, - size: Option, + slice_offset: BufferAddress, + slice_size: BufferSize, ) { // A slice of length 0 is invalid, so the offset must not be equal to or greater than the buffer size. - if offset >= buffer_size { + if slice_offset >= buffer_size { panic!( "slice offset {} is out of range for buffer of size {}", - offset, buffer_size + slice_offset, buffer_size ); } - if let Some(size) = size { - // Detect integer overflow. - let end = offset.checked_add(size.get()); - if end.is_none_or(|end| end > buffer_size) { - panic!( - "slice offset {} size {} is out of range for buffer of size {}", - offset, size, buffer_size - ); - } + // Detect integer overflow. + let end = slice_offset.checked_add(slice_size.get()); + if end.is_none_or(|end| end > buffer_size) { + panic!( + "slice offset {} size {} is out of range for buffer of size {}", + slice_offset, slice_size, buffer_size + ); } } -fn range_to_offset_size>( +#[track_caller] +pub(crate) fn range_to_offset_size>( bounds: S, -) -> (BufferAddress, Option) { + whole_size: BufferAddress, +) -> (BufferAddress, BufferSize) { let offset = match bounds.start_bound() { Bound::Included(&bound) => bound, Bound::Excluded(&bound) => bound + 1, Bound::Unbounded => 0, }; - let size = match bounds.end_bound() { - Bound::Included(&bound) => Some(bound + 1 - offset), - Bound::Excluded(&bound) => Some(bound - offset), - Bound::Unbounded => None, - } - .map(|size| BufferSize::new(size).expect("Buffer slices can not be empty")); + let size = BufferSize::new(match bounds.end_bound() { + Bound::Included(&bound) => bound + 1 - offset, + Bound::Excluded(&bound) => bound - offset, + Bound::Unbounded => whole_size - offset, + }) + .expect("buffer slices can not be empty"); (offset, size) } #[cfg(test)] mod tests { - use super::{check_buffer_bounds, range_to_offset_size, BufferSize}; + use super::{ + check_buffer_bounds, range_overlaps, range_to_offset_size, BufferAddress, BufferSize, + }; + + fn bs(value: BufferAddress) -> BufferSize { + BufferSize::new(value).unwrap() + } #[test] fn range_to_offset_size_works() { - assert_eq!(range_to_offset_size(0..2), (0, BufferSize::new(2))); - assert_eq!(range_to_offset_size(2..5), (2, BufferSize::new(3))); - assert_eq!(range_to_offset_size(..), (0, None)); - assert_eq!(range_to_offset_size(21..), (21, None)); - assert_eq!(range_to_offset_size(0..), (0, None)); - assert_eq!(range_to_offset_size(..21), (0, BufferSize::new(21))); + let whole = 100; + + assert_eq!(range_to_offset_size(0..2, whole), (0, bs(2))); + assert_eq!(range_to_offset_size(2..5, whole), (2, bs(3))); + assert_eq!(range_to_offset_size(.., whole), (0, bs(whole))); + assert_eq!(range_to_offset_size(21.., whole), (21, bs(whole - 21))); + assert_eq!(range_to_offset_size(0.., whole), (0, bs(whole))); + assert_eq!(range_to_offset_size(..21, whole), (0, bs(21))); } #[test] - #[should_panic] + #[should_panic = "buffer slices can not be empty"] fn range_to_offset_size_panics_for_empty_range() { - range_to_offset_size(123..123); + range_to_offset_size(123..123, 200); } #[test] - #[should_panic] + #[should_panic = "buffer slices can not be empty"] fn range_to_offset_size_panics_for_unbounded_empty_range() { - range_to_offset_size(..0); - } - - #[test] - #[should_panic] - fn check_buffer_bounds_panics_for_offset_at_size() { - check_buffer_bounds(100, 100, None); + range_to_offset_size(..0, 100); } #[test] fn check_buffer_bounds_works_for_end_in_range() { - check_buffer_bounds(200, 100, BufferSize::new(50)); - check_buffer_bounds(200, 100, BufferSize::new(100)); - check_buffer_bounds(u64::MAX, u64::MAX - 100, BufferSize::new(100)); - check_buffer_bounds(u64::MAX, 0, BufferSize::new(u64::MAX)); - check_buffer_bounds(u64::MAX, 1, BufferSize::new(u64::MAX - 1)); + check_buffer_bounds(200, 100, bs(50)); + check_buffer_bounds(200, 100, bs(100)); + check_buffer_bounds(u64::MAX, u64::MAX - 100, bs(100)); + check_buffer_bounds(u64::MAX, 0, bs(u64::MAX)); + check_buffer_bounds(u64::MAX, 1, bs(u64::MAX - 1)); } #[test] #[should_panic] fn check_buffer_bounds_panics_for_end_over_size() { - check_buffer_bounds(200, 100, BufferSize::new(101)); + check_buffer_bounds(200, 100, bs(101)); } #[test] #[should_panic] fn check_buffer_bounds_panics_for_end_wraparound() { - check_buffer_bounds(u64::MAX, 1, BufferSize::new(u64::MAX)); + check_buffer_bounds(u64::MAX, 1, bs(u64::MAX)); + } + + #[test] + fn range_overlapping() { + // First range to the left + assert_eq!(range_overlaps(&(0..1), &(1..3)), false); + // First range overlaps left edge + assert_eq!(range_overlaps(&(0..2), &(1..3)), true); + // First range completely inside second + assert_eq!(range_overlaps(&(1..2), &(0..3)), true); + // First range completely surrounds second + assert_eq!(range_overlaps(&(0..3), &(1..2)), true); + // First range overlaps right edge + assert_eq!(range_overlaps(&(1..3), &(0..2)), true); + // First range entirely to the right + assert_eq!(range_overlaps(&(2..3), &(0..2)), false); } } diff --git a/wgpu/src/api/command_buffer.rs b/wgpu/src/api/command_buffer.rs index 00c84af30..7685e2403 100644 --- a/wgpu/src/api/command_buffer.rs +++ b/wgpu/src/api/command_buffer.rs @@ -1,4 +1,7 @@ -use crate::*; +use crate::{ + api::{impl_deferred_command_buffer_actions, SharedDeferredCommandBufferActions}, + *, +}; /// Handle to a command buffer on the GPU. /// @@ -10,6 +13,20 @@ use crate::*; #[derive(Debug)] pub struct CommandBuffer { pub(crate) buffer: dispatch::DispatchCommandBuffer, + /// Deferred actions recorded at encode time, to run at Queue::submit. + pub(crate) actions: SharedDeferredCommandBufferActions, } #[cfg(send_sync)] static_assertions::assert_impl_all!(CommandBuffer: Send, Sync); + +impl CommandBuffer { + #[cfg(custom)] + /// Returns custom implementation of CommandBuffer (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.buffer.as_custom() + } + + // Expose map_buffer_on_submit/on_submitted_work_done on CommandBuffer as well, + // so callers can schedule after finishing encoding. + impl_deferred_command_buffer_actions!(); +} diff --git a/wgpu/src/api/command_buffer_actions.rs b/wgpu/src/api/command_buffer_actions.rs new file mode 100644 index 000000000..1c79b16ff --- /dev/null +++ b/wgpu/src/api/command_buffer_actions.rs @@ -0,0 +1,149 @@ +use alloc::{sync::Arc, vec::Vec}; +use core::num::NonZeroU64; + +use crate::{util::Mutex, *}; + +/// A deferred buffer mapping request captured during encoding (or a pass) +/// and executed later when the command buffer is submitted. +pub(crate) struct DeferredBufferMapping { + pub buffer: api::Buffer, + pub mode: MapMode, + pub offset: u64, + pub size: NonZeroU64, + pub callback: dispatch::BufferMapCallback, +} + +pub(super) type SharedDeferredCommandBufferActions = Arc>; + +/// Set of actions to take when the command buffer is submitted. +#[derive(Default)] +pub(crate) struct DeferredCommandBufferActions { + pub buffer_mappings: Vec, + pub on_submitted_work_done_callbacks: Vec, +} + +impl DeferredCommandBufferActions { + pub fn append(&mut self, other: &mut Self) { + self.buffer_mappings.append(&mut other.buffer_mappings); + self.on_submitted_work_done_callbacks + .append(&mut other.on_submitted_work_done_callbacks); + } + + pub fn execute(self, queue: &dispatch::DispatchQueue) { + for mapping in self.buffer_mappings { + mapping.buffer.map_async( + mapping.mode, + mapping.offset..mapping.offset + mapping.size.get(), + mapping.callback, + ); + } + for callback in self.on_submitted_work_done_callbacks { + queue.on_submitted_work_done(callback); + } + } +} + +impl core::fmt::Debug for DeferredCommandBufferActions { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("DeferredCommandBufferActions") + .field("buffer_mappings.len()", &self.buffer_mappings.len()) + .field( + "on_submitted_work_done_callbacks.len()", + &self.on_submitted_work_done_callbacks.len(), + ) + .finish() + } +} + +// We can't just implement this on CommandEncoders as by default passes make it so that +// you can't call any commands on the encoder while this is happening. As such, we need +// to implement these methods on the passes too. Use a macro to avoid massive code duplication +macro_rules! impl_deferred_command_buffer_actions { + () => { + /// On submission, maps the buffer to host (CPU) memory, making it available + /// for reading or writing via [`get_mapped_range()`](Buffer::get_mapped_range). + /// The buffer becomes accessible once the `callback` is invoked with [`Ok`]. + /// + /// Use this when you need to submit work that uses the buffer before mapping it. + /// Because that submission must happen before calling `map_async`, this method + /// schedules the mapping for after submission, avoiding extra calls to + /// [`Buffer::map_async()`] or [`BufferSlice::map_async()`] and letting you start + /// the mapping from a more convenient place. + /// + /// For the callback to run, either [`queue.submit(..)`][q::s], [`instance.poll_all(..)`][i::p_a], + /// or [`device.poll(..)`][d::p] must be called elsewhere in the runtime, possibly integrated + /// into an event loop or run on a separate thread. + /// + /// The callback runs on the thread that first calls one of the above functions + /// after the GPU work completes. There are no restrictions on the code you can run + /// in the callback; however, on native the polling call will not return until the + /// callback finishes, so keep callbacks short (set flags, send messages, etc.). + /// + /// While a buffer is mapped, it cannot be used by other commands; at any time, + /// either the GPU or the CPU has exclusive access to the buffer’s contents. + /// + /// # Panics + /// + /// - If `bounds` is outside the bounds of `buffer`. + /// - If `bounds` has a length less than 1. + /// + /// # Panics During Submit + /// + /// - If the buffer is already mapped. + /// - If the buffer’s [`BufferUsages`] do not allow the requested [`MapMode`]. + /// - If `bounds` is outside of the bounds of `buffer`. + /// - If `bounds` does not start at a multiple of [`MAP_ALIGNMENT`]. + /// - If `bounds` has a length that is not a multiple of 4 greater than 0. + /// + /// [q::s]: Queue::submit + /// [i::p_a]: Instance::poll_all + /// [d::p]: Device::poll + /// [CEmbos]: CommandEncoder::map_buffer_on_submit + /// [CBmbos]: CommandBuffer::map_buffer_on_submit + /// [RPmbos]: RenderPass::map_buffer_on_submit + /// [CPmbos]: ComputePass::map_buffer_on_submit + pub fn map_buffer_on_submit>( + &self, + buffer: &api::Buffer, + mode: MapMode, + bounds: S, + callback: impl FnOnce(Result<(), BufferAsyncError>) + WasmNotSend + 'static, + ) { + let (offset, size) = range_to_offset_size(bounds, buffer.size); + self.actions.lock().buffer_mappings.push( + crate::api::command_buffer_actions::DeferredBufferMapping { + buffer: buffer.clone(), + mode, + offset, + size, + callback: alloc::boxed::Box::new(callback), + }, + ); + } + + /// Registers a callback that is invoked when this command buffer’s work finishes + /// executing on the GPU. When this callback runs, all mapped-buffer callbacks + /// registered for the same submission are guaranteed to have been called. + /// + /// For the callback to run, either [`queue.submit(..)`][q::s], [`instance.poll_all(..)`][i::p_a], + /// or [`device.poll(..)`][d::p] must be called elsewhere in the runtime, possibly integrated + /// into an event loop or run on a separate thread. + /// + /// The callback runs on the thread that first calls one of the above functions + /// after the GPU work completes. There are no restrictions on the code you can run + /// in the callback; however, on native the polling call will not return until the + /// callback finishes, so keep callbacks short (set flags, send messages, etc.). + /// + /// [q::s]: Queue::submit + /// [i::p_a]: Instance::poll_all + /// [d::p]: Device::poll + pub fn on_submitted_work_done(&self, callback: impl FnOnce() + Send + 'static) { + self.actions + .lock() + .on_submitted_work_done_callbacks + .push(alloc::boxed::Box::new(callback)); + } + }; +} + +pub(crate) use impl_deferred_command_buffer_actions; diff --git a/wgpu/src/api/command_encoder.rs b/wgpu/src/api/command_encoder.rs index 1262863bd..9f3daf06a 100644 --- a/wgpu/src/api/command_encoder.rs +++ b/wgpu/src/api/command_encoder.rs @@ -1,9 +1,10 @@ +use alloc::sync::Arc; use core::ops::Range; use crate::{ api::{ - blas::BlasBuildEntry, - tlas::{TlasBuildEntry, TlasPackage}, + blas::BlasBuildEntry, impl_deferred_command_buffer_actions, tlas::Tlas, + SharedDeferredCommandBufferActions, }, *, }; @@ -20,6 +21,7 @@ use crate::{ #[derive(Debug)] pub struct CommandEncoder { pub(crate) inner: dispatch::DispatchCommandEncoder, + pub(crate) actions: SharedDeferredCommandBufferActions, } #[cfg(send_sync)] static_assertions::assert_impl_all!(CommandEncoder: Send, Sync); @@ -55,10 +57,10 @@ static_assertions::assert_impl_all!(TexelCopyTextureInfo<'_>: Send, Sync); impl CommandEncoder { /// Finishes recording and returns a [`CommandBuffer`] that can be submitted for execution. - pub fn finish(mut self) -> CommandBuffer { - let buffer = self.inner.finish(); - - CommandBuffer { buffer } + pub fn finish(self) -> CommandBuffer { + let Self { mut inner, actions } = self; + let buffer = inner.finish(); + CommandBuffer { buffer, actions } } /// Begins recording of a render pass. @@ -78,6 +80,7 @@ impl CommandEncoder { let rpass = self.inner.begin_render_pass(desc); RenderPass { inner: rpass, + actions: Arc::clone(&self.actions), _encoder_guard: api::PhantomDrop::default(), } } @@ -99,6 +102,7 @@ impl CommandEncoder { let cpass = self.inner.begin_compute_pass(desc); ComputePass { inner: cpass, + actions: Arc::clone(&self.actions), _encoder_guard: api::PhantomDrop::default(), } } @@ -116,14 +120,14 @@ impl CommandEncoder { source_offset: BufferAddress, destination: &Buffer, destination_offset: BufferAddress, - copy_size: BufferAddress, + copy_size: impl Into>, ) { self.inner.copy_buffer_to_buffer( &source.inner, source_offset, &destination.inner, destination_offset, - copy_size, + copy_size.into(), ); } @@ -235,20 +239,35 @@ impl CommandEncoder { ); } - /// Returns the inner hal CommandEncoder using a callback. The hal command encoder will be `None` if the - /// backend type argument does not match with this wgpu CommandEncoder + impl_deferred_command_buffer_actions!(); + + /// Get the [`wgpu_hal`] command encoder from this `CommandEncoder`. /// - /// This method will start the wgpu_core level command recording. + /// The returned command encoder will be ready to record onto. + /// + /// # Errors + /// + /// This method will pass in [`None`] if: + /// - The encoder is not from the backend specified by `A`. + /// - The encoder is from the `webgpu` or `custom` backend. + /// + /// # Types + /// + /// The callback argument depends on the backend: + /// + #[doc = crate::hal_type_vulkan!("CommandEncoder")] + #[doc = crate::hal_type_metal!("CommandEncoder")] + #[doc = crate::hal_type_dx12!("CommandEncoder")] + #[doc = crate::hal_type_gles!("CommandEncoder")] /// /// # Safety /// - /// - The raw handle obtained from the hal CommandEncoder must not be manually destroyed + /// - The raw handle obtained from the `A::CommandEncoder` must not be manually destroyed. + /// - You must not end the command buffer; wgpu will do it when you call finish. + /// - The wgpu command encoder must not be interacted with in any way while recording is + /// happening to the wgpu_hal or backend command encoder. #[cfg(wgpu_core)] - pub unsafe fn as_hal_mut< - A: wgc::hal_api::HalApi, - F: FnOnce(Option<&mut A::CommandEncoder>) -> R, - R, - >( + pub unsafe fn as_hal_mut) -> R, R>( &mut self, hal_command_encoder_callback: F, ) -> R { @@ -262,6 +281,12 @@ impl CommandEncoder { hal_command_encoder_callback(None) } } + + #[cfg(custom)] + /// Returns custom implementation of CommandEncoder (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() + } } /// [`Features::TIMESTAMP_QUERY_INSIDE_ENCODERS`] must be enabled on the device in order to call these functions. @@ -283,8 +308,32 @@ impl CommandEncoder { } } -/// [`Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE`] must be enabled on the device in order to call these functions. +/// [`Features::EXPERIMENTAL_RAY_QUERY`] must be enabled on the device in order to call these functions. impl CommandEncoder { + /// When encoding the acceleration structure build with the raw Hal encoder + /// (obtained from [`CommandEncoder::as_hal_mut`]), this function marks the + /// acceleration structures as having been built. + /// + /// This function must only be used with the raw encoder API. When using the + /// wgpu encoding API, acceleration structure build is tracked automatically. + /// + /// # Panics + /// + /// - If the encoder is being used with the wgpu encoding API. + /// + /// # Safety + /// + /// - All acceleration structures must have been build in this command encoder. + /// - All BLASes inputted must have been built before all TLASes that were inputted here and + /// which use them. + pub unsafe fn mark_acceleration_structures_built<'a>( + &self, + blas: impl IntoIterator, + tlas: impl IntoIterator, + ) { + self.inner + .mark_acceleration_structures_built(&mut blas.into_iter(), &mut tlas.into_iter()) + } /// Build bottom and top level acceleration structures. /// /// Builds the BLASes then the TLASes, but does ***not*** build the BLASes into the TLASes, @@ -304,7 +353,7 @@ impl CommandEncoder { /// - Each BLAS in each TLAS instance must have been being built in the current call or in a previous call to `build_acceleration_structures` or `build_acceleration_structures_unsafe_tlas` /// - The number of TLAS instances must be less than or equal to the max number of tlas instances when creating (if creating a package with `TlasPackage::new()` this is already satisfied) /// - /// If the device the command encoder is created from does not have [Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE] enabled then a validation error is generated + /// If the device the command encoder is created from does not have [Features::EXPERIMENTAL_RAY_QUERY] enabled then a validation error is generated /// /// A bottom level acceleration structure may be build and used as a reference in a top level acceleration structure in the same invocation of this function. /// @@ -315,38 +364,16 @@ impl CommandEncoder { /// - All the bottom level acceleration structures referenced by the top level acceleration structure are valid and have been built prior, /// or at same time as the containing top level acceleration structure. /// - /// [Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE]: wgt::Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE + /// [Features::EXPERIMENTAL_RAY_QUERY]: wgt::Features::EXPERIMENTAL_RAY_QUERY pub fn build_acceleration_structures<'a>( &mut self, blas: impl IntoIterator>, - tlas: impl IntoIterator, + tlas: impl IntoIterator, ) { self.inner .build_acceleration_structures(&mut blas.into_iter(), &mut tlas.into_iter()); } - /// Build bottom and top level acceleration structures. - /// See [`CommandEncoder::build_acceleration_structures`] for the safe version and more details. All validation in [`CommandEncoder::build_acceleration_structures`] except that - /// listed under tlas applies here as well. - /// - /// # Safety - /// - /// - The contents of the raw instance buffer must be valid for the underling api. - /// - All bottom level acceleration structures, referenced in the raw instance buffer must be valid and built, - /// when the corresponding top level acceleration structure is built. (builds may happen in the same invocation of this function). - /// - At the time when the top level acceleration structure is used in a bind group, all associated bottom level acceleration structures must be valid, - /// and built (no later than the time when the top level acceleration structure was built). - pub unsafe fn build_acceleration_structures_unsafe_tlas<'a>( - &mut self, - blas: impl IntoIterator>, - tlas: impl IntoIterator>, - ) { - self.inner.build_acceleration_structures_unsafe_tlas( - &mut blas.into_iter(), - &mut tlas.into_iter(), - ); - } - /// Transition resources to an underlying hal resource state. /// /// This is an advanced, native-only API (no-op on web) that has two main use cases: diff --git a/wgpu/src/api/compute_pass.rs b/wgpu/src/api/compute_pass.rs index c7fa7462f..9c62ca312 100644 --- a/wgpu/src/api/compute_pass.rs +++ b/wgpu/src/api/compute_pass.rs @@ -1,4 +1,7 @@ -use crate::*; +use crate::{ + api::{impl_deferred_command_buffer_actions, SharedDeferredCommandBufferActions}, + *, +}; /// In-progress recording of a compute pass. /// @@ -10,6 +13,9 @@ use crate::*; pub struct ComputePass<'encoder> { pub(crate) inner: dispatch::DispatchComputePass, + /// Shared with CommandEncoder to enqueue deferred actions from within a pass. + pub(crate) actions: SharedDeferredCommandBufferActions, + /// This lifetime is used to protect the [`CommandEncoder`] from being used /// while the pass is alive. This needs to be PhantomDrop to prevent the lifetime /// from being shortened. @@ -37,6 +43,7 @@ impl ComputePass<'_> { pub fn forget_lifetime(self) -> ComputePass<'static> { ComputePass { inner: self.inner, + actions: self.actions, _encoder_guard: crate::api::PhantomDrop::default(), } } @@ -94,6 +101,14 @@ impl ComputePass<'_> { self.inner .dispatch_workgroups_indirect(&indirect_buffer.inner, indirect_offset); } + + impl_deferred_command_buffer_actions!(); + + #[cfg(custom)] + /// Returns custom implementation of ComputePass (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() + } } /// [`Features::PUSH_CONSTANTS`] must be enabled on the device in order to call these functions. diff --git a/wgpu/src/api/compute_pipeline.rs b/wgpu/src/api/compute_pipeline.rs index 325f0ba1f..499f967b5 100644 --- a/wgpu/src/api/compute_pipeline.rs +++ b/wgpu/src/api/compute_pipeline.rs @@ -27,6 +27,12 @@ impl ComputePipeline { let bind_group = self.inner.get_bind_group_layout(index); BindGroupLayout { inner: bind_group } } + + #[cfg(custom)] + /// Returns custom implementation of ComputePipeline (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() + } } /// Describes a compute pipeline. diff --git a/wgpu/src/api/device.rs b/wgpu/src/api/device.rs index 5971b061d..2cc384091 100644 --- a/wgpu/src/api/device.rs +++ b/wgpu/src/api/device.rs @@ -1,10 +1,11 @@ -use alloc::{boxed::Box, string::String, sync::Arc}; +use alloc::{boxed::Box, string::String, sync::Arc, vec}; +#[cfg(wgpu_core)] +use core::ops::Deref; use core::{error, fmt, future::Future}; -use parking_lot::Mutex; - use crate::api::blas::{Blas, BlasGeometrySizeDescriptors, CreateBlasDescriptor}; use crate::api::tlas::{CreateTlasDescriptor, Tlas}; +use crate::util::Mutex; use crate::*; /// Open connection to a graphics and/or compute device. @@ -34,6 +35,12 @@ pub type DeviceDescriptor<'a> = wgt::DeviceDescriptor>; static_assertions::assert_impl_all!(DeviceDescriptor<'_>: Send, Sync); impl Device { + #[cfg(custom)] + /// Returns custom implementation of Device (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() + } + #[cfg(custom)] /// Creates Device from custom implementation pub fn from_custom(device: T) -> Self { @@ -51,7 +58,7 @@ impl Device { use core::future::Future as _; use core::pin::pin; use core::task; - let ctx = &mut task::Context::from_waker(waker::noop_waker_ref()); + let ctx = &mut task::Context::from_waker(task::Waker::noop()); let instance = Instance::new(&InstanceDescriptor { backends: Backends::NOOP, @@ -86,7 +93,7 @@ impl Device { /// /// When running on WebGPU, this is a no-op. `Device`s are automatically polled. pub fn poll(&self, poll_type: PollType) -> Result { - self.inner.poll(poll_type) + self.inner.poll(poll_type.map_index(|s| s.index)) } /// The features which can be used on this device. @@ -172,20 +179,18 @@ impl Device { ShaderModule { inner: module } } - /// Creates a shader module from SPIR-V binary directly. + /// Creates a shader module which will bypass wgpu's shader tooling and validation and be used directly by the backend. /// /// # Safety /// - /// This function passes binary data to the backend as-is and can potentially result in a - /// driver crash or bogus behaviour. No attempt is made to ensure that data is valid SPIR-V. - /// - /// See also [`include_spirv_raw!`] and [`util::make_spirv_raw`]. + /// This function passes data to the backend as-is and can potentially result in a + /// driver crash or bogus behaviour. No attempt is made to ensure that data is valid. #[must_use] - pub unsafe fn create_shader_module_spirv( + pub unsafe fn create_shader_module_passthrough( &self, - desc: &ShaderModuleDescriptorSpirV<'_>, + desc: ShaderModuleDescriptorPassthrough<'_>, ) -> ShaderModule { - let module = unsafe { self.inner.create_shader_module_spirv(desc) }; + let module = unsafe { self.inner.create_shader_module_passthrough(&desc) }; ShaderModule { inner: module } } @@ -193,7 +198,12 @@ impl Device { #[must_use] pub fn create_command_encoder(&self, desc: &CommandEncoderDescriptor<'_>) -> CommandEncoder { let encoder = self.inner.create_command_encoder(desc); - CommandEncoder { inner: encoder } + // Each encoder starts with its own deferred-action store that travels + // with the CommandBuffer produced by finish(). + CommandEncoder { + inner: encoder, + actions: Default::default(), + } } /// Creates an empty [`RenderBundleEncoder`]. @@ -240,6 +250,13 @@ impl Device { RenderPipeline { inner: pipeline } } + /// Creates a mesh shader based [`RenderPipeline`]. + #[must_use] + pub fn create_mesh_pipeline(&self, desc: &MeshPipelineDescriptor<'_>) -> RenderPipeline { + let pipeline = self.inner.create_mesh_pipeline(desc); + RenderPipeline { inner: pipeline } + } + /// Creates a [`ComputePipeline`]. #[must_use] pub fn create_compute_pipeline(&self, desc: &ComputePipelineDescriptor<'_>) -> ComputePipeline { @@ -250,10 +267,7 @@ impl Device { /// Creates a [`Buffer`]. #[must_use] pub fn create_buffer(&self, desc: &BufferDescriptor<'_>) -> Buffer { - let mut map_context = MapContext::new(desc.size); - if desc.mapped_at_creation { - map_context.initial_range = 0..desc.size; - } + let map_context = MapContext::new(desc.mapped_at_creation.then_some(0..desc.size)); let buffer = self.inner.create_buffer(desc); @@ -284,6 +298,15 @@ impl Device { /// Creates a [`Texture`] from a wgpu-hal Texture. /// + /// # Types + /// + /// The type of `A::Texture` depends on the backend: + /// + #[doc = crate::hal_type_vulkan!("Texture")] + #[doc = crate::hal_type_metal!("Texture")] + #[doc = crate::hal_type_dx12!("Texture")] + #[doc = crate::hal_type_gles!("Texture")] + /// /// # Safety /// /// - `hal_texture` must be created from this device internal handle @@ -291,7 +314,7 @@ impl Device { /// - `hal_texture` must be initialized #[cfg(wgpu_core)] #[must_use] - pub unsafe fn create_texture_from_hal( + pub unsafe fn create_texture_from_hal( &self, hal_texture: A::Texture, desc: &TextureDescriptor<'_>, @@ -312,24 +335,45 @@ impl Device { } } + /// Creates a new [`ExternalTexture`]. + #[must_use] + pub fn create_external_texture( + &self, + desc: &ExternalTextureDescriptor<'_>, + planes: &[&TextureView], + ) -> ExternalTexture { + let external_texture = self.inner.create_external_texture(desc, planes); + + ExternalTexture { + inner: external_texture, + } + } + /// Creates a [`Buffer`] from a wgpu-hal Buffer. /// + /// # Types + /// + /// The type of `A::Buffer` depends on the backend: + /// + #[doc = crate::hal_type_vulkan!("Buffer")] + #[doc = crate::hal_type_metal!("Buffer")] + #[doc = crate::hal_type_dx12!("Buffer")] + #[doc = crate::hal_type_gles!("Buffer")] + /// /// # Safety /// /// - `hal_buffer` must be created from this device internal handle /// - `hal_buffer` must be created respecting `desc` /// - `hal_buffer` must be initialized + /// - `hal_buffer` must not have zero size #[cfg(wgpu_core)] #[must_use] - pub unsafe fn create_buffer_from_hal( + pub unsafe fn create_buffer_from_hal( &self, hal_buffer: A::Buffer, desc: &BufferDescriptor<'_>, ) -> Buffer { - let mut map_context = MapContext::new(desc.size); - if desc.mapped_at_creation { - map_context.initial_range = 0..desc.size; - } + let map_context = MapContext::new(desc.mapped_at_creation.then_some(0..desc.size)); let buffer = unsafe { let core_device = self.inner.as_core(); @@ -362,8 +406,8 @@ impl Device { QuerySet { inner: query_set } } - /// Set a callback for errors that are not handled in error scopes. - pub fn on_uncaptured_error(&self, handler: Box) { + /// Set a callback which will be called for all errors that are not handled in error scopes. + pub fn on_uncaptured_error(&self, handler: Arc) { self.inner.on_uncaptured_error(handler) } @@ -377,14 +421,65 @@ impl Device { self.inner.pop_error_scope() } - /// Starts frame capture. - pub fn start_capture(&self) { - self.inner.start_capture() + /// Starts a capture in the attached graphics debugger. + /// + /// This behaves differently depending on which graphics debugger is attached: + /// + /// - Renderdoc: Calls [`StartFrameCapture(device, NULL)`][rd]. + /// - Xcode: Creates a capture with [`MTLCaptureManager`][xcode]. + /// - None: No action is taken. + /// + /// # Safety + /// + /// - There should not be any other captures currently active. + /// - All other safety rules are defined by the graphics debugger, see the + /// documentation for the specific debugger. + /// - In general, graphics debuggers can easily cause crashes, so this isn't + /// ever guaranteed to be sound. + /// + /// # Tips + /// + /// - Debuggers need to capture both the recording of the commands and the + /// submission of the commands to the GPU. Try to wrap all of your + /// gpu work in a capture. + /// - If you encounter issues, try waiting for the GPU to finish all work + /// before stopping the capture. + /// + /// [rd]: https://renderdoc.org/docs/in_application_api.html#_CPPv417StartFrameCapture23RENDERDOC_DevicePointer22RENDERDOC_WindowHandle + /// [xcode]: https://developer.apple.com/documentation/metal/mtlcapturemanager + #[doc(alias = "start_renderdoc_capture")] + #[doc(alias = "start_xcode_capture")] + pub unsafe fn start_graphics_debugger_capture(&self) { + unsafe { self.inner.start_graphics_debugger_capture() } } - /// Stops frame capture. - pub fn stop_capture(&self) { - self.inner.stop_capture() + /// Stops the current capture in the attached graphics debugger. + /// + /// This behaves differently depending on which graphics debugger is attached: + /// + /// - Renderdoc: Calls [`EndFrameCapture(device, NULL)`][rd]. + /// - Xcode: Stops the capture with [`MTLCaptureManager`][xcode]. + /// - None: No action is taken. + /// + /// # Safety + /// + /// - There should be a capture currently active. + /// - All other safety rules are defined by the graphics debugger, see the + /// documentation for the specific debugger. + /// - In general, graphics debuggers can easily cause crashes, so this isn't + /// ever guaranteed to be sound. + /// + /// # Tips + /// + /// - If you encounter issues, try to submit all work to the GPU, and waiting + /// for that work to finish before stopping the capture. + /// + /// [rd]: https://renderdoc.org/docs/in_application_api.html#_CPPv415EndFrameCapture23RENDERDOC_DevicePointer22RENDERDOC_WindowHandle + /// [xcode]: https://developer.apple.com/documentation/metal/mtlcapturemanager + #[doc(alias = "stop_renderdoc_capture")] + #[doc(alias = "stop_xcode_capture")] + pub unsafe fn stop_graphics_debugger_capture(&self) { + unsafe { self.inner.stop_graphics_debugger_capture() } } /// Query internal counters from the native backend for debugging purposes. @@ -408,39 +503,43 @@ impl Device { self.inner.generate_allocator_report() } - /// Apply a callback to this `Device`'s underlying backend device. + /// Get the [`wgpu_hal`] device from this `Device`. /// - /// If this `Device` is implemented by the backend API given by `A` (Vulkan, - /// Dx12, etc.), then apply `hal_device_callback` to `Some(&device)`, where - /// `device` is the underlying backend device type, [`A::Device`]. + /// Find the Api struct corresponding to the active backend in [`wgpu_hal::api`], + /// and pass that struct to the to the `A` type parameter. /// - /// If this `Device` uses a different backend, apply `hal_device_callback` - /// to `None`. + /// Returns a guard that dereferences to the type of the hal backend + /// which implements [`A::Device`]. /// - /// The device is locked for reading while `hal_device_callback` runs. If - /// the callback attempts to perform any `wgpu` operations that require - /// write access to the device (destroying a buffer, say), deadlock will - /// occur. The locks are automatically released when the callback returns. + /// # Types + /// + /// The returned type depends on the backend: + /// + #[doc = crate::hal_type_vulkan!("Device")] + #[doc = crate::hal_type_metal!("Device")] + #[doc = crate::hal_type_dx12!("Device")] + #[doc = crate::hal_type_gles!("Device")] + /// + /// # Errors + /// + /// This method will return None if: + /// - The device is not from the backend specified by `A`. + /// - The device is from the `webgpu` or `custom` backend. /// /// # Safety /// - /// - The raw handle passed to the callback must not be manually destroyed. + /// - The returned resource must not be destroyed unless the guard + /// is the last reference to it and it is not in use by the GPU. + /// The guard and handle may be dropped at any time however. + /// - All the safety requirements of wgpu-hal must be upheld. /// /// [`A::Device`]: hal::Api::Device #[cfg(wgpu_core)] - pub unsafe fn as_hal) -> R, R>( + pub unsafe fn as_hal( &self, - hal_device_callback: F, - ) -> R { - if let Some(core_device) = self.inner.as_core_opt() { - unsafe { - core_device - .context - .device_as_hal::(core_device, hal_device_callback) - } - } else { - hal_device_callback(None) - } + ) -> Option + WasmNotSendSync> { + let device = self.inner.as_core_opt()?; + unsafe { device.context.device_as_hal::(device) } } /// Destroy this device. @@ -503,7 +602,7 @@ impl Device { } } -/// [`Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE`] must be enabled on the device in order to call these functions. +/// [`Features::EXPERIMENTAL_RAY_QUERY`] must be enabled on the device in order to call these functions. impl Device { /// Create a bottom level acceleration structure, used inside a top level acceleration structure for ray tracing. /// - `desc`: The descriptor of the acceleration structure. @@ -512,14 +611,14 @@ impl Device { /// # Validation /// If any of the following is not satisfied a validation error is generated /// - /// The device ***must*** have [`Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE`] enabled. + /// The device ***must*** have [`Features::EXPERIMENTAL_RAY_QUERY`] enabled. /// if `sizes` is [`BlasGeometrySizeDescriptors::Triangles`] then the following must be satisfied /// - For every geometry descriptor (for the purposes this is called `geo_desc`) of `sizes.descriptors` the following must be satisfied: /// - `geo_desc.vertex_format` must be within allowed formats (allowed formats for a given feature set /// may be queried with [`Features::allowed_vertex_formats_for_blas`]). /// - Both or neither of `geo_desc.index_format` and `geo_desc.index_count` must be provided. /// - /// [`Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE`]: wgt::Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE + /// [`Features::EXPERIMENTAL_RAY_QUERY`]: wgt::Features::EXPERIMENTAL_RAY_QUERY /// [`Features::allowed_vertex_formats_for_blas`]: wgt::Features::allowed_vertex_formats_for_blas #[must_use] pub fn create_blas( @@ -541,18 +640,17 @@ impl Device { /// # Validation /// If any of the following is not satisfied a validation error is generated /// - /// The device ***must*** have [`Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE`] enabled. + /// The device ***must*** have [`Features::EXPERIMENTAL_RAY_QUERY`] enabled. /// - /// [`Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE`]: wgt::Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE + /// [`Features::EXPERIMENTAL_RAY_QUERY`]: wgt::Features::EXPERIMENTAL_RAY_QUERY #[must_use] pub fn create_tlas(&self, desc: &CreateTlasDescriptor<'_>) -> Tlas { let tlas = self.inner.create_tlas(desc); Tlas { - shared: Arc::new(TlasShared { - inner: tlas, - max_instances: desc.max_instances, - }), + inner: tlas, + instances: vec![None; desc.max_instances as usize], + lowest_unmodified: 0, } } } @@ -615,9 +713,11 @@ impl From for RequestDeviceError { } } -/// Type for the callback of uncaptured error handler -pub trait UncapturedErrorHandler: Fn(Error) + Send + 'static {} -impl UncapturedErrorHandler for T where T: Fn(Error) + Send + 'static {} +/// The callback of [`Device::on_uncaptured_error()`]. +/// +/// It must be a function with this signature. +pub trait UncapturedErrorHandler: Fn(Error) + Send + Sync + 'static {} +impl UncapturedErrorHandler for T where T: Fn(Error) + Send + Sync + 'static {} /// Kinds of [`Error`]s a [`Device::push_error_scope()`] may be configured to catch. #[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd)] @@ -695,36 +795,3 @@ impl fmt::Display for Error { } } } - -// Copied from [`futures::task::noop_waker`]. -// Needed until MSRV is 1.85 with `task::Waker::noop()` available -#[cfg(feature = "noop")] -mod waker { - use core::ptr::null; - use core::task::{RawWaker, RawWakerVTable, Waker}; - - unsafe fn noop_clone(_data: *const ()) -> RawWaker { - noop_raw_waker() - } - - unsafe fn noop(_data: *const ()) {} - - const NOOP_WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new(noop_clone, noop, noop, noop); - - const fn noop_raw_waker() -> RawWaker { - RawWaker::new(null(), &NOOP_WAKER_VTABLE) - } - - /// Get a static reference to a [`Waker`] which - /// does nothing when `wake()` is called on it. - #[inline] - pub fn noop_waker_ref() -> &'static Waker { - struct SyncRawWaker(RawWaker); - unsafe impl Sync for SyncRawWaker {} - - static NOOP_WAKER_INSTANCE: SyncRawWaker = SyncRawWaker(noop_raw_waker()); - - // SAFETY: `Waker` is #[repr(transparent)] over its `RawWaker`. - unsafe { &*(&NOOP_WAKER_INSTANCE.0 as *const RawWaker as *const Waker) } - } -} diff --git a/wgpu/src/api/external_texture.rs b/wgpu/src/api/external_texture.rs new file mode 100644 index 000000000..d41f41c56 --- /dev/null +++ b/wgpu/src/api/external_texture.rs @@ -0,0 +1,31 @@ +use crate::*; + +/// Handle to an external texture on the GPU. +/// +/// It can be created with [`Device::create_external_texture`]. +/// +/// Corresponds to [WebGPU `GPUExternalTexture`](https://gpuweb.github.io/gpuweb/#gpuexternaltexture). +#[derive(Debug, Clone)] +pub struct ExternalTexture { + pub(crate) inner: dispatch::DispatchExternalTexture, +} +#[cfg(send_sync)] +static_assertions::assert_impl_all!(ExternalTexture: Send, Sync); + +crate::cmp::impl_eq_ord_hash_proxy!(ExternalTexture => .inner); + +impl ExternalTexture { + /// Destroy the associated native resources as soon as possible. + pub fn destroy(&self) { + self.inner.destroy(); + } +} + +/// Describes an [`ExternalTexture`]. +/// +/// For use with [`Device::create_external_texture`]. +/// +/// Corresponds to [WebGPU `GPUExternalTextureDescriptor`]( +/// https://gpuweb.github.io/gpuweb/#dictdef-gpuexternaltexturedescriptor). +pub type ExternalTextureDescriptor<'a> = wgt::ExternalTextureDescriptor>; +static_assertions::assert_impl_all!(ExternalTextureDescriptor<'_>: Send, Sync); diff --git a/wgpu/src/api/instance.rs b/wgpu/src/api/instance.rs index dc34a7817..77b70f51c 100644 --- a/wgpu/src/api/instance.rs +++ b/wgpu/src/api/instance.rs @@ -1,10 +1,7 @@ -#[cfg(wgpu_core)] use alloc::vec::Vec; use core::future::Future; -use parking_lot::Mutex; - -use crate::{dispatch::InstanceInterface, *}; +use crate::{dispatch::InstanceInterface, util::Mutex, *}; bitflags::bitflags! { /// WGSL language extensions. @@ -23,7 +20,7 @@ bitflags::bitflags! { } } -/// Context for all other wgpu objects. Instance of wgpu. +/// Contains the various entry points to start interacting with the system's GPUs. /// /// This is the first thing you create when using wgpu. /// Its primary use is to create [`Adapter`]s and [`Surface`]s. @@ -55,6 +52,51 @@ impl Default for Instance { } impl Instance { + /// Create an new instance of wgpu using the given options and enabled backends. + /// + /// # Panics + /// + /// - If no backend feature for the active target platform is enabled, + /// this method will panic; see [`Instance::enabled_backend_features()`]. + #[allow(clippy::allow_attributes, unreachable_code)] + pub fn new(desc: &InstanceDescriptor) -> Self { + if Self::enabled_backend_features().is_empty() { + panic!( + "No wgpu backend feature that is implemented for the target platform was enabled. \ + See `wgpu::Instance::enabled_backend_features()` for more information." + ); + } + + #[cfg(webgpu)] + { + let is_only_available_backend = !cfg!(wgpu_core); + let requested_webgpu = desc.backends.contains(Backends::BROWSER_WEBGPU); + let support_webgpu = crate::backend::get_browser_gpu_property() + .map(|maybe_gpu| maybe_gpu.is_some()) + .unwrap_or(false); + + if is_only_available_backend || (requested_webgpu && support_webgpu) { + return Self { + inner: crate::backend::ContextWebGpu::new(desc).into(), + }; + } + } + + #[cfg(wgpu_core)] + { + return Self { + inner: crate::backend::ContextWgpuCore::new(desc).into(), + }; + } + + // Silence unused variable warnings without adding _ to the parameter name (which shows up in docs). + let _ = desc; + + unreachable!( + "Earlier check of `enabled_backend_features` should have prevented getting here!" + ); + } + /// Returns which backends can be picked for the current build configuration. /// /// The returned set depends on a combination of target platform and enabled features. @@ -86,126 +128,12 @@ impl Instance { backends } - /// Create an new instance of wgpu. + /// Returns the set of [WGSL language extensions] supported by this instance. /// - /// # Arguments - /// - /// - `instance_desc` - Has fields for which [backends][Backends] wgpu will choose - /// during instantiation, and which [DX12 shader compiler][Dx12Compiler] wgpu will use. - /// - /// [`Backends::BROWSER_WEBGPU`] takes a special role: - /// If it is set and a [`navigator.gpu`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/gpu) - /// object is present, this instance will *only* be able to create WebGPU adapters. - /// - /// ⚠️ On some browsers this check is insufficient to determine whether WebGPU is supported, - /// as the browser may define the `navigator.gpu` object, but be unable to create any WebGPU adapters. - /// For targeting _both_ WebGPU & WebGL is recommended to use [`crate::util::new_instance_with_webgpu_detection`]. - /// - /// If you instead want to force use of WebGL, either disable the `webgpu` compile-time feature - /// or don't add the [`Backends::BROWSER_WEBGPU`] flag to the the `instance_desc`'s `backends` field. - /// If it is set and WebGPU support is *not* detected, the instance will use wgpu-core - /// to create adapters. Meaning that if the `webgl` feature is enabled, it is able to create - /// a WebGL adapter. - /// - /// # Panics - /// - /// If no backend feature for the active target platform is enabled, - /// this method will panic, see [`Instance::enabled_backend_features()`]. - #[allow(clippy::allow_attributes, unreachable_code)] - pub fn new(_instance_desc: &InstanceDescriptor) -> Self { - if Self::enabled_backend_features().is_empty() { - panic!( - "No wgpu backend feature that is implemented for the target platform was enabled. \ - See `wgpu::Instance::enabled_backend_features()` for more information." - ); - } - - #[cfg(webgpu)] - { - let is_only_available_backend = !cfg!(wgpu_core); - let requested_webgpu = _instance_desc.backends.contains(Backends::BROWSER_WEBGPU); - let support_webgpu = crate::backend::get_browser_gpu_property() - .map(|maybe_gpu| maybe_gpu.is_some()) - .unwrap_or(false); - - if is_only_available_backend || (requested_webgpu && support_webgpu) { - return Self { - inner: crate::backend::ContextWebGpu::new(_instance_desc).into(), - }; - } - } - - #[cfg(wgpu_core)] - { - return Self { - inner: crate::backend::ContextWgpuCore::new(_instance_desc).into(), - }; - } - - unreachable!( - "Earlier check of `enabled_backend_features` should have prevented getting here!" - ); - } - - /// Create an new instance of wgpu from a wgpu-hal instance. - /// - /// # Arguments - /// - /// - `hal_instance` - wgpu-hal instance. - /// - /// # Safety - /// - /// Refer to the creation of wgpu-hal Instance for every backend. - #[cfg(wgpu_core)] - pub unsafe fn from_hal(hal_instance: A::Instance) -> Self { - Self { - inner: unsafe { - crate::backend::ContextWgpuCore::from_hal_instance::(hal_instance).into() - }, - } - } - - /// Return a reference to a specific backend instance, if available. - /// - /// If this `Instance` has a wgpu-hal [`Instance`] for backend - /// `A`, return a reference to it. Otherwise, return `None`. - /// - /// # Safety - /// - /// - The raw instance handle returned must not be manually destroyed. - /// - /// [`Instance`]: hal::Api::Instance - #[cfg(wgpu_core)] - pub unsafe fn as_hal(&self) -> Option<&A::Instance> { - self.inner - .as_core_opt() - .and_then(|ctx| unsafe { ctx.instance_as_hal::() }) - } - - /// Create an new instance of wgpu from a wgpu-core instance. - /// - /// # Arguments - /// - /// - `core_instance` - wgpu-core instance. - /// - /// # Safety - /// - /// Refer to the creation of wgpu-core Instance. - #[cfg(wgpu_core)] - pub unsafe fn from_core(core_instance: wgc::instance::Instance) -> Self { - Self { - inner: unsafe { - crate::backend::ContextWgpuCore::from_core_instance(core_instance).into() - }, - } - } - - #[cfg(custom)] - /// Creates instance from custom context implementation - pub fn from_custom(instance: T) -> Self { - Self { - inner: dispatch::DispatchInstance::Custom(backend::custom::DynContext::new(instance)), - } + /// [WGSL language extensions]: https://www.w3.org/TR/webgpu/#gpuwgsllanguagefeatures + #[cfg(feature = "wgsl")] + pub fn wgsl_language_features(&self) -> WgslLanguageFeatures { + self.inner.wgsl_language_features() } /// Retrieves all available [`Adapter`]s that match the given [`Backends`]. @@ -213,23 +141,18 @@ impl Instance { /// # Arguments /// /// - `backends` - Backends from which to enumerate adapters. - #[cfg(wgpu_core)] - pub fn enumerate_adapters(&self, backends: Backends) -> Vec { - let Some(core_instance) = self.inner.as_core_opt() else { - return Vec::new(); - }; + pub fn enumerate_adapters(&self, backends: Backends) -> impl Future> { + let future = self.inner.enumerate_adapters(backends); - core_instance - .enumerate_adapters(backends) - .into_iter() - .map(|adapter| { - let core = backend::wgpu_core::CoreAdapter { - context: core_instance.clone(), - id: adapter, - }; - crate::Adapter { inner: core.into() } - }) - .collect() + async move { + future + .await + .iter() + .map(|adapter| Adapter { + inner: adapter.clone(), + }) + .collect() + } } /// Retrieves an [`Adapter`] which matches the given [`RequestAdapterOptions`]. @@ -248,26 +171,6 @@ impl Instance { async move { future.await.map(|adapter| Adapter { inner: adapter }) } } - /// Converts a wgpu-hal `ExposedAdapter` to a wgpu [`Adapter`]. - /// - /// # Safety - /// - /// `hal_adapter` must be created from this instance internal handle. - #[cfg(wgpu_core)] - pub unsafe fn create_adapter_from_hal( - &self, - hal_adapter: hal::ExposedAdapter, - ) -> Adapter { - let core_instance = self.inner.as_core(); - let adapter = unsafe { core_instance.create_adapter_from_hal(hal_adapter) }; - let core = backend::wgpu_core::CoreAdapter { - context: core_instance.clone(), - id: adapter, - }; - - Adapter { inner: core.into() } - } - /// Creates a new surface targeting a given window/canvas/surface/etc.. /// /// Internally, this creates surfaces for all backends that are enabled for this instance. @@ -297,7 +200,7 @@ impl Instance { surface }?, - #[cfg(any(webgpu, webgl))] + #[cfg(web)] SurfaceTarget::Canvas(canvas) => { handle_source = None; @@ -316,7 +219,7 @@ impl Instance { }? } - #[cfg(any(webgpu, webgl))] + #[cfg(web)] SurfaceTarget::OffscreenCanvas(canvas) => { handle_source = None; @@ -393,12 +296,135 @@ impl Instance { pub fn generate_report(&self) -> Option { self.inner.as_core_opt().map(|ctx| ctx.generate_report()) } +} - /// Returns set of supported WGSL language extensions supported by this instance. +/// Interop with wgpu-hal. +#[cfg(wgpu_core)] +impl Instance { + /// Create an new instance of wgpu from a wgpu-hal instance. This is often useful + /// when you need to do backend specific logic, or interop with an existing backend + /// instance. /// - /// - #[cfg(feature = "wgsl")] - pub fn wgsl_language_features(&self) -> WgslLanguageFeatures { - self.inner.wgsl_language_features() + /// # Types + /// + /// The type of `A::Instance` depends on the backend: + /// + #[doc = crate::hal_type_vulkan!("Instance")] + #[doc = crate::hal_type_metal!("Instance")] + #[doc = crate::hal_type_dx12!("Instance")] + #[doc = crate::hal_type_gles!("Instance")] + /// + /// # Safety + /// + /// - The `hal_instance` must be a valid and usable instance of the backend specified by `A`. + /// - wgpu will act like it has complete ownership of this instance, and will destroy it + /// when the last reference to the instance, internal or external, is dropped. + pub unsafe fn from_hal(hal_instance: A::Instance) -> Self { + Self { + inner: unsafe { + crate::backend::ContextWgpuCore::from_hal_instance::(hal_instance).into() + }, + } + } + + /// Get the [`wgpu_hal`] instance from this `Instance`. + /// + /// Find the Api struct corresponding to the active backend in [`wgpu_hal::api`], + /// and pass that struct to the to the `A` type parameter. + /// + /// Returns a guard that dereferences to the type of the hal backend + /// which implements [`A::Instance`]. + /// + /// # Types + /// + #[doc = crate::hal_type_vulkan!("Instance")] + #[doc = crate::hal_type_metal!("Instance")] + #[doc = crate::hal_type_dx12!("Instance")] + #[doc = crate::hal_type_gles!("Instance")] + /// + /// # Errors + /// + /// This method will return None if: + /// - The instance is not from the backend specified by `A`. + /// - The instance is from the `webgpu` or `custom` backend. + /// + /// # Safety + /// + /// - The returned resource must not be destroyed unless the guard + /// is the last reference to it and it is not in use by the GPU. + /// The guard and handle may be dropped at any time however. + /// - All the safety requirements of wgpu-hal must be upheld. + /// + /// [`A::Instance`]: hal::Api::Instance + pub unsafe fn as_hal(&self) -> Option<&A::Instance> { + self.inner + .as_core_opt() + .and_then(|ctx| unsafe { ctx.instance_as_hal::() }) + } + + /// Converts a wgpu-hal [`hal::ExposedAdapter`] to a wgpu [`Adapter`]. + /// + /// # Types + /// + /// The type of `hal_adapter.adapter` depends on the backend: + /// + #[doc = crate::hal_type_vulkan!("Adapter")] + #[doc = crate::hal_type_metal!("Adapter")] + #[doc = crate::hal_type_dx12!("Adapter")] + #[doc = crate::hal_type_gles!("Adapter")] + /// + /// # Safety + /// + /// `hal_adapter` must be created from this instance internal handle. + pub unsafe fn create_adapter_from_hal( + &self, + hal_adapter: hal::ExposedAdapter, + ) -> Adapter { + let core_instance = self.inner.as_core(); + let adapter = unsafe { core_instance.create_adapter_from_hal(hal_adapter) }; + let core = backend::wgpu_core::CoreAdapter { + context: core_instance.clone(), + id: adapter, + }; + + Adapter { inner: core.into() } + } +} + +/// Interop with wgpu-core. +#[cfg(wgpu_core)] +impl Instance { + /// Create an new instance of wgpu from a wgpu-core instance. + /// + /// # Arguments + /// + /// - `core_instance` - wgpu-core instance. + /// + /// # Safety + /// + /// Refer to the creation of wgpu-core Instance. + pub unsafe fn from_core(core_instance: wgc::instance::Instance) -> Self { + Self { + inner: unsafe { + crate::backend::ContextWgpuCore::from_core_instance(core_instance).into() + }, + } + } +} + +/// Interop with custom backends. +#[cfg(custom)] +impl Instance { + /// Creates instance from custom context implementation + pub fn from_custom(instance: T) -> Self { + Self { + inner: dispatch::DispatchInstance::Custom(backend::custom::DynContext::new(instance)), + } + } + + #[cfg(custom)] + /// Returns custom implementation of Instance (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() } } diff --git a/wgpu/src/api/mod.rs b/wgpu/src/api/mod.rs index c4804d8b6..b564aa75f 100644 --- a/wgpu/src/api/mod.rs +++ b/wgpu/src/api/mod.rs @@ -26,12 +26,15 @@ mod bind_group_layout; mod blas; mod buffer; mod command_buffer; +/// Not a root type, but common types for command buffer deferral actions. +mod command_buffer_actions; mod command_encoder; // Not a root type, but common descriptor types for pipelines. mod common_pipeline; mod compute_pass; mod compute_pipeline; mod device; +mod external_texture; mod instance; mod pipeline_cache; mod pipeline_layout; @@ -55,11 +58,13 @@ pub use bind_group_layout::*; pub use blas::*; pub use buffer::*; pub use command_buffer::*; +use command_buffer_actions::*; pub use command_encoder::*; pub use common_pipeline::*; pub use compute_pass::*; pub use compute_pipeline::*; pub use device::*; +pub use external_texture::*; pub use instance::*; pub use pipeline_cache::*; pub use pipeline_layout::*; diff --git a/wgpu/src/api/pipeline_cache.rs b/wgpu/src/api/pipeline_cache.rs index f1cd414f5..c6f161aba 100644 --- a/wgpu/src/api/pipeline_cache.rs +++ b/wgpu/src/api/pipeline_cache.rs @@ -87,4 +87,10 @@ impl PipelineCache { pub fn get_data(&self) -> Option> { self.inner.get_data() } + + #[cfg(custom)] + /// Returns custom implementation of PipelineCache (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() + } } diff --git a/wgpu/src/api/pipeline_layout.rs b/wgpu/src/api/pipeline_layout.rs index 7baa91555..6bd71093c 100644 --- a/wgpu/src/api/pipeline_layout.rs +++ b/wgpu/src/api/pipeline_layout.rs @@ -15,6 +15,14 @@ static_assertions::assert_impl_all!(PipelineLayout: Send, Sync); crate::cmp::impl_eq_ord_hash_proxy!(PipelineLayout => .inner); +impl PipelineLayout { + #[cfg(custom)] + /// Returns custom implementation of PipelineLayout (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() + } +} + /// Describes a [`PipelineLayout`]. /// /// For use with [`Device::create_pipeline_layout`]. diff --git a/wgpu/src/api/query_set.rs b/wgpu/src/api/query_set.rs index 24b5a0280..dc89330f1 100644 --- a/wgpu/src/api/query_set.rs +++ b/wgpu/src/api/query_set.rs @@ -15,6 +15,14 @@ static_assertions::assert_impl_all!(QuerySet: Send, Sync); crate::cmp::impl_eq_ord_hash_proxy!(QuerySet => .inner); +impl QuerySet { + #[cfg(custom)] + /// Returns custom implementation of QuerySet (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() + } +} + /// Describes a [`QuerySet`]. /// /// For use with [`Device::create_query_set`]. diff --git a/wgpu/src/api/queue.rs b/wgpu/src/api/queue.rs index 7a03f8c0b..a61d0b023 100644 --- a/wgpu/src/api/queue.rs +++ b/wgpu/src/api/queue.rs @@ -1,7 +1,7 @@ use alloc::boxed::Box; use core::ops::{Deref, DerefMut}; -use crate::*; +use crate::{api::DeferredCommandBufferActions, *}; /// Handle to a command queue on a device. /// @@ -19,6 +19,22 @@ static_assertions::assert_impl_all!(Queue: Send, Sync); crate::cmp::impl_eq_ord_hash_proxy!(Queue => .inner); +impl Queue { + #[cfg(custom)] + /// Returns custom implementation of Queue (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() + } + + #[cfg(custom)] + /// Creates Queue from custom implementation + pub fn from_custom(queue: T) -> Self { + Self { + inner: dispatch::DispatchQueue::custom(queue), + } + } +} + /// Identifier for a particular call to [`Queue::submit`]. Can be used /// as part of an argument to [`Device::poll`] to block for a particular /// submission to finish. @@ -27,20 +43,11 @@ crate::cmp::impl_eq_ord_hash_proxy!(Queue => .inner); /// There is no analogue in the WebGPU specification. #[derive(Debug, Clone)] pub struct SubmissionIndex { - #[cfg_attr( - all( - target_arch = "wasm32", - not(target_os = "emscripten"), - not(feature = "webgl"), - ), - expect(dead_code) - )] pub(crate) index: u64, } #[cfg(send_sync)] static_assertions::assert_impl_all!(SubmissionIndex: Send, Sync); -pub use wgt::PollType as MaintainBase; /// Passed to [`Device::poll`] to control how and if it should block. pub type PollType = wgt::PollType; #[cfg(send_sync)] @@ -51,16 +58,24 @@ static_assertions::assert_impl_all!(PollType: Send, Sync); /// Reading into this buffer won't yield the contents of the buffer from the /// GPU and is likely to be slow. Because of this, although [`AsMut`] is /// implemented for this type, [`AsRef`] is not. -pub struct QueueWriteBufferView<'a> { - queue: &'a Queue, - buffer: &'a Buffer, +pub struct QueueWriteBufferView { + queue: Queue, + buffer: Buffer, offset: BufferAddress, inner: dispatch::DispatchQueueWriteBuffer, } #[cfg(send_sync)] -static_assertions::assert_impl_all!(QueueWriteBufferView<'_>: Send, Sync); +static_assertions::assert_impl_all!(QueueWriteBufferView: Send, Sync); -impl Deref for QueueWriteBufferView<'_> { +impl QueueWriteBufferView { + #[cfg(custom)] + /// Returns custom implementation of QueueWriteBufferView (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() + } +} + +impl Deref for QueueWriteBufferView { type Target = [u8]; fn deref(&self) -> &Self::Target { @@ -69,19 +84,19 @@ impl Deref for QueueWriteBufferView<'_> { } } -impl DerefMut for QueueWriteBufferView<'_> { +impl DerefMut for QueueWriteBufferView { fn deref_mut(&mut self) -> &mut Self::Target { self.inner.slice_mut() } } -impl AsMut<[u8]> for QueueWriteBufferView<'_> { +impl AsMut<[u8]> for QueueWriteBufferView { fn as_mut(&mut self) -> &mut [u8] { self.inner.slice_mut() } } -impl Drop for QueueWriteBufferView<'_> { +impl Drop for QueueWriteBufferView { fn drop(&mut self) { self.queue .inner @@ -90,14 +105,6 @@ impl Drop for QueueWriteBufferView<'_> { } impl Queue { - #[cfg(custom)] - /// Creates Queue from custom implementation - pub fn from_custom(queue: T) -> Self { - Self { - inner: dispatch::DispatchQueue::custom(queue), - } - } - /// Copies the bytes of `data` into `buffer` starting at `offset`. /// /// The data must be written fully in-bounds, that is, `offset + data.len() <= buffer.len()`. @@ -175,19 +182,19 @@ impl Queue { /// allocations, you might be able to use [`StagingBelt`](crate::util::StagingBelt), /// or buffers you explicitly create, map, and unmap yourself. #[must_use] - pub fn write_buffer_with<'a>( - &'a self, - buffer: &'a Buffer, + pub fn write_buffer_with( + &self, + buffer: &Buffer, offset: BufferAddress, size: BufferSize, - ) -> Option> { + ) -> Option { profiling::scope!("Queue::write_buffer_with"); self.inner .validate_write_buffer(&buffer.inner, offset, size)?; let staging_buffer = self.inner.create_staging_buffer(size)?; Some(QueueWriteBufferView { - queue: self, - buffer, + queue: self.clone(), + buffer: buffer.clone(), offset, inner: staging_buffer, }) @@ -225,7 +232,7 @@ impl Queue { } /// Schedule a copy of data from `image` into `texture`. - #[cfg(any(webgpu, webgl))] + #[cfg(web)] pub fn copy_external_image_to_texture( &self, source: &wgt::CopyExternalImageSourceInfo, @@ -241,10 +248,19 @@ impl Queue { &self, command_buffers: I, ) -> SubmissionIndex { - let mut command_buffers = command_buffers.into_iter().map(|comb| comb.buffer); + // As submit drains the iterator (even on error), collect deferred actions + // from each CommandBuffer along the way. + let mut actions = DeferredCommandBufferActions::default(); + let mut command_buffers = command_buffers.into_iter().map(|comb| { + actions.append(&mut comb.actions.lock()); + comb.buffer + }); let index = self.inner.submit(&mut command_buffers); + // Execute all deferred actions after submit. + actions.execute(&self.inner); + SubmissionIndex { index } } @@ -258,40 +274,75 @@ impl Queue { self.inner.get_timestamp_period() } - /// Registers a callback when the previous call to submit finishes running on the gpu. This callback - /// being called implies that all mapped buffer callbacks which were registered before this call will - /// have been called. + /// Registers a callback that is invoked when the previous [`Queue::submit`] finishes executing + /// on the GPU. When this callback runs, all mapped-buffer callbacks registered for the same + /// submission are guaranteed to have been called. /// - /// For the callback to complete, either `queue.submit(..)`, `instance.poll_all(..)`, or `device.poll(..)` - /// must be called elsewhere in the runtime, possibly integrated into an event loop or run on a separate thread. + /// For the callback to run, either [`queue.submit(..)`][q::s], [`instance.poll_all(..)`][i::p_a], + /// or [`device.poll(..)`][d::p] must be called elsewhere in the runtime, possibly integrated into + /// an event loop or run on a separate thread. /// - /// The callback will be called on the thread that first calls the above functions after the gpu work - /// has completed. There are no restrictions on the code you can run in the callback, however on native the - /// call to the function will not complete until the callback returns, so prefer keeping callbacks short - /// and used to set flags, send messages, etc. + /// The callback runs on the thread that first calls one of the above functions after the GPU work + /// completes. There are no restrictions on the code you can run in the callback; however, on native + /// the polling call will not return until the callback finishes, so keep callbacks short (set flags, + /// send messages, etc.). + /// + /// [q::s]: Queue::submit + /// [i::p_a]: Instance::poll_all + /// [d::p]: Device::poll pub fn on_submitted_work_done(&self, callback: impl FnOnce() + Send + 'static) { self.inner.on_submitted_work_done(Box::new(callback)); } - /// Returns the inner hal Queue using a callback. The hal queue will be `None` if the - /// backend type argument does not match with this wgpu Queue + /// Get the [`wgpu_hal`] device from this `Queue`. + /// + /// Find the Api struct corresponding to the active backend in [`wgpu_hal::api`], + /// and pass that struct to the to the `A` type parameter. + /// + /// Returns a guard that dereferences to the type of the hal backend + /// which implements [`A::Queue`]. + /// + /// # Types + /// + /// The returned type depends on the backend: + /// + #[doc = crate::hal_type_vulkan!("Queue")] + #[doc = crate::hal_type_metal!("Queue")] + #[doc = crate::hal_type_dx12!("Queue")] + #[doc = crate::hal_type_gles!("Queue")] + /// + /// # Errors + /// + /// This method will return None if: + /// - The queue is not from the backend specified by `A`. + /// - The queue is from the `webgpu` or `custom` backend. /// /// # Safety /// - /// - The raw handle obtained from the hal Queue must not be manually destroyed + /// - The returned resource must not be destroyed unless the guard + /// is the last reference to it and it is not in use by the GPU. + /// The guard and handle may be dropped at any time however. + /// - All the safety requirements of wgpu-hal must be upheld. + /// + /// [`A::Queue`]: hal::Api::Queue #[cfg(wgpu_core)] - pub unsafe fn as_hal) -> R, R>( + pub unsafe fn as_hal( &self, - hal_queue_callback: F, - ) -> R { - if let Some(core_queue) = self.inner.as_core_opt() { - unsafe { - core_queue - .context - .queue_as_hal::(core_queue, hal_queue_callback) - } - } else { - hal_queue_callback(None) + ) -> Option + WasmNotSendSync> { + let queue = self.inner.as_core_opt()?; + unsafe { queue.context.queue_as_hal::(queue) } + } + + /// Compact a BLAS, it must have had [`Blas::prepare_compaction_async`] called on it and had the + /// callback provided called. + /// + /// The returned BLAS is more restricted than a normal BLAS because it may not be rebuilt or + /// compacted. + pub fn compact_blas(&self, blas: &Blas) -> Blas { + let (handle, dispatch) = self.inner.compact_blas(&blas.inner); + Blas { + handle, + inner: dispatch, } } } diff --git a/wgpu/src/api/render_bundle.rs b/wgpu/src/api/render_bundle.rs index 95de97620..2ea592940 100644 --- a/wgpu/src/api/render_bundle.rs +++ b/wgpu/src/api/render_bundle.rs @@ -18,6 +18,14 @@ static_assertions::assert_impl_all!(RenderBundle: Send, Sync); crate::cmp::impl_eq_ord_hash_proxy!(RenderBundle => .inner); +impl RenderBundle { + #[cfg(custom)] + /// Returns custom implementation of RenderBundle (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() + } +} + /// Describes a [`RenderBundle`]. /// /// For use with [`RenderBundleEncoder::finish`]. diff --git a/wgpu/src/api/render_bundle_encoder.rs b/wgpu/src/api/render_bundle_encoder.rs index bd64dbbc7..483bfd084 100644 --- a/wgpu/src/api/render_bundle_encoder.rs +++ b/wgpu/src/api/render_bundle_encoder.rs @@ -93,7 +93,7 @@ impl<'a> RenderBundleEncoder<'a> { &buffer_slice.buffer.inner, index_format, buffer_slice.offset, - buffer_slice.size, + Some(buffer_slice.size), ); } @@ -112,7 +112,7 @@ impl<'a> RenderBundleEncoder<'a> { slot, &buffer_slice.buffer.inner, buffer_slice.offset, - buffer_slice.size, + Some(buffer_slice.size), ); } @@ -188,6 +188,12 @@ impl<'a> RenderBundleEncoder<'a> { self.inner .draw_indexed_indirect(&indirect_buffer.inner, indirect_offset); } + + #[cfg(custom)] + /// Returns custom implementation of RenderBundleEncoder (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() + } } /// [`Features::PUSH_CONSTANTS`] must be enabled on the device in order to call these functions. diff --git a/wgpu/src/api/render_pass.rs b/wgpu/src/api/render_pass.rs index 6c30543f6..bd250e7b3 100644 --- a/wgpu/src/api/render_pass.rs +++ b/wgpu/src/api/render_pass.rs @@ -1,6 +1,9 @@ -use core::ops::Range; +use core::{num::NonZeroU32, ops::Range}; -use crate::*; +use crate::{ + api::{impl_deferred_command_buffer_actions, SharedDeferredCommandBufferActions}, + *, +}; pub use wgt::{LoadOp, Operations, StoreOp}; /// In-progress recording of a render pass: a list of render commands in a [`CommandEncoder`]. @@ -24,6 +27,7 @@ pub use wgt::{LoadOp, Operations, StoreOp}; #[derive(Debug)] pub struct RenderPass<'encoder> { pub(crate) inner: dispatch::DispatchRenderPass, + pub(crate) actions: SharedDeferredCommandBufferActions, /// This lifetime is used to protect the [`CommandEncoder`] from being used /// while the pass is alive. This needs to be PhantomDrop to prevent the lifetime @@ -52,6 +56,7 @@ impl RenderPass<'_> { pub fn forget_lifetime(self) -> RenderPass<'static> { RenderPass { inner: self.inner, + actions: self.actions, _encoder_guard: crate::api::PhantomDrop::default(), } } @@ -100,7 +105,7 @@ impl RenderPass<'_> { &buffer_slice.buffer.inner, index_format, buffer_slice.offset, - buffer_slice.size, + Some(buffer_slice.size), ); } @@ -121,7 +126,7 @@ impl RenderPass<'_> { slot, &buffer_slice.buffer.inner, buffer_slice.offset, - buffer_slice.size, + Some(buffer_slice.size), ); } @@ -226,19 +231,44 @@ impl RenderPass<'_> { self.inner.draw_indexed(indices, base_vertex, instances); } + /// Draws using a mesh pipeline. + /// + /// The current pipeline must be a mesh pipeline. + /// + /// If the current pipeline has a task shader, run it with an workgroup for + /// every `vec3(i, j, k)` where `i`, `j`, and `k` are between `0` and + /// `group_count_x`, `group_count_y`, and `group_count_z`. The invocation with + /// index zero in each group is responsible for determining the mesh shader dispatch. + /// Its return value indicates the number of workgroups of mesh shaders to invoke. It also + /// passes a payload value for them to consume. Because each task workgroup is essentially + /// a mesh shader draw call, mesh workgroups dispatched by different task workgroups + /// cannot interact in any way, and `workgroup_id` corresponds to its location in the + /// calling specific task shader's dispatch group. + /// + /// If the current pipeline lacks a task shader, run its mesh shader with a + /// workgroup for every `vec3(i, j, k)` where `i`, `j`, and `k` are + /// between `0` and `group_count_x`, `group_count_y`, and `group_count_z`. + /// + /// Each mesh shader workgroup outputs a set of vertices and indices for primitives. + /// The indices outputted correspond to the vertices outputted by that same workgroup; + /// there is no global vertex buffer. These primitives are passed to the rasterizer and + /// essentially treated like a vertex shader output, except that the mesh shader may + /// choose to cull specific primitives or pass per-primitive non-interpolated values + /// to the fragment shader. As such, each primitive is then rendered with the current + /// pipeline's fragment shader, if present. Otherwise, [No Color Output mode] is used. + /// + /// [No Color Output mode]: https://www.w3.org/TR/webgpu/#no-color-output + pub fn draw_mesh_tasks(&mut self, group_count_x: u32, group_count_y: u32, group_count_z: u32) { + self.inner + .draw_mesh_tasks(group_count_x, group_count_y, group_count_z); + } + /// Draws primitives from the active vertex buffer(s) based on the contents of the `indirect_buffer`. /// /// This is like calling [`RenderPass::draw`] but the contents of the call are specified in the `indirect_buffer`. /// The structure expected in `indirect_buffer` must conform to [`DrawIndirectArgs`](crate::util::DrawIndirectArgs). /// - /// Indirect drawing has some caveats depending on the features available. We are not currently able to validate - /// these and issue an error. - /// - If [`Features::INDIRECT_FIRST_INSTANCE`] is not present on the adapter, - /// [`DrawIndirectArgs::first_instance`](crate::util::DrawIndirectArgs::first_instance) will be ignored. - /// - If [`DownlevelFlags::VERTEX_AND_INSTANCE_INDEX_RESPECTS_RESPECTIVE_FIRST_VALUE_IN_INDIRECT_DRAW`] is not present on the adapter, - /// any use of `@builtin(vertex_index)` or `@builtin(instance_index)` in the vertex shader will have different values. - /// - /// See details on the individual flags for more information. + /// Calling this requires the device support [`DownlevelFlags::INDIRECT_EXECUTION`]. pub fn draw_indirect(&mut self, indirect_buffer: &Buffer, indirect_offset: BufferAddress) { self.inner .draw_indirect(&indirect_buffer.inner, indirect_offset); @@ -250,14 +280,7 @@ impl RenderPass<'_> { /// This is like calling [`RenderPass::draw_indexed`] but the contents of the call are specified in the `indirect_buffer`. /// The structure expected in `indirect_buffer` must conform to [`DrawIndexedIndirectArgs`](crate::util::DrawIndexedIndirectArgs). /// - /// Indirect drawing has some caveats depending on the features available. We are not currently able to validate - /// these and issue an error. - /// - If [`Features::INDIRECT_FIRST_INSTANCE`] is not present on the adapter, - /// [`DrawIndexedIndirectArgs::first_instance`](crate::util::DrawIndexedIndirectArgs::first_instance) will be ignored. - /// - If [`DownlevelFlags::VERTEX_AND_INSTANCE_INDEX_RESPECTS_RESPECTIVE_FIRST_VALUE_IN_INDIRECT_DRAW`] is not present on the adapter, - /// any use of `@builtin(vertex_index)` or `@builtin(instance_index)` in the vertex shader will have different values. - /// - /// See details on the individual flags for more information. + /// Calling this requires the device support [`DownlevelFlags::INDIRECT_EXECUTION`]. pub fn draw_indexed_indirect( &mut self, indirect_buffer: &Buffer, @@ -267,6 +290,27 @@ impl RenderPass<'_> { .draw_indexed_indirect(&indirect_buffer.inner, indirect_offset); } + /// Draws using a mesh pipeline, + /// based on the contents of the `indirect_buffer` + /// + /// This is like calling [`RenderPass::draw_mesh_tasks`] but the contents of the call are specified in the `indirect_buffer`. + /// The structure expected in the `indirect_buffer` must conform to [`DispatchIndirectArgs`](crate::util::DispatchIndirectArgs). + /// + /// Indirect drawing has some caveats depending on the features available. We are not currently able to validate + /// these and issue an error. + /// + /// See details on the individual flags for more information. + pub fn draw_mesh_tasks_indirect( + &mut self, + indirect_buffer: &Buffer, + indirect_offset: BufferAddress, + ) { + self.inner + .draw_mesh_tasks_indirect(&indirect_buffer.inner, indirect_offset); + } + + impl_deferred_command_buffer_actions!(); + /// Execute a [render bundle][RenderBundle], which is a set of pre-recorded commands /// that can be run together. /// @@ -280,10 +324,7 @@ impl RenderPass<'_> { self.inner.execute_bundles(&mut render_bundles); } -} -/// [`Features::MULTI_DRAW_INDIRECT`] must be enabled on the device in order to call these functions. -impl RenderPass<'_> { /// Dispatches multiple draw calls from the active vertex buffer(s) based on the contents of the `indirect_buffer`. /// `count` draw calls are issued. /// @@ -292,6 +333,8 @@ impl RenderPass<'_> { /// The structure expected in `indirect_buffer` must conform to [`DrawIndirectArgs`](crate::util::DrawIndirectArgs). /// These draw structures are expected to be tightly packed. /// + /// Calling this requires the device support [`DownlevelFlags::INDIRECT_EXECUTION`]. + /// /// This drawing command uses the current render state, as set by preceding `set_*()` methods. /// It is not affected by changes to the state that are performed after it is called. pub fn multi_draw_indirect( @@ -313,6 +356,8 @@ impl RenderPass<'_> { /// The structure expected in `indirect_buffer` must conform to [`DrawIndexedIndirectArgs`](crate::util::DrawIndexedIndirectArgs). /// These draw structures are expected to be tightly packed. /// + /// Calling this requires the device support [`DownlevelFlags::INDIRECT_EXECUTION`]. + /// /// This drawing command uses the current render state, as set by preceding `set_*()` methods. /// It is not affected by changes to the state that are performed after it is called. pub fn multi_draw_indexed_indirect( @@ -324,6 +369,29 @@ impl RenderPass<'_> { self.inner .multi_draw_indexed_indirect(&indirect_buffer.inner, indirect_offset, count); } + + /// Dispatches multiple draw calls based on the contents of the `indirect_buffer`. + /// `count` draw calls are issued. + /// + /// The structure expected in the `indirect_buffer` must conform to [`DispatchIndirectArgs`](crate::util::DispatchIndirectArgs). + /// + /// This drawing command uses the current render state, as set by preceding `set_*()` methods. + /// It is not affected by changes to the state that are performed after it is called. + pub fn multi_draw_mesh_tasks_indirect( + &mut self, + indirect_buffer: &Buffer, + indirect_offset: BufferAddress, + count: u32, + ) { + self.inner + .multi_draw_mesh_tasks_indirect(&indirect_buffer.inner, indirect_offset, count); + } + + #[cfg(custom)] + /// Returns custom implementation of RenderPass (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() + } } /// [`Features::MULTI_DRAW_INDIRECT_COUNT`] must be enabled on the device in order to call these functions. @@ -407,6 +475,34 @@ impl RenderPass<'_> { max_count, ); } + + /// Dispatches multiple draw calls based on the contents of the `indirect_buffer`. The count buffer is read to determine how many draws to issue. + /// + /// The indirect buffer must be long enough to account for `max_count` draws, however only `count` + /// draws will be read. If `count` is greater than `max_count`, `max_count` will be used. + /// + /// The structure expected in the `indirect_buffer` must conform to [`DispatchIndirectArgs`](crate::util::DispatchIndirectArgs). + /// + /// These draw structures are expected to be tightly packed. + /// + /// This drawing command uses the current render state, as set by preceding `set_*()` methods. + /// It is not affected by changes to the state that are performed after it is called. + pub fn multi_draw_mesh_tasks_indirect_count( + &mut self, + indirect_buffer: &Buffer, + indirect_offset: BufferAddress, + count_buffer: &Buffer, + count_offset: BufferAddress, + max_count: u32, + ) { + self.inner.multi_draw_mesh_tasks_indirect_count( + &indirect_buffer.inner, + indirect_offset, + &count_buffer.inner, + count_offset, + max_count, + ); + } } /// [`Features::PUSH_CONSTANTS`] must be enabled on the device in order to call these functions. @@ -534,6 +630,8 @@ static_assertions::assert_impl_all!(RenderPassTimestampWrites<'_>: Send, Sync); pub struct RenderPassColorAttachment<'tex> { /// The view to use as an attachment. pub view: &'tex TextureView, + /// The depth slice index of a 3D view. It must not be provided if the view is not 3D. + pub depth_slice: Option, /// The view that will receive the resolved output if multisampling is used. /// /// If set, it is always written to, regardless of how [`Self::ops`] is configured. @@ -582,6 +680,12 @@ pub struct RenderPassDescriptor<'a> { pub timestamp_writes: Option>, /// Defines where the occlusion query results will be stored for this pass. pub occlusion_query_set: Option<&'a QuerySet>, + /// The mask of multiview image layers to use for this render pass. For example, if you wish + /// to render to the first 2 layers, you would use 3=0b11. If you wanted ro render to only the + /// 2nd layer, you would use 2=0b10. If you aren't using multiview this should be `None`. + /// + /// Note that setting bits higher than the number of texture layers is a validation error. + pub multiview_mask: Option, } #[cfg(send_sync)] static_assertions::assert_impl_all!(RenderPassDescriptor<'_>: Send, Sync); diff --git a/wgpu/src/api/render_pipeline.rs b/wgpu/src/api/render_pipeline.rs index 5ef23ff0d..ebc89633b 100644 --- a/wgpu/src/api/render_pipeline.rs +++ b/wgpu/src/api/render_pipeline.rs @@ -28,6 +28,12 @@ impl RenderPipeline { let layout = self.inner.get_bind_group_layout(index); BindGroupLayout { inner: layout } } + + #[cfg(custom)] + /// Returns custom implementation of RenderPipeline (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() + } } /// Specifies an interpretation of the bytes of a vertex buffer as vertex attributes. @@ -70,7 +76,7 @@ impl RenderPipeline { pub struct VertexBufferLayout<'a> { /// The stride, in bytes, between elements of this buffer (between vertices). /// - /// This must be a multiple of [`VERTEX_STRIDE_ALIGNMENT`]. + /// This must be a multiple of [`VERTEX_ALIGNMENT`]. pub array_stride: BufferAddress, /// How often this vertex buffer is "stepped" forward. pub step_mode: VertexStepMode, @@ -139,6 +145,50 @@ pub struct FragmentState<'a> { #[cfg(send_sync)] static_assertions::assert_impl_all!(FragmentState<'_>: Send, Sync); +/// Describes the task shader stage in a mesh shader pipeline. +/// +/// For use in [`MeshPipelineDescriptor`] +#[derive(Clone, Debug)] +pub struct TaskState<'a> { + /// The compiled shader module for this stage. + pub module: &'a ShaderModule, + + /// The name of the task shader entry point in the shader module to use. + /// + /// If [`Some`], there must be a task shader entry point with the given name + /// in `module`. Otherwise, there must be exactly one task shader entry + /// point in `module`, which will be selected. + pub entry_point: Option<&'a str>, + + /// Advanced options for when this pipeline is compiled. + /// + /// This implements `Default`, and for most users can be set to `Default::default()` + pub compilation_options: PipelineCompilationOptions<'a>, +} +#[cfg(send_sync)] +static_assertions::assert_impl_all!(TaskState<'_>: Send, Sync); + +/// Describes the mesh shader stage in a mesh shader pipeline. +/// +/// For use in [`MeshPipelineDescriptor`] +#[derive(Clone, Debug)] +pub struct MeshState<'a> { + /// The compiled shader module for this stage. + pub module: &'a ShaderModule, + /// The name of the entry point in the compiled shader to use. + /// + /// If [`Some`], there must be a vertex-stage shader entry point with this name in `module`. + /// Otherwise, expect exactly one vertex-stage entry point in `module`, which will be + /// selected. + pub entry_point: Option<&'a str>, + /// Advanced options for when this pipeline is compiled + /// + /// This implements `Default`, and for most users can be set to `Default::default()` + pub compilation_options: PipelineCompilationOptions<'a>, +} +#[cfg(send_sync)] +static_assertions::assert_impl_all!(MeshState<'_>: Send, Sync); + /// Describes a render (graphics) pipeline. /// /// For use with [`Device::create_render_pipeline`]. @@ -179,6 +229,101 @@ pub struct RenderPipelineDescriptor<'a> { pub multisample: MultisampleState, /// The compiled fragment stage, its entry point, and the color targets. pub fragment: Option>, + /// If the pipeline will be used with a multiview render pass, this indicates what multiview + /// mask the render pass will be used with. The masks must match exactly. + /// + /// For example, if you wish to render to the first 2 layers, you would use 3=0b11. If you + /// wanted to render to only the 2nd layer, you would use 2=0b10. If you aren't using + /// multiview this should be `None`. + pub multiview_mask: Option, + /// The pipeline cache to use when creating this pipeline. + pub cache: Option<&'a PipelineCache>, +} +#[cfg(send_sync)] +static_assertions::assert_impl_all!(RenderPipelineDescriptor<'_>: Send, Sync); + +/// Describes a mesh shader (graphics) pipeline. +/// +/// For use with [`Device::create_mesh_pipeline`]. A mesh pipeline is very much +/// like a render pipeline, except that instead of [`RenderPass::draw`] it is +/// invoked with [`RenderPass::draw_mesh_tasks`], and instead of a vertex shader +/// and a fragment shader: +/// +/// - [`task`] specifies an optional task shader entry point, which determines how +/// many groups of mesh shaders to dispatch. +/// +/// - [`mesh`] specifies a mesh shader entry point, which generates groups of +/// primitives to draw +/// +/// - [`fragment`] specifies as fragment shader for drawing those primitives, +/// just like in an ordinary render pipeline. +/// +/// The key difference is that, whereas a vertex shader is invoked on the +/// elements of vertex buffers, the task shader gets to decide how many mesh +/// shader workgroups to make, and then each mesh shader workgroup gets to +/// decide which primitives it wants to generate, and what their vertex +/// attributes are. Task and mesh shaders can use whatever they please as +/// inputs, like a compute shader. However, they cannot use specialized vertex +/// or index buffers. +/// +/// A mesh pipeline is invoked by [`RenderPass::draw_mesh_tasks`], which looks +/// like a compute shader dispatch with [`ComputePass::dispatch_workgroups`]: +/// you pass `x`, `y`, and `z` values indicating the number of task shaders to +/// invoke in parallel. The output value of the first thread in a task shader +/// workgroup determines how many mesh workgroups should be dispatched from there. +/// Those mesh workgroups also get a special payload passed from the task shader. +/// +/// If the task shader is omitted, then the (`x`, `y`, `z`) parameters to +/// `draw_mesh_tasks` are used to decide how many invocations of the mesh shader +/// to invoke directly, without a task payload. +/// +/// [vertex formats]: wgpu_types::VertexFormat +/// [`task`]: Self::task +/// [`mesh`]: Self::mesh +/// [`fragment`]: Self::fragment +#[derive(Clone, Debug)] +pub struct MeshPipelineDescriptor<'a> { + /// Debug label of the pipeline. This will show up in graphics debuggers for easy identification. + pub label: Label<'a>, + /// The layout of bind groups for this pipeline. + /// + /// If this is set, then [`Device::create_render_pipeline`] will raise a validation error if + /// the layout doesn't match what the shader module(s) expect. + /// + /// Using the same [`PipelineLayout`] for many [`RenderPipeline`] or [`ComputePipeline`] + /// pipelines guarantees that you don't have to rebind any resources when switching between + /// those pipelines. + /// + /// ## Default pipeline layout + /// + /// If `layout` is `None`, then the pipeline has a [default layout] created and used instead. + /// The default layout is deduced from the shader modules. + /// + /// You can use [`RenderPipeline::get_bind_group_layout`] to create bind groups for use with the + /// default layout. However, these bind groups cannot be used with any other pipelines. This is + /// convenient for simple pipelines, but using an explicit layout is recommended in most cases. + /// + /// [default layout]: https://www.w3.org/TR/webgpu/#default-pipeline-layout + pub layout: Option<&'a PipelineLayout>, + + /// The mesh pipeline's task shader. + /// + /// If this is `None`, the mesh pipeline has no task shader. Executing a + /// mesh drawing command simply dispatches a grid of mesh shaders directly. + /// + /// [`draw_mesh_tasks`]: RenderPass::draw_mesh_tasks + pub task: Option>, + + /// The compiled mesh stage and its entry point + pub mesh: MeshState<'a>, + /// The properties of the pipeline at the primitive assembly and rasterization level. + pub primitive: PrimitiveState, + /// The effect of draw calls on the depth and stencil aspects of the output target, if any. + pub depth_stencil: Option, + /// The multi-sampling properties of the pipeline. + pub multisample: MultisampleState, + /// The compiled fragment stage, its entry point, and the color targets. + pub fragment: Option>, /// If the pipeline will be used with a multiview render pass, this indicates how many array /// layers the attachments will have. pub multiview: Option, @@ -186,4 +331,4 @@ pub struct RenderPipelineDescriptor<'a> { pub cache: Option<&'a PipelineCache>, } #[cfg(send_sync)] -static_assertions::assert_impl_all!(RenderPipelineDescriptor<'_>: Send, Sync); +static_assertions::assert_impl_all!(MeshPipelineDescriptor<'_>: Send, Sync); diff --git a/wgpu/src/api/sampler.rs b/wgpu/src/api/sampler.rs index 49c988e85..a8916829c 100644 --- a/wgpu/src/api/sampler.rs +++ b/wgpu/src/api/sampler.rs @@ -18,6 +18,14 @@ static_assertions::assert_impl_all!(Sampler: Send, Sync); crate::cmp::impl_eq_ord_hash_proxy!(Sampler => .inner); +impl Sampler { + #[cfg(custom)] + /// Returns custom implementation of Sampler (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() + } +} + /// Describes a [`Sampler`]. /// /// For use with [`Device::create_sampler`]. diff --git a/wgpu/src/api/shader_module.rs b/wgpu/src/api/shader_module.rs index 241d19b09..b2aad03ab 100644 --- a/wgpu/src/api/shader_module.rs +++ b/wgpu/src/api/shader_module.rs @@ -1,9 +1,4 @@ -use alloc::{ - borrow::Cow, - string::{String, ToString as _}, - vec, - vec::Vec, -}; +use alloc::{string::String, vec::Vec}; use core::{future::Future, marker::PhantomData}; use crate::*; @@ -11,9 +6,9 @@ use crate::*; /// Handle to a compiled shader module. /// /// A `ShaderModule` represents a compiled shader module on the GPU. It can be created by passing -/// source code to [`Device::create_shader_module`] or valid SPIR-V binary to -/// [`Device::create_shader_module_spirv`]. Shader modules are used to define programmable stages -/// of a pipeline. +/// source code to [`Device::create_shader_module`]. MSL shader or SPIR-V binary can also be passed +/// directly using [`Device::create_shader_module_passthrough`]. Shader modules are used to define +/// programmable stages of a pipeline. /// /// Corresponds to [WebGPU `GPUShaderModule`](https://gpuweb.github.io/gpuweb/#shader-module). #[derive(Debug, Clone)] @@ -30,6 +25,12 @@ impl ShaderModule { pub fn get_compilation_info(&self) -> impl Future + WasmNotSend { self.inner.get_compilation_info() } + + #[cfg(custom)] + /// Returns custom implementation of ShaderModule (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() + } } /// Compilation information for a shader module. @@ -93,6 +94,7 @@ impl From> for CompilationInfo { fn from(value: crate::naga::error::ShaderError) -> Self { + use alloc::{string::ToString, vec}; CompilationInfo { messages: vec![CompilationMessage { message: value.to_string(), @@ -105,6 +107,7 @@ impl From> #[cfg(feature = "glsl")] impl From> for CompilationInfo { fn from(value: naga::error::ShaderError) -> Self { + use alloc::string::ToString; let messages = value .inner .errors @@ -122,6 +125,7 @@ impl From> for Compilat #[cfg(feature = "spirv")] impl From> for CompilationInfo { fn from(value: naga::error::ShaderError) -> Self { + use alloc::{string::ToString, vec}; CompilationInfo { messages: vec![CompilationMessage { message: value.to_string(), @@ -143,6 +147,7 @@ impl crate::naga::WithSpan, >, ) -> Self { + use alloc::{string::ToString, vec}; CompilationInfo { messages: vec![CompilationMessage { message: value.to_string(), @@ -182,14 +187,14 @@ pub enum ShaderSource<'a> { /// /// See also: [`util::make_spirv`], [`include_spirv`] #[cfg(feature = "spirv")] - SpirV(Cow<'a, [u32]>), + SpirV(alloc::borrow::Cow<'a, [u32]>), /// GLSL module as a string slice. /// /// Note: GLSL is not yet fully supported and must be a specific ShaderStage. #[cfg(feature = "glsl")] Glsl { /// The source code of the shader. - shader: Cow<'a, str>, + shader: alloc::borrow::Cow<'a, str>, /// The shader stage that the shader targets. For example, `naga::ShaderStage::Vertex` stage: naga::ShaderStage, /// Key-value pairs to represent defines sent to the glsl preprocessor. @@ -199,10 +204,10 @@ pub enum ShaderSource<'a> { }, /// WGSL module as a string slice. #[cfg(feature = "wgsl")] - Wgsl(Cow<'a, str>), + Wgsl(alloc::borrow::Cow<'a, str>), /// Naga module. #[cfg(feature = "naga-ir")] - Naga(Cow<'static, naga::Module>), + Naga(alloc::borrow::Cow<'static, naga::Module>), /// Dummy variant because `Naga` doesn't have a lifetime and without enough active features it /// could be the last one active. #[doc(hidden)] @@ -223,16 +228,10 @@ pub struct ShaderModuleDescriptor<'a> { } static_assertions::assert_impl_all!(ShaderModuleDescriptor<'_>: Send, Sync); -/// Descriptor for a shader module given by SPIR-V binary, for use with -/// [`Device::create_shader_module_spirv`]. +/// Descriptor for a shader module given by any of several sources. +/// At least one of the shader types that may be used by the backend must be `Some` /// /// This type is unique to the Rust API of `wgpu`. In the WebGPU specification, /// only WGSL source code strings are accepted. -#[derive(Debug)] -pub struct ShaderModuleDescriptorSpirV<'a> { - /// Debug label of the shader module. This will show up in graphics debuggers for easy identification. - pub label: Label<'a>, - /// Binary SPIR-V data, in 4-byte words. - pub source: Cow<'a, [u32]>, -} -static_assertions::assert_impl_all!(ShaderModuleDescriptorSpirV<'_>: Send, Sync); +pub type ShaderModuleDescriptorPassthrough<'a> = + wgt::CreateShaderModuleDescriptorPassthrough<'a, Label<'a>>; diff --git a/wgpu/src/api/surface.rs b/wgpu/src/api/surface.rs index bc94a4d21..113f46639 100644 --- a/wgpu/src/api/surface.rs +++ b/wgpu/src/api/surface.rs @@ -1,9 +1,11 @@ use alloc::{boxed::Box, string::String, vec, vec::Vec}; +#[cfg(wgpu_core)] +use core::ops::Deref; use core::{error, fmt}; -use parking_lot::Mutex; use raw_window_handle::{HasDisplayHandle, HasWindowHandle}; +use crate::util::Mutex; use crate::*; /// Describes a [`Surface`]. @@ -148,28 +150,50 @@ impl Surface<'_> { .ok_or(SurfaceError::Lost) } - /// Returns the inner hal Surface using a callback. The hal surface will be `None` if the - /// backend type argument does not match with this wgpu Surface + /// Get the [`wgpu_hal`] surface from this `Surface`. + /// + /// Find the Api struct corresponding to the active backend in [`wgpu_hal::api`], + /// and pass that struct to the to the `A` type parameter. + /// + /// Returns a guard that dereferences to the type of the hal backend + /// which implements [`A::Surface`]. + /// + /// # Types + /// + /// The returned type depends on the backend: + /// + #[doc = crate::hal_type_vulkan!("Surface")] + #[doc = crate::hal_type_metal!("Surface")] + #[doc = crate::hal_type_dx12!("Surface")] + #[doc = crate::hal_type_gles!("Surface")] + /// + /// # Errors + /// + /// This method will return None if: + /// - The surface is not from the backend specified by `A`. + /// - The surface is from the `webgpu` or `custom` backend. /// /// # Safety /// - /// - The raw handle obtained from the hal Surface must not be manually destroyed + /// - The returned resource must not be destroyed unless the guard + /// is the last reference to it and it is not in use by the GPU. + /// The guard and handle may be dropped at any time however. + /// - All the safety requirements of wgpu-hal must be upheld. + /// + /// [`A::Surface`]: hal::Api::Surface #[cfg(wgpu_core)] - pub unsafe fn as_hal) -> R, R>( + pub unsafe fn as_hal( &self, - hal_surface_callback: F, - ) -> R { - let core_surface = self.inner.as_core_opt(); + ) -> Option + WasmNotSendSync> { + let core_surface = self.inner.as_core_opt()?; - if let Some(core_surface) = core_surface { - unsafe { - core_surface - .context - .surface_as_hal::(core_surface, hal_surface_callback) - } - } else { - hal_surface_callback(None) - } + unsafe { core_surface.context.surface_as_hal::(core_surface) } + } + + #[cfg(custom)] + /// Returns custom implementation of Surface (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() } } @@ -237,7 +261,7 @@ pub enum SurfaceTarget<'window> { /// /// - On WebGL2: surface creation will return an error if the browser does not support WebGL2, /// or declines to provide GPU access (such as due to a resource shortage). - #[cfg(any(webgpu, webgl))] + #[cfg(web)] Canvas(web_sys::HtmlCanvasElement), /// Surface from a `web_sys::OffscreenCanvas`. @@ -249,7 +273,7 @@ pub enum SurfaceTarget<'window> { /// /// - On WebGL2: surface creation will return an error if the browser does not support WebGL2, /// or declines to provide GPU access (such as due to a resource shortage). - #[cfg(any(webgpu, webgl))] + #[cfg(web)] OffscreenCanvas(web_sys::OffscreenCanvas), } @@ -407,7 +431,10 @@ impl error::Error for CreateSurfaceError { #[cfg(wgpu_core)] CreateSurfaceErrorKind::Hal(e) => e.source(), CreateSurfaceErrorKind::Web(_) => None, + #[cfg(feature = "std")] CreateSurfaceErrorKind::RawHandle(e) => e.source(), + #[cfg(not(feature = "std"))] + CreateSurfaceErrorKind::RawHandle(_) => None, } } } diff --git a/wgpu/src/api/surface_texture.rs b/wgpu/src/api/surface_texture.rs index 7ceeffb95..28298c9f2 100644 --- a/wgpu/src/api/surface_texture.rs +++ b/wgpu/src/api/surface_texture.rs @@ -1,5 +1,4 @@ use core::{error, fmt}; -use std::thread; use crate::*; @@ -38,11 +37,17 @@ impl SurfaceTexture { self.presented = true; self.detail.present(); } + + #[cfg(custom)] + /// Returns custom implementation of SurfaceTexture (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.detail.as_custom() + } } impl Drop for SurfaceTexture { fn drop(&mut self) { - if !self.presented && !thread::panicking() { + if !self.presented && !thread_panicking() { self.detail.texture_discard(); } } @@ -77,3 +82,22 @@ impl fmt::Display for SurfaceError { } impl error::Error for SurfaceError {} + +fn thread_panicking() -> bool { + cfg_if::cfg_if! { + if #[cfg(std)] { + std::thread::panicking() + } else if #[cfg(panic = "abort")] { + // If `panic = "abort"` then a thread _cannot_ be observably panicking by definition. + false + } else { + // TODO: This is potentially overly pessimistic; it may be appropriate to instead allow a + // texture to not be discarded. + // Alternatively, this could _also_ be a `panic!`, since we only care if the thread is panicking + // when the surface has not been presented. + compile_error!( + "cannot determine if a thread is panicking without either `panic = \"abort\"` or `std`" + ); + } + } +} diff --git a/wgpu/src/api/texture.rs b/wgpu/src/api/texture.rs index 8ac80e650..2f1034331 100644 --- a/wgpu/src/api/texture.rs +++ b/wgpu/src/api/texture.rs @@ -1,3 +1,6 @@ +#[cfg(wgpu_core)] +use core::ops::Deref; + use crate::*; /// Handle to a texture on the GPU. @@ -16,24 +19,69 @@ static_assertions::assert_impl_all!(Texture: Send, Sync); crate::cmp::impl_eq_ord_hash_proxy!(Texture => .inner); impl Texture { - /// Returns the inner hal Texture using a callback. The hal texture will be `None` if the - /// backend type argument does not match with this wgpu Texture + /// Get the [`wgpu_hal`] texture from this `Texture`. + /// + /// Find the Api struct corresponding to the active backend in [`wgpu_hal::api`], + /// and pass that struct to the to the `A` type parameter. + /// + /// Returns a guard that dereferences to the type of the hal backend + /// which implements [`A::Texture`]. + /// + /// # Types + /// + /// The returned type depends on the backend: + /// + #[doc = crate::hal_type_vulkan!("Texture")] + #[doc = crate::hal_type_metal!("Texture")] + #[doc = crate::hal_type_dx12!("Texture")] + #[doc = crate::hal_type_gles!("Texture")] + /// + /// # Deadlocks + /// + /// - The returned guard holds a read-lock on a device-local "destruction" + /// lock, which will cause all calls to `destroy` to block until the + /// guard is released. + /// + /// # Errors + /// + /// This method will return None if: + /// - The texture is not from the backend specified by `A`. + /// - The texture is from the `webgpu` or `custom` backend. + /// - The texture has had [`Self::destroy()`] called on it. /// /// # Safety /// - /// - The raw handle obtained from the hal Texture must not be manually destroyed + /// - The returned resource must not be destroyed unless the guard + /// is the last reference to it and it is not in use by the GPU. + /// The guard and handle may be dropped at any time however. + /// - All the safety requirements of wgpu-hal must be upheld. + /// + /// [`A::Texture`]: hal::Api::Texture #[cfg(wgpu_core)] - pub unsafe fn as_hal) -> R, R>( - &self, - hal_texture_callback: F, - ) -> R { - if let Some(tex) = self.inner.as_core_opt() { - unsafe { - tex.context - .texture_as_hal::(tex, hal_texture_callback) - } - } else { - hal_texture_callback(None) + pub unsafe fn as_hal(&self) -> Option> { + let texture = self.inner.as_core_opt()?; + unsafe { texture.context.texture_as_hal::(texture) } + } + + #[cfg(custom)] + /// Returns custom implementation of Texture (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() + } + + #[cfg(custom)] + /// Creates a texture from already created custom implementation with the given description + pub fn from_custom( + texture: T, + desc: &TextureDescriptor<'_>, + ) -> Self { + Self { + inner: dispatch::DispatchTexture::custom(texture), + descriptor: TextureDescriptor { + label: None, + view_formats: &[], + ..desc.clone() + }, } } @@ -45,7 +93,10 @@ impl Texture { pub fn create_view(&self, desc: &TextureViewDescriptor<'_>) -> TextureView { let view = self.inner.create_view(desc); - TextureView { inner: view } + TextureView { + inner: view, + texture: self.clone(), + } } /// Destroy the associated native resources as soon as possible. diff --git a/wgpu/src/api/texture_view.rs b/wgpu/src/api/texture_view.rs index 1fff6f86b..7d578a25f 100644 --- a/wgpu/src/api/texture_view.rs +++ b/wgpu/src/api/texture_view.rs @@ -1,3 +1,6 @@ +#[cfg(wgpu_core)] +use core::ops::Deref; + use crate::*; /// Handle to a texture view. @@ -12,6 +15,7 @@ use crate::*; #[derive(Debug, Clone)] pub struct TextureView { pub(crate) inner: dispatch::DispatchTextureView, + pub(crate) texture: Texture, } #[cfg(send_sync)] static_assertions::assert_impl_all!(TextureView: Send, Sync); @@ -19,26 +23,62 @@ static_assertions::assert_impl_all!(TextureView: Send, Sync); crate::cmp::impl_eq_ord_hash_proxy!(TextureView => .inner); impl TextureView { - /// Returns the inner hal `TextureView` using a callback. The hal texture will be `None` if the - /// backend type argument does not match with this wgpu Texture + /// Returns the [`Texture`] that this `TextureView` refers to. + /// + /// All wgpu resources are refcounted, so you can own the returned [`Texture`] + /// by cloning it. + pub fn texture(&self) -> &Texture { + &self.texture + } + + /// Get the [`wgpu_hal`] texture view from this `TextureView`. + /// + /// Find the Api struct corresponding to the active backend in [`wgpu_hal::api`], + /// and pass that struct to the to the `A` type parameter. + /// + /// Returns a guard that dereferences to the type of the hal backend + /// which implements [`A::TextureView`]. + /// + /// # Types + /// + /// The returned type depends on the backend: + /// + #[doc = crate::hal_type_vulkan!("TextureView")] + #[doc = crate::hal_type_metal!("TextureView")] + #[doc = crate::hal_type_dx12!("TextureView")] + #[doc = crate::hal_type_gles!("TextureView")] + /// + /// # Deadlocks + /// + /// - The returned guard holds a read-lock on a device-local "destruction" + /// lock, which will cause all calls to `destroy` to block until the + /// guard is released. + /// + /// # Errors + /// + /// This method will return None if: + /// - The texture view is not from the backend specified by `A`. + /// - The texture view is from the `webgpu` or `custom` backend. + /// - The texture this view points to has had [`Texture::destroy()`] called on it. /// /// # Safety /// - /// - The raw handle obtained from the hal `TextureView` must not be manually destroyed + /// - The returned resource must not be destroyed unless the guard + /// is the last reference to it and it is not in use by the GPU. + /// The guard and handle may be dropped at any time however. + /// - All the safety requirements of wgpu-hal must be upheld. + /// + /// [`A::TextureView`]: hal::Api::TextureView #[cfg(wgpu_core)] - pub unsafe fn as_hal) -> R, R>( - &self, - hal_texture_view_callback: F, - ) -> R { - if let Some(core_view) = self.inner.as_core_opt() { - unsafe { - core_view - .context - .texture_view_as_hal::(core_view, hal_texture_view_callback) - } - } else { - hal_texture_view_callback(None) - } + pub unsafe fn as_hal(&self) -> Option> { + let view = self.inner.as_core_opt()?; + unsafe { view.context.texture_view_as_hal::(view) } + } + + #[cfg(custom)] + /// Returns custom implementation of TextureView (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() } } diff --git a/wgpu/src/api/tlas.rs b/wgpu/src/api/tlas.rs index 45a5f54a7..4b1c34ad4 100644 --- a/wgpu/src/api/tlas.rs +++ b/wgpu/src/api/tlas.rs @@ -1,74 +1,84 @@ -use alloc::{sync::Arc, vec, vec::Vec}; -use core::ops::{Index, IndexMut, Range}; - use crate::{api::blas::TlasInstance, dispatch}; -use crate::{BindingResource, Buffer, Label}; +use crate::{BindingResource, Label}; +use alloc::vec::Vec; +#[cfg(wgpu_core)] +use core::ops::Deref; +use core::ops::{Index, IndexMut, Range}; use wgt::WasmNotSendSync; /// Descriptor to create top level acceleration structures. pub type CreateTlasDescriptor<'a> = wgt::CreateTlasDescriptor>; static_assertions::assert_impl_all!(CreateTlasDescriptor<'_>: Send, Sync); -#[derive(Debug)] -pub(crate) struct TlasShared { - pub(crate) inner: dispatch::DispatchTlas, - pub(crate) max_instances: u32, -} - #[derive(Debug, Clone)] /// Top Level Acceleration Structure (TLAS). /// /// A TLAS contains a series of [TLAS instances], which are a reference to /// a BLAS and a transformation matrix placing the geometry in the world. /// -/// A TLAS contains TLAS instances in a device readable form, you cant interact +/// A TLAS also contains an extra set of TLAS instances in a device readable form, you cant interact /// directly with these, instead you have to build the TLAS with [TLAS instances]. /// /// [TLAS instances]: TlasInstance pub struct Tlas { - pub(crate) shared: Arc, -} -static_assertions::assert_impl_all!(Tlas: WasmNotSendSync); - -crate::cmp::impl_eq_ord_hash_proxy!(Tlas => .shared.inner); - -/// Entry for a top level acceleration structure build. -/// Used with raw instance buffers for an unvalidated builds. -/// See [`TlasPackage`] for the safe version. -pub struct TlasBuildEntry<'a> { - /// Reference to the acceleration structure. - pub tlas: &'a Tlas, - /// Reference to the raw instance buffer, each instance is similar to [`TlasInstance`] but contains a handle to the BLAS. - pub instance_buffer: &'a Buffer, - /// Number of instances in the instance buffer. - pub instance_count: u32, -} -static_assertions::assert_impl_all!(TlasBuildEntry<'_>: WasmNotSendSync); - -/// The safe version of [`TlasBuildEntry`], containing [`TlasInstance`]s instead of a raw buffer. -pub struct TlasPackage { - pub(crate) tlas: Tlas, + pub(crate) inner: dispatch::DispatchTlas, pub(crate) instances: Vec>, pub(crate) lowest_unmodified: u32, } -static_assertions::assert_impl_all!(TlasPackage: WasmNotSendSync); +static_assertions::assert_impl_all!(Tlas: WasmNotSendSync); -impl TlasPackage { - /// Construct [`TlasPackage`] consuming the [`Tlas`] (prevents modification of the [`Tlas`] without using this package). - pub fn new(tlas: Tlas) -> Self { - let max_instances = tlas.shared.max_instances; - Self::new_with_instances(tlas, vec![None; max_instances as usize]) +crate::cmp::impl_eq_ord_hash_proxy!(Tlas => .inner); + +impl Tlas { + /// Get the [`wgpu_hal`] acceleration structure from this `Tlas`. + /// + /// Find the Api struct corresponding to the active backend in [`wgpu_hal::api`], + /// and pass that struct to the to the `A` type parameter. + /// + /// Returns a guard that dereferences to the type of the hal backend + /// which implements [`A::AccelerationStructure`]. + /// + /// # Types + /// + /// The returned type depends on the backend: + /// + #[doc = crate::hal_type_vulkan!("AccelerationStructure")] + #[doc = crate::hal_type_metal!("AccelerationStructure")] + #[doc = crate::hal_type_dx12!("AccelerationStructure")] + #[doc = crate::hal_type_gles!("AccelerationStructure")] + /// + /// # Deadlocks + /// + /// - The returned guard holds a read-lock on a device-local "destruction" + /// lock, which will cause all calls to `destroy` to block until the + /// guard is released. + /// + /// # Errors + /// + /// This method will return None if: + /// - The acceleration structure is not from the backend specified by `A`. + /// - The acceleration structure is from the `webgpu` or `custom` backend. + /// + /// # Safety + /// + /// - The returned resource must not be destroyed unless the guard + /// is the last reference to it and it is not in use by the GPU. + /// The guard and handle may be dropped at any time however. + /// - All the safety requirements of wgpu-hal must be upheld. + /// + /// [`A::AccelerationStructure`]: hal::Api::AccelerationStructure + #[cfg(wgpu_core)] + pub unsafe fn as_hal( + &mut self, + ) -> Option> { + let tlas = self.inner.as_core_opt()?; + unsafe { tlas.context.tlas_as_hal::(tlas) } } - /// Construct [`TlasPackage`] consuming the [`Tlas`] (prevents modification of the [`Tlas`] without using this package). - /// This constructor moves the instances into the package (the number of instances needs to fit into tlas, - /// otherwise when building a validation error will be raised). - pub fn new_with_instances(tlas: Tlas, instances: Vec>) -> Self { - Self { - tlas, - lowest_unmodified: instances.len() as u32, - instances, - } + #[cfg(custom)] + /// Returns custom implementation of Tlas (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() } /// Get a reference to all instances. @@ -114,16 +124,11 @@ impl TlasPackage { /// /// [`BindGroup`]: super::BindGroup pub fn as_binding(&self) -> BindingResource<'_> { - BindingResource::AccelerationStructure(&self.tlas) - } - - /// Get a reference to the underling [`Tlas`]. - pub fn tlas(&self) -> &Tlas { - &self.tlas + BindingResource::AccelerationStructure(self) } } -impl Index for TlasPackage { +impl Index for Tlas { type Output = Option; fn index(&self, index: usize) -> &Self::Output { @@ -131,7 +136,7 @@ impl Index for TlasPackage { } } -impl Index> for TlasPackage { +impl Index> for Tlas { type Output = [Option]; fn index(&self, index: Range) -> &Self::Output { @@ -139,7 +144,7 @@ impl Index> for TlasPackage { } } -impl IndexMut for TlasPackage { +impl IndexMut for Tlas { fn index_mut(&mut self, index: usize) -> &mut Self::Output { let idx = self.instances.index_mut(index); if index as u32 + 1 > self.lowest_unmodified { @@ -149,7 +154,7 @@ impl IndexMut for TlasPackage { } } -impl IndexMut> for TlasPackage { +impl IndexMut> for Tlas { fn index_mut(&mut self, index: Range) -> &mut Self::Output { let idx = self.instances.index_mut(index.clone()); if index.end > self.lowest_unmodified as usize { diff --git a/wgpu/src/backend/custom.rs b/wgpu/src/backend/custom.rs index 471ccb88e..4d205e001 100644 --- a/wgpu/src/backend/custom.rs +++ b/wgpu/src/backend/custom.rs @@ -18,6 +18,11 @@ macro_rules! dyn_type { pub(crate) fn new(t: T) -> Self { Self(Arc::new(t)) } + + #[allow(clippy::allow_attributes, dead_code)] + pub(crate) fn downcast(&self) -> Option<&T> { + self.0.as_ref().as_any().downcast_ref() + } } impl core::ops::Deref for $name { @@ -46,6 +51,10 @@ macro_rules! dyn_type { pub(crate) fn new(t: T) -> Self { Self(Arc::new(t)) } + + pub(crate) fn downcast(&self) -> Option<&T> { + self.0.as_ref().as_any().downcast_ref() + } } impl core::ops::Deref for $name { @@ -70,6 +79,7 @@ dyn_type!(pub ref struct DynTextureView(dyn TextureViewInterface)); dyn_type!(pub ref struct DynSampler(dyn SamplerInterface)); dyn_type!(pub ref struct DynBuffer(dyn BufferInterface)); dyn_type!(pub ref struct DynTexture(dyn TextureInterface)); +dyn_type!(pub ref struct DynExternalTexture(dyn ExternalTextureInterface)); dyn_type!(pub ref struct DynBlas(dyn BlasInterface)); dyn_type!(pub ref struct DynTlas(dyn TlasInterface)); dyn_type!(pub ref struct DynQuerySet(dyn QuerySetInterface)); @@ -80,7 +90,7 @@ dyn_type!(pub ref struct DynPipelineCache(dyn PipelineCacheInterface)); dyn_type!(pub mut struct DynCommandEncoder(dyn CommandEncoderInterface)); dyn_type!(pub mut struct DynComputePass(dyn ComputePassInterface)); dyn_type!(pub mut struct DynRenderPass(dyn RenderPassInterface)); -dyn_type!(pub ref struct DynCommandBuffer(dyn CommandBufferInterface)); +dyn_type!(pub mut struct DynCommandBuffer(dyn CommandBufferInterface)); dyn_type!(pub mut struct DynRenderBundleEncoder(dyn RenderBundleEncoderInterface)); dyn_type!(pub ref struct DynRenderBundle(dyn RenderBundleInterface)); dyn_type!(pub ref struct DynSurface(dyn SurfaceInterface)); diff --git a/wgpu/src/backend/webgpu.rs b/wgpu/src/backend/webgpu.rs index d7a76384f..800820bbb 100644 --- a/wgpu/src/backend/webgpu.rs +++ b/wgpu/src/backend/webgpu.rs @@ -10,10 +10,12 @@ use alloc::{ format, rc::Rc, string::{String, ToString as _}, + sync::Arc, vec, vec::Vec, }; use core::{ + cell::OnceCell, cell::RefCell, fmt, future::Future, @@ -26,7 +28,10 @@ use wgt::Backends; use js_sys::Promise; use wasm_bindgen::{prelude::*, JsCast}; -use crate::{dispatch, SurfaceTargetUnsafe}; +use crate::{ + dispatch::{self, BlasCompactCallback}, + Blas, SurfaceTargetUnsafe, Tlas, +}; use defined_non_null_js_value::DefinedNonNullJsValue; @@ -46,6 +51,7 @@ macro_rules! impl_send_sync { }; } +#[derive(Clone)] pub struct ContextWebGpu { /// `None` if browser does not advertise support for WebGPU. gpu: Option>, @@ -81,7 +87,7 @@ impl crate::Error { } } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WebShaderModule { module: webgpu_sys::GpuShaderModule, compilation_info: WebShaderCompilationInfo, @@ -112,11 +118,7 @@ fn map_utf16_to_utf8_offset(utf16_offset: u32, text: &str) -> u32 { if utf16_i >= utf16_offset { text.len() as u32 } else { - log::error!( - "UTF16 offset {} is out of bounds for string {}", - utf16_offset, - text - ); + log::error!("UTF16 offset {utf16_offset} is out of bounds for string {text}"); u32::MAX } } @@ -376,8 +378,7 @@ fn map_primitive_state(primitive: &wgt::PrimitiveState) -> webgpu_sys::GpuPrimit PrimitiveTopology::TriangleStrip => pt::TriangleStrip, }); - //TODO: - //mapped.unclipped_depth(primitive.unclipped_depth); + mapped.set_unclipped_depth(primitive.unclipped_depth); match primitive.polygon_mode { wgt::PolygonMode::Fill => {} @@ -631,6 +632,7 @@ fn map_texture_copy_view( let mapped = webgpu_sys::GpuTexelCopyTextureInfo::new(&texture.inner); mapped.set_mip_level(view.mip_level); mapped.set_origin(&map_origin_3d(view.origin)); + mapped.set_aspect(map_texture_aspect(view.aspect)); mapped } @@ -674,10 +676,10 @@ fn map_filter_mode(mode: wgt::FilterMode) -> webgpu_sys::GpuFilterMode { } } -fn map_mipmap_filter_mode(mode: wgt::FilterMode) -> webgpu_sys::GpuMipmapFilterMode { +fn map_mipmap_filter_mode(mode: wgt::MipmapFilterMode) -> webgpu_sys::GpuMipmapFilterMode { match mode { - wgt::FilterMode::Nearest => webgpu_sys::GpuMipmapFilterMode::Nearest, - wgt::FilterMode::Linear => webgpu_sys::GpuMipmapFilterMode::Linear, + wgt::MipmapFilterMode::Nearest => webgpu_sys::GpuMipmapFilterMode::Nearest, + wgt::MipmapFilterMode::Linear => webgpu_sys::GpuMipmapFilterMode::Linear, } } @@ -708,7 +710,7 @@ fn map_map_mode(mode: crate::MapMode) -> u32 { } } -const FEATURES_MAPPING: [(wgt::Features, webgpu_sys::GpuFeatureName); 13] = [ +const FEATURES_MAPPING: [(wgt::Features, webgpu_sys::GpuFeatureName); 15] = [ ( wgt::Features::DEPTH_CLIP_CONTROL, webgpu_sys::GpuFeatureName::DepthClipControl, @@ -733,6 +735,10 @@ const FEATURES_MAPPING: [(wgt::Features, webgpu_sys::GpuFeatureName); 13] = [ wgt::Features::TEXTURE_COMPRESSION_ASTC, webgpu_sys::GpuFeatureName::TextureCompressionAstc, ), + ( + wgt::Features::TEXTURE_COMPRESSION_ASTC_SLICED_3D, + webgpu_sys::GpuFeatureName::TextureCompressionAstcSliced3d, + ), ( wgt::Features::TIMESTAMP_QUERY, webgpu_sys::GpuFeatureName::TimestampQuery, @@ -761,11 +767,14 @@ const FEATURES_MAPPING: [(wgt::Features, webgpu_sys::GpuFeatureName); 13] = [ wgt::Features::DUAL_SOURCE_BLENDING, webgpu_sys::GpuFeatureName::DualSourceBlending, ), + ( + wgt::Features::CLIP_DISTANCES, + webgpu_sys::GpuFeatureName::ClipDistances, + ), ]; fn map_wgt_features(supported_features: webgpu_sys::GpuSupportedFeatures) -> wgt::Features { - // We emulate MDI. - let mut features = wgt::Features::MULTI_DRAW_INDIRECT; + let mut features = wgt::Features::empty(); for (wgpu_feat, web_feat) in FEATURES_MAPPING { match wasm_bindgen::JsValue::from(web_feat).as_string() { Some(value) if supported_features.has(&value) => features |= wgpu_feat, @@ -816,6 +825,19 @@ fn map_wgt_limits(limits: webgpu_sys::GpuSupportedLimits) -> wgt::Limits { max_push_constant_size: wgt::Limits::default().max_push_constant_size, max_non_sampler_bindings: wgt::Limits::default().max_non_sampler_bindings, max_inter_stage_shader_components: wgt::Limits::default().max_inter_stage_shader_components, + + max_task_workgroup_total_count: wgt::Limits::default().max_task_workgroup_total_count, + max_task_workgroups_per_dimension: wgt::Limits::default().max_task_workgroups_per_dimension, + max_mesh_output_layers: wgt::Limits::default().max_mesh_output_layers, + max_mesh_multiview_view_count: wgt::Limits::default().max_mesh_multiview_view_count, + + max_blas_primitive_count: wgt::Limits::default().max_blas_primitive_count, + max_blas_geometry_count: wgt::Limits::default().max_blas_geometry_count, + max_tlas_instance_count: wgt::Limits::default().max_tlas_instance_count, + max_acceleration_structures_per_shader_stage: wgt::Limits::default() + .max_acceleration_structures_per_shader_stage, + + max_multiview_view_count: wgt::Limits::default().max_multiview_view_count, } } @@ -839,6 +861,7 @@ fn map_js_sys_limits(limits: &wgt::Limits) -> js_sys::Object { } } + // https://gpuweb.github.io/gpuweb/#gpusupportedlimits set_properties![ (limits) => (object): (maxTextureDimension1D, max_texture_dimension_1d), @@ -846,6 +869,7 @@ fn map_js_sys_limits(limits: &wgt::Limits) -> js_sys::Object { (maxTextureDimension3D, max_texture_dimension_3d), (maxTextureArrayLayers, max_texture_array_layers), (maxBindGroups, max_bind_groups), + // TODO: (maxBindGroupsPlusVertexBuffers, max_bind_groups_plus_vertex_buffers), (maxBindingsPerBindGroup, max_bindings_per_bind_group), (maxDynamicUniformBuffersPerPipelineLayout, max_dynamic_uniform_buffers_per_pipeline_layout), (maxDynamicStorageBuffersPerPipelineLayout, max_dynamic_storage_buffers_per_pipeline_layout), @@ -862,6 +886,9 @@ fn map_js_sys_limits(limits: &wgt::Limits) -> js_sys::Object { (maxBufferSize, max_buffer_size), (maxVertexAttributes, max_vertex_attributes), (maxVertexBufferArrayStride, max_vertex_buffer_array_stride), + // TODO: (maxInterStageShaderVariables, max_inter_stage_shader_variables), + (maxColorAttachments, max_color_attachments), + (maxColorAttachmentBytesPerSample, max_color_attachment_bytes_per_sample), (maxComputeWorkgroupStorageSize, max_compute_workgroup_storage_size), (maxComputeInvocationsPerWorkgroup, max_compute_invocations_per_workgroup), (maxComputeWorkgroupSizeX, max_compute_workgroup_size_x), @@ -1089,7 +1116,7 @@ extern "C" { fn worker(this: &Global) -> JsValue; } -#[derive(Debug)] +#[derive(Debug, Clone)] pub enum Canvas { Canvas(web_sys::HtmlCanvasElement), Offscreen(web_sys::OffscreenCanvas), @@ -1129,49 +1156,49 @@ pub fn get_browser_gpu_property( Ok(DefinedNonNullJsValue::new(maybe_undefined_gpu)) } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WebAdapter { pub(crate) inner: webgpu_sys::GpuAdapter, /// Unique identifier for this Adapter. ident: crate::cmp::Identifier, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WebDevice { pub(crate) inner: webgpu_sys::GpuDevice, /// Unique identifier for this Device. ident: crate::cmp::Identifier, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WebQueue { pub(crate) inner: webgpu_sys::GpuQueue, /// Unique identifier for this Queue. ident: crate::cmp::Identifier, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WebBindGroupLayout { pub(crate) inner: webgpu_sys::GpuBindGroupLayout, /// Unique identifier for this BindGroupLayout. ident: crate::cmp::Identifier, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WebBindGroup { pub(crate) inner: webgpu_sys::GpuBindGroup, /// Unique identifier for this BindGroup. ident: crate::cmp::Identifier, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WebTextureView { pub(crate) inner: webgpu_sys::GpuTextureView, /// Unique identifier for this TextureView. ident: crate::cmp::Identifier, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WebSampler { pub(crate) inner: webgpu_sys::GpuSampler, /// Unique identifier for this Sampler. @@ -1180,7 +1207,7 @@ pub struct WebSampler { /// Remembers which portion of a buffer has been mapped, along with a reference /// to the mapped portion. -#[derive(Debug)] +#[derive(Debug, Clone)] struct WebBufferMapState { /// The mapped memory of the buffer. pub mapped_buffer: Option, @@ -1192,12 +1219,12 @@ struct WebBufferMapState { /// The WebGPU specification forbids calling `getMappedRange` on a `webgpu_sys::GpuBuffer` more than /// once, so this struct stores the initial mapped range and re-uses it, allowing for multiple `get_mapped_range` /// calls on the Rust-side. -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WebBuffer { /// The associated GPU buffer. inner: webgpu_sys::GpuBuffer, /// The mapped array buffer and mapped range. - mapping: RefCell, + mapping: Rc>, /// Unique identifier for this Buffer. ident: crate::cmp::Identifier, } @@ -1207,24 +1234,14 @@ impl WebBuffer { fn new(inner: webgpu_sys::GpuBuffer, desc: &crate::BufferDescriptor<'_>) -> Self { Self { inner, - mapping: RefCell::new(WebBufferMapState { + mapping: Rc::new(RefCell::new(WebBufferMapState { mapped_buffer: None, range: 0..desc.size, - }), + })), ident: crate::cmp::Identifier::create(), } } - /// Creates a raw Javascript array buffer over the provided range. - fn get_mapped_array_buffer(&self, sub_range: Range) -> js_sys::ArrayBuffer { - self.inner - .get_mapped_range_with_f64_and_f64( - sub_range.start as f64, - (sub_range.end - sub_range.start) as f64, - ) - .unwrap() - } - /// Obtains a reference to the re-usable buffer mapping as a Javascript array view. fn get_mapped_range(&self, sub_range: Range) -> js_sys::Uint8Array { let mut mapping = self.mapping.borrow_mut(); @@ -1250,60 +1267,66 @@ impl WebBuffer { } } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WebTexture { pub(crate) inner: webgpu_sys::GpuTexture, /// Unique identifier for this Texture. ident: crate::cmp::Identifier, } -#[derive(Debug)] +#[derive(Debug, Clone)] +pub struct WebExternalTexture { + /// Unique identifier for this ExternalTexture. + ident: crate::cmp::Identifier, +} + +#[derive(Debug, Clone)] pub struct WebBlas { /// Unique identifier for this Blas. ident: crate::cmp::Identifier, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WebTlas { /// Unique identifier for this Blas. ident: crate::cmp::Identifier, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WebQuerySet { pub(crate) inner: webgpu_sys::GpuQuerySet, /// Unique identifier for this QuerySet. ident: crate::cmp::Identifier, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WebPipelineLayout { pub(crate) inner: webgpu_sys::GpuPipelineLayout, /// Unique identifier for this PipelineLayout. ident: crate::cmp::Identifier, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WebRenderPipeline { pub(crate) inner: webgpu_sys::GpuRenderPipeline, /// Unique identifier for this RenderPipeline. ident: crate::cmp::Identifier, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WebComputePipeline { pub(crate) inner: webgpu_sys::GpuComputePipeline, /// Unique identifier for this ComputePipeline. ident: crate::cmp::Identifier, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WebPipelineCache { /// Unique identifier for this PipelineCache. ident: crate::cmp::Identifier, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WebCommandEncoder { pub(crate) inner: webgpu_sys::GpuCommandEncoder, /// Unique identifier for this CommandEncoder. @@ -1331,21 +1354,21 @@ pub struct WebCommandBuffer { ident: crate::cmp::Identifier, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WebRenderBundleEncoder { pub(crate) inner: webgpu_sys::GpuRenderBundleEncoder, /// Unique identifier for this RenderBundleEncoder. ident: crate::cmp::Identifier, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WebRenderBundle { pub(crate) inner: webgpu_sys::GpuRenderBundle, /// Unique identifier for this RenderBundle. ident: crate::cmp::Identifier, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WebSurface { gpu: Option>, canvas: Canvas, @@ -1354,7 +1377,7 @@ pub struct WebSurface { ident: crate::cmp::Identifier, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct WebSurfaceOutputDetail { /// Unique identifier for this SurfaceOutputDetail. ident: crate::cmp::Identifier, @@ -1370,9 +1393,9 @@ pub struct WebQueueWriteBuffer { #[derive(Debug)] pub struct WebBufferMappedRange { actual_mapping: js_sys::Uint8Array, - /// Copy of the mapped data that lives in the Rust/Wasm heap instead of JS, - /// so Rust code can borrow it. - temporary_mapping: Vec, + /// Copy of actual_mapping that lives in the Rust/Wasm heap instead of JS. This + /// is done only when accessed for the first time to avoid unnecessary allocations. + temporary_mapping: OnceCell>, /// Whether `temporary_mapping` has possibly been written to and needs to be written back to JS. temporary_mapping_modified: bool, /// Unique identifier for this BufferMappedRange. @@ -1390,6 +1413,7 @@ impl_send_sync!(WebTextureView); impl_send_sync!(WebSampler); impl_send_sync!(WebBuffer); impl_send_sync!(WebTexture); +impl_send_sync!(WebExternalTexture); impl_send_sync!(WebBlas); impl_send_sync!(WebTlas); impl_send_sync!(WebQuerySet); @@ -1419,6 +1443,7 @@ crate::cmp::impl_eq_ord_hash_proxy!(WebTextureView => .ident); crate::cmp::impl_eq_ord_hash_proxy!(WebSampler => .ident); crate::cmp::impl_eq_ord_hash_proxy!(WebBuffer => .ident); crate::cmp::impl_eq_ord_hash_proxy!(WebTexture => .ident); +crate::cmp::impl_eq_ord_hash_proxy!(WebExternalTexture => .ident); crate::cmp::impl_eq_ord_hash_proxy!(WebBlas => .ident); crate::cmp::impl_eq_ord_hash_proxy!(WebTlas => .ident); crate::cmp::impl_eq_ord_hash_proxy!(WebQuerySet => .ident); @@ -1552,6 +1577,20 @@ impl dispatch::InstanceInterface for ContextWebGpu { )))) } } + fn enumerate_adapters( + &self, + _backends: crate::Backends, + ) -> Pin> { + let future = self.request_adapter(&crate::RequestAdapterOptions::default()); + let enumerate_future = async move { + let adapter = future.await; + match adapter { + Ok(a) => vec![a], + Err(_) => vec![], + } + }; + Box::pin(enumerate_future) + } fn poll_all_devices(&self, _force_wait: bool) -> bool { // Devices are automatically polled. @@ -1671,9 +1710,11 @@ impl dispatch::AdapterInterface for WebAdapter { vendor: 0, device: 0, device_type: wgt::DeviceType::Other, + device_pci_bus_id: String::new(), driver: String::new(), driver_info: String::new(), backend: wgt::Backend::BrowserWebGpu, + transient_saves_memory: false, } } @@ -1843,11 +1884,45 @@ impl dispatch::DeviceInterface for WebDevice { .into() } - unsafe fn create_shader_module_spirv( + unsafe fn create_shader_module_passthrough( &self, - _desc: &crate::ShaderModuleDescriptorSpirV<'_>, + desc: &crate::ShaderModuleDescriptorPassthrough<'_>, ) -> dispatch::DispatchShaderModule { - unreachable!("SPIRV_SHADER_PASSTHROUGH is not enabled for this backend") + let shader_module_result = if let Some(ref code) = desc.wgsl { + let shader_module = webgpu_sys::GpuShaderModuleDescriptor::new(code); + Ok(( + shader_module, + WebShaderCompilationInfo::Wgsl { + source: code.to_string(), + }, + )) + } else { + Err(crate::CompilationInfo { + messages: vec![crate::CompilationMessage { + message: + "Passthrough shader not compiled for WGSL on WebGPU backend (wgpu error)" + .to_string(), + location: None, + message_type: crate::CompilationMessageType::Error, + }], + }) + }; + let (descriptor, compilation_info) = match shader_module_result { + Ok(v) => v, + Err(compilation_info) => ( + webgpu_sys::GpuShaderModuleDescriptor::new(""), + WebShaderCompilationInfo::Transformed { compilation_info }, + ), + }; + if let Some(label) = desc.label { + descriptor.set_label(label); + } + WebShaderModule { + module: self.inner.create_shader_module(&descriptor), + compilation_info, + ident: crate::cmp::Identifier::create(), + } + .into() } fn create_bind_group_layout( @@ -1940,6 +2015,11 @@ impl dispatch::DeviceInterface for WebDevice { mapped_entry.set_storage_texture(&storage_texture); } wgt::BindingType::AccelerationStructure { .. } => todo!(), + wgt::BindingType::ExternalTexture => { + mapped_entry.set_external_texture( + &webgpu_sys::GpuExternalTextureBindingLayout::new(), + ); + } } mapped_entry @@ -2002,6 +2082,9 @@ impl dispatch::DeviceInterface for WebDevice { crate::BindingResource::AccelerationStructure(_) => { unimplemented!("Raytracing not implemented for web") } + crate::BindingResource::ExternalTexture(_) => { + unimplemented!("ExternalTexture not implemented for web") + } }; webgpu_sys::GpuBindGroupEntry::new(binding.binding, &mapped_resource) @@ -2130,7 +2213,7 @@ impl dispatch::DeviceInterface for WebDevice { .collect::(); let module = frag.module.inner.as_webgpu(); let mapped_fragment_desc = webgpu_sys::GpuFragmentState::new(&module.module, &targets); - insert_constants_map(&mapped_vertex_state, frag.compilation_options.constants); + insert_constants_map(&mapped_fragment_desc, frag.compilation_options.constants); if let Some(ep) = frag.entry_point { mapped_fragment_desc.set_entry_point(ep); } @@ -2156,6 +2239,13 @@ impl dispatch::DeviceInterface for WebDevice { .into() } + fn create_mesh_pipeline( + &self, + _desc: &crate::MeshPipelineDescriptor<'_>, + ) -> dispatch::DispatchRenderPipeline { + panic!("MESH_SHADER feature must be enabled to call create_mesh_pipeline") + } + fn create_compute_pipeline( &self, desc: &crate::ComputePipelineDescriptor<'_>, @@ -2236,6 +2326,14 @@ impl dispatch::DeviceInterface for WebDevice { .into() } + fn create_external_texture( + &self, + _desc: &crate::ExternalTextureDescriptor<'_>, + _planes: &[&crate::TextureView], + ) -> dispatch::DispatchExternalTexture { + unimplemented!("ExternalTexture not implemented for web"); + } + fn create_blas( &self, _desc: &crate::CreateBlasDescriptor<'_>, @@ -2365,16 +2463,20 @@ impl dispatch::DeviceInterface for WebDevice { ); }); let _ = self.inner.lost().then(&closure); + // Release memory management of this closure from Rust to the JS GC. + // TODO: This will leak if weak references is not supported. + closure.forget(); } - fn on_uncaptured_error(&self, handler: Box) { + fn on_uncaptured_error(&self, handler: Arc) { let f = Closure::wrap(Box::new(move |event: webgpu_sys::GpuUncapturedErrorEvent| { let error = crate::Error::from_js(event.error().value_of()); handler(error); }) as Box); self.inner .set_onuncapturederror(Some(f.as_ref().unchecked_ref())); - // TODO: This will leak the memory associated with the error handler by default. + // Release memory management of this closure from Rust to the JS GC. + // TODO: This will leak if weak references is not supported. f.forget(); } @@ -2394,15 +2496,15 @@ impl dispatch::DeviceInterface for WebDevice { )) } - fn start_capture(&self) { + unsafe fn start_graphics_debugger_capture(&self) { // No capturing api in webgpu } - fn stop_capture(&self) { + unsafe fn stop_graphics_debugger_capture(&self) { // No capturing api in webgpu } - fn poll(&self, _poll_type: crate::PollType) -> Result { + fn poll(&self, _poll_type: wgt::PollType) -> Result { // Device is polled automatically Ok(crate::PollStatus::QueueEmpty) } @@ -2482,16 +2584,12 @@ impl dispatch::QueueInterface for WebQueue { } let write_size = u64::from(size); if write_size % wgt::COPY_BUFFER_ALIGNMENT != 0 { - log::error!( - "Copy size {} does not respect `COPY_BUFFER_ALIGNMENT`", - size - ); + log::error!("Copy size {size} does not respect `COPY_BUFFER_ALIGNMENT`"); return None; } if offset % wgt::COPY_BUFFER_ALIGNMENT != 0 { log::error!( - "Buffer offset {} is not aligned to block size or `COPY_BUFFER_ALIGNMENT`", - offset + "Buffer offset {offset} is not aligned to block size or `COPY_BUFFER_ALIGNMENT`" ); return None; } @@ -2583,8 +2681,24 @@ impl dispatch::QueueInterface for WebQueue { 1.0 } - fn on_submitted_work_done(&self, _callback: dispatch::BoxSubmittedWorkDoneCallback) { - unimplemented!("on_submitted_work_done is not yet implemented"); + fn on_submitted_work_done(&self, callback: dispatch::BoxSubmittedWorkDoneCallback) { + let promise = self.inner.on_submitted_work_done(); + wasm_bindgen_futures::spawn_local(async move { + match wasm_bindgen_futures::JsFuture::from(promise).await { + Ok(_) => callback(), + Err(error) => { + log::error!("on_submitted_work_done promise failed: {error:?}"); + callback(); + } + } + }); + } + + fn compact_blas( + &self, + _blas: &dispatch::DispatchBlas, + ) -> (Option, dispatch::DispatchBlas) { + unimplemented!("Raytracing not implemented for web") } } impl Drop for WebQueue { @@ -2663,23 +2777,15 @@ impl dispatch::BufferInterface for WebBuffer { sub_range: Range, ) -> dispatch::DispatchBufferMappedRange { let actual_mapping = self.get_mapped_range(sub_range); - let temporary_mapping = actual_mapping.to_vec(); WebBufferMappedRange { actual_mapping, - temporary_mapping, + temporary_mapping: OnceCell::new(), temporary_mapping_modified: false, ident: crate::cmp::Identifier::create(), } .into() } - fn get_mapped_range_as_array_buffer( - &self, - sub_range: Range, - ) -> Option { - Some(self.get_mapped_array_buffer(sub_range)) - } - fn unmap(&self) { self.inner.unmap(); self.mapping.borrow_mut().mapped_buffer = None; @@ -2740,7 +2846,25 @@ impl Drop for WebTexture { } } -impl dispatch::BlasInterface for WebBlas {} +impl dispatch::ExternalTextureInterface for WebExternalTexture { + fn destroy(&self) { + unimplemented!("ExternalTexture not implemented for web"); + } +} +impl Drop for WebExternalTexture { + fn drop(&mut self) { + unimplemented!("ExternalTexture not implemented for web"); + } +} + +impl dispatch::BlasInterface for WebBlas { + fn prepare_compact_async(&self, _callback: BlasCompactCallback) { + unimplemented!("Raytracing not implemented for web") + } + fn ready_for_compaction(&self) -> bool { + unimplemented!("Raytracing not implemented for web") + } +} impl Drop for WebBlas { fn drop(&mut self) { // no-op @@ -2809,20 +2933,31 @@ impl dispatch::CommandEncoderInterface for WebCommandEncoder { source_offset: crate::BufferAddress, destination: &dispatch::DispatchBuffer, destination_offset: crate::BufferAddress, - copy_size: crate::BufferAddress, + copy_size: Option, ) { let source = source.as_webgpu(); let destination = destination.as_webgpu(); - self.inner - .copy_buffer_to_buffer_with_f64_and_f64_and_f64( - &source.inner, - source_offset as f64, - &destination.inner, - destination_offset as f64, - copy_size as f64, - ) - .unwrap(); + if let Some(size) = copy_size { + self.inner + .copy_buffer_to_buffer_with_f64_and_f64_and_f64( + &source.inner, + source_offset as f64, + &destination.inner, + destination_offset as f64, + size as f64, + ) + .unwrap(); + } else { + self.inner + .copy_buffer_to_buffer_with_f64_and_f64( + &source.inner, + source_offset as f64, + &destination.inner, + destination_offset as f64, + ) + .unwrap(); + } } fn copy_buffer_to_texture( @@ -3084,10 +3219,10 @@ impl dispatch::CommandEncoderInterface for WebCommandEncoder { ); } - fn build_acceleration_structures_unsafe_tlas<'a>( + fn mark_acceleration_structures_built<'a>( &self, - _blas: &mut dyn Iterator>, - _tlas: &mut dyn Iterator>, + _blas: &mut dyn Iterator, + _tlas: &mut dyn Iterator, ) { unimplemented!("Raytracing not implemented for web"); } @@ -3095,7 +3230,7 @@ impl dispatch::CommandEncoderInterface for WebCommandEncoder { fn build_acceleration_structures<'a>( &self, _blas: &mut dyn Iterator>, - _tlas: &mut dyn Iterator, + _tlas: &mut dyn Iterator, ) { unimplemented!("Raytracing not implemented for web"); } @@ -3352,6 +3487,10 @@ impl dispatch::RenderPassInterface for WebRenderPassEncoder { ) } + fn draw_mesh_tasks(&mut self, _group_count_x: u32, _group_count_y: u32, _group_count_z: u32) { + panic!("MESH_SHADER feature must be enabled to call draw_mesh_tasks") + } + fn draw_indirect( &mut self, indirect_buffer: &dispatch::DispatchBuffer, @@ -3372,6 +3511,14 @@ impl dispatch::RenderPassInterface for WebRenderPassEncoder { .draw_indexed_indirect_with_f64(&buffer.inner, indirect_offset as f64); } + fn draw_mesh_tasks_indirect( + &mut self, + _indirect_buffer: &dispatch::DispatchBuffer, + _indirect_offset: crate::BufferAddress, + ) { + panic!("MESH_SHADER feature must be enabled to call draw_mesh_tasks_indirect") + } + fn multi_draw_indirect( &mut self, indirect_buffer: &dispatch::DispatchBuffer, @@ -3402,6 +3549,15 @@ impl dispatch::RenderPassInterface for WebRenderPassEncoder { } } + fn multi_draw_mesh_tasks_indirect( + &mut self, + _indirect_buffer: &dispatch::DispatchBuffer, + _indirect_offset: crate::BufferAddress, + _count: u32, + ) { + panic!("MESH_SHADER feature must be enabled to call multi_draw_mesh_tasks_indirect") + } + fn multi_draw_indirect_count( &mut self, _indirect_buffer: &dispatch::DispatchBuffer, @@ -3426,6 +3582,17 @@ impl dispatch::RenderPassInterface for WebRenderPassEncoder { panic!("MULTI_DRAW_INDIRECT_COUNT feature must be enabled to call multi_draw_indexed_indirect_count") } + fn multi_draw_mesh_tasks_indirect_count( + &mut self, + _indirect_buffer: &dispatch::DispatchBuffer, + _indirect_offset: crate::BufferAddress, + _count_buffer: &dispatch::DispatchBuffer, + _count_buffer_offset: crate::BufferAddress, + _max_count: u32, + ) { + panic!("MESH_SHADER feature must be enabled to call multi_draw_mesh_tasks_indirect_count") + } + fn insert_debug_marker(&mut self, _label: &str) { // Not available in gecko yet // self.inner.insert_debug_marker(label); @@ -3771,13 +3938,22 @@ impl Drop for WebSurfaceOutputDetail { impl dispatch::BufferMappedRangeInterface for WebBufferMappedRange { #[inline] fn slice(&self) -> &[u8] { - &self.temporary_mapping + self.temporary_mapping + .get_or_init(|| self.actual_mapping.to_vec()) + .as_slice() } #[inline] fn slice_mut(&mut self) -> &mut [u8] { self.temporary_mapping_modified = true; - &mut self.temporary_mapping + self.temporary_mapping + .get_or_init(|| self.actual_mapping.to_vec()); + self.temporary_mapping.get_mut().unwrap() + } + + #[inline] + fn as_uint8array(&self) -> &js_sys::Uint8Array { + &self.actual_mapping } } impl Drop for WebBufferMappedRange { @@ -3790,7 +3966,7 @@ impl Drop for WebBufferMappedRange { // Copy from the temporary mapping back into the array buffer that was // originally provided by the browser - let temporary_mapping_slice = self.temporary_mapping.as_slice(); + let temporary_mapping_slice = self.temporary_mapping.get().unwrap().as_slice(); unsafe { // Note: no allocations can happen between `view` and `set`, or this // will break diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_Gpu.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_Gpu.rs index 63248496f..3a70b0c2f 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_Gpu.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_Gpu.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `Gpu`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type Gpu; # [wasm_bindgen (structural , method , getter , js_class = "GPU" , js_name = wgslLanguageFeatures)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `Gpu`, `WgslLanguageFeatures`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn wgsl_language_features(this: &Gpu) -> WgslLanguageFeatures; # [wasm_bindgen (method , structural , js_class = "GPU" , js_name = getPreferredCanvasFormat)] @@ -57,7 +57,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `Gpu`, `GpuTextureFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn get_preferred_canvas_format(this: &Gpu) -> GpuTextureFormat; # [wasm_bindgen (method , structural , js_class = "GPU" , js_name = requestAdapter)] @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `Gpu`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn request_adapter(this: &Gpu) -> ::js_sys::Promise; # [wasm_bindgen (method , structural , js_class = "GPU" , js_name = requestAdapter)] @@ -79,7 +79,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `Gpu`, `GpuRequestAdapterOptions`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn request_adapter_with_options( this: &Gpu, options: &GpuRequestAdapterOptions, diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuAdapter.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuAdapter.rs index 56f55c917..c1bc6d461 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuAdapter.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuAdapter.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuAdapter`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuAdapter; # [wasm_bindgen (structural , method , getter , js_class = "GPUAdapter" , js_name = features)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuAdapter`, `GpuSupportedFeatures`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn features(this: &GpuAdapter) -> GpuSupportedFeatures; # [wasm_bindgen (structural , method , getter , js_class = "GPUAdapter" , js_name = limits)] @@ -57,7 +57,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuAdapter`, `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn limits(this: &GpuAdapter) -> GpuSupportedLimits; # [wasm_bindgen (structural , method , getter , js_class = "GPUAdapter" , js_name = info)] @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuAdapter`, `GpuAdapterInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn info(this: &GpuAdapter) -> GpuAdapterInfo; # [wasm_bindgen (structural , method , getter , js_class = "GPUAdapter" , js_name = isFallbackAdapter)] @@ -79,7 +79,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuAdapter`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn is_fallback_adapter(this: &GpuAdapter) -> bool; # [wasm_bindgen (method , structural , js_class = "GPUAdapter" , js_name = requestDevice)] @@ -90,7 +90,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuAdapter`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn request_device(this: &GpuAdapter) -> ::js_sys::Promise; # [wasm_bindgen (method , structural , js_class = "GPUAdapter" , js_name = requestDevice)] @@ -101,7 +101,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuAdapter`, `GpuDeviceDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn request_device_with_descriptor( this: &GpuAdapter, descriptor: &GpuDeviceDescriptor, diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuAdapterInfo.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuAdapterInfo.rs index 04a6e36e4..c99000fda 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuAdapterInfo.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuAdapterInfo.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuAdapterInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuAdapterInfo; # [wasm_bindgen (structural , method , getter , js_class = "GPUAdapterInfo" , js_name = vendor)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuAdapterInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn vendor(this: &GpuAdapterInfo) -> ::alloc::string::String; # [wasm_bindgen (structural , method , getter , js_class = "GPUAdapterInfo" , js_name = architecture)] @@ -57,7 +57,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuAdapterInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn architecture(this: &GpuAdapterInfo) -> ::alloc::string::String; # [wasm_bindgen (structural , method , getter , js_class = "GPUAdapterInfo" , js_name = device)] @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuAdapterInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn device(this: &GpuAdapterInfo) -> ::alloc::string::String; # [wasm_bindgen (structural , method , getter , js_class = "GPUAdapterInfo" , js_name = description)] @@ -79,6 +79,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuAdapterInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn description(this: &GpuAdapterInfo) -> ::alloc::string::String; } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuAddressMode.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuAddressMode.rs index c86d2dc8e..11e70cff2 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuAddressMode.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuAddressMode.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuAddressMode`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuAddressMode { ClampToEdge = "clamp-to-edge", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuAutoLayoutMode.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuAutoLayoutMode.rs index 0a5cd490c..62d94465a 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuAutoLayoutMode.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuAutoLayoutMode.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuAutoLayoutMode`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuAutoLayoutMode { Auto = "auto", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroup.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroup.rs index 50e9c38d5..c056487ad 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroup.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroup.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuBindGroup; # [wasm_bindgen (structural , method , getter , js_class = "GPUBindGroup" , js_name = label)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn label(this: &GpuBindGroup) -> ::alloc::string::String; # [wasm_bindgen (structural , method , setter , js_class = "GPUBindGroup" , js_name = label)] @@ -57,6 +57,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_label(this: &GpuBindGroup, value: &str); } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroupDescriptor.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroupDescriptor.rs index dd861c6b0..3c58c1c20 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroupDescriptor.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroupDescriptor.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuBindGroupDescriptor; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuBindGroupDescriptor) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuBindGroupDescriptor, val: &str); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "entries")] pub fn get_entries(this: &GpuBindGroupDescriptor) -> ::js_sys::Array; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "entries")] pub fn set_entries(this: &GpuBindGroupDescriptor, val: &::wasm_bindgen::JsValue); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupDescriptor`, `GpuBindGroupLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "layout")] pub fn get_layout(this: &GpuBindGroupDescriptor) -> GpuBindGroupLayout; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupDescriptor`, `GpuBindGroupLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "layout")] pub fn set_layout(this: &GpuBindGroupDescriptor, val: &GpuBindGroupLayout); } @@ -97,7 +97,7 @@ impl GpuBindGroupDescriptor { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupDescriptor`, `GpuBindGroupLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(entries: &::wasm_bindgen::JsValue, layout: &GpuBindGroupLayout) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroupEntry.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroupEntry.rs index bb55ea5b8..266fd1cbf 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroupEntry.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroupEntry.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupEntry`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuBindGroupEntry; #[doc = "Get the `binding` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupEntry`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "binding")] pub fn get_binding(this: &GpuBindGroupEntry) -> u32; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupEntry`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "binding")] pub fn set_binding(this: &GpuBindGroupEntry, val: u32); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupEntry`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "resource")] pub fn get_resource(this: &GpuBindGroupEntry) -> ::wasm_bindgen::JsValue; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupEntry`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "resource")] pub fn set_resource(this: &GpuBindGroupEntry, val: &::wasm_bindgen::JsValue); } @@ -79,7 +79,7 @@ impl GpuBindGroupEntry { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupEntry`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(binding: u32, resource: &::wasm_bindgen::JsValue) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroupLayout.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroupLayout.rs index f11a13393..7c500ea0f 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroupLayout.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroupLayout.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuBindGroupLayout; # [wasm_bindgen (structural , method , getter , js_class = "GPUBindGroupLayout" , js_name = label)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn label(this: &GpuBindGroupLayout) -> ::alloc::string::String; # [wasm_bindgen (structural , method , setter , js_class = "GPUBindGroupLayout" , js_name = label)] @@ -57,6 +57,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_label(this: &GpuBindGroupLayout, value: &str); } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroupLayoutDescriptor.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroupLayoutDescriptor.rs index 7e4a50a2d..5e11b9f8f 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroupLayoutDescriptor.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroupLayoutDescriptor.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuBindGroupLayoutDescriptor; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuBindGroupLayoutDescriptor) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuBindGroupLayoutDescriptor, val: &str); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "entries")] pub fn get_entries(this: &GpuBindGroupLayoutDescriptor) -> ::js_sys::Array; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "entries")] pub fn set_entries(this: &GpuBindGroupLayoutDescriptor, val: &::wasm_bindgen::JsValue); } @@ -79,7 +79,7 @@ impl GpuBindGroupLayoutDescriptor { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(entries: &::wasm_bindgen::JsValue) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroupLayoutEntry.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroupLayoutEntry.rs index e13a7b575..d641712e3 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroupLayoutEntry.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBindGroupLayoutEntry.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutEntry`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuBindGroupLayoutEntry; #[doc = "Get the `binding` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutEntry`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "binding")] pub fn get_binding(this: &GpuBindGroupLayoutEntry) -> u32; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutEntry`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "binding")] pub fn set_binding(this: &GpuBindGroupLayoutEntry, val: u32); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutEntry`, `GpuBufferBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "buffer")] pub fn get_buffer(this: &GpuBindGroupLayoutEntry) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutEntry`, `GpuBufferBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "buffer")] pub fn set_buffer(this: &GpuBindGroupLayoutEntry, val: &GpuBufferBindingLayout); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutEntry`, `GpuExternalTextureBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "externalTexture")] pub fn get_external_texture( this: &GpuBindGroupLayoutEntry, @@ -88,7 +88,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutEntry`, `GpuExternalTextureBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "externalTexture")] pub fn set_external_texture( this: &GpuBindGroupLayoutEntry, @@ -100,7 +100,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutEntry`, `GpuSamplerBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "sampler")] pub fn get_sampler(this: &GpuBindGroupLayoutEntry) -> Option; @@ -109,7 +109,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutEntry`, `GpuSamplerBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "sampler")] pub fn set_sampler(this: &GpuBindGroupLayoutEntry, val: &GpuSamplerBindingLayout); @@ -118,7 +118,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutEntry`, `GpuStorageTextureBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "storageTexture")] pub fn get_storage_texture( this: &GpuBindGroupLayoutEntry, @@ -129,7 +129,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutEntry`, `GpuStorageTextureBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "storageTexture")] pub fn set_storage_texture( this: &GpuBindGroupLayoutEntry, @@ -141,7 +141,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutEntry`, `GpuTextureBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "texture")] pub fn get_texture(this: &GpuBindGroupLayoutEntry) -> Option; @@ -150,7 +150,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutEntry`, `GpuTextureBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "texture")] pub fn set_texture(this: &GpuBindGroupLayoutEntry, val: &GpuTextureBindingLayout); @@ -159,7 +159,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutEntry`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "visibility")] pub fn get_visibility(this: &GpuBindGroupLayoutEntry) -> u32; @@ -168,7 +168,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutEntry`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "visibility")] pub fn set_visibility(this: &GpuBindGroupLayoutEntry, val: u32); } @@ -179,7 +179,7 @@ impl GpuBindGroupLayoutEntry { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayoutEntry`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(binding: u32, visibility: u32) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBlendComponent.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBlendComponent.rs index 99d708b72..0f11495e3 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBlendComponent.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBlendComponent.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBlendComponent`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuBlendComponent; #[doc = "Get the `dstFactor` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBlendComponent`, `GpuBlendFactor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "dstFactor")] pub fn get_dst_factor(this: &GpuBlendComponent) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBlendComponent`, `GpuBlendFactor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "dstFactor")] pub fn set_dst_factor(this: &GpuBlendComponent, val: GpuBlendFactor); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBlendComponent`, `GpuBlendOperation`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "operation")] pub fn get_operation(this: &GpuBlendComponent) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBlendComponent`, `GpuBlendOperation`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "operation")] pub fn set_operation(this: &GpuBlendComponent, val: GpuBlendOperation); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBlendComponent`, `GpuBlendFactor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "srcFactor")] pub fn get_src_factor(this: &GpuBlendComponent) -> Option; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBlendComponent`, `GpuBlendFactor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "srcFactor")] pub fn set_src_factor(this: &GpuBlendComponent, val: GpuBlendFactor); } @@ -97,7 +97,7 @@ impl GpuBlendComponent { #[doc = "*This API requires the following crate features to be activated: `GpuBlendComponent`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBlendFactor.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBlendFactor.rs index 37b7978da..0b1f7c391 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBlendFactor.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBlendFactor.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuBlendFactor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuBlendFactor { Zero = "zero", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBlendOperation.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBlendOperation.rs index 9ce4393be..13da1a1b7 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBlendOperation.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBlendOperation.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuBlendOperation`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuBlendOperation { Add = "add", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBlendState.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBlendState.rs index 043460b8a..8c54586f3 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBlendState.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBlendState.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBlendState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuBlendState; #[doc = "Get the `alpha` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBlendComponent`, `GpuBlendState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "alpha")] pub fn get_alpha(this: &GpuBlendState) -> GpuBlendComponent; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBlendComponent`, `GpuBlendState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "alpha")] pub fn set_alpha(this: &GpuBlendState, val: &GpuBlendComponent); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBlendComponent`, `GpuBlendState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "color")] pub fn get_color(this: &GpuBlendState) -> GpuBlendComponent; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBlendComponent`, `GpuBlendState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "color")] pub fn set_color(this: &GpuBlendState, val: &GpuBlendComponent); } @@ -79,7 +79,7 @@ impl GpuBlendState { #[doc = "*This API requires the following crate features to be activated: `GpuBlendComponent`, `GpuBlendState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(alpha: &GpuBlendComponent, color: &GpuBlendComponent) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBuffer.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBuffer.rs index e336ba4fb..05f60aa54 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBuffer.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBuffer.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuBuffer; # [wasm_bindgen (structural , method , getter , js_class = "GPUBuffer" , js_name = size)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn size(this: &GpuBuffer) -> f64; # [wasm_bindgen (structural , method , getter , js_class = "GPUBuffer" , js_name = usage)] @@ -57,7 +57,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn usage(this: &GpuBuffer) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUBuffer" , js_name = mapState)] @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuBufferMapState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn map_state(this: &GpuBuffer) -> GpuBufferMapState; # [wasm_bindgen (structural , method , getter , js_class = "GPUBuffer" , js_name = label)] @@ -79,7 +79,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn label(this: &GpuBuffer) -> ::alloc::string::String; # [wasm_bindgen (structural , method , setter , js_class = "GPUBuffer" , js_name = label)] @@ -90,7 +90,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_label(this: &GpuBuffer, value: &str); # [wasm_bindgen (method , structural , js_class = "GPUBuffer" , js_name = destroy)] @@ -101,7 +101,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn destroy(this: &GpuBuffer); # [wasm_bindgen (catch , method , structural , js_class = "GPUBuffer" , js_name = getMappedRange)] @@ -112,7 +112,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn get_mapped_range(this: &GpuBuffer) -> Result<::js_sys::ArrayBuffer, JsValue>; # [wasm_bindgen (catch , method , structural , js_class = "GPUBuffer" , js_name = getMappedRange)] @@ -123,7 +123,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn get_mapped_range_with_u32( this: &GpuBuffer, offset: u32, @@ -137,7 +137,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn get_mapped_range_with_f64( this: &GpuBuffer, offset: f64, @@ -151,7 +151,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn get_mapped_range_with_u32_and_u32( this: &GpuBuffer, offset: u32, @@ -166,7 +166,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn get_mapped_range_with_f64_and_u32( this: &GpuBuffer, offset: f64, @@ -181,7 +181,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn get_mapped_range_with_u32_and_f64( this: &GpuBuffer, offset: u32, @@ -196,7 +196,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn get_mapped_range_with_f64_and_f64( this: &GpuBuffer, offset: f64, @@ -211,7 +211,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn map_async(this: &GpuBuffer, mode: u32) -> ::js_sys::Promise; # [wasm_bindgen (method , structural , js_class = "GPUBuffer" , js_name = mapAsync)] @@ -222,7 +222,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn map_async_with_u32(this: &GpuBuffer, mode: u32, offset: u32) -> ::js_sys::Promise; # [wasm_bindgen (method , structural , js_class = "GPUBuffer" , js_name = mapAsync)] @@ -233,7 +233,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn map_async_with_f64(this: &GpuBuffer, mode: u32, offset: f64) -> ::js_sys::Promise; # [wasm_bindgen (method , structural , js_class = "GPUBuffer" , js_name = mapAsync)] @@ -244,7 +244,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn map_async_with_u32_and_u32( this: &GpuBuffer, mode: u32, @@ -260,7 +260,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn map_async_with_f64_and_u32( this: &GpuBuffer, mode: u32, @@ -276,7 +276,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn map_async_with_u32_and_f64( this: &GpuBuffer, mode: u32, @@ -292,7 +292,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn map_async_with_f64_and_f64( this: &GpuBuffer, mode: u32, @@ -308,6 +308,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn unmap(this: &GpuBuffer); } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBufferBinding.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBufferBinding.rs index 0e56f2ede..5174557c6 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBufferBinding.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBufferBinding.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBufferBinding`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuBufferBinding; #[doc = "Get the `buffer` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuBufferBinding`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "buffer")] pub fn get_buffer(this: &GpuBufferBinding) -> GpuBuffer; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuBufferBinding`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "buffer")] pub fn set_buffer(this: &GpuBufferBinding, val: &GpuBuffer); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBufferBinding`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "offset")] pub fn get_offset(this: &GpuBufferBinding) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBufferBinding`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "offset")] pub fn set_offset(this: &GpuBufferBinding, val: f64); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBufferBinding`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "size")] pub fn get_size(this: &GpuBufferBinding) -> Option; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBufferBinding`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "size")] pub fn set_size(this: &GpuBufferBinding, val: f64); } @@ -97,7 +97,7 @@ impl GpuBufferBinding { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuBufferBinding`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(buffer: &GpuBuffer) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBufferBindingLayout.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBufferBindingLayout.rs index fb626c971..311d42bc1 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBufferBindingLayout.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBufferBindingLayout.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBufferBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuBufferBindingLayout; #[doc = "Get the `hasDynamicOffset` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBufferBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "hasDynamicOffset")] pub fn get_has_dynamic_offset(this: &GpuBufferBindingLayout) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBufferBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "hasDynamicOffset")] pub fn set_has_dynamic_offset(this: &GpuBufferBindingLayout, val: bool); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBufferBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "minBindingSize")] pub fn get_min_binding_size(this: &GpuBufferBindingLayout) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBufferBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "minBindingSize")] pub fn set_min_binding_size(this: &GpuBufferBindingLayout, val: f64); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBufferBindingLayout`, `GpuBufferBindingType`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "type")] pub fn get_type(this: &GpuBufferBindingLayout) -> Option; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBufferBindingLayout`, `GpuBufferBindingType`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "type")] pub fn set_type(this: &GpuBufferBindingLayout, val: GpuBufferBindingType); } @@ -97,7 +97,7 @@ impl GpuBufferBindingLayout { #[doc = "*This API requires the following crate features to be activated: `GpuBufferBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBufferBindingType.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBufferBindingType.rs index 32c345dd3..7b1a6478d 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBufferBindingType.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBufferBindingType.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuBufferBindingType`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuBufferBindingType { Uniform = "uniform", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBufferDescriptor.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBufferDescriptor.rs index 364ec90ef..0303470cf 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBufferDescriptor.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBufferDescriptor.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBufferDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuBufferDescriptor; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBufferDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuBufferDescriptor) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBufferDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuBufferDescriptor, val: &str); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBufferDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "mappedAtCreation")] pub fn get_mapped_at_creation(this: &GpuBufferDescriptor) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBufferDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "mappedAtCreation")] pub fn set_mapped_at_creation(this: &GpuBufferDescriptor, val: bool); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBufferDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "size")] pub fn get_size(this: &GpuBufferDescriptor) -> f64; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBufferDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "size")] pub fn set_size(this: &GpuBufferDescriptor, val: f64); @@ -95,7 +95,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBufferDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "usage")] pub fn get_usage(this: &GpuBufferDescriptor) -> u32; @@ -104,7 +104,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBufferDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "usage")] pub fn set_usage(this: &GpuBufferDescriptor, val: u32); } @@ -115,7 +115,7 @@ impl GpuBufferDescriptor { #[doc = "*This API requires the following crate features to be activated: `GpuBufferDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(size: f64, usage: u32) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBufferMapState.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBufferMapState.rs index ef5843a1e..c44b6ec45 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBufferMapState.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuBufferMapState.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuBufferMapState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuBufferMapState { Unmapped = "unmapped", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCanvasAlphaMode.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCanvasAlphaMode.rs index 2f05cc060..0ec4ac45f 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCanvasAlphaMode.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCanvasAlphaMode.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuCanvasAlphaMode`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuCanvasAlphaMode { Opaque = "opaque", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCanvasConfiguration.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCanvasConfiguration.rs index 383ea0e26..469376aff 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCanvasConfiguration.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCanvasConfiguration.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasConfiguration`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuCanvasConfiguration; #[doc = "Get the `alphaMode` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasAlphaMode`, `GpuCanvasConfiguration`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "alphaMode")] pub fn get_alpha_mode(this: &GpuCanvasConfiguration) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasAlphaMode`, `GpuCanvasConfiguration`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "alphaMode")] pub fn set_alpha_mode(this: &GpuCanvasConfiguration, val: GpuCanvasAlphaMode); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasConfiguration`, `GpuDevice`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "device")] pub fn get_device(this: &GpuCanvasConfiguration) -> GpuDevice; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasConfiguration`, `GpuDevice`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "device")] pub fn set_device(this: &GpuCanvasConfiguration, val: &GpuDevice); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasConfiguration`, `GpuTextureFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "format")] pub fn get_format(this: &GpuCanvasConfiguration) -> GpuTextureFormat; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasConfiguration`, `GpuTextureFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "format")] pub fn set_format(this: &GpuCanvasConfiguration, val: GpuTextureFormat); @@ -95,7 +95,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasConfiguration`, `GpuCanvasToneMapping`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "toneMapping")] pub fn get_tone_mapping(this: &GpuCanvasConfiguration) -> Option; @@ -104,7 +104,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasConfiguration`, `GpuCanvasToneMapping`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "toneMapping")] pub fn set_tone_mapping(this: &GpuCanvasConfiguration, val: &GpuCanvasToneMapping); @@ -113,7 +113,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasConfiguration`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "usage")] pub fn get_usage(this: &GpuCanvasConfiguration) -> Option; @@ -122,7 +122,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasConfiguration`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "usage")] pub fn set_usage(this: &GpuCanvasConfiguration, val: u32); @@ -131,7 +131,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasConfiguration`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "viewFormats")] pub fn get_view_formats(this: &GpuCanvasConfiguration) -> Option<::js_sys::Array>; @@ -140,7 +140,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasConfiguration`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "viewFormats")] pub fn set_view_formats(this: &GpuCanvasConfiguration, val: &::wasm_bindgen::JsValue); } @@ -151,7 +151,7 @@ impl GpuCanvasConfiguration { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasConfiguration`, `GpuDevice`, `GpuTextureFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(device: &GpuDevice, format: GpuTextureFormat) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCanvasContext.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCanvasContext.rs index b9a006bac..5504b3bdf 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCanvasContext.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCanvasContext.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasContext`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuCanvasContext; # [wasm_bindgen (structural , method , getter , js_class = "GPUCanvasContext" , js_name = canvas)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasContext`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn canvas(this: &GpuCanvasContext) -> ::js_sys::Object; # [wasm_bindgen (catch , method , structural , js_class = "GPUCanvasContext" , js_name = configure)] @@ -57,7 +57,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasConfiguration`, `GpuCanvasContext`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn configure( this: &GpuCanvasContext, configuration: &GpuCanvasConfiguration, @@ -71,7 +71,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasConfiguration`, `GpuCanvasContext`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn get_configuration(this: &GpuCanvasContext) -> Option; # [wasm_bindgen (catch , method , structural , js_class = "GPUCanvasContext" , js_name = getCurrentTexture)] @@ -82,7 +82,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasContext`, `GpuTexture`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn get_current_texture(this: &GpuCanvasContext) -> Result; # [wasm_bindgen (method , structural , js_class = "GPUCanvasContext" , js_name = unconfigure)] @@ -93,6 +93,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasContext`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn unconfigure(this: &GpuCanvasContext); } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCanvasToneMapping.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCanvasToneMapping.rs index 899f95608..8b528f73e 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCanvasToneMapping.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCanvasToneMapping.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasToneMapping`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuCanvasToneMapping; #[doc = "Get the `mode` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasToneMapping`, `GpuCanvasToneMappingMode`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "mode")] pub fn get_mode(this: &GpuCanvasToneMapping) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasToneMapping`, `GpuCanvasToneMappingMode`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "mode")] pub fn set_mode(this: &GpuCanvasToneMapping, val: GpuCanvasToneMappingMode); } @@ -61,7 +61,7 @@ impl GpuCanvasToneMapping { #[doc = "*This API requires the following crate features to be activated: `GpuCanvasToneMapping`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCanvasToneMappingMode.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCanvasToneMappingMode.rs index efe6985b0..e601a631e 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCanvasToneMappingMode.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCanvasToneMappingMode.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuCanvasToneMappingMode`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuCanvasToneMappingMode { Standard = "standard", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuColorDict.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuColorDict.rs index 96117f719..eb02d9613 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuColorDict.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuColorDict.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuColorDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuColorDict; #[doc = "Get the `a` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuColorDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "a")] pub fn get_a(this: &GpuColorDict) -> f64; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuColorDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "a")] pub fn set_a(this: &GpuColorDict, val: f64); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuColorDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "b")] pub fn get_b(this: &GpuColorDict) -> f64; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuColorDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "b")] pub fn set_b(this: &GpuColorDict, val: f64); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuColorDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "g")] pub fn get_g(this: &GpuColorDict) -> f64; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuColorDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "g")] pub fn set_g(this: &GpuColorDict, val: f64); @@ -95,7 +95,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuColorDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "r")] pub fn get_r(this: &GpuColorDict) -> f64; @@ -104,7 +104,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuColorDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "r")] pub fn set_r(this: &GpuColorDict, val: f64); } @@ -115,7 +115,7 @@ impl GpuColorDict { #[doc = "*This API requires the following crate features to be activated: `GpuColorDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(a: f64, b: f64, g: f64, r: f64) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuColorTargetState.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuColorTargetState.rs index 864510774..4f92ba301 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuColorTargetState.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuColorTargetState.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuColorTargetState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuColorTargetState; #[doc = "Get the `blend` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBlendState`, `GpuColorTargetState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "blend")] pub fn get_blend(this: &GpuColorTargetState) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBlendState`, `GpuColorTargetState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "blend")] pub fn set_blend(this: &GpuColorTargetState, val: &GpuBlendState); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuColorTargetState`, `GpuTextureFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "format")] pub fn get_format(this: &GpuColorTargetState) -> GpuTextureFormat; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuColorTargetState`, `GpuTextureFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "format")] pub fn set_format(this: &GpuColorTargetState, val: GpuTextureFormat); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuColorTargetState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "writeMask")] pub fn get_write_mask(this: &GpuColorTargetState) -> Option; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuColorTargetState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "writeMask")] pub fn set_write_mask(this: &GpuColorTargetState, val: u32); } @@ -97,7 +97,7 @@ impl GpuColorTargetState { #[doc = "*This API requires the following crate features to be activated: `GpuColorTargetState`, `GpuTextureFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(format: GpuTextureFormat) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCommandBuffer.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCommandBuffer.rs index dabe282b6..44e47a236 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCommandBuffer.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCommandBuffer.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuCommandBuffer; # [wasm_bindgen (structural , method , getter , js_class = "GPUCommandBuffer" , js_name = label)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn label(this: &GpuCommandBuffer) -> ::alloc::string::String; # [wasm_bindgen (structural , method , setter , js_class = "GPUCommandBuffer" , js_name = label)] @@ -57,6 +57,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandBuffer`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_label(this: &GpuCommandBuffer, value: &str); } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCommandBufferDescriptor.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCommandBufferDescriptor.rs index b3b55f506..c571b4082 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCommandBufferDescriptor.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCommandBufferDescriptor.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandBufferDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuCommandBufferDescriptor; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandBufferDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuCommandBufferDescriptor) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandBufferDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuCommandBufferDescriptor, val: &str); } @@ -61,7 +61,7 @@ impl GpuCommandBufferDescriptor { #[doc = "*This API requires the following crate features to be activated: `GpuCommandBufferDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCommandEncoder.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCommandEncoder.rs index 604b5de65..2116f8a1a 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCommandEncoder.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCommandEncoder.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuCommandEncoder; # [wasm_bindgen (structural , method , getter , js_class = "GPUCommandEncoder" , js_name = label)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn label(this: &GpuCommandEncoder) -> ::alloc::string::String; # [wasm_bindgen (structural , method , setter , js_class = "GPUCommandEncoder" , js_name = label)] @@ -57,7 +57,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_label(this: &GpuCommandEncoder, value: &str); # [wasm_bindgen (method , structural , js_class = "GPUCommandEncoder" , js_name = beginComputePass)] @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandEncoder`, `GpuComputePassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn begin_compute_pass(this: &GpuCommandEncoder) -> GpuComputePassEncoder; # [wasm_bindgen (method , structural , js_class = "GPUCommandEncoder" , js_name = beginComputePass)] @@ -79,7 +79,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandEncoder`, `GpuComputePassDescriptor`, `GpuComputePassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn begin_compute_pass_with_descriptor( this: &GpuCommandEncoder, descriptor: &GpuComputePassDescriptor, @@ -93,7 +93,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandEncoder`, `GpuRenderPassDescriptor`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn begin_render_pass( this: &GpuCommandEncoder, descriptor: &GpuRenderPassDescriptor, @@ -107,7 +107,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn clear_buffer(this: &GpuCommandEncoder, buffer: &GpuBuffer); # [wasm_bindgen (method , structural , js_class = "GPUCommandEncoder" , js_name = clearBuffer)] @@ -118,7 +118,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn clear_buffer_with_u32(this: &GpuCommandEncoder, buffer: &GpuBuffer, offset: u32); # [wasm_bindgen (method , structural , js_class = "GPUCommandEncoder" , js_name = clearBuffer)] @@ -129,7 +129,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn clear_buffer_with_f64(this: &GpuCommandEncoder, buffer: &GpuBuffer, offset: f64); # [wasm_bindgen (method , structural , js_class = "GPUCommandEncoder" , js_name = clearBuffer)] @@ -140,7 +140,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn clear_buffer_with_u32_and_u32( this: &GpuCommandEncoder, buffer: &GpuBuffer, @@ -156,7 +156,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn clear_buffer_with_f64_and_u32( this: &GpuCommandEncoder, buffer: &GpuBuffer, @@ -172,7 +172,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn clear_buffer_with_u32_and_f64( this: &GpuCommandEncoder, buffer: &GpuBuffer, @@ -188,7 +188,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn clear_buffer_with_f64_and_f64( this: &GpuCommandEncoder, buffer: &GpuBuffer, @@ -204,7 +204,75 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] + pub fn copy_buffer_to_buffer_with_u32_and_u32( + this: &GpuCommandEncoder, + source: &GpuBuffer, + source_offset: u32, + destination: &GpuBuffer, + destination_offset: u32, + ) -> Result<(), JsValue>; + + # [wasm_bindgen (catch , method , structural , js_class = "GPUCommandEncoder" , js_name = copyBufferToBuffer)] + #[doc = "The `copyBufferToBuffer()` method."] + #[doc = ""] + #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/GPUCommandEncoder/copyBufferToBuffer)"] + #[doc = ""] + #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuCommandEncoder`*"] + #[doc = ""] + #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] + pub fn copy_buffer_to_buffer_with_f64_and_u32( + this: &GpuCommandEncoder, + source: &GpuBuffer, + source_offset: f64, + destination: &GpuBuffer, + destination_offset: u32, + ) -> Result<(), JsValue>; + + # [wasm_bindgen (catch , method , structural , js_class = "GPUCommandEncoder" , js_name = copyBufferToBuffer)] + #[doc = "The `copyBufferToBuffer()` method."] + #[doc = ""] + #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/GPUCommandEncoder/copyBufferToBuffer)"] + #[doc = ""] + #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuCommandEncoder`*"] + #[doc = ""] + #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] + pub fn copy_buffer_to_buffer_with_u32_and_f64( + this: &GpuCommandEncoder, + source: &GpuBuffer, + source_offset: u32, + destination: &GpuBuffer, + destination_offset: f64, + ) -> Result<(), JsValue>; + + # [wasm_bindgen (catch , method , structural , js_class = "GPUCommandEncoder" , js_name = copyBufferToBuffer)] + #[doc = "The `copyBufferToBuffer()` method."] + #[doc = ""] + #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/GPUCommandEncoder/copyBufferToBuffer)"] + #[doc = ""] + #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuCommandEncoder`*"] + #[doc = ""] + #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] + pub fn copy_buffer_to_buffer_with_f64_and_f64( + this: &GpuCommandEncoder, + source: &GpuBuffer, + source_offset: f64, + destination: &GpuBuffer, + destination_offset: f64, + ) -> Result<(), JsValue>; + + # [wasm_bindgen (catch , method , structural , js_class = "GPUCommandEncoder" , js_name = copyBufferToBuffer)] + #[doc = "The `copyBufferToBuffer()` method."] + #[doc = ""] + #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/GPUCommandEncoder/copyBufferToBuffer)"] + #[doc = ""] + #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuCommandEncoder`*"] + #[doc = ""] + #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn copy_buffer_to_buffer_with_u32_and_u32_and_u32( this: &GpuCommandEncoder, source: &GpuBuffer, @@ -222,7 +290,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn copy_buffer_to_buffer_with_f64_and_u32_and_u32( this: &GpuCommandEncoder, source: &GpuBuffer, @@ -240,7 +308,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn copy_buffer_to_buffer_with_u32_and_f64_and_u32( this: &GpuCommandEncoder, source: &GpuBuffer, @@ -258,7 +326,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn copy_buffer_to_buffer_with_f64_and_f64_and_u32( this: &GpuCommandEncoder, source: &GpuBuffer, @@ -276,7 +344,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn copy_buffer_to_buffer_with_u32_and_u32_and_f64( this: &GpuCommandEncoder, source: &GpuBuffer, @@ -294,7 +362,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn copy_buffer_to_buffer_with_f64_and_u32_and_f64( this: &GpuCommandEncoder, source: &GpuBuffer, @@ -312,7 +380,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn copy_buffer_to_buffer_with_u32_and_f64_and_f64( this: &GpuCommandEncoder, source: &GpuBuffer, @@ -330,7 +398,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn copy_buffer_to_buffer_with_f64_and_f64_and_f64( this: &GpuCommandEncoder, source: &GpuBuffer, @@ -348,7 +416,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandEncoder`, `GpuTexelCopyBufferInfo`, `GpuTexelCopyTextureInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn copy_buffer_to_texture_with_u32_sequence( this: &GpuCommandEncoder, source: &GpuTexelCopyBufferInfo, @@ -364,7 +432,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandEncoder`, `GpuExtent3dDict`, `GpuTexelCopyBufferInfo`, `GpuTexelCopyTextureInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn copy_buffer_to_texture_with_gpu_extent_3d_dict( this: &GpuCommandEncoder, source: &GpuTexelCopyBufferInfo, @@ -380,7 +448,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandEncoder`, `GpuTexelCopyBufferInfo`, `GpuTexelCopyTextureInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn copy_texture_to_buffer_with_u32_sequence( this: &GpuCommandEncoder, source: &GpuTexelCopyTextureInfo, @@ -396,7 +464,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandEncoder`, `GpuExtent3dDict`, `GpuTexelCopyBufferInfo`, `GpuTexelCopyTextureInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn copy_texture_to_buffer_with_gpu_extent_3d_dict( this: &GpuCommandEncoder, source: &GpuTexelCopyTextureInfo, @@ -412,7 +480,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandEncoder`, `GpuTexelCopyTextureInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn copy_texture_to_texture_with_u32_sequence( this: &GpuCommandEncoder, source: &GpuTexelCopyTextureInfo, @@ -428,7 +496,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandEncoder`, `GpuExtent3dDict`, `GpuTexelCopyTextureInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn copy_texture_to_texture_with_gpu_extent_3d_dict( this: &GpuCommandEncoder, source: &GpuTexelCopyTextureInfo, @@ -444,7 +512,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandBuffer`, `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn finish(this: &GpuCommandEncoder) -> GpuCommandBuffer; # [wasm_bindgen (method , structural , js_class = "GPUCommandEncoder" , js_name = finish)] @@ -455,7 +523,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandBuffer`, `GpuCommandBufferDescriptor`, `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn finish_with_descriptor( this: &GpuCommandEncoder, descriptor: &GpuCommandBufferDescriptor, @@ -469,7 +537,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuCommandEncoder`, `GpuQuerySet`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn resolve_query_set_with_u32( this: &GpuCommandEncoder, query_set: &GpuQuerySet, @@ -487,7 +555,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuCommandEncoder`, `GpuQuerySet`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn resolve_query_set_with_f64( this: &GpuCommandEncoder, query_set: &GpuQuerySet, @@ -505,7 +573,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn insert_debug_marker(this: &GpuCommandEncoder, marker_label: &str); # [wasm_bindgen (method , structural , js_class = "GPUCommandEncoder" , js_name = popDebugGroup)] @@ -516,7 +584,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn pop_debug_group(this: &GpuCommandEncoder); # [wasm_bindgen (method , structural , js_class = "GPUCommandEncoder" , js_name = pushDebugGroup)] @@ -527,6 +595,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn push_debug_group(this: &GpuCommandEncoder, group_label: &str); } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCommandEncoderDescriptor.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCommandEncoderDescriptor.rs index 3b6d9c8d8..64d08c43d 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCommandEncoderDescriptor.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCommandEncoderDescriptor.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandEncoderDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuCommandEncoderDescriptor; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandEncoderDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuCommandEncoderDescriptor) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandEncoderDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuCommandEncoderDescriptor, val: &str); } @@ -61,7 +61,7 @@ impl GpuCommandEncoderDescriptor { #[doc = "*This API requires the following crate features to be activated: `GpuCommandEncoderDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCompareFunction.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCompareFunction.rs index 615f82de9..bd7008fe2 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCompareFunction.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCompareFunction.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuCompareFunction`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuCompareFunction { Never = "never", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCompilationInfo.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCompilationInfo.rs index b2a4c1722..029797d14 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCompilationInfo.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCompilationInfo.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCompilationInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuCompilationInfo; # [wasm_bindgen (structural , method , getter , js_class = "GPUCompilationInfo" , js_name = messages)] @@ -46,6 +46,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCompilationInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn messages(this: &GpuCompilationInfo) -> ::js_sys::Array; } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCompilationMessage.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCompilationMessage.rs index ca7fec811..927af7391 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCompilationMessage.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCompilationMessage.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCompilationMessage`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuCompilationMessage; # [wasm_bindgen (structural , method , getter , js_class = "GPUCompilationMessage" , js_name = message)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCompilationMessage`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn message(this: &GpuCompilationMessage) -> ::alloc::string::String; # [wasm_bindgen (structural , method , getter , js_class = "GPUCompilationMessage" , js_name = type)] @@ -57,7 +57,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCompilationMessage`, `GpuCompilationMessageType`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn type_(this: &GpuCompilationMessage) -> GpuCompilationMessageType; # [wasm_bindgen (structural , method , getter , js_class = "GPUCompilationMessage" , js_name = lineNum)] @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCompilationMessage`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn line_num(this: &GpuCompilationMessage) -> f64; # [wasm_bindgen (structural , method , getter , js_class = "GPUCompilationMessage" , js_name = linePos)] @@ -79,7 +79,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCompilationMessage`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn line_pos(this: &GpuCompilationMessage) -> f64; # [wasm_bindgen (structural , method , getter , js_class = "GPUCompilationMessage" , js_name = offset)] @@ -90,7 +90,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCompilationMessage`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn offset(this: &GpuCompilationMessage) -> f64; # [wasm_bindgen (structural , method , getter , js_class = "GPUCompilationMessage" , js_name = length)] @@ -101,6 +101,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCompilationMessage`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn length(this: &GpuCompilationMessage) -> f64; } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCompilationMessageType.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCompilationMessageType.rs index 4db916ce8..6b98eb784 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCompilationMessageType.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCompilationMessageType.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuCompilationMessageType`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuCompilationMessageType { Error = "error", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuComputePassDescriptor.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuComputePassDescriptor.rs index 4658d3f69..593a06f44 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuComputePassDescriptor.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuComputePassDescriptor.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuComputePassDescriptor; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuComputePassDescriptor) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuComputePassDescriptor, val: &str); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassDescriptor`, `GpuComputePassTimestampWrites`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "timestampWrites")] pub fn get_timestamp_writes( this: &GpuComputePassDescriptor, @@ -70,7 +70,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassDescriptor`, `GpuComputePassTimestampWrites`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "timestampWrites")] pub fn set_timestamp_writes( this: &GpuComputePassDescriptor, @@ -84,7 +84,7 @@ impl GpuComputePassDescriptor { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuComputePassEncoder.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuComputePassEncoder.rs index e84fce360..1e57894e2 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuComputePassEncoder.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuComputePassEncoder.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuComputePassEncoder; # [wasm_bindgen (structural , method , getter , js_class = "GPUComputePassEncoder" , js_name = label)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn label(this: &GpuComputePassEncoder) -> ::alloc::string::String; # [wasm_bindgen (structural , method , setter , js_class = "GPUComputePassEncoder" , js_name = label)] @@ -57,7 +57,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_label(this: &GpuComputePassEncoder, value: &str); # [wasm_bindgen (method , structural , js_class = "GPUComputePassEncoder" , js_name = dispatchWorkgroups)] @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn dispatch_workgroups(this: &GpuComputePassEncoder, workgroup_count_x: u32); # [wasm_bindgen (method , structural , js_class = "GPUComputePassEncoder" , js_name = dispatchWorkgroups)] @@ -79,7 +79,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn dispatch_workgroups_with_workgroup_count_y( this: &GpuComputePassEncoder, workgroup_count_x: u32, @@ -94,7 +94,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn dispatch_workgroups_with_workgroup_count_y_and_workgroup_count_z( this: &GpuComputePassEncoder, workgroup_count_x: u32, @@ -110,7 +110,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuComputePassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn dispatch_workgroups_indirect_with_u32( this: &GpuComputePassEncoder, indirect_buffer: &GpuBuffer, @@ -125,7 +125,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuComputePassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn dispatch_workgroups_indirect_with_f64( this: &GpuComputePassEncoder, indirect_buffer: &GpuBuffer, @@ -140,7 +140,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn end(this: &GpuComputePassEncoder); # [wasm_bindgen (method , structural , js_class = "GPUComputePassEncoder" , js_name = setPipeline)] @@ -151,7 +151,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassEncoder`, `GpuComputePipeline`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_pipeline(this: &GpuComputePassEncoder, pipeline: &GpuComputePipeline); # [wasm_bindgen (method , structural , js_class = "GPUComputePassEncoder" , js_name = setBindGroup)] @@ -162,7 +162,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`, `GpuComputePassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_bind_group( this: &GpuComputePassEncoder, index: u32, @@ -177,7 +177,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`, `GpuComputePassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_bind_group_with_u32_sequence( this: &GpuComputePassEncoder, index: u32, @@ -193,7 +193,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`, `GpuComputePassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_bind_group_with_u32_slice_and_u32_and_dynamic_offsets_data_length( this: &GpuComputePassEncoder, index: u32, @@ -211,7 +211,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`, `GpuComputePassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_bind_group_with_u32_array_and_u32_and_dynamic_offsets_data_length( this: &GpuComputePassEncoder, index: u32, @@ -229,7 +229,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`, `GpuComputePassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_bind_group_with_u32_slice_and_f64_and_dynamic_offsets_data_length( this: &GpuComputePassEncoder, index: u32, @@ -247,7 +247,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`, `GpuComputePassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_bind_group_with_u32_array_and_f64_and_dynamic_offsets_data_length( this: &GpuComputePassEncoder, index: u32, @@ -265,7 +265,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn insert_debug_marker(this: &GpuComputePassEncoder, marker_label: &str); # [wasm_bindgen (method , structural , js_class = "GPUComputePassEncoder" , js_name = popDebugGroup)] @@ -276,7 +276,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn pop_debug_group(this: &GpuComputePassEncoder); # [wasm_bindgen (method , structural , js_class = "GPUComputePassEncoder" , js_name = pushDebugGroup)] @@ -287,6 +287,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn push_debug_group(this: &GpuComputePassEncoder, group_label: &str); } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuComputePassTimestampWrites.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuComputePassTimestampWrites.rs index 8471fcc68..7d91fd2ab 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuComputePassTimestampWrites.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuComputePassTimestampWrites.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassTimestampWrites`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuComputePassTimestampWrites; #[doc = "Get the `beginningOfPassWriteIndex` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassTimestampWrites`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "beginningOfPassWriteIndex")] pub fn get_beginning_of_pass_write_index(this: &GpuComputePassTimestampWrites) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassTimestampWrites`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "beginningOfPassWriteIndex")] pub fn set_beginning_of_pass_write_index(this: &GpuComputePassTimestampWrites, val: u32); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassTimestampWrites`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "endOfPassWriteIndex")] pub fn get_end_of_pass_write_index(this: &GpuComputePassTimestampWrites) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassTimestampWrites`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "endOfPassWriteIndex")] pub fn set_end_of_pass_write_index(this: &GpuComputePassTimestampWrites, val: u32); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassTimestampWrites`, `GpuQuerySet`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "querySet")] pub fn get_query_set(this: &GpuComputePassTimestampWrites) -> GpuQuerySet; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassTimestampWrites`, `GpuQuerySet`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "querySet")] pub fn set_query_set(this: &GpuComputePassTimestampWrites, val: &GpuQuerySet); } @@ -97,7 +97,7 @@ impl GpuComputePassTimestampWrites { #[doc = "*This API requires the following crate features to be activated: `GpuComputePassTimestampWrites`, `GpuQuerySet`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(query_set: &GpuQuerySet) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuComputePipeline.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuComputePipeline.rs index b83697327..c022652a5 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuComputePipeline.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuComputePipeline.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePipeline`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuComputePipeline; # [wasm_bindgen (structural , method , getter , js_class = "GPUComputePipeline" , js_name = label)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePipeline`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn label(this: &GpuComputePipeline) -> ::alloc::string::String; # [wasm_bindgen (structural , method , setter , js_class = "GPUComputePipeline" , js_name = label)] @@ -57,7 +57,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePipeline`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_label(this: &GpuComputePipeline, value: &str); # [wasm_bindgen (method , structural , js_class = "GPUComputePipeline" , js_name = getBindGroupLayout)] @@ -68,6 +68,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayout`, `GpuComputePipeline`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn get_bind_group_layout(this: &GpuComputePipeline, index: u32) -> GpuBindGroupLayout; } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuComputePipelineDescriptor.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuComputePipelineDescriptor.rs index b066e55cc..2ca6458d1 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuComputePipelineDescriptor.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuComputePipelineDescriptor.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePipelineDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuComputePipelineDescriptor; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePipelineDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuComputePipelineDescriptor) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePipelineDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuComputePipelineDescriptor, val: &str); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePipelineDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "layout")] pub fn get_layout(this: &GpuComputePipelineDescriptor) -> ::wasm_bindgen::JsValue; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePipelineDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "layout")] pub fn set_layout(this: &GpuComputePipelineDescriptor, val: &::wasm_bindgen::JsValue); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePipelineDescriptor`, `GpuProgrammableStage`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "compute")] pub fn get_compute(this: &GpuComputePipelineDescriptor) -> GpuProgrammableStage; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePipelineDescriptor`, `GpuProgrammableStage`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "compute")] pub fn set_compute(this: &GpuComputePipelineDescriptor, val: &GpuProgrammableStage); } @@ -97,7 +97,7 @@ impl GpuComputePipelineDescriptor { #[doc = "*This API requires the following crate features to be activated: `GpuComputePipelineDescriptor`, `GpuProgrammableStage`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(layout: &::wasm_bindgen::JsValue, compute: &GpuProgrammableStage) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCopyExternalImageDestInfo.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCopyExternalImageDestInfo.rs index b7eab80a0..4b9eaa3f8 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCopyExternalImageDestInfo.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCopyExternalImageDestInfo.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageDestInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuCopyExternalImageDestInfo; #[doc = "Get the `aspect` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageDestInfo`, `GpuTextureAspect`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "aspect")] pub fn get_aspect(this: &GpuCopyExternalImageDestInfo) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageDestInfo`, `GpuTextureAspect`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "aspect")] pub fn set_aspect(this: &GpuCopyExternalImageDestInfo, val: GpuTextureAspect); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageDestInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "mipLevel")] pub fn get_mip_level(this: &GpuCopyExternalImageDestInfo) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageDestInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "mipLevel")] pub fn set_mip_level(this: &GpuCopyExternalImageDestInfo, val: u32); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageDestInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "origin")] pub fn get_origin(this: &GpuCopyExternalImageDestInfo) -> ::wasm_bindgen::JsValue; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageDestInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "origin")] pub fn set_origin(this: &GpuCopyExternalImageDestInfo, val: &::wasm_bindgen::JsValue); @@ -95,7 +95,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageDestInfo`, `GpuTexture`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "texture")] pub fn get_texture(this: &GpuCopyExternalImageDestInfo) -> GpuTexture; @@ -104,7 +104,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageDestInfo`, `GpuTexture`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "texture")] pub fn set_texture(this: &GpuCopyExternalImageDestInfo, val: &GpuTexture); @@ -113,7 +113,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageDestInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "premultipliedAlpha")] pub fn get_premultiplied_alpha(this: &GpuCopyExternalImageDestInfo) -> Option; @@ -122,7 +122,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageDestInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "premultipliedAlpha")] pub fn set_premultiplied_alpha(this: &GpuCopyExternalImageDestInfo, val: bool); } @@ -133,7 +133,7 @@ impl GpuCopyExternalImageDestInfo { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageDestInfo`, `GpuTexture`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(texture: &GpuTexture) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCopyExternalImageSourceInfo.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCopyExternalImageSourceInfo.rs index 87456d7dc..bd7878990 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCopyExternalImageSourceInfo.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCopyExternalImageSourceInfo.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageSourceInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuCopyExternalImageSourceInfo; #[doc = "Get the `flipY` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageSourceInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "flipY")] pub fn get_flip_y(this: &GpuCopyExternalImageSourceInfo) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageSourceInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "flipY")] pub fn set_flip_y(this: &GpuCopyExternalImageSourceInfo, val: bool); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageSourceInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "origin")] pub fn get_origin(this: &GpuCopyExternalImageSourceInfo) -> ::wasm_bindgen::JsValue; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageSourceInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "origin")] pub fn set_origin(this: &GpuCopyExternalImageSourceInfo, val: &::wasm_bindgen::JsValue); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageSourceInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "source")] pub fn get_source(this: &GpuCopyExternalImageSourceInfo) -> ::js_sys::Object; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageSourceInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "source")] pub fn set_source(this: &GpuCopyExternalImageSourceInfo, val: &::js_sys::Object); } @@ -97,7 +97,7 @@ impl GpuCopyExternalImageSourceInfo { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageSourceInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(source: &::js_sys::Object) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCullMode.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCullMode.rs index 4bb8c48b8..02e0a666a 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCullMode.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuCullMode.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuCullMode`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuCullMode { None = "none", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuDepthStencilState.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuDepthStencilState.rs index 577b39cf7..58de872ff 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuDepthStencilState.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuDepthStencilState.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuDepthStencilState; #[doc = "Get the `depthBias` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "depthBias")] pub fn get_depth_bias(this: &GpuDepthStencilState) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "depthBias")] pub fn set_depth_bias(this: &GpuDepthStencilState, val: i32); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "depthBiasClamp")] pub fn get_depth_bias_clamp(this: &GpuDepthStencilState) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "depthBiasClamp")] pub fn set_depth_bias_clamp(this: &GpuDepthStencilState, val: f32); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "depthBiasSlopeScale")] pub fn get_depth_bias_slope_scale(this: &GpuDepthStencilState) -> Option; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "depthBiasSlopeScale")] pub fn set_depth_bias_slope_scale(this: &GpuDepthStencilState, val: f32); @@ -95,7 +95,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCompareFunction`, `GpuDepthStencilState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "depthCompare")] pub fn get_depth_compare(this: &GpuDepthStencilState) -> Option; @@ -104,7 +104,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCompareFunction`, `GpuDepthStencilState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "depthCompare")] pub fn set_depth_compare(this: &GpuDepthStencilState, val: GpuCompareFunction); @@ -113,7 +113,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "depthWriteEnabled")] pub fn get_depth_write_enabled(this: &GpuDepthStencilState) -> Option; @@ -122,7 +122,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "depthWriteEnabled")] pub fn set_depth_write_enabled(this: &GpuDepthStencilState, val: bool); @@ -131,7 +131,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`, `GpuTextureFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "format")] pub fn get_format(this: &GpuDepthStencilState) -> GpuTextureFormat; @@ -140,7 +140,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`, `GpuTextureFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "format")] pub fn set_format(this: &GpuDepthStencilState, val: GpuTextureFormat); @@ -149,7 +149,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`, `GpuStencilFaceState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "stencilBack")] pub fn get_stencil_back(this: &GpuDepthStencilState) -> Option; @@ -158,7 +158,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`, `GpuStencilFaceState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "stencilBack")] pub fn set_stencil_back(this: &GpuDepthStencilState, val: &GpuStencilFaceState); @@ -167,7 +167,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`, `GpuStencilFaceState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "stencilFront")] pub fn get_stencil_front(this: &GpuDepthStencilState) -> Option; @@ -176,7 +176,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`, `GpuStencilFaceState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "stencilFront")] pub fn set_stencil_front(this: &GpuDepthStencilState, val: &GpuStencilFaceState); @@ -185,7 +185,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "stencilReadMask")] pub fn get_stencil_read_mask(this: &GpuDepthStencilState) -> Option; @@ -194,7 +194,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "stencilReadMask")] pub fn set_stencil_read_mask(this: &GpuDepthStencilState, val: u32); @@ -203,7 +203,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "stencilWriteMask")] pub fn get_stencil_write_mask(this: &GpuDepthStencilState) -> Option; @@ -212,7 +212,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "stencilWriteMask")] pub fn set_stencil_write_mask(this: &GpuDepthStencilState, val: u32); } @@ -223,7 +223,7 @@ impl GpuDepthStencilState { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`, `GpuTextureFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(format: GpuTextureFormat) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuDevice.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuDevice.rs index 9e283c4ab..966c0bd59 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuDevice.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuDevice.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuDevice; # [wasm_bindgen (structural , method , getter , js_class = "GPUDevice" , js_name = features)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`, `GpuSupportedFeatures`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn features(this: &GpuDevice) -> GpuSupportedFeatures; # [wasm_bindgen (structural , method , getter , js_class = "GPUDevice" , js_name = limits)] @@ -57,7 +57,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`, `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn limits(this: &GpuDevice) -> GpuSupportedLimits; # [wasm_bindgen (structural , method , getter , js_class = "GPUDevice" , js_name = adapterInfo)] @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuAdapterInfo`, `GpuDevice`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn adapter_info(this: &GpuDevice) -> GpuAdapterInfo; # [wasm_bindgen (structural , method , getter , js_class = "GPUDevice" , js_name = queue)] @@ -79,7 +79,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn queue(this: &GpuDevice) -> GpuQueue; # [wasm_bindgen (structural , method , getter , js_class = "GPUDevice" , js_name = lost)] @@ -90,7 +90,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn lost(this: &GpuDevice) -> ::js_sys::Promise; # [wasm_bindgen (structural , method , getter , js_class = "GPUDevice" , js_name = onuncapturederror)] @@ -101,7 +101,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn onuncapturederror(this: &GpuDevice) -> Option<::js_sys::Function>; # [wasm_bindgen (structural , method , setter , js_class = "GPUDevice" , js_name = onuncapturederror)] @@ -112,7 +112,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_onuncapturederror(this: &GpuDevice, value: Option<&::js_sys::Function>); # [wasm_bindgen (structural , method , getter , js_class = "GPUDevice" , js_name = label)] @@ -123,7 +123,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn label(this: &GpuDevice) -> ::alloc::string::String; # [wasm_bindgen (structural , method , setter , js_class = "GPUDevice" , js_name = label)] @@ -134,7 +134,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_label(this: &GpuDevice, value: &str); # [wasm_bindgen (method , structural , js_class = "GPUDevice" , js_name = createBindGroup)] @@ -145,7 +145,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`, `GpuBindGroupDescriptor`, `GpuDevice`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn create_bind_group(this: &GpuDevice, descriptor: &GpuBindGroupDescriptor) -> GpuBindGroup; @@ -157,7 +157,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayout`, `GpuBindGroupLayoutDescriptor`, `GpuDevice`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn create_bind_group_layout( this: &GpuDevice, descriptor: &GpuBindGroupLayoutDescriptor, @@ -171,7 +171,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuBufferDescriptor`, `GpuDevice`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn create_buffer( this: &GpuDevice, descriptor: &GpuBufferDescriptor, @@ -185,7 +185,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandEncoder`, `GpuDevice`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn create_command_encoder(this: &GpuDevice) -> GpuCommandEncoder; # [wasm_bindgen (method , structural , js_class = "GPUDevice" , js_name = createCommandEncoder)] @@ -196,7 +196,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCommandEncoder`, `GpuCommandEncoderDescriptor`, `GpuDevice`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn create_command_encoder_with_descriptor( this: &GpuDevice, descriptor: &GpuCommandEncoderDescriptor, @@ -210,7 +210,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePipeline`, `GpuComputePipelineDescriptor`, `GpuDevice`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn create_compute_pipeline( this: &GpuDevice, descriptor: &GpuComputePipelineDescriptor, @@ -224,7 +224,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuComputePipelineDescriptor`, `GpuDevice`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn create_compute_pipeline_async( this: &GpuDevice, descriptor: &GpuComputePipelineDescriptor, @@ -238,7 +238,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`, `GpuPipelineLayout`, `GpuPipelineLayoutDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn create_pipeline_layout( this: &GpuDevice, descriptor: &GpuPipelineLayoutDescriptor, @@ -252,7 +252,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`, `GpuQuerySet`, `GpuQuerySetDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn create_query_set( this: &GpuDevice, descriptor: &GpuQuerySetDescriptor, @@ -266,7 +266,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`, `GpuRenderBundleEncoder`, `GpuRenderBundleEncoderDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn create_render_bundle_encoder( this: &GpuDevice, descriptor: &GpuRenderBundleEncoderDescriptor, @@ -280,7 +280,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`, `GpuRenderPipeline`, `GpuRenderPipelineDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn create_render_pipeline( this: &GpuDevice, descriptor: &GpuRenderPipelineDescriptor, @@ -294,7 +294,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`, `GpuRenderPipelineDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn create_render_pipeline_async( this: &GpuDevice, descriptor: &GpuRenderPipelineDescriptor, @@ -308,7 +308,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`, `GpuSampler`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn create_sampler(this: &GpuDevice) -> GpuSampler; # [wasm_bindgen (method , structural , js_class = "GPUDevice" , js_name = createSampler)] @@ -319,7 +319,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`, `GpuSampler`, `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn create_sampler_with_descriptor( this: &GpuDevice, descriptor: &GpuSamplerDescriptor, @@ -333,7 +333,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`, `GpuShaderModule`, `GpuShaderModuleDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn create_shader_module( this: &GpuDevice, descriptor: &GpuShaderModuleDescriptor, @@ -347,7 +347,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`, `GpuTexture`, `GpuTextureDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn create_texture( this: &GpuDevice, descriptor: &GpuTextureDescriptor, @@ -361,7 +361,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn destroy(this: &GpuDevice); # [wasm_bindgen (catch , method , structural , js_class = "GPUDevice" , js_name = importExternalTexture)] @@ -372,7 +372,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`, `GpuExternalTexture`, `GpuExternalTextureDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn import_external_texture( this: &GpuDevice, descriptor: &GpuExternalTextureDescriptor, @@ -386,7 +386,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn pop_error_scope(this: &GpuDevice) -> ::js_sys::Promise; # [wasm_bindgen (method , structural , js_class = "GPUDevice" , js_name = pushErrorScope)] @@ -397,6 +397,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDevice`, `GpuErrorFilter`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn push_error_scope(this: &GpuDevice, filter: GpuErrorFilter); } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuDeviceDescriptor.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuDeviceDescriptor.rs index 6c4641ffc..9a1bb4f20 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuDeviceDescriptor.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuDeviceDescriptor.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDeviceDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuDeviceDescriptor; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDeviceDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuDeviceDescriptor) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDeviceDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuDeviceDescriptor, val: &str); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDeviceDescriptor`, `GpuQueueDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "defaultQueue")] pub fn get_default_queue(this: &GpuDeviceDescriptor) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDeviceDescriptor`, `GpuQueueDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "defaultQueue")] pub fn set_default_queue(this: &GpuDeviceDescriptor, val: &GpuQueueDescriptor); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDeviceDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "requiredFeatures")] pub fn get_required_features(this: &GpuDeviceDescriptor) -> Option<::js_sys::Array>; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDeviceDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "requiredFeatures")] pub fn set_required_features(this: &GpuDeviceDescriptor, val: &::wasm_bindgen::JsValue); @@ -95,7 +95,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDeviceDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "requiredLimits")] pub fn get_required_limits(this: &GpuDeviceDescriptor) -> Option<::js_sys::Object>; @@ -104,7 +104,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDeviceDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "requiredLimits")] pub fn set_required_limits(this: &GpuDeviceDescriptor, val: &::js_sys::Object); } @@ -115,7 +115,7 @@ impl GpuDeviceDescriptor { #[doc = "*This API requires the following crate features to be activated: `GpuDeviceDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuDeviceLostInfo.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuDeviceLostInfo.rs index b85fd45b0..898c45c62 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuDeviceLostInfo.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuDeviceLostInfo.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDeviceLostInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuDeviceLostInfo; # [wasm_bindgen (structural , method , getter , js_class = "GPUDeviceLostInfo" , js_name = reason)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDeviceLostInfo`, `GpuDeviceLostReason`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn reason(this: &GpuDeviceLostInfo) -> GpuDeviceLostReason; # [wasm_bindgen (structural , method , getter , js_class = "GPUDeviceLostInfo" , js_name = message)] @@ -57,6 +57,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDeviceLostInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn message(this: &GpuDeviceLostInfo) -> ::alloc::string::String; } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuDeviceLostReason.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuDeviceLostReason.rs index 748016e29..31ed7b13e 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuDeviceLostReason.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuDeviceLostReason.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuDeviceLostReason`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuDeviceLostReason { Unknown = "unknown", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuError.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuError.rs index 3517ece14..6ce5b5fe9 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuError.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuError.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuError`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuError; # [wasm_bindgen (structural , method , getter , js_class = "GPUError" , js_name = message)] @@ -46,6 +46,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuError`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn message(this: &GpuError) -> ::alloc::string::String; } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuErrorFilter.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuErrorFilter.rs index 15b38a413..26a63aef1 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuErrorFilter.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuErrorFilter.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuErrorFilter`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuErrorFilter { Validation = "validation", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuExtent3dDict.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuExtent3dDict.rs index e06b12f5b..0f81c3835 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuExtent3dDict.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuExtent3dDict.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuExtent3dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuExtent3dDict; #[doc = "Get the `depthOrArrayLayers` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuExtent3dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "depthOrArrayLayers")] pub fn get_depth_or_array_layers(this: &GpuExtent3dDict) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuExtent3dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "depthOrArrayLayers")] pub fn set_depth_or_array_layers(this: &GpuExtent3dDict, val: u32); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuExtent3dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "height")] pub fn get_height(this: &GpuExtent3dDict) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuExtent3dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "height")] pub fn set_height(this: &GpuExtent3dDict, val: u32); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuExtent3dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "width")] pub fn get_width(this: &GpuExtent3dDict) -> u32; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuExtent3dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "width")] pub fn set_width(this: &GpuExtent3dDict, val: u32); } @@ -97,7 +97,7 @@ impl GpuExtent3dDict { #[doc = "*This API requires the following crate features to be activated: `GpuExtent3dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(width: u32) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuExternalTexture.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuExternalTexture.rs index e4effa78c..ea9a557b9 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuExternalTexture.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuExternalTexture.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuExternalTexture`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuExternalTexture; # [wasm_bindgen (structural , method , getter , js_class = "GPUExternalTexture" , js_name = label)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuExternalTexture`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn label(this: &GpuExternalTexture) -> ::alloc::string::String; # [wasm_bindgen (structural , method , setter , js_class = "GPUExternalTexture" , js_name = label)] @@ -57,6 +57,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuExternalTexture`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_label(this: &GpuExternalTexture, value: &str); } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuExternalTextureBindingLayout.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuExternalTextureBindingLayout.rs index 4597f2786..c773de83d 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuExternalTextureBindingLayout.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuExternalTextureBindingLayout.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuExternalTextureBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuExternalTextureBindingLayout; } @@ -43,7 +43,7 @@ impl GpuExternalTextureBindingLayout { #[doc = "*This API requires the following crate features to be activated: `GpuExternalTextureBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuExternalTextureDescriptor.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuExternalTextureDescriptor.rs index 2c950be65..b1c6cdc86 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuExternalTextureDescriptor.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuExternalTextureDescriptor.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuExternalTextureDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuExternalTextureDescriptor; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuExternalTextureDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuExternalTextureDescriptor) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuExternalTextureDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuExternalTextureDescriptor, val: &str); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuExternalTextureDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "source")] pub fn get_source(this: &GpuExternalTextureDescriptor) -> ::js_sys::Object; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuExternalTextureDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "source")] pub fn set_source(this: &GpuExternalTextureDescriptor, val: &::js_sys::Object); } @@ -79,7 +79,7 @@ impl GpuExternalTextureDescriptor { #[doc = "*This API requires the following crate features to be activated: `GpuExternalTextureDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(source: &::js_sys::Object) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuFeatureName.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuFeatureName.rs index 7fa2799d4..cf3a5e853 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuFeatureName.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuFeatureName.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuFeatureName`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuFeatureName { DepthClipControl = "depth-clip-control", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuFilterMode.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuFilterMode.rs index b7cb82cd4..46fb0b642 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuFilterMode.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuFilterMode.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuFilterMode`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuFilterMode { Nearest = "nearest", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuFragmentState.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuFragmentState.rs index 9490fc3dc..ba16aca0c 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuFragmentState.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuFragmentState.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuFragmentState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuFragmentState; #[doc = "Get the `constants` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuFragmentState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "constants")] pub fn get_constants(this: &GpuFragmentState) -> Option<::js_sys::Object>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuFragmentState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "constants")] pub fn set_constants(this: &GpuFragmentState, val: &::js_sys::Object); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuFragmentState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "entryPoint")] pub fn get_entry_point(this: &GpuFragmentState) -> Option<::alloc::string::String>; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuFragmentState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "entryPoint")] pub fn set_entry_point(this: &GpuFragmentState, val: &str); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuFragmentState`, `GpuShaderModule`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "module")] pub fn get_module(this: &GpuFragmentState) -> GpuShaderModule; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuFragmentState`, `GpuShaderModule`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "module")] pub fn set_module(this: &GpuFragmentState, val: &GpuShaderModule); @@ -95,7 +95,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuFragmentState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "targets")] pub fn get_targets(this: &GpuFragmentState) -> ::js_sys::Array; @@ -104,7 +104,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuFragmentState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "targets")] pub fn set_targets(this: &GpuFragmentState, val: &::wasm_bindgen::JsValue); } @@ -115,7 +115,7 @@ impl GpuFragmentState { #[doc = "*This API requires the following crate features to be activated: `GpuFragmentState`, `GpuShaderModule`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(module: &GpuShaderModule, targets: &::wasm_bindgen::JsValue) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuFrontFace.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuFrontFace.rs index 07a487224..eb9eda7b5 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuFrontFace.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuFrontFace.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuFrontFace`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuFrontFace { Ccw = "ccw", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuIndexFormat.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuIndexFormat.rs index c70d34a37..7931e961c 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuIndexFormat.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuIndexFormat.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuIndexFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuIndexFormat { Uint16 = "uint16", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuLoadOp.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuLoadOp.rs index 7963f5aff..6717dc764 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuLoadOp.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuLoadOp.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuLoadOp`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuLoadOp { Load = "load", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuMipmapFilterMode.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuMipmapFilterMode.rs index 531607e88..9d962297d 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuMipmapFilterMode.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuMipmapFilterMode.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuMipmapFilterMode`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuMipmapFilterMode { Nearest = "nearest", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuMultisampleState.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuMultisampleState.rs index f517ae3a6..28cd36d2f 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuMultisampleState.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuMultisampleState.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuMultisampleState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuMultisampleState; #[doc = "Get the `alphaToCoverageEnabled` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuMultisampleState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "alphaToCoverageEnabled")] pub fn get_alpha_to_coverage_enabled(this: &GpuMultisampleState) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuMultisampleState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "alphaToCoverageEnabled")] pub fn set_alpha_to_coverage_enabled(this: &GpuMultisampleState, val: bool); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuMultisampleState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "count")] pub fn get_count(this: &GpuMultisampleState) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuMultisampleState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "count")] pub fn set_count(this: &GpuMultisampleState, val: u32); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuMultisampleState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "mask")] pub fn get_mask(this: &GpuMultisampleState) -> Option; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuMultisampleState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "mask")] pub fn set_mask(this: &GpuMultisampleState, val: u32); } @@ -97,7 +97,7 @@ impl GpuMultisampleState { #[doc = "*This API requires the following crate features to be activated: `GpuMultisampleState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuObjectDescriptorBase.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuObjectDescriptorBase.rs index 7666dc76b..f46278f77 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuObjectDescriptorBase.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuObjectDescriptorBase.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuObjectDescriptorBase`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuObjectDescriptorBase; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuObjectDescriptorBase`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuObjectDescriptorBase) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuObjectDescriptorBase`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuObjectDescriptorBase, val: &str); } @@ -61,7 +61,7 @@ impl GpuObjectDescriptorBase { #[doc = "*This API requires the following crate features to be activated: `GpuObjectDescriptorBase`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuOrigin2dDict.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuOrigin2dDict.rs index a055e9719..c8b521005 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuOrigin2dDict.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuOrigin2dDict.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuOrigin2dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuOrigin2dDict; #[doc = "Get the `x` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuOrigin2dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "x")] pub fn get_x(this: &GpuOrigin2dDict) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuOrigin2dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "x")] pub fn set_x(this: &GpuOrigin2dDict, val: u32); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuOrigin2dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "y")] pub fn get_y(this: &GpuOrigin2dDict) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuOrigin2dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "y")] pub fn set_y(this: &GpuOrigin2dDict, val: u32); } @@ -79,7 +79,7 @@ impl GpuOrigin2dDict { #[doc = "*This API requires the following crate features to be activated: `GpuOrigin2dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuOrigin3dDict.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuOrigin3dDict.rs index a3356ed2f..a6c77558c 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuOrigin3dDict.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuOrigin3dDict.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuOrigin3dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuOrigin3dDict; #[doc = "Get the `x` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuOrigin3dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "x")] pub fn get_x(this: &GpuOrigin3dDict) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuOrigin3dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "x")] pub fn set_x(this: &GpuOrigin3dDict, val: u32); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuOrigin3dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "y")] pub fn get_y(this: &GpuOrigin3dDict) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuOrigin3dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "y")] pub fn set_y(this: &GpuOrigin3dDict, val: u32); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuOrigin3dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "z")] pub fn get_z(this: &GpuOrigin3dDict) -> Option; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuOrigin3dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "z")] pub fn set_z(this: &GpuOrigin3dDict, val: u32); } @@ -97,7 +97,7 @@ impl GpuOrigin3dDict { #[doc = "*This API requires the following crate features to be activated: `GpuOrigin3dDict`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuOutOfMemoryError.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuOutOfMemoryError.rs index 6affb6550..21f527dea 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuOutOfMemoryError.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuOutOfMemoryError.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuOutOfMemoryError`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuOutOfMemoryError; #[wasm_bindgen(catch, constructor, js_class = "GPUOutOfMemoryError")] @@ -46,6 +46,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuOutOfMemoryError`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(message: &str) -> Result; } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPipelineDescriptorBase.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPipelineDescriptorBase.rs index 17b670864..e0067ddcd 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPipelineDescriptorBase.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPipelineDescriptorBase.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPipelineDescriptorBase`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuPipelineDescriptorBase; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPipelineDescriptorBase`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuPipelineDescriptorBase) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPipelineDescriptorBase`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuPipelineDescriptorBase, val: &str); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPipelineDescriptorBase`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "layout")] pub fn get_layout(this: &GpuPipelineDescriptorBase) -> ::wasm_bindgen::JsValue; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPipelineDescriptorBase`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "layout")] pub fn set_layout(this: &GpuPipelineDescriptorBase, val: &::wasm_bindgen::JsValue); } @@ -79,7 +79,7 @@ impl GpuPipelineDescriptorBase { #[doc = "*This API requires the following crate features to be activated: `GpuPipelineDescriptorBase`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(layout: &::wasm_bindgen::JsValue) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPipelineLayout.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPipelineLayout.rs index 659e4d576..da21f62ef 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPipelineLayout.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPipelineLayout.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPipelineLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuPipelineLayout; # [wasm_bindgen (structural , method , getter , js_class = "GPUPipelineLayout" , js_name = label)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPipelineLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn label(this: &GpuPipelineLayout) -> ::alloc::string::String; # [wasm_bindgen (structural , method , setter , js_class = "GPUPipelineLayout" , js_name = label)] @@ -57,6 +57,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPipelineLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_label(this: &GpuPipelineLayout, value: &str); } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPipelineLayoutDescriptor.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPipelineLayoutDescriptor.rs index 8d63b6e59..7fc190563 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPipelineLayoutDescriptor.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPipelineLayoutDescriptor.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPipelineLayoutDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuPipelineLayoutDescriptor; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPipelineLayoutDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuPipelineLayoutDescriptor) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPipelineLayoutDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuPipelineLayoutDescriptor, val: &str); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPipelineLayoutDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "bindGroupLayouts")] pub fn get_bind_group_layouts(this: &GpuPipelineLayoutDescriptor) -> ::js_sys::Array; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPipelineLayoutDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "bindGroupLayouts")] pub fn set_bind_group_layouts( this: &GpuPipelineLayoutDescriptor, @@ -82,7 +82,7 @@ impl GpuPipelineLayoutDescriptor { #[doc = "*This API requires the following crate features to be activated: `GpuPipelineLayoutDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(bind_group_layouts: &::wasm_bindgen::JsValue) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPowerPreference.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPowerPreference.rs index 5b0209b06..d674f0efc 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPowerPreference.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPowerPreference.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuPowerPreference`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuPowerPreference { LowPower = "low-power", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPrimitiveState.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPrimitiveState.rs index 8ac4acecc..cf9cdb3e5 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPrimitiveState.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPrimitiveState.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPrimitiveState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuPrimitiveState; #[doc = "Get the `cullMode` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCullMode`, `GpuPrimitiveState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "cullMode")] pub fn get_cull_mode(this: &GpuPrimitiveState) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCullMode`, `GpuPrimitiveState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "cullMode")] pub fn set_cull_mode(this: &GpuPrimitiveState, val: GpuCullMode); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuFrontFace`, `GpuPrimitiveState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "frontFace")] pub fn get_front_face(this: &GpuPrimitiveState) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuFrontFace`, `GpuPrimitiveState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "frontFace")] pub fn set_front_face(this: &GpuPrimitiveState, val: GpuFrontFace); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuIndexFormat`, `GpuPrimitiveState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "stripIndexFormat")] pub fn get_strip_index_format(this: &GpuPrimitiveState) -> Option; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuIndexFormat`, `GpuPrimitiveState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "stripIndexFormat")] pub fn set_strip_index_format(this: &GpuPrimitiveState, val: GpuIndexFormat); @@ -95,7 +95,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPrimitiveState`, `GpuPrimitiveTopology`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "topology")] pub fn get_topology(this: &GpuPrimitiveState) -> Option; @@ -104,7 +104,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPrimitiveState`, `GpuPrimitiveTopology`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "topology")] pub fn set_topology(this: &GpuPrimitiveState, val: GpuPrimitiveTopology); @@ -113,7 +113,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPrimitiveState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "unclippedDepth")] pub fn get_unclipped_depth(this: &GpuPrimitiveState) -> Option; @@ -122,7 +122,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPrimitiveState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "unclippedDepth")] pub fn set_unclipped_depth(this: &GpuPrimitiveState, val: bool); } @@ -133,7 +133,7 @@ impl GpuPrimitiveState { #[doc = "*This API requires the following crate features to be activated: `GpuPrimitiveState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPrimitiveTopology.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPrimitiveTopology.rs index 157a37fed..6ec5b2817 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPrimitiveTopology.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuPrimitiveTopology.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuPrimitiveTopology`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuPrimitiveTopology { PointList = "point-list", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuProgrammableStage.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuProgrammableStage.rs index b1c526cd0..03110080d 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuProgrammableStage.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuProgrammableStage.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuProgrammableStage`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuProgrammableStage; #[doc = "Get the `constants` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuProgrammableStage`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "constants")] pub fn get_constants(this: &GpuProgrammableStage) -> Option<::js_sys::Object>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuProgrammableStage`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "constants")] pub fn set_constants(this: &GpuProgrammableStage, val: &::js_sys::Object); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuProgrammableStage`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "entryPoint")] pub fn get_entry_point(this: &GpuProgrammableStage) -> Option<::alloc::string::String>; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuProgrammableStage`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "entryPoint")] pub fn set_entry_point(this: &GpuProgrammableStage, val: &str); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuProgrammableStage`, `GpuShaderModule`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "module")] pub fn get_module(this: &GpuProgrammableStage) -> GpuShaderModule; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuProgrammableStage`, `GpuShaderModule`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "module")] pub fn set_module(this: &GpuProgrammableStage, val: &GpuShaderModule); } @@ -97,7 +97,7 @@ impl GpuProgrammableStage { #[doc = "*This API requires the following crate features to be activated: `GpuProgrammableStage`, `GpuShaderModule`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(module: &GpuShaderModule) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuQuerySet.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuQuerySet.rs index 5d103a487..ddaf35ac7 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuQuerySet.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuQuerySet.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQuerySet`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuQuerySet; # [wasm_bindgen (structural , method , getter , js_class = "GPUQuerySet" , js_name = type)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQuerySet`, `GpuQueryType`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn type_(this: &GpuQuerySet) -> GpuQueryType; # [wasm_bindgen (structural , method , getter , js_class = "GPUQuerySet" , js_name = count)] @@ -57,7 +57,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQuerySet`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn count(this: &GpuQuerySet) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUQuerySet" , js_name = label)] @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQuerySet`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn label(this: &GpuQuerySet) -> ::alloc::string::String; # [wasm_bindgen (structural , method , setter , js_class = "GPUQuerySet" , js_name = label)] @@ -79,7 +79,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQuerySet`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_label(this: &GpuQuerySet, value: &str); # [wasm_bindgen (method , structural , js_class = "GPUQuerySet" , js_name = destroy)] @@ -90,6 +90,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQuerySet`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn destroy(this: &GpuQuerySet); } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuQuerySetDescriptor.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuQuerySetDescriptor.rs index 6c3716e5d..def89e147 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuQuerySetDescriptor.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuQuerySetDescriptor.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQuerySetDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuQuerySetDescriptor; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQuerySetDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuQuerySetDescriptor) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQuerySetDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuQuerySetDescriptor, val: &str); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQuerySetDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "count")] pub fn get_count(this: &GpuQuerySetDescriptor) -> u32; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQuerySetDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "count")] pub fn set_count(this: &GpuQuerySetDescriptor, val: u32); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQuerySetDescriptor`, `GpuQueryType`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "type")] pub fn get_type(this: &GpuQuerySetDescriptor) -> GpuQueryType; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQuerySetDescriptor`, `GpuQueryType`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "type")] pub fn set_type(this: &GpuQuerySetDescriptor, val: GpuQueryType); } @@ -97,7 +97,7 @@ impl GpuQuerySetDescriptor { #[doc = "*This API requires the following crate features to be activated: `GpuQuerySetDescriptor`, `GpuQueryType`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(count: u32, type_: GpuQueryType) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuQueryType.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuQueryType.rs index eb845fefa..58d693abe 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuQueryType.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuQueryType.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuQueryType`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuQueryType { Occlusion = "occlusion", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuQueue.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuQueue.rs index b69151efe..4b65d7ad7 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuQueue.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuQueue.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuQueue; # [wasm_bindgen (structural , method , getter , js_class = "GPUQueue" , js_name = label)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn label(this: &GpuQueue) -> ::alloc::string::String; # [wasm_bindgen (structural , method , setter , js_class = "GPUQueue" , js_name = label)] @@ -57,7 +57,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_label(this: &GpuQueue, value: &str); # [wasm_bindgen (catch , method , structural , js_class = "GPUQueue" , js_name = copyExternalImageToTexture)] @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageDestInfo`, `GpuCopyExternalImageSourceInfo`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn copy_external_image_to_texture_with_u32_sequence( this: &GpuQueue, source: &GpuCopyExternalImageSourceInfo, @@ -84,7 +84,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCopyExternalImageDestInfo`, `GpuCopyExternalImageSourceInfo`, `GpuExtent3dDict`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn copy_external_image_to_texture_with_gpu_extent_3d_dict( this: &GpuQueue, source: &GpuCopyExternalImageSourceInfo, @@ -100,7 +100,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn on_submitted_work_done(this: &GpuQueue) -> ::js_sys::Promise; # [wasm_bindgen (method , structural , js_class = "GPUQueue" , js_name = submit)] @@ -111,7 +111,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn submit(this: &GpuQueue, command_buffers: &::wasm_bindgen::JsValue); # [wasm_bindgen (catch , method , structural , js_class = "GPUQueue" , js_name = writeBuffer)] @@ -122,7 +122,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_u32_and_buffer_source( this: &GpuQueue, buffer: &GpuBuffer, @@ -138,7 +138,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_f64_and_buffer_source( this: &GpuQueue, buffer: &GpuBuffer, @@ -154,7 +154,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_u32_and_u8_slice( this: &GpuQueue, buffer: &GpuBuffer, @@ -170,7 +170,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_f64_and_u8_slice( this: &GpuQueue, buffer: &GpuBuffer, @@ -186,7 +186,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_u32_and_u8_array( this: &GpuQueue, buffer: &GpuBuffer, @@ -202,7 +202,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_f64_and_u8_array( this: &GpuQueue, buffer: &GpuBuffer, @@ -218,7 +218,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_u32_and_buffer_source_and_u32( this: &GpuQueue, buffer: &GpuBuffer, @@ -235,7 +235,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_f64_and_buffer_source_and_u32( this: &GpuQueue, buffer: &GpuBuffer, @@ -252,7 +252,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_u32_and_u8_slice_and_u32( this: &GpuQueue, buffer: &GpuBuffer, @@ -269,7 +269,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_f64_and_u8_slice_and_u32( this: &GpuQueue, buffer: &GpuBuffer, @@ -286,7 +286,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_u32_and_u8_array_and_u32( this: &GpuQueue, buffer: &GpuBuffer, @@ -303,7 +303,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_f64_and_u8_array_and_u32( this: &GpuQueue, buffer: &GpuBuffer, @@ -320,7 +320,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_u32_and_buffer_source_and_f64( this: &GpuQueue, buffer: &GpuBuffer, @@ -337,7 +337,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_f64_and_buffer_source_and_f64( this: &GpuQueue, buffer: &GpuBuffer, @@ -354,7 +354,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_u32_and_u8_slice_and_f64( this: &GpuQueue, buffer: &GpuBuffer, @@ -371,7 +371,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_f64_and_u8_slice_and_f64( this: &GpuQueue, buffer: &GpuBuffer, @@ -388,7 +388,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_u32_and_u8_array_and_f64( this: &GpuQueue, buffer: &GpuBuffer, @@ -405,7 +405,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_f64_and_u8_array_and_f64( this: &GpuQueue, buffer: &GpuBuffer, @@ -422,7 +422,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_u32_and_buffer_source_and_u32_and_u32( this: &GpuQueue, buffer: &GpuBuffer, @@ -440,7 +440,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_f64_and_buffer_source_and_u32_and_u32( this: &GpuQueue, buffer: &GpuBuffer, @@ -458,7 +458,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_u32_and_u8_slice_and_u32_and_u32( this: &GpuQueue, buffer: &GpuBuffer, @@ -476,7 +476,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_f64_and_u8_slice_and_u32_and_u32( this: &GpuQueue, buffer: &GpuBuffer, @@ -494,7 +494,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_u32_and_u8_array_and_u32_and_u32( this: &GpuQueue, buffer: &GpuBuffer, @@ -512,7 +512,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_f64_and_u8_array_and_u32_and_u32( this: &GpuQueue, buffer: &GpuBuffer, @@ -530,7 +530,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_u32_and_buffer_source_and_f64_and_u32( this: &GpuQueue, buffer: &GpuBuffer, @@ -548,7 +548,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_f64_and_buffer_source_and_f64_and_u32( this: &GpuQueue, buffer: &GpuBuffer, @@ -566,7 +566,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_u32_and_u8_slice_and_f64_and_u32( this: &GpuQueue, buffer: &GpuBuffer, @@ -584,7 +584,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_f64_and_u8_slice_and_f64_and_u32( this: &GpuQueue, buffer: &GpuBuffer, @@ -602,7 +602,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_u32_and_u8_array_and_f64_and_u32( this: &GpuQueue, buffer: &GpuBuffer, @@ -620,7 +620,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_f64_and_u8_array_and_f64_and_u32( this: &GpuQueue, buffer: &GpuBuffer, @@ -638,7 +638,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_u32_and_buffer_source_and_u32_and_f64( this: &GpuQueue, buffer: &GpuBuffer, @@ -656,7 +656,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_f64_and_buffer_source_and_u32_and_f64( this: &GpuQueue, buffer: &GpuBuffer, @@ -674,7 +674,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_u32_and_u8_slice_and_u32_and_f64( this: &GpuQueue, buffer: &GpuBuffer, @@ -692,7 +692,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_f64_and_u8_slice_and_u32_and_f64( this: &GpuQueue, buffer: &GpuBuffer, @@ -710,7 +710,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_u32_and_u8_array_and_u32_and_f64( this: &GpuQueue, buffer: &GpuBuffer, @@ -728,7 +728,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_f64_and_u8_array_and_u32_and_f64( this: &GpuQueue, buffer: &GpuBuffer, @@ -746,7 +746,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_u32_and_buffer_source_and_f64_and_f64( this: &GpuQueue, buffer: &GpuBuffer, @@ -764,7 +764,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_f64_and_buffer_source_and_f64_and_f64( this: &GpuQueue, buffer: &GpuBuffer, @@ -782,7 +782,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_u32_and_u8_slice_and_f64_and_f64( this: &GpuQueue, buffer: &GpuBuffer, @@ -800,7 +800,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_f64_and_u8_slice_and_f64_and_f64( this: &GpuQueue, buffer: &GpuBuffer, @@ -818,7 +818,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_u32_and_u8_array_and_f64_and_f64( this: &GpuQueue, buffer: &GpuBuffer, @@ -836,7 +836,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuQueue`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_buffer_with_f64_and_u8_array_and_f64_and_f64( this: &GpuQueue, buffer: &GpuBuffer, @@ -854,7 +854,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQueue`, `GpuTexelCopyBufferLayout`, `GpuTexelCopyTextureInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_texture_with_buffer_source_and_u32_sequence( this: &GpuQueue, destination: &GpuTexelCopyTextureInfo, @@ -871,7 +871,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQueue`, `GpuTexelCopyBufferLayout`, `GpuTexelCopyTextureInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_texture_with_u8_slice_and_u32_sequence( this: &GpuQueue, destination: &GpuTexelCopyTextureInfo, @@ -888,7 +888,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQueue`, `GpuTexelCopyBufferLayout`, `GpuTexelCopyTextureInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_texture_with_u8_array_and_u32_sequence( this: &GpuQueue, destination: &GpuTexelCopyTextureInfo, @@ -905,7 +905,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuExtent3dDict`, `GpuQueue`, `GpuTexelCopyBufferLayout`, `GpuTexelCopyTextureInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_texture_with_buffer_source_and_gpu_extent_3d_dict( this: &GpuQueue, destination: &GpuTexelCopyTextureInfo, @@ -922,7 +922,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuExtent3dDict`, `GpuQueue`, `GpuTexelCopyBufferLayout`, `GpuTexelCopyTextureInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_texture_with_u8_slice_and_gpu_extent_3d_dict( this: &GpuQueue, destination: &GpuTexelCopyTextureInfo, @@ -939,7 +939,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuExtent3dDict`, `GpuQueue`, `GpuTexelCopyBufferLayout`, `GpuTexelCopyTextureInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn write_texture_with_u8_array_and_gpu_extent_3d_dict( this: &GpuQueue, destination: &GpuTexelCopyTextureInfo, diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuQueueDescriptor.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuQueueDescriptor.rs index e035547b4..822a6f069 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuQueueDescriptor.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuQueueDescriptor.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQueueDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuQueueDescriptor; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQueueDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuQueueDescriptor) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQueueDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuQueueDescriptor, val: &str); } @@ -61,7 +61,7 @@ impl GpuQueueDescriptor { #[doc = "*This API requires the following crate features to be activated: `GpuQueueDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderBundle.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderBundle.rs index 704cc6e72..36f85f3b2 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderBundle.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderBundle.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundle`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuRenderBundle; # [wasm_bindgen (structural , method , getter , js_class = "GPURenderBundle" , js_name = label)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundle`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn label(this: &GpuRenderBundle) -> ::alloc::string::String; # [wasm_bindgen (structural , method , setter , js_class = "GPURenderBundle" , js_name = label)] @@ -57,6 +57,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundle`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_label(this: &GpuRenderBundle, value: &str); } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderBundleDescriptor.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderBundleDescriptor.rs index 2d471d255..4f2c6c286 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderBundleDescriptor.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderBundleDescriptor.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuRenderBundleDescriptor; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuRenderBundleDescriptor) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuRenderBundleDescriptor, val: &str); } @@ -61,7 +61,7 @@ impl GpuRenderBundleDescriptor { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderBundleEncoder.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderBundleEncoder.rs index 57ed468c7..36519cd32 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderBundleEncoder.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderBundleEncoder.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuRenderBundleEncoder; # [wasm_bindgen (structural , method , getter , js_class = "GPURenderBundleEncoder" , js_name = label)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn label(this: &GpuRenderBundleEncoder) -> ::alloc::string::String; # [wasm_bindgen (structural , method , setter , js_class = "GPURenderBundleEncoder" , js_name = label)] @@ -57,7 +57,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_label(this: &GpuRenderBundleEncoder, value: &str); # [wasm_bindgen (method , structural , js_class = "GPURenderBundleEncoder" , js_name = finish)] @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundle`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn finish(this: &GpuRenderBundleEncoder) -> GpuRenderBundle; # [wasm_bindgen (method , structural , js_class = "GPURenderBundleEncoder" , js_name = finish)] @@ -79,7 +79,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundle`, `GpuRenderBundleDescriptor`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn finish_with_descriptor( this: &GpuRenderBundleEncoder, descriptor: &GpuRenderBundleDescriptor, @@ -93,7 +93,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_bind_group( this: &GpuRenderBundleEncoder, index: u32, @@ -108,7 +108,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_bind_group_with_u32_sequence( this: &GpuRenderBundleEncoder, index: u32, @@ -124,7 +124,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_bind_group_with_u32_slice_and_u32_and_dynamic_offsets_data_length( this: &GpuRenderBundleEncoder, index: u32, @@ -142,7 +142,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_bind_group_with_u32_array_and_u32_and_dynamic_offsets_data_length( this: &GpuRenderBundleEncoder, index: u32, @@ -160,7 +160,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_bind_group_with_u32_slice_and_f64_and_dynamic_offsets_data_length( this: &GpuRenderBundleEncoder, index: u32, @@ -178,7 +178,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_bind_group_with_u32_array_and_f64_and_dynamic_offsets_data_length( this: &GpuRenderBundleEncoder, index: u32, @@ -196,7 +196,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn insert_debug_marker(this: &GpuRenderBundleEncoder, marker_label: &str); # [wasm_bindgen (method , structural , js_class = "GPURenderBundleEncoder" , js_name = popDebugGroup)] @@ -207,7 +207,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn pop_debug_group(this: &GpuRenderBundleEncoder); # [wasm_bindgen (method , structural , js_class = "GPURenderBundleEncoder" , js_name = pushDebugGroup)] @@ -218,7 +218,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn push_debug_group(this: &GpuRenderBundleEncoder, group_label: &str); # [wasm_bindgen (method , structural , js_class = "GPURenderBundleEncoder" , js_name = draw)] @@ -229,7 +229,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw(this: &GpuRenderBundleEncoder, vertex_count: u32); # [wasm_bindgen (method , structural , js_class = "GPURenderBundleEncoder" , js_name = draw)] @@ -240,7 +240,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_with_instance_count( this: &GpuRenderBundleEncoder, vertex_count: u32, @@ -255,7 +255,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_with_instance_count_and_first_vertex( this: &GpuRenderBundleEncoder, vertex_count: u32, @@ -271,7 +271,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_with_instance_count_and_first_vertex_and_first_instance( this: &GpuRenderBundleEncoder, vertex_count: u32, @@ -288,7 +288,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_indexed(this: &GpuRenderBundleEncoder, index_count: u32); # [wasm_bindgen (method , structural , js_class = "GPURenderBundleEncoder" , js_name = drawIndexed)] @@ -299,7 +299,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_indexed_with_instance_count( this: &GpuRenderBundleEncoder, index_count: u32, @@ -314,7 +314,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_indexed_with_instance_count_and_first_index( this: &GpuRenderBundleEncoder, index_count: u32, @@ -330,7 +330,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_indexed_with_instance_count_and_first_index_and_base_vertex( this: &GpuRenderBundleEncoder, index_count: u32, @@ -347,7 +347,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_indexed_with_instance_count_and_first_index_and_base_vertex_and_first_instance( this: &GpuRenderBundleEncoder, index_count: u32, @@ -365,7 +365,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_indexed_indirect_with_u32( this: &GpuRenderBundleEncoder, indirect_buffer: &GpuBuffer, @@ -380,7 +380,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_indexed_indirect_with_f64( this: &GpuRenderBundleEncoder, indirect_buffer: &GpuBuffer, @@ -395,7 +395,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_indirect_with_u32( this: &GpuRenderBundleEncoder, indirect_buffer: &GpuBuffer, @@ -410,7 +410,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_indirect_with_f64( this: &GpuRenderBundleEncoder, indirect_buffer: &GpuBuffer, @@ -425,7 +425,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuIndexFormat`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_index_buffer( this: &GpuRenderBundleEncoder, buffer: &GpuBuffer, @@ -440,7 +440,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuIndexFormat`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_index_buffer_with_u32( this: &GpuRenderBundleEncoder, buffer: &GpuBuffer, @@ -456,7 +456,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuIndexFormat`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_index_buffer_with_f64( this: &GpuRenderBundleEncoder, buffer: &GpuBuffer, @@ -472,7 +472,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuIndexFormat`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_index_buffer_with_u32_and_u32( this: &GpuRenderBundleEncoder, buffer: &GpuBuffer, @@ -489,7 +489,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuIndexFormat`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_index_buffer_with_f64_and_u32( this: &GpuRenderBundleEncoder, buffer: &GpuBuffer, @@ -506,7 +506,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuIndexFormat`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_index_buffer_with_u32_and_f64( this: &GpuRenderBundleEncoder, buffer: &GpuBuffer, @@ -523,7 +523,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuIndexFormat`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_index_buffer_with_f64_and_f64( this: &GpuRenderBundleEncoder, buffer: &GpuBuffer, @@ -540,7 +540,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoder`, `GpuRenderPipeline`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_pipeline(this: &GpuRenderBundleEncoder, pipeline: &GpuRenderPipeline); # [wasm_bindgen (method , structural , js_class = "GPURenderBundleEncoder" , js_name = setVertexBuffer)] @@ -551,7 +551,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_vertex_buffer(this: &GpuRenderBundleEncoder, slot: u32, buffer: Option<&GpuBuffer>); # [wasm_bindgen (method , structural , js_class = "GPURenderBundleEncoder" , js_name = setVertexBuffer)] @@ -562,7 +562,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_vertex_buffer_with_u32( this: &GpuRenderBundleEncoder, slot: u32, @@ -578,7 +578,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_vertex_buffer_with_f64( this: &GpuRenderBundleEncoder, slot: u32, @@ -594,7 +594,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_vertex_buffer_with_u32_and_u32( this: &GpuRenderBundleEncoder, slot: u32, @@ -611,7 +611,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_vertex_buffer_with_f64_and_u32( this: &GpuRenderBundleEncoder, slot: u32, @@ -628,7 +628,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_vertex_buffer_with_u32_and_f64( this: &GpuRenderBundleEncoder, slot: u32, @@ -645,7 +645,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderBundleEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_vertex_buffer_with_f64_and_f64( this: &GpuRenderBundleEncoder, slot: u32, diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderBundleEncoderDescriptor.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderBundleEncoderDescriptor.rs index f093f66d2..e4a7939aa 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderBundleEncoderDescriptor.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderBundleEncoderDescriptor.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoderDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuRenderBundleEncoderDescriptor; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoderDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuRenderBundleEncoderDescriptor) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoderDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuRenderBundleEncoderDescriptor, val: &str); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoderDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "colorFormats")] pub fn get_color_formats(this: &GpuRenderBundleEncoderDescriptor) -> ::js_sys::Array; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoderDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "colorFormats")] pub fn set_color_formats( this: &GpuRenderBundleEncoderDescriptor, @@ -80,7 +80,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoderDescriptor`, `GpuTextureFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "depthStencilFormat")] pub fn get_depth_stencil_format( this: &GpuRenderBundleEncoderDescriptor, @@ -91,7 +91,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoderDescriptor`, `GpuTextureFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "depthStencilFormat")] pub fn set_depth_stencil_format(this: &GpuRenderBundleEncoderDescriptor, val: GpuTextureFormat); @@ -100,7 +100,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoderDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "sampleCount")] pub fn get_sample_count(this: &GpuRenderBundleEncoderDescriptor) -> Option; @@ -109,7 +109,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoderDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "sampleCount")] pub fn set_sample_count(this: &GpuRenderBundleEncoderDescriptor, val: u32); @@ -118,7 +118,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoderDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "depthReadOnly")] pub fn get_depth_read_only(this: &GpuRenderBundleEncoderDescriptor) -> Option; @@ -127,7 +127,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoderDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "depthReadOnly")] pub fn set_depth_read_only(this: &GpuRenderBundleEncoderDescriptor, val: bool); @@ -136,7 +136,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoderDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "stencilReadOnly")] pub fn get_stencil_read_only(this: &GpuRenderBundleEncoderDescriptor) -> Option; @@ -145,7 +145,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoderDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "stencilReadOnly")] pub fn set_stencil_read_only(this: &GpuRenderBundleEncoderDescriptor, val: bool); } @@ -156,7 +156,7 @@ impl GpuRenderBundleEncoderDescriptor { #[doc = "*This API requires the following crate features to be activated: `GpuRenderBundleEncoderDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(color_formats: &::wasm_bindgen::JsValue) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPassColorAttachment.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPassColorAttachment.rs index 3e2bdcf3c..7bba182b1 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPassColorAttachment.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPassColorAttachment.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassColorAttachment`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuRenderPassColorAttachment; #[doc = "Get the `clearValue` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassColorAttachment`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "clearValue")] pub fn get_clear_value(this: &GpuRenderPassColorAttachment) -> ::wasm_bindgen::JsValue; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassColorAttachment`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "clearValue")] pub fn set_clear_value(this: &GpuRenderPassColorAttachment, val: &::wasm_bindgen::JsValue); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassColorAttachment`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "depthSlice")] pub fn get_depth_slice(this: &GpuRenderPassColorAttachment) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassColorAttachment`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "depthSlice")] pub fn set_depth_slice(this: &GpuRenderPassColorAttachment, val: u32); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuLoadOp`, `GpuRenderPassColorAttachment`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "loadOp")] pub fn get_load_op(this: &GpuRenderPassColorAttachment) -> GpuLoadOp; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuLoadOp`, `GpuRenderPassColorAttachment`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "loadOp")] pub fn set_load_op(this: &GpuRenderPassColorAttachment, val: GpuLoadOp); @@ -95,7 +95,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassColorAttachment`, `GpuTextureView`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "resolveTarget")] pub fn get_resolve_target(this: &GpuRenderPassColorAttachment) -> Option; @@ -104,7 +104,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassColorAttachment`, `GpuTextureView`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "resolveTarget")] pub fn set_resolve_target(this: &GpuRenderPassColorAttachment, val: &GpuTextureView); @@ -113,7 +113,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassColorAttachment`, `GpuStoreOp`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "storeOp")] pub fn get_store_op(this: &GpuRenderPassColorAttachment) -> GpuStoreOp; @@ -122,7 +122,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassColorAttachment`, `GpuStoreOp`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "storeOp")] pub fn set_store_op(this: &GpuRenderPassColorAttachment, val: GpuStoreOp); @@ -131,7 +131,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassColorAttachment`, `GpuTextureView`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "view")] pub fn get_view(this: &GpuRenderPassColorAttachment) -> GpuTextureView; @@ -140,7 +140,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassColorAttachment`, `GpuTextureView`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "view")] pub fn set_view(this: &GpuRenderPassColorAttachment, val: &GpuTextureView); } @@ -151,7 +151,7 @@ impl GpuRenderPassColorAttachment { #[doc = "*This API requires the following crate features to be activated: `GpuLoadOp`, `GpuRenderPassColorAttachment`, `GpuStoreOp`, `GpuTextureView`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(load_op: GpuLoadOp, store_op: GpuStoreOp, view: &GpuTextureView) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPassDepthStencilAttachment.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPassDepthStencilAttachment.rs index 7d945689d..41135ecff 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPassDepthStencilAttachment.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPassDepthStencilAttachment.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDepthStencilAttachment`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuRenderPassDepthStencilAttachment; #[doc = "Get the `depthClearValue` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDepthStencilAttachment`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "depthClearValue")] pub fn get_depth_clear_value(this: &GpuRenderPassDepthStencilAttachment) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDepthStencilAttachment`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "depthClearValue")] pub fn set_depth_clear_value(this: &GpuRenderPassDepthStencilAttachment, val: f32); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuLoadOp`, `GpuRenderPassDepthStencilAttachment`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "depthLoadOp")] pub fn get_depth_load_op(this: &GpuRenderPassDepthStencilAttachment) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuLoadOp`, `GpuRenderPassDepthStencilAttachment`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "depthLoadOp")] pub fn set_depth_load_op(this: &GpuRenderPassDepthStencilAttachment, val: GpuLoadOp); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDepthStencilAttachment`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "depthReadOnly")] pub fn get_depth_read_only(this: &GpuRenderPassDepthStencilAttachment) -> Option; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDepthStencilAttachment`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "depthReadOnly")] pub fn set_depth_read_only(this: &GpuRenderPassDepthStencilAttachment, val: bool); @@ -95,7 +95,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDepthStencilAttachment`, `GpuStoreOp`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "depthStoreOp")] pub fn get_depth_store_op(this: &GpuRenderPassDepthStencilAttachment) -> Option; @@ -104,7 +104,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDepthStencilAttachment`, `GpuStoreOp`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "depthStoreOp")] pub fn set_depth_store_op(this: &GpuRenderPassDepthStencilAttachment, val: GpuStoreOp); @@ -113,7 +113,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDepthStencilAttachment`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "stencilClearValue")] pub fn get_stencil_clear_value(this: &GpuRenderPassDepthStencilAttachment) -> Option; @@ -122,7 +122,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDepthStencilAttachment`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "stencilClearValue")] pub fn set_stencil_clear_value(this: &GpuRenderPassDepthStencilAttachment, val: u32); @@ -131,7 +131,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuLoadOp`, `GpuRenderPassDepthStencilAttachment`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "stencilLoadOp")] pub fn get_stencil_load_op(this: &GpuRenderPassDepthStencilAttachment) -> Option; @@ -140,7 +140,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuLoadOp`, `GpuRenderPassDepthStencilAttachment`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "stencilLoadOp")] pub fn set_stencil_load_op(this: &GpuRenderPassDepthStencilAttachment, val: GpuLoadOp); @@ -149,7 +149,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDepthStencilAttachment`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "stencilReadOnly")] pub fn get_stencil_read_only(this: &GpuRenderPassDepthStencilAttachment) -> Option; @@ -158,7 +158,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDepthStencilAttachment`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "stencilReadOnly")] pub fn set_stencil_read_only(this: &GpuRenderPassDepthStencilAttachment, val: bool); @@ -167,7 +167,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDepthStencilAttachment`, `GpuStoreOp`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "stencilStoreOp")] pub fn get_stencil_store_op(this: &GpuRenderPassDepthStencilAttachment) -> Option; @@ -176,7 +176,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDepthStencilAttachment`, `GpuStoreOp`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "stencilStoreOp")] pub fn set_stencil_store_op(this: &GpuRenderPassDepthStencilAttachment, val: GpuStoreOp); @@ -185,7 +185,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDepthStencilAttachment`, `GpuTextureView`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "view")] pub fn get_view(this: &GpuRenderPassDepthStencilAttachment) -> GpuTextureView; @@ -194,7 +194,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDepthStencilAttachment`, `GpuTextureView`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "view")] pub fn set_view(this: &GpuRenderPassDepthStencilAttachment, val: &GpuTextureView); } @@ -205,7 +205,7 @@ impl GpuRenderPassDepthStencilAttachment { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDepthStencilAttachment`, `GpuTextureView`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(view: &GpuTextureView) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPassDescriptor.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPassDescriptor.rs index 61d63faef..97cefbe36 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPassDescriptor.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPassDescriptor.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuRenderPassDescriptor; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuRenderPassDescriptor) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuRenderPassDescriptor, val: &str); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "colorAttachments")] pub fn get_color_attachments(this: &GpuRenderPassDescriptor) -> ::js_sys::Array; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "colorAttachments")] pub fn set_color_attachments(this: &GpuRenderPassDescriptor, val: &::wasm_bindgen::JsValue); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDepthStencilAttachment`, `GpuRenderPassDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "depthStencilAttachment")] pub fn get_depth_stencil_attachment( this: &GpuRenderPassDescriptor, @@ -88,7 +88,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDepthStencilAttachment`, `GpuRenderPassDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "depthStencilAttachment")] pub fn set_depth_stencil_attachment( this: &GpuRenderPassDescriptor, @@ -100,7 +100,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "maxDrawCount")] pub fn get_max_draw_count(this: &GpuRenderPassDescriptor) -> Option; @@ -109,7 +109,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "maxDrawCount")] pub fn set_max_draw_count(this: &GpuRenderPassDescriptor, val: f64); @@ -118,7 +118,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQuerySet`, `GpuRenderPassDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "occlusionQuerySet")] pub fn get_occlusion_query_set(this: &GpuRenderPassDescriptor) -> Option; @@ -127,7 +127,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQuerySet`, `GpuRenderPassDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "occlusionQuerySet")] pub fn set_occlusion_query_set(this: &GpuRenderPassDescriptor, val: &GpuQuerySet); @@ -136,7 +136,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDescriptor`, `GpuRenderPassTimestampWrites`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "timestampWrites")] pub fn get_timestamp_writes( this: &GpuRenderPassDescriptor, @@ -147,7 +147,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDescriptor`, `GpuRenderPassTimestampWrites`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "timestampWrites")] pub fn set_timestamp_writes(this: &GpuRenderPassDescriptor, val: &GpuRenderPassTimestampWrites); } @@ -158,7 +158,7 @@ impl GpuRenderPassDescriptor { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(color_attachments: &::wasm_bindgen::JsValue) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPassEncoder.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPassEncoder.rs index 04f1812bf..7de607c63 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPassEncoder.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPassEncoder.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuRenderPassEncoder; # [wasm_bindgen (structural , method , getter , js_class = "GPURenderPassEncoder" , js_name = label)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn label(this: &GpuRenderPassEncoder) -> ::alloc::string::String; # [wasm_bindgen (structural , method , setter , js_class = "GPURenderPassEncoder" , js_name = label)] @@ -57,7 +57,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_label(this: &GpuRenderPassEncoder, value: &str); # [wasm_bindgen (method , structural , js_class = "GPURenderPassEncoder" , js_name = beginOcclusionQuery)] @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn begin_occlusion_query(this: &GpuRenderPassEncoder, query_index: u32); # [wasm_bindgen (method , structural , js_class = "GPURenderPassEncoder" , js_name = end)] @@ -79,7 +79,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn end(this: &GpuRenderPassEncoder); # [wasm_bindgen (method , structural , js_class = "GPURenderPassEncoder" , js_name = endOcclusionQuery)] @@ -90,7 +90,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn end_occlusion_query(this: &GpuRenderPassEncoder); # [wasm_bindgen (method , structural , js_class = "GPURenderPassEncoder" , js_name = executeBundles)] @@ -101,7 +101,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn execute_bundles(this: &GpuRenderPassEncoder, bundles: &::wasm_bindgen::JsValue); # [wasm_bindgen (catch , method , structural , js_class = "GPURenderPassEncoder" , js_name = setBlendConstant)] @@ -112,7 +112,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_blend_constant_with_f64_sequence( this: &GpuRenderPassEncoder, color: &::wasm_bindgen::JsValue, @@ -126,7 +126,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuColorDict`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_blend_constant_with_gpu_color_dict( this: &GpuRenderPassEncoder, color: &GpuColorDict, @@ -140,7 +140,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_scissor_rect(this: &GpuRenderPassEncoder, x: u32, y: u32, width: u32, height: u32); # [wasm_bindgen (method , structural , js_class = "GPURenderPassEncoder" , js_name = setStencilReference)] @@ -151,7 +151,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_stencil_reference(this: &GpuRenderPassEncoder, reference: u32); # [wasm_bindgen (method , structural , js_class = "GPURenderPassEncoder" , js_name = setViewport)] @@ -162,7 +162,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_viewport( this: &GpuRenderPassEncoder, x: f32, @@ -181,7 +181,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_bind_group( this: &GpuRenderPassEncoder, index: u32, @@ -196,7 +196,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_bind_group_with_u32_sequence( this: &GpuRenderPassEncoder, index: u32, @@ -212,7 +212,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_bind_group_with_u32_slice_and_u32_and_dynamic_offsets_data_length( this: &GpuRenderPassEncoder, index: u32, @@ -230,7 +230,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_bind_group_with_u32_array_and_u32_and_dynamic_offsets_data_length( this: &GpuRenderPassEncoder, index: u32, @@ -248,7 +248,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_bind_group_with_u32_slice_and_f64_and_dynamic_offsets_data_length( this: &GpuRenderPassEncoder, index: u32, @@ -266,7 +266,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroup`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_bind_group_with_u32_array_and_f64_and_dynamic_offsets_data_length( this: &GpuRenderPassEncoder, index: u32, @@ -284,7 +284,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn insert_debug_marker(this: &GpuRenderPassEncoder, marker_label: &str); # [wasm_bindgen (method , structural , js_class = "GPURenderPassEncoder" , js_name = popDebugGroup)] @@ -295,7 +295,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn pop_debug_group(this: &GpuRenderPassEncoder); # [wasm_bindgen (method , structural , js_class = "GPURenderPassEncoder" , js_name = pushDebugGroup)] @@ -306,7 +306,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn push_debug_group(this: &GpuRenderPassEncoder, group_label: &str); # [wasm_bindgen (method , structural , js_class = "GPURenderPassEncoder" , js_name = draw)] @@ -317,7 +317,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw(this: &GpuRenderPassEncoder, vertex_count: u32); # [wasm_bindgen (method , structural , js_class = "GPURenderPassEncoder" , js_name = draw)] @@ -328,7 +328,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_with_instance_count( this: &GpuRenderPassEncoder, vertex_count: u32, @@ -343,7 +343,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_with_instance_count_and_first_vertex( this: &GpuRenderPassEncoder, vertex_count: u32, @@ -359,7 +359,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_with_instance_count_and_first_vertex_and_first_instance( this: &GpuRenderPassEncoder, vertex_count: u32, @@ -376,7 +376,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_indexed(this: &GpuRenderPassEncoder, index_count: u32); # [wasm_bindgen (method , structural , js_class = "GPURenderPassEncoder" , js_name = drawIndexed)] @@ -387,7 +387,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_indexed_with_instance_count( this: &GpuRenderPassEncoder, index_count: u32, @@ -402,7 +402,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_indexed_with_instance_count_and_first_index( this: &GpuRenderPassEncoder, index_count: u32, @@ -418,7 +418,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_indexed_with_instance_count_and_first_index_and_base_vertex( this: &GpuRenderPassEncoder, index_count: u32, @@ -435,7 +435,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_indexed_with_instance_count_and_first_index_and_base_vertex_and_first_instance( this: &GpuRenderPassEncoder, index_count: u32, @@ -453,7 +453,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_indexed_indirect_with_u32( this: &GpuRenderPassEncoder, indirect_buffer: &GpuBuffer, @@ -468,7 +468,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_indexed_indirect_with_f64( this: &GpuRenderPassEncoder, indirect_buffer: &GpuBuffer, @@ -483,7 +483,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_indirect_with_u32( this: &GpuRenderPassEncoder, indirect_buffer: &GpuBuffer, @@ -498,7 +498,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn draw_indirect_with_f64( this: &GpuRenderPassEncoder, indirect_buffer: &GpuBuffer, @@ -513,7 +513,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuIndexFormat`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_index_buffer( this: &GpuRenderPassEncoder, buffer: &GpuBuffer, @@ -528,7 +528,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuIndexFormat`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_index_buffer_with_u32( this: &GpuRenderPassEncoder, buffer: &GpuBuffer, @@ -544,7 +544,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuIndexFormat`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_index_buffer_with_f64( this: &GpuRenderPassEncoder, buffer: &GpuBuffer, @@ -560,7 +560,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuIndexFormat`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_index_buffer_with_u32_and_u32( this: &GpuRenderPassEncoder, buffer: &GpuBuffer, @@ -577,7 +577,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuIndexFormat`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_index_buffer_with_f64_and_u32( this: &GpuRenderPassEncoder, buffer: &GpuBuffer, @@ -594,7 +594,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuIndexFormat`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_index_buffer_with_u32_and_f64( this: &GpuRenderPassEncoder, buffer: &GpuBuffer, @@ -611,7 +611,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuIndexFormat`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_index_buffer_with_f64_and_f64( this: &GpuRenderPassEncoder, buffer: &GpuBuffer, @@ -628,7 +628,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassEncoder`, `GpuRenderPipeline`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_pipeline(this: &GpuRenderPassEncoder, pipeline: &GpuRenderPipeline); # [wasm_bindgen (method , structural , js_class = "GPURenderPassEncoder" , js_name = setVertexBuffer)] @@ -639,7 +639,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_vertex_buffer(this: &GpuRenderPassEncoder, slot: u32, buffer: Option<&GpuBuffer>); # [wasm_bindgen (method , structural , js_class = "GPURenderPassEncoder" , js_name = setVertexBuffer)] @@ -650,7 +650,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_vertex_buffer_with_u32( this: &GpuRenderPassEncoder, slot: u32, @@ -666,7 +666,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_vertex_buffer_with_f64( this: &GpuRenderPassEncoder, slot: u32, @@ -682,7 +682,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_vertex_buffer_with_u32_and_u32( this: &GpuRenderPassEncoder, slot: u32, @@ -699,7 +699,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_vertex_buffer_with_f64_and_u32( this: &GpuRenderPassEncoder, slot: u32, @@ -716,7 +716,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_vertex_buffer_with_u32_and_f64( this: &GpuRenderPassEncoder, slot: u32, @@ -733,7 +733,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuRenderPassEncoder`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_vertex_buffer_with_f64_and_f64( this: &GpuRenderPassEncoder, slot: u32, diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPassTimestampWrites.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPassTimestampWrites.rs index 50de9a1e1..3d6b4d1ed 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPassTimestampWrites.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPassTimestampWrites.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassTimestampWrites`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuRenderPassTimestampWrites; #[doc = "Get the `beginningOfPassWriteIndex` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassTimestampWrites`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "beginningOfPassWriteIndex")] pub fn get_beginning_of_pass_write_index(this: &GpuRenderPassTimestampWrites) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassTimestampWrites`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "beginningOfPassWriteIndex")] pub fn set_beginning_of_pass_write_index(this: &GpuRenderPassTimestampWrites, val: u32); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassTimestampWrites`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "endOfPassWriteIndex")] pub fn get_end_of_pass_write_index(this: &GpuRenderPassTimestampWrites) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPassTimestampWrites`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "endOfPassWriteIndex")] pub fn set_end_of_pass_write_index(this: &GpuRenderPassTimestampWrites, val: u32); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQuerySet`, `GpuRenderPassTimestampWrites`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "querySet")] pub fn get_query_set(this: &GpuRenderPassTimestampWrites) -> GpuQuerySet; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuQuerySet`, `GpuRenderPassTimestampWrites`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "querySet")] pub fn set_query_set(this: &GpuRenderPassTimestampWrites, val: &GpuQuerySet); } @@ -97,7 +97,7 @@ impl GpuRenderPassTimestampWrites { #[doc = "*This API requires the following crate features to be activated: `GpuQuerySet`, `GpuRenderPassTimestampWrites`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(query_set: &GpuQuerySet) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPipeline.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPipeline.rs index 615aac5c9..795bc24d1 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPipeline.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPipeline.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPipeline`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuRenderPipeline; # [wasm_bindgen (structural , method , getter , js_class = "GPURenderPipeline" , js_name = label)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPipeline`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn label(this: &GpuRenderPipeline) -> ::alloc::string::String; # [wasm_bindgen (structural , method , setter , js_class = "GPURenderPipeline" , js_name = label)] @@ -57,7 +57,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPipeline`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_label(this: &GpuRenderPipeline, value: &str); # [wasm_bindgen (method , structural , js_class = "GPURenderPipeline" , js_name = getBindGroupLayout)] @@ -68,6 +68,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBindGroupLayout`, `GpuRenderPipeline`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn get_bind_group_layout(this: &GpuRenderPipeline, index: u32) -> GpuBindGroupLayout; } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPipelineDescriptor.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPipelineDescriptor.rs index c9e24c778..a0f2875b6 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPipelineDescriptor.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRenderPipelineDescriptor.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPipelineDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuRenderPipelineDescriptor; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPipelineDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuRenderPipelineDescriptor) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPipelineDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuRenderPipelineDescriptor, val: &str); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPipelineDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "layout")] pub fn get_layout(this: &GpuRenderPipelineDescriptor) -> ::wasm_bindgen::JsValue; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPipelineDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "layout")] pub fn set_layout(this: &GpuRenderPipelineDescriptor, val: &::wasm_bindgen::JsValue); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`, `GpuRenderPipelineDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "depthStencil")] pub fn get_depth_stencil(this: &GpuRenderPipelineDescriptor) -> Option; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuDepthStencilState`, `GpuRenderPipelineDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "depthStencil")] pub fn set_depth_stencil(this: &GpuRenderPipelineDescriptor, val: &GpuDepthStencilState); @@ -95,7 +95,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuFragmentState`, `GpuRenderPipelineDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "fragment")] pub fn get_fragment(this: &GpuRenderPipelineDescriptor) -> Option; @@ -104,7 +104,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuFragmentState`, `GpuRenderPipelineDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "fragment")] pub fn set_fragment(this: &GpuRenderPipelineDescriptor, val: &GpuFragmentState); @@ -113,7 +113,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuMultisampleState`, `GpuRenderPipelineDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "multisample")] pub fn get_multisample(this: &GpuRenderPipelineDescriptor) -> Option; @@ -122,7 +122,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuMultisampleState`, `GpuRenderPipelineDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "multisample")] pub fn set_multisample(this: &GpuRenderPipelineDescriptor, val: &GpuMultisampleState); @@ -131,7 +131,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPrimitiveState`, `GpuRenderPipelineDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "primitive")] pub fn get_primitive(this: &GpuRenderPipelineDescriptor) -> Option; @@ -140,7 +140,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPrimitiveState`, `GpuRenderPipelineDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "primitive")] pub fn set_primitive(this: &GpuRenderPipelineDescriptor, val: &GpuPrimitiveState); @@ -149,7 +149,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPipelineDescriptor`, `GpuVertexState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "vertex")] pub fn get_vertex(this: &GpuRenderPipelineDescriptor) -> GpuVertexState; @@ -158,7 +158,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPipelineDescriptor`, `GpuVertexState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "vertex")] pub fn set_vertex(this: &GpuRenderPipelineDescriptor, val: &GpuVertexState); } @@ -169,7 +169,7 @@ impl GpuRenderPipelineDescriptor { #[doc = "*This API requires the following crate features to be activated: `GpuRenderPipelineDescriptor`, `GpuVertexState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(layout: &::wasm_bindgen::JsValue, vertex: &GpuVertexState) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRequestAdapterOptions.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRequestAdapterOptions.rs index 22ab89df6..3543ad8e1 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRequestAdapterOptions.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuRequestAdapterOptions.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRequestAdapterOptions`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuRequestAdapterOptions; #[doc = "Get the `featureLevel` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRequestAdapterOptions`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "featureLevel")] pub fn get_feature_level(this: &GpuRequestAdapterOptions) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRequestAdapterOptions`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "featureLevel")] pub fn set_feature_level(this: &GpuRequestAdapterOptions, val: &str); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRequestAdapterOptions`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "forceFallbackAdapter")] pub fn get_force_fallback_adapter(this: &GpuRequestAdapterOptions) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRequestAdapterOptions`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "forceFallbackAdapter")] pub fn set_force_fallback_adapter(this: &GpuRequestAdapterOptions, val: bool); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPowerPreference`, `GpuRequestAdapterOptions`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "powerPreference")] pub fn get_power_preference(this: &GpuRequestAdapterOptions) -> Option; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuPowerPreference`, `GpuRequestAdapterOptions`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "powerPreference")] pub fn set_power_preference(this: &GpuRequestAdapterOptions, val: GpuPowerPreference); @@ -95,7 +95,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRequestAdapterOptions`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "xrCompatible")] pub fn get_xr_compatible(this: &GpuRequestAdapterOptions) -> Option; @@ -104,7 +104,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuRequestAdapterOptions`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "xrCompatible")] pub fn set_xr_compatible(this: &GpuRequestAdapterOptions, val: bool); } @@ -115,7 +115,7 @@ impl GpuRequestAdapterOptions { #[doc = "*This API requires the following crate features to be activated: `GpuRequestAdapterOptions`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSampler.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSampler.rs index 4ec4f604b..5f88d5244 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSampler.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSampler.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSampler`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuSampler; # [wasm_bindgen (structural , method , getter , js_class = "GPUSampler" , js_name = label)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSampler`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn label(this: &GpuSampler) -> ::alloc::string::String; # [wasm_bindgen (structural , method , setter , js_class = "GPUSampler" , js_name = label)] @@ -57,6 +57,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSampler`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_label(this: &GpuSampler, value: &str); } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSamplerBindingLayout.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSamplerBindingLayout.rs index 2a6852d3f..b14f29014 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSamplerBindingLayout.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSamplerBindingLayout.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSamplerBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuSamplerBindingLayout; #[doc = "Get the `type` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSamplerBindingLayout`, `GpuSamplerBindingType`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "type")] pub fn get_type(this: &GpuSamplerBindingLayout) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSamplerBindingLayout`, `GpuSamplerBindingType`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "type")] pub fn set_type(this: &GpuSamplerBindingLayout, val: GpuSamplerBindingType); } @@ -61,7 +61,7 @@ impl GpuSamplerBindingLayout { #[doc = "*This API requires the following crate features to be activated: `GpuSamplerBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSamplerBindingType.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSamplerBindingType.rs index 11d87ff08..6cebb0386 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSamplerBindingType.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSamplerBindingType.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuSamplerBindingType`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuSamplerBindingType { Filtering = "filtering", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSamplerDescriptor.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSamplerDescriptor.rs index 49998661f..3cb3237dd 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSamplerDescriptor.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSamplerDescriptor.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuSamplerDescriptor; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuSamplerDescriptor) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuSamplerDescriptor, val: &str); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuAddressMode`, `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "addressModeU")] pub fn get_address_mode_u(this: &GpuSamplerDescriptor) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuAddressMode`, `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "addressModeU")] pub fn set_address_mode_u(this: &GpuSamplerDescriptor, val: GpuAddressMode); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuAddressMode`, `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "addressModeV")] pub fn get_address_mode_v(this: &GpuSamplerDescriptor) -> Option; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuAddressMode`, `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "addressModeV")] pub fn set_address_mode_v(this: &GpuSamplerDescriptor, val: GpuAddressMode); @@ -95,7 +95,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuAddressMode`, `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "addressModeW")] pub fn get_address_mode_w(this: &GpuSamplerDescriptor) -> Option; @@ -104,7 +104,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuAddressMode`, `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "addressModeW")] pub fn set_address_mode_w(this: &GpuSamplerDescriptor, val: GpuAddressMode); @@ -113,7 +113,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCompareFunction`, `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "compare")] pub fn get_compare(this: &GpuSamplerDescriptor) -> Option; @@ -122,7 +122,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCompareFunction`, `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "compare")] pub fn set_compare(this: &GpuSamplerDescriptor, val: GpuCompareFunction); @@ -131,7 +131,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "lodMaxClamp")] pub fn get_lod_max_clamp(this: &GpuSamplerDescriptor) -> Option; @@ -140,7 +140,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "lodMaxClamp")] pub fn set_lod_max_clamp(this: &GpuSamplerDescriptor, val: f32); @@ -149,7 +149,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "lodMinClamp")] pub fn get_lod_min_clamp(this: &GpuSamplerDescriptor) -> Option; @@ -158,7 +158,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "lodMinClamp")] pub fn set_lod_min_clamp(this: &GpuSamplerDescriptor, val: f32); @@ -167,7 +167,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuFilterMode`, `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "magFilter")] pub fn get_mag_filter(this: &GpuSamplerDescriptor) -> Option; @@ -176,7 +176,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuFilterMode`, `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "magFilter")] pub fn set_mag_filter(this: &GpuSamplerDescriptor, val: GpuFilterMode); @@ -185,7 +185,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "maxAnisotropy")] pub fn get_max_anisotropy(this: &GpuSamplerDescriptor) -> Option; @@ -194,7 +194,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "maxAnisotropy")] pub fn set_max_anisotropy(this: &GpuSamplerDescriptor, val: u16); @@ -203,7 +203,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuFilterMode`, `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "minFilter")] pub fn get_min_filter(this: &GpuSamplerDescriptor) -> Option; @@ -212,7 +212,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuFilterMode`, `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "minFilter")] pub fn set_min_filter(this: &GpuSamplerDescriptor, val: GpuFilterMode); @@ -221,7 +221,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuMipmapFilterMode`, `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "mipmapFilter")] pub fn get_mipmap_filter(this: &GpuSamplerDescriptor) -> Option; @@ -230,7 +230,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuMipmapFilterMode`, `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "mipmapFilter")] pub fn set_mipmap_filter(this: &GpuSamplerDescriptor, val: GpuMipmapFilterMode); } @@ -241,7 +241,7 @@ impl GpuSamplerDescriptor { #[doc = "*This API requires the following crate features to be activated: `GpuSamplerDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuShaderModule.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuShaderModule.rs index 033d1e4de..bbebbb426 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuShaderModule.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuShaderModule.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuShaderModule`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuShaderModule; # [wasm_bindgen (structural , method , getter , js_class = "GPUShaderModule" , js_name = label)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuShaderModule`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn label(this: &GpuShaderModule) -> ::alloc::string::String; # [wasm_bindgen (structural , method , setter , js_class = "GPUShaderModule" , js_name = label)] @@ -57,7 +57,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuShaderModule`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_label(this: &GpuShaderModule, value: &str); # [wasm_bindgen (method , structural , js_class = "GPUShaderModule" , js_name = getCompilationInfo)] @@ -68,6 +68,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuShaderModule`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn get_compilation_info(this: &GpuShaderModule) -> ::js_sys::Promise; } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuShaderModuleDescriptor.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuShaderModuleDescriptor.rs index 526bcce19..e0d08610f 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuShaderModuleDescriptor.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuShaderModuleDescriptor.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuShaderModuleDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuShaderModuleDescriptor; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuShaderModuleDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuShaderModuleDescriptor) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuShaderModuleDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuShaderModuleDescriptor, val: &str); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuShaderModuleDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "code")] pub fn get_code(this: &GpuShaderModuleDescriptor) -> ::alloc::string::String; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuShaderModuleDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "code")] pub fn set_code(this: &GpuShaderModuleDescriptor, val: &str); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuShaderModuleDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "compilationHints")] pub fn get_compilation_hints(this: &GpuShaderModuleDescriptor) -> Option<::js_sys::Array>; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuShaderModuleDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "compilationHints")] pub fn set_compilation_hints(this: &GpuShaderModuleDescriptor, val: &::wasm_bindgen::JsValue); } @@ -97,7 +97,7 @@ impl GpuShaderModuleDescriptor { #[doc = "*This API requires the following crate features to be activated: `GpuShaderModuleDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(code: &str) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuStencilFaceState.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuStencilFaceState.rs index 7af7f1c1f..96fedd785 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuStencilFaceState.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuStencilFaceState.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuStencilFaceState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuStencilFaceState; #[doc = "Get the `compare` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCompareFunction`, `GpuStencilFaceState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "compare")] pub fn get_compare(this: &GpuStencilFaceState) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuCompareFunction`, `GpuStencilFaceState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "compare")] pub fn set_compare(this: &GpuStencilFaceState, val: GpuCompareFunction); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuStencilFaceState`, `GpuStencilOperation`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "depthFailOp")] pub fn get_depth_fail_op(this: &GpuStencilFaceState) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuStencilFaceState`, `GpuStencilOperation`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "depthFailOp")] pub fn set_depth_fail_op(this: &GpuStencilFaceState, val: GpuStencilOperation); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuStencilFaceState`, `GpuStencilOperation`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "failOp")] pub fn get_fail_op(this: &GpuStencilFaceState) -> Option; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuStencilFaceState`, `GpuStencilOperation`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "failOp")] pub fn set_fail_op(this: &GpuStencilFaceState, val: GpuStencilOperation); @@ -95,7 +95,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuStencilFaceState`, `GpuStencilOperation`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "passOp")] pub fn get_pass_op(this: &GpuStencilFaceState) -> Option; @@ -104,7 +104,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuStencilFaceState`, `GpuStencilOperation`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "passOp")] pub fn set_pass_op(this: &GpuStencilFaceState, val: GpuStencilOperation); } @@ -115,7 +115,7 @@ impl GpuStencilFaceState { #[doc = "*This API requires the following crate features to be activated: `GpuStencilFaceState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuStencilOperation.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuStencilOperation.rs index 858794c04..f5137d892 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuStencilOperation.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuStencilOperation.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuStencilOperation`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuStencilOperation { Keep = "keep", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuStorageTextureAccess.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuStorageTextureAccess.rs index 6bd5b14f2..43499d6df 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuStorageTextureAccess.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuStorageTextureAccess.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuStorageTextureAccess`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuStorageTextureAccess { WriteOnly = "write-only", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuStorageTextureBindingLayout.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuStorageTextureBindingLayout.rs index 093bcd6be..f694316e1 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuStorageTextureBindingLayout.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuStorageTextureBindingLayout.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuStorageTextureBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuStorageTextureBindingLayout; #[doc = "Get the `access` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuStorageTextureAccess`, `GpuStorageTextureBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "access")] pub fn get_access(this: &GpuStorageTextureBindingLayout) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuStorageTextureAccess`, `GpuStorageTextureBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "access")] pub fn set_access(this: &GpuStorageTextureBindingLayout, val: GpuStorageTextureAccess); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuStorageTextureBindingLayout`, `GpuTextureFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "format")] pub fn get_format(this: &GpuStorageTextureBindingLayout) -> GpuTextureFormat; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuStorageTextureBindingLayout`, `GpuTextureFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "format")] pub fn set_format(this: &GpuStorageTextureBindingLayout, val: GpuTextureFormat); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuStorageTextureBindingLayout`, `GpuTextureViewDimension`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "viewDimension")] pub fn get_view_dimension( this: &GpuStorageTextureBindingLayout, @@ -88,7 +88,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuStorageTextureBindingLayout`, `GpuTextureViewDimension`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "viewDimension")] pub fn set_view_dimension(this: &GpuStorageTextureBindingLayout, val: GpuTextureViewDimension); } @@ -99,7 +99,7 @@ impl GpuStorageTextureBindingLayout { #[doc = "*This API requires the following crate features to be activated: `GpuStorageTextureBindingLayout`, `GpuTextureFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(format: GpuTextureFormat) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuStoreOp.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuStoreOp.rs index 7206c4ba7..f32edb3f9 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuStoreOp.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuStoreOp.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuStoreOp`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuStoreOp { Store = "store", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSupportedFeatures.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSupportedFeatures.rs index 1f3843bee..fc70e2f17 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSupportedFeatures.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSupportedFeatures.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedFeatures`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuSupportedFeatures; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedFeatures" , js_name = size)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedFeatures`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn size(this: &GpuSupportedFeatures) -> u32; # [wasm_bindgen (method , structural , js_class = "GPUSupportedFeatures" , js_name = entries)] @@ -57,7 +57,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedFeatures`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn entries(this: &GpuSupportedFeatures) -> ::js_sys::Iterator; # [wasm_bindgen (catch , method , structural , js_class = "GPUSupportedFeatures" , js_name = forEach)] @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedFeatures`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn for_each( this: &GpuSupportedFeatures, callback: &::js_sys::Function, @@ -82,7 +82,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedFeatures`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn has(this: &GpuSupportedFeatures, value: &str) -> bool; # [wasm_bindgen (method , structural , js_class = "GPUSupportedFeatures" , js_name = keys)] @@ -93,7 +93,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedFeatures`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn keys(this: &GpuSupportedFeatures) -> ::js_sys::Iterator; # [wasm_bindgen (method , structural , js_class = "GPUSupportedFeatures" , js_name = values)] @@ -104,6 +104,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedFeatures`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn values(this: &GpuSupportedFeatures) -> ::js_sys::Iterator; } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSupportedLimits.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSupportedLimits.rs index 1cdaa1e63..8323fe6e2 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSupportedLimits.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuSupportedLimits.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuSupportedLimits; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxTextureDimension1D)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_texture_dimension_1d(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxTextureDimension2D)] @@ -57,7 +57,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_texture_dimension_2d(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxTextureDimension3D)] @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_texture_dimension_3d(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxTextureArrayLayers)] @@ -79,7 +79,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_texture_array_layers(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxBindGroups)] @@ -90,7 +90,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_bind_groups(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxBindGroupsPlusVertexBuffers)] @@ -101,7 +101,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_bind_groups_plus_vertex_buffers(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxBindingsPerBindGroup)] @@ -112,7 +112,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_bindings_per_bind_group(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxDynamicUniformBuffersPerPipelineLayout)] @@ -123,7 +123,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_dynamic_uniform_buffers_per_pipeline_layout(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxDynamicStorageBuffersPerPipelineLayout)] @@ -134,7 +134,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_dynamic_storage_buffers_per_pipeline_layout(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxSampledTexturesPerShaderStage)] @@ -145,7 +145,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_sampled_textures_per_shader_stage(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxSamplersPerShaderStage)] @@ -156,7 +156,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_samplers_per_shader_stage(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxStorageBuffersPerShaderStage)] @@ -167,7 +167,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_storage_buffers_per_shader_stage(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxStorageTexturesPerShaderStage)] @@ -178,7 +178,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_storage_textures_per_shader_stage(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxUniformBuffersPerShaderStage)] @@ -189,7 +189,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_uniform_buffers_per_shader_stage(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxUniformBufferBindingSize)] @@ -200,7 +200,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_uniform_buffer_binding_size(this: &GpuSupportedLimits) -> f64; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxStorageBufferBindingSize)] @@ -211,7 +211,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_storage_buffer_binding_size(this: &GpuSupportedLimits) -> f64; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = minUniformBufferOffsetAlignment)] @@ -222,7 +222,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn min_uniform_buffer_offset_alignment(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = minStorageBufferOffsetAlignment)] @@ -233,7 +233,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn min_storage_buffer_offset_alignment(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxVertexBuffers)] @@ -244,7 +244,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_vertex_buffers(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxBufferSize)] @@ -255,7 +255,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_buffer_size(this: &GpuSupportedLimits) -> f64; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxVertexAttributes)] @@ -266,7 +266,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_vertex_attributes(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxVertexBufferArrayStride)] @@ -277,7 +277,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_vertex_buffer_array_stride(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxInterStageShaderVariables)] @@ -288,7 +288,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_inter_stage_shader_variables(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxColorAttachments)] @@ -299,7 +299,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_color_attachments(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxColorAttachmentBytesPerSample)] @@ -310,7 +310,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_color_attachment_bytes_per_sample(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxComputeWorkgroupStorageSize)] @@ -321,7 +321,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_compute_workgroup_storage_size(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxComputeInvocationsPerWorkgroup)] @@ -332,7 +332,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_compute_invocations_per_workgroup(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxComputeWorkgroupSizeX)] @@ -343,7 +343,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_compute_workgroup_size_x(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxComputeWorkgroupSizeY)] @@ -354,7 +354,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_compute_workgroup_size_y(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxComputeWorkgroupSizeZ)] @@ -365,7 +365,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_compute_workgroup_size_z(this: &GpuSupportedLimits) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxComputeWorkgroupsPerDimension)] @@ -376,6 +376,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuSupportedLimits`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn max_compute_workgroups_per_dimension(this: &GpuSupportedLimits) -> u32; } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTexelCopyBufferInfo.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTexelCopyBufferInfo.rs index 28a794a64..dad3f24b2 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTexelCopyBufferInfo.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTexelCopyBufferInfo.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyBufferInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuTexelCopyBufferInfo; #[doc = "Get the `bytesPerRow` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyBufferInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "bytesPerRow")] pub fn get_bytes_per_row(this: &GpuTexelCopyBufferInfo) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyBufferInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "bytesPerRow")] pub fn set_bytes_per_row(this: &GpuTexelCopyBufferInfo, val: u32); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyBufferInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "offset")] pub fn get_offset(this: &GpuTexelCopyBufferInfo) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyBufferInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "offset")] pub fn set_offset(this: &GpuTexelCopyBufferInfo, val: f64); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyBufferInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "rowsPerImage")] pub fn get_rows_per_image(this: &GpuTexelCopyBufferInfo) -> Option; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyBufferInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "rowsPerImage")] pub fn set_rows_per_image(this: &GpuTexelCopyBufferInfo, val: u32); @@ -95,7 +95,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuTexelCopyBufferInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "buffer")] pub fn get_buffer(this: &GpuTexelCopyBufferInfo) -> GpuBuffer; @@ -104,7 +104,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuTexelCopyBufferInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "buffer")] pub fn set_buffer(this: &GpuTexelCopyBufferInfo, val: &GpuBuffer); } @@ -115,7 +115,7 @@ impl GpuTexelCopyBufferInfo { #[doc = "*This API requires the following crate features to be activated: `GpuBuffer`, `GpuTexelCopyBufferInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(buffer: &GpuBuffer) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTexelCopyBufferLayout.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTexelCopyBufferLayout.rs index 32459bf15..26f9a4f3c 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTexelCopyBufferLayout.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTexelCopyBufferLayout.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyBufferLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuTexelCopyBufferLayout; #[doc = "Get the `bytesPerRow` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyBufferLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "bytesPerRow")] pub fn get_bytes_per_row(this: &GpuTexelCopyBufferLayout) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyBufferLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "bytesPerRow")] pub fn set_bytes_per_row(this: &GpuTexelCopyBufferLayout, val: u32); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyBufferLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "offset")] pub fn get_offset(this: &GpuTexelCopyBufferLayout) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyBufferLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "offset")] pub fn set_offset(this: &GpuTexelCopyBufferLayout, val: f64); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyBufferLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "rowsPerImage")] pub fn get_rows_per_image(this: &GpuTexelCopyBufferLayout) -> Option; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyBufferLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "rowsPerImage")] pub fn set_rows_per_image(this: &GpuTexelCopyBufferLayout, val: u32); } @@ -97,7 +97,7 @@ impl GpuTexelCopyBufferLayout { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyBufferLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTexelCopyTextureInfo.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTexelCopyTextureInfo.rs index c02bc48e3..e948503de 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTexelCopyTextureInfo.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTexelCopyTextureInfo.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyTextureInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuTexelCopyTextureInfo; #[doc = "Get the `aspect` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyTextureInfo`, `GpuTextureAspect`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "aspect")] pub fn get_aspect(this: &GpuTexelCopyTextureInfo) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyTextureInfo`, `GpuTextureAspect`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "aspect")] pub fn set_aspect(this: &GpuTexelCopyTextureInfo, val: GpuTextureAspect); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyTextureInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "mipLevel")] pub fn get_mip_level(this: &GpuTexelCopyTextureInfo) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyTextureInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "mipLevel")] pub fn set_mip_level(this: &GpuTexelCopyTextureInfo, val: u32); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyTextureInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "origin")] pub fn get_origin(this: &GpuTexelCopyTextureInfo) -> ::wasm_bindgen::JsValue; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyTextureInfo`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "origin")] pub fn set_origin(this: &GpuTexelCopyTextureInfo, val: &::wasm_bindgen::JsValue); @@ -95,7 +95,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyTextureInfo`, `GpuTexture`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "texture")] pub fn get_texture(this: &GpuTexelCopyTextureInfo) -> GpuTexture; @@ -104,7 +104,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyTextureInfo`, `GpuTexture`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "texture")] pub fn set_texture(this: &GpuTexelCopyTextureInfo, val: &GpuTexture); } @@ -115,7 +115,7 @@ impl GpuTexelCopyTextureInfo { #[doc = "*This API requires the following crate features to be activated: `GpuTexelCopyTextureInfo`, `GpuTexture`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(texture: &GpuTexture) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTexture.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTexture.rs index 50437cc1e..20c3eb8cb 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTexture.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTexture.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexture`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuTexture; # [wasm_bindgen (structural , method , getter , js_class = "GPUTexture" , js_name = width)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexture`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn width(this: &GpuTexture) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUTexture" , js_name = height)] @@ -57,7 +57,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexture`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn height(this: &GpuTexture) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUTexture" , js_name = depthOrArrayLayers)] @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexture`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn depth_or_array_layers(this: &GpuTexture) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUTexture" , js_name = mipLevelCount)] @@ -79,7 +79,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexture`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn mip_level_count(this: &GpuTexture) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUTexture" , js_name = sampleCount)] @@ -90,7 +90,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexture`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn sample_count(this: &GpuTexture) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUTexture" , js_name = dimension)] @@ -101,7 +101,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexture`, `GpuTextureDimension`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn dimension(this: &GpuTexture) -> GpuTextureDimension; # [wasm_bindgen (structural , method , getter , js_class = "GPUTexture" , js_name = format)] @@ -112,7 +112,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexture`, `GpuTextureFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn format(this: &GpuTexture) -> GpuTextureFormat; # [wasm_bindgen (structural , method , getter , js_class = "GPUTexture" , js_name = usage)] @@ -123,7 +123,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexture`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn usage(this: &GpuTexture) -> u32; # [wasm_bindgen (structural , method , getter , js_class = "GPUTexture" , js_name = label)] @@ -134,7 +134,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexture`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn label(this: &GpuTexture) -> ::alloc::string::String; # [wasm_bindgen (structural , method , setter , js_class = "GPUTexture" , js_name = label)] @@ -145,7 +145,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexture`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_label(this: &GpuTexture, value: &str); # [wasm_bindgen (catch , method , structural , js_class = "GPUTexture" , js_name = createView)] @@ -156,7 +156,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexture`, `GpuTextureView`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn create_view(this: &GpuTexture) -> Result; # [wasm_bindgen (catch , method , structural , js_class = "GPUTexture" , js_name = createView)] @@ -167,7 +167,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexture`, `GpuTextureView`, `GpuTextureViewDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn create_view_with_descriptor( this: &GpuTexture, descriptor: &GpuTextureViewDescriptor, @@ -181,6 +181,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTexture`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn destroy(this: &GpuTexture); } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureAspect.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureAspect.rs index b4e485939..c8d7739b8 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureAspect.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureAspect.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuTextureAspect`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuTextureAspect { All = "all", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureBindingLayout.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureBindingLayout.rs index cd71dd32b..2a7bd017c 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureBindingLayout.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureBindingLayout.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuTextureBindingLayout; #[doc = "Get the `multisampled` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "multisampled")] pub fn get_multisampled(this: &GpuTextureBindingLayout) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "multisampled")] pub fn set_multisampled(this: &GpuTextureBindingLayout, val: bool); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureBindingLayout`, `GpuTextureSampleType`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "sampleType")] pub fn get_sample_type(this: &GpuTextureBindingLayout) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureBindingLayout`, `GpuTextureSampleType`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "sampleType")] pub fn set_sample_type(this: &GpuTextureBindingLayout, val: GpuTextureSampleType); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureBindingLayout`, `GpuTextureViewDimension`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "viewDimension")] pub fn get_view_dimension(this: &GpuTextureBindingLayout) -> Option; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureBindingLayout`, `GpuTextureViewDimension`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "viewDimension")] pub fn set_view_dimension(this: &GpuTextureBindingLayout, val: GpuTextureViewDimension); } @@ -97,7 +97,7 @@ impl GpuTextureBindingLayout { #[doc = "*This API requires the following crate features to be activated: `GpuTextureBindingLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureDescriptor.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureDescriptor.rs index 4ddbba8c3..dc6be0175 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureDescriptor.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureDescriptor.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuTextureDescriptor; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuTextureDescriptor) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuTextureDescriptor, val: &str); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureDescriptor`, `GpuTextureDimension`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "dimension")] pub fn get_dimension(this: &GpuTextureDescriptor) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureDescriptor`, `GpuTextureDimension`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "dimension")] pub fn set_dimension(this: &GpuTextureDescriptor, val: GpuTextureDimension); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureDescriptor`, `GpuTextureFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "format")] pub fn get_format(this: &GpuTextureDescriptor) -> GpuTextureFormat; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureDescriptor`, `GpuTextureFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "format")] pub fn set_format(this: &GpuTextureDescriptor, val: GpuTextureFormat); @@ -95,7 +95,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "mipLevelCount")] pub fn get_mip_level_count(this: &GpuTextureDescriptor) -> Option; @@ -104,7 +104,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "mipLevelCount")] pub fn set_mip_level_count(this: &GpuTextureDescriptor, val: u32); @@ -113,7 +113,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "sampleCount")] pub fn get_sample_count(this: &GpuTextureDescriptor) -> Option; @@ -122,7 +122,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "sampleCount")] pub fn set_sample_count(this: &GpuTextureDescriptor, val: u32); @@ -131,7 +131,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "size")] pub fn get_size(this: &GpuTextureDescriptor) -> ::wasm_bindgen::JsValue; @@ -140,7 +140,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "size")] pub fn set_size(this: &GpuTextureDescriptor, val: &::wasm_bindgen::JsValue); @@ -149,7 +149,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "usage")] pub fn get_usage(this: &GpuTextureDescriptor) -> u32; @@ -158,7 +158,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "usage")] pub fn set_usage(this: &GpuTextureDescriptor, val: u32); @@ -167,7 +167,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "viewFormats")] pub fn get_view_formats(this: &GpuTextureDescriptor) -> Option<::js_sys::Array>; @@ -176,7 +176,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "viewFormats")] pub fn set_view_formats(this: &GpuTextureDescriptor, val: &::wasm_bindgen::JsValue); } @@ -187,7 +187,7 @@ impl GpuTextureDescriptor { #[doc = "*This API requires the following crate features to be activated: `GpuTextureDescriptor`, `GpuTextureFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(format: GpuTextureFormat, size: &::wasm_bindgen::JsValue, usage: u32) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureDimension.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureDimension.rs index 3e3c5c681..d860c9d13 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureDimension.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureDimension.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuTextureDimension`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuTextureDimension { N1d = "1d", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureFormat.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureFormat.rs index 63df3f566..c861a82fc 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureFormat.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureFormat.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuTextureFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuTextureFormat { R8unorm = "r8unorm", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureSampleType.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureSampleType.rs index 91a4e985f..04fdb2e3b 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureSampleType.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureSampleType.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuTextureSampleType`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuTextureSampleType { Float = "float", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureView.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureView.rs index 2edf02f7e..6ece29498 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureView.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureView.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureView`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuTextureView; # [wasm_bindgen (structural , method , getter , js_class = "GPUTextureView" , js_name = label)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureView`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn label(this: &GpuTextureView) -> ::alloc::string::String; # [wasm_bindgen (structural , method , setter , js_class = "GPUTextureView" , js_name = label)] @@ -57,6 +57,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureView`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn set_label(this: &GpuTextureView, value: &str); } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureViewDescriptor.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureViewDescriptor.rs index db48b8cdb..49c642d31 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureViewDescriptor.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureViewDescriptor.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureViewDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuTextureViewDescriptor; #[doc = "Get the `label` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureViewDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "label")] pub fn get_label(this: &GpuTextureViewDescriptor) -> Option<::alloc::string::String>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureViewDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "label")] pub fn set_label(this: &GpuTextureViewDescriptor, val: &str); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureViewDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "arrayLayerCount")] pub fn get_array_layer_count(this: &GpuTextureViewDescriptor) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureViewDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "arrayLayerCount")] pub fn set_array_layer_count(this: &GpuTextureViewDescriptor, val: u32); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureAspect`, `GpuTextureViewDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "aspect")] pub fn get_aspect(this: &GpuTextureViewDescriptor) -> Option; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureAspect`, `GpuTextureViewDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "aspect")] pub fn set_aspect(this: &GpuTextureViewDescriptor, val: GpuTextureAspect); @@ -95,7 +95,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureViewDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "baseArrayLayer")] pub fn get_base_array_layer(this: &GpuTextureViewDescriptor) -> Option; @@ -104,7 +104,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureViewDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "baseArrayLayer")] pub fn set_base_array_layer(this: &GpuTextureViewDescriptor, val: u32); @@ -113,7 +113,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureViewDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "baseMipLevel")] pub fn get_base_mip_level(this: &GpuTextureViewDescriptor) -> Option; @@ -122,7 +122,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureViewDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "baseMipLevel")] pub fn set_base_mip_level(this: &GpuTextureViewDescriptor, val: u32); @@ -131,7 +131,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureViewDescriptor`, `GpuTextureViewDimension`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "dimension")] pub fn get_dimension(this: &GpuTextureViewDescriptor) -> Option; @@ -140,7 +140,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureViewDescriptor`, `GpuTextureViewDimension`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "dimension")] pub fn set_dimension(this: &GpuTextureViewDescriptor, val: GpuTextureViewDimension); @@ -149,7 +149,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureFormat`, `GpuTextureViewDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "format")] pub fn get_format(this: &GpuTextureViewDescriptor) -> Option; @@ -158,7 +158,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureFormat`, `GpuTextureViewDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "format")] pub fn set_format(this: &GpuTextureViewDescriptor, val: GpuTextureFormat); @@ -167,7 +167,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureViewDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "mipLevelCount")] pub fn get_mip_level_count(this: &GpuTextureViewDescriptor) -> Option; @@ -176,7 +176,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureViewDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "mipLevelCount")] pub fn set_mip_level_count(this: &GpuTextureViewDescriptor, val: u32); @@ -185,7 +185,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureViewDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "usage")] pub fn get_usage(this: &GpuTextureViewDescriptor) -> Option; @@ -194,7 +194,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuTextureViewDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "usage")] pub fn set_usage(this: &GpuTextureViewDescriptor, val: u32); } @@ -205,7 +205,7 @@ impl GpuTextureViewDescriptor { #[doc = "*This API requires the following crate features to be activated: `GpuTextureViewDescriptor`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new() -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureViewDimension.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureViewDimension.rs index 1878f41c6..57ccb0360 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureViewDimension.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuTextureViewDimension.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuTextureViewDimension`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuTextureViewDimension { N1d = "1d", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuUncapturedErrorEvent.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuUncapturedErrorEvent.rs index 015f07907..a59f1dbe0 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuUncapturedErrorEvent.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuUncapturedErrorEvent.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuUncapturedErrorEvent`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuUncapturedErrorEvent; # [wasm_bindgen (structural , method , getter , js_class = "GPUUncapturedErrorEvent" , js_name = error)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuError`, `GpuUncapturedErrorEvent`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn error(this: &GpuUncapturedErrorEvent) -> GpuError; #[wasm_bindgen(catch, constructor, js_class = "GPUUncapturedErrorEvent")] @@ -57,7 +57,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuUncapturedErrorEvent`, `GpuUncapturedErrorEventInit`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new( type_: &str, gpu_uncaptured_error_event_init_dict: &GpuUncapturedErrorEventInit, diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuUncapturedErrorEventInit.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuUncapturedErrorEventInit.rs index 555607c31..32597521e 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuUncapturedErrorEventInit.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuUncapturedErrorEventInit.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuUncapturedErrorEventInit`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuUncapturedErrorEventInit; #[doc = "Get the `bubbles` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuUncapturedErrorEventInit`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "bubbles")] pub fn get_bubbles(this: &GpuUncapturedErrorEventInit) -> Option; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuUncapturedErrorEventInit`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "bubbles")] pub fn set_bubbles(this: &GpuUncapturedErrorEventInit, val: bool); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuUncapturedErrorEventInit`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "cancelable")] pub fn get_cancelable(this: &GpuUncapturedErrorEventInit) -> Option; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuUncapturedErrorEventInit`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "cancelable")] pub fn set_cancelable(this: &GpuUncapturedErrorEventInit, val: bool); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuUncapturedErrorEventInit`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "composed")] pub fn get_composed(this: &GpuUncapturedErrorEventInit) -> Option; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuUncapturedErrorEventInit`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "composed")] pub fn set_composed(this: &GpuUncapturedErrorEventInit, val: bool); @@ -95,7 +95,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuError`, `GpuUncapturedErrorEventInit`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "error")] pub fn get_error(this: &GpuUncapturedErrorEventInit) -> GpuError; @@ -104,7 +104,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuError`, `GpuUncapturedErrorEventInit`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "error")] pub fn set_error(this: &GpuUncapturedErrorEventInit, val: &GpuError); } @@ -115,7 +115,7 @@ impl GpuUncapturedErrorEventInit { #[doc = "*This API requires the following crate features to be activated: `GpuError`, `GpuUncapturedErrorEventInit`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(error: &GpuError) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuValidationError.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuValidationError.rs index 87ef8a5b6..f29b3b861 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuValidationError.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuValidationError.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuValidationError`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuValidationError; #[wasm_bindgen(catch, constructor, js_class = "GPUValidationError")] @@ -46,6 +46,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuValidationError`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(message: &str) -> Result; } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuVertexAttribute.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuVertexAttribute.rs index a8260b418..298b21340 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuVertexAttribute.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuVertexAttribute.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuVertexAttribute`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuVertexAttribute; #[doc = "Get the `format` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuVertexAttribute`, `GpuVertexFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "format")] pub fn get_format(this: &GpuVertexAttribute) -> GpuVertexFormat; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuVertexAttribute`, `GpuVertexFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "format")] pub fn set_format(this: &GpuVertexAttribute, val: GpuVertexFormat); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuVertexAttribute`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "offset")] pub fn get_offset(this: &GpuVertexAttribute) -> f64; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuVertexAttribute`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "offset")] pub fn set_offset(this: &GpuVertexAttribute, val: f64); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuVertexAttribute`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "shaderLocation")] pub fn get_shader_location(this: &GpuVertexAttribute) -> u32; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuVertexAttribute`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "shaderLocation")] pub fn set_shader_location(this: &GpuVertexAttribute, val: u32); } @@ -97,7 +97,7 @@ impl GpuVertexAttribute { #[doc = "*This API requires the following crate features to be activated: `GpuVertexAttribute`, `GpuVertexFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(format: GpuVertexFormat, offset: f64, shader_location: u32) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuVertexBufferLayout.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuVertexBufferLayout.rs index d05413bd9..9ebf3e6ec 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuVertexBufferLayout.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuVertexBufferLayout.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuVertexBufferLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuVertexBufferLayout; #[doc = "Get the `arrayStride` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuVertexBufferLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "arrayStride")] pub fn get_array_stride(this: &GpuVertexBufferLayout) -> f64; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuVertexBufferLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "arrayStride")] pub fn set_array_stride(this: &GpuVertexBufferLayout, val: f64); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuVertexBufferLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "attributes")] pub fn get_attributes(this: &GpuVertexBufferLayout) -> ::js_sys::Array; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuVertexBufferLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "attributes")] pub fn set_attributes(this: &GpuVertexBufferLayout, val: &::wasm_bindgen::JsValue); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuVertexBufferLayout`, `GpuVertexStepMode`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "stepMode")] pub fn get_step_mode(this: &GpuVertexBufferLayout) -> Option; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuVertexBufferLayout`, `GpuVertexStepMode`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "stepMode")] pub fn set_step_mode(this: &GpuVertexBufferLayout, val: GpuVertexStepMode); } @@ -97,7 +97,7 @@ impl GpuVertexBufferLayout { #[doc = "*This API requires the following crate features to be activated: `GpuVertexBufferLayout`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(array_stride: f64, attributes: &::wasm_bindgen::JsValue) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuVertexFormat.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuVertexFormat.rs index 67eb10514..167c67a60 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuVertexFormat.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuVertexFormat.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuVertexFormat`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuVertexFormat { Uint8 = "uint8", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuVertexState.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuVertexState.rs index faac3a11b..a60ef9e6b 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuVertexState.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuVertexState.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -33,7 +33,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuVertexState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type GpuVertexState; #[doc = "Get the `constants` field of this object."] @@ -41,7 +41,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuVertexState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "constants")] pub fn get_constants(this: &GpuVertexState) -> Option<::js_sys::Object>; @@ -50,7 +50,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuVertexState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "constants")] pub fn set_constants(this: &GpuVertexState, val: &::js_sys::Object); @@ -59,7 +59,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuVertexState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "entryPoint")] pub fn get_entry_point(this: &GpuVertexState) -> Option<::alloc::string::String>; @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuVertexState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "entryPoint")] pub fn set_entry_point(this: &GpuVertexState, val: &str); @@ -77,7 +77,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuShaderModule`, `GpuVertexState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "module")] pub fn get_module(this: &GpuVertexState) -> GpuShaderModule; @@ -86,7 +86,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuShaderModule`, `GpuVertexState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "module")] pub fn set_module(this: &GpuVertexState, val: &GpuShaderModule); @@ -95,7 +95,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuVertexState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, getter = "buffers")] pub fn get_buffers(this: &GpuVertexState) -> Option<::js_sys::Array>; @@ -104,7 +104,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `GpuVertexState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[wasm_bindgen(method, setter = "buffers")] pub fn set_buffers(this: &GpuVertexState, val: &::wasm_bindgen::JsValue); } @@ -115,7 +115,7 @@ impl GpuVertexState { #[doc = "*This API requires the following crate features to be activated: `GpuShaderModule`, `GpuVertexState`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn new(module: &GpuShaderModule) -> Self { #[allow(unused_mut)] let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new()); diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuVertexStepMode.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuVertexStepMode.rs index 556609d54..29a0b857b 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuVertexStepMode.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_GpuVertexStepMode.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use wasm_bindgen::prelude::*; @@ -29,7 +29,7 @@ use wasm_bindgen::prelude::*; #[doc = "*This API requires the following crate features to be activated: `GpuVertexStepMode`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GpuVertexStepMode { Vertex = "vertex", diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_WgslLanguageFeatures.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_WgslLanguageFeatures.rs index cd0cd7704..d6fe55d0c 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_WgslLanguageFeatures.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_WgslLanguageFeatures.rs @@ -16,9 +16,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports)] #![allow(clippy::all)] use super::*; @@ -35,7 +35,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `WgslLanguageFeatures`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub type WgslLanguageFeatures; # [wasm_bindgen (structural , method , getter , js_class = "WGSLLanguageFeatures" , js_name = size)] @@ -46,7 +46,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `WgslLanguageFeatures`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn size(this: &WgslLanguageFeatures) -> u32; # [wasm_bindgen (method , structural , js_class = "WGSLLanguageFeatures" , js_name = entries)] @@ -57,7 +57,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `WgslLanguageFeatures`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn entries(this: &WgslLanguageFeatures) -> ::js_sys::Iterator; # [wasm_bindgen (catch , method , structural , js_class = "WGSLLanguageFeatures" , js_name = forEach)] @@ -68,7 +68,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `WgslLanguageFeatures`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn for_each( this: &WgslLanguageFeatures, callback: &::js_sys::Function, @@ -82,7 +82,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `WgslLanguageFeatures`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn has(this: &WgslLanguageFeatures, value: &str) -> bool; # [wasm_bindgen (method , structural , js_class = "WGSLLanguageFeatures" , js_name = keys)] @@ -93,7 +93,7 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `WgslLanguageFeatures`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn keys(this: &WgslLanguageFeatures) -> ::js_sys::Iterator; # [wasm_bindgen (method , structural , js_class = "WGSLLanguageFeatures" , js_name = values)] @@ -104,6 +104,6 @@ extern "C" { #[doc = "*This API requires the following crate features to be activated: `WgslLanguageFeatures`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub fn values(this: &WgslLanguageFeatures) -> ::js_sys::Iterator; } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/gen_gpu_map_mode.rs b/wgpu/src/backend/webgpu/webgpu_sys/gen_gpu_map_mode.rs index c63dbff35..4b620cb07 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/gen_gpu_map_mode.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/gen_gpu_map_mode.rs @@ -16,13 +16,13 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] -#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] +#[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub mod gpu_map_mode { #![allow(unused_imports)] #![allow(clippy::all)] @@ -34,7 +34,7 @@ pub mod gpu_map_mode { #[doc = "*This API requires the following crate features to be activated: `gpu_map_mode`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub const READ: u32 = 1u64 as u32; #[doc = "The `GPUMapMode.WRITE` const."] @@ -42,6 +42,6 @@ pub mod gpu_map_mode { #[doc = "*This API requires the following crate features to be activated: `gpu_map_mode`*"] #[doc = ""] #[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"] - #[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html)*"] + #[doc = "[described in the `wasm-bindgen` guide](https://wasm-bindgen.github.io/wasm-bindgen/web-sys/unstable-apis.html)*"] pub const WRITE: u32 = 2u64 as u32; } diff --git a/wgpu/src/backend/webgpu/webgpu_sys/mod.rs b/wgpu/src/backend/webgpu/webgpu_sys/mod.rs index 3e703d3bb..49bcd32fd 100644 --- a/wgpu/src/backend/webgpu/webgpu_sys/mod.rs +++ b/wgpu/src/backend/webgpu/webgpu_sys/mod.rs @@ -19,9 +19,9 @@ // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // -// If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. +// If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. // -// This file was generated by the `cargo xtask vendor-web-sys --version 0.2.97` command. +// This file was generated by the `cargo xtask vendor-web-sys --version f7e0467c4b4d88303eb79fba485320cfb4dfdd58` command. #![allow(unused_imports, non_snake_case)] use web_sys::{Event, EventTarget}; diff --git a/wgpu/src/backend/wgpu_core.rs b/wgpu/src/backend/wgpu_core.rs index 926d7ddc2..2c5b3fea7 100644 --- a/wgpu/src/backend/wgpu_core.rs +++ b/wgpu/src/backend/wgpu_core.rs @@ -1,5 +1,5 @@ use alloc::{ - borrow::Cow::Borrowed, + borrow::Cow::{self, Borrowed}, boxed::Box, format, string::{String, ToString as _}, @@ -7,21 +7,35 @@ use alloc::{ vec, vec::Vec, }; -use core::{error::Error, fmt, future::ready, ops::Range, pin::Pin, ptr::NonNull, slice}; +use core::{ + error::Error, + fmt, + future::ready, + ops::{Deref, Range}, + pin::Pin, + ptr::NonNull, + slice, +}; use arrayvec::ArrayVec; -use parking_lot::Mutex; use smallvec::SmallVec; -use wgc::{command::bundle_ffi::*, error::ContextErrorSource, pipeline::CreateShaderModuleError}; -use wgt::WasmNotSendSync; +use wgc::{ + command::bundle_ffi::*, error::ContextErrorSource, pipeline::CreateShaderModuleError, + resource::BlasPrepareCompactResult, +}; +use wgt::{ + error::{ErrorType, WebGpuError}, + WasmNotSendSync, +}; use crate::{ api, - dispatch::{self, BufferMappedRangeInterface}, - BindingResource, BufferBinding, BufferDescriptor, CompilationInfo, CompilationMessage, + dispatch::{self, BlasCompactCallback, BufferMappedRangeInterface}, + BindingResource, Blas, BufferBinding, BufferDescriptor, CompilationInfo, CompilationMessage, CompilationMessageType, ErrorSource, Features, Label, LoadOp, MapMode, Operations, - ShaderSource, SurfaceTargetUnsafe, TextureDescriptor, + ShaderSource, SurfaceTargetUnsafe, TextureDescriptor, Tlas, }; +use crate::{dispatch::DispatchAdapter, util::Mutex}; #[derive(Clone)] pub struct ContextWgpuCore(Arc); @@ -41,7 +55,7 @@ impl fmt::Debug for ContextWgpuCore { } impl ContextWgpuCore { - pub unsafe fn from_hal_instance(hal_instance: A::Instance) -> Self { + pub unsafe fn from_hal_instance(hal_instance: A::Instance) -> Self { Self(unsafe { Arc::new(wgc::global::Global::from_hal_instance::( "wgpu", @@ -53,7 +67,7 @@ impl ContextWgpuCore { /// # Safety /// /// - The raw instance handle returned must not be manually destroyed. - pub unsafe fn instance_as_hal(&self) -> Option<&A::Instance> { + pub unsafe fn instance_as_hal(&self) -> Option<&A::Instance> { unsafe { self.0.instance_as_hal::() } } @@ -66,40 +80,28 @@ impl ContextWgpuCore { self.0.enumerate_adapters(backends) } - pub unsafe fn create_adapter_from_hal( + pub unsafe fn create_adapter_from_hal( &self, hal_adapter: hal::ExposedAdapter, ) -> wgc::id::AdapterId { unsafe { self.0.create_adapter_from_hal(hal_adapter.into(), None) } } - pub unsafe fn adapter_as_hal< - A: wgc::hal_api::HalApi, - F: FnOnce(Option<&A::Adapter>) -> R, - R, - >( + pub unsafe fn adapter_as_hal( &self, adapter: &CoreAdapter, - hal_adapter_callback: F, - ) -> R { - unsafe { - self.0 - .adapter_as_hal::(adapter.id, hal_adapter_callback) - } + ) -> Option + WasmNotSendSync> { + unsafe { self.0.adapter_as_hal::(adapter.id) } } - pub unsafe fn buffer_as_hal) -> R, R>( + pub unsafe fn buffer_as_hal( &self, buffer: &CoreBuffer, - hal_buffer_callback: F, - ) -> R { - unsafe { - self.0 - .buffer_as_hal::(buffer.id, hal_buffer_callback) - } + ) -> Option> { + unsafe { self.0.buffer_as_hal::(buffer.id) } } - pub unsafe fn create_device_from_hal( + pub unsafe fn create_device_from_hal( &self, adapter: &CoreAdapter, hal_device: hal::OpenDevice, @@ -138,7 +140,7 @@ impl ContextWgpuCore { Ok((device, queue)) } - pub unsafe fn create_texture_from_hal( + pub unsafe fn create_texture_from_hal( &self, hal_texture: A::Texture, device: &CoreDevice, @@ -164,7 +166,13 @@ impl ContextWgpuCore { } } - pub unsafe fn create_buffer_from_hal( + /// # Safety + /// + /// - `hal_buffer` must be created from `device`. + /// - `hal_buffer` must be created respecting `desc` + /// - `hal_buffer` must be initialized + /// - `hal_buffer` must not have zero size. + pub unsafe fn create_buffer_from_hal( &self, hal_buffer: A::Buffer, device: &CoreDevice, @@ -193,65 +201,37 @@ impl ContextWgpuCore { } } - pub unsafe fn device_as_hal) -> R, R>( + pub unsafe fn device_as_hal( &self, device: &CoreDevice, - hal_device_callback: F, - ) -> R { - unsafe { - self.0 - .device_as_hal::(device.id, hal_device_callback) - } + ) -> Option> { + unsafe { self.0.device_as_hal::(device.id) } } - pub unsafe fn surface_as_hal< - A: wgc::hal_api::HalApi, - F: FnOnce(Option<&A::Surface>) -> R, - R, - >( + pub unsafe fn surface_as_hal( &self, surface: &CoreSurface, - hal_surface_callback: F, - ) -> R { - unsafe { - self.0 - .surface_as_hal::(surface.id, hal_surface_callback) - } + ) -> Option> { + unsafe { self.0.surface_as_hal::(surface.id) } } - pub unsafe fn texture_as_hal< - A: wgc::hal_api::HalApi, - F: FnOnce(Option<&A::Texture>) -> R, - R, - >( + pub unsafe fn texture_as_hal( &self, texture: &CoreTexture, - hal_texture_callback: F, - ) -> R { - unsafe { - self.0 - .texture_as_hal::(texture.id, hal_texture_callback) - } + ) -> Option> { + unsafe { self.0.texture_as_hal::(texture.id) } } - pub unsafe fn texture_view_as_hal< - A: wgc::hal_api::HalApi, - F: FnOnce(Option<&A::TextureView>) -> R, - R, - >( + pub unsafe fn texture_view_as_hal( &self, texture_view: &CoreTextureView, - hal_texture_view_callback: F, - ) -> R { - unsafe { - self.0 - .texture_view_as_hal::(texture_view.id, hal_texture_view_callback) - } + ) -> Option> { + unsafe { self.0.texture_view_as_hal::(texture_view.id) } } /// This method will start the wgpu_core level command recording. pub unsafe fn command_encoder_as_hal_mut< - A: wgc::hal_api::HalApi, + A: hal::Api, F: FnOnce(Option<&mut A::CommandEncoder>) -> R, R, >( @@ -267,6 +247,20 @@ impl ContextWgpuCore { } } + pub unsafe fn blas_as_hal( + &self, + blas: &CoreBlas, + ) -> Option> { + unsafe { self.0.blas_as_hal::(blas.id) } + } + + pub unsafe fn tlas_as_hal( + &self, + tlas: &CoreTlas, + ) -> Option> { + unsafe { self.0.tlas_as_hal::(tlas.id) } + } + pub fn generate_report(&self) -> wgc::global::GlobalReport { self.0.generate_report() } @@ -277,36 +271,46 @@ impl ContextWgpuCore { fn handle_error_inner( &self, sink_mutex: &Mutex, + error_type: ErrorType, source: ContextErrorSource, label: Label<'_>, fn_ident: &'static str, ) { - let source_error: ErrorSource = Box::new(wgc::error::ContextError { + let source: ErrorSource = Box::new(wgc::error::ContextError { fn_ident, source, label: label.unwrap_or_default().to_string(), }); - let mut sink = sink_mutex.lock(); - let mut source_opt: Option<&(dyn Error + 'static)> = Some(&*source_error); - let error = loop { - if let Some(source) = source_opt { - if let Some(wgc::device::DeviceError::OutOfMemory) = - source.downcast_ref::() - { - break crate::Error::OutOfMemory { - source: source_error, - }; + let final_error_handling = { + let mut sink = sink_mutex.lock(); + let description = || self.format_error(&*source); + let error = match error_type { + ErrorType::Internal => { + let description = description(); + crate::Error::Internal { + source, + description, + } } - source_opt = source.source(); - } else { - // Otherwise, it is a validation error - break crate::Error::Validation { - description: self.format_error(&*source_error), - source: source_error, - }; - } + ErrorType::OutOfMemory => crate::Error::OutOfMemory { source }, + ErrorType::Validation => { + let description = description(); + crate::Error::Validation { + source, + description, + } + } + ErrorType::DeviceLost => return, // will be surfaced via callback + }; + sink.handle_error_or_return_handler(error) }; - sink.handle_error(error); + + if let Some(f) = final_error_handling { + // If the user has provided their own `uncaptured_handler` callback, invoke it now, + // having released our lock on `sink_mutex`. See the comments on + // `handle_error_or_return_handler` for details. + f(); + } } #[inline] @@ -314,11 +318,12 @@ impl ContextWgpuCore { fn handle_error( &self, sink_mutex: &Mutex, - source: impl Error + WasmNotSendSync + 'static, + source: impl WebGpuError + WasmNotSendSync + 'static, label: Label<'_>, fn_ident: &'static str, ) { - self.handle_error_inner(sink_mutex, Box::new(source), label, fn_ident) + let error_type = source.webgpu_error_type(); + self.handle_error_inner(sink_mutex, error_type, Box::new(source), label, fn_ident) } #[inline] @@ -326,10 +331,11 @@ impl ContextWgpuCore { fn handle_error_nolabel( &self, sink_mutex: &Mutex, - source: impl Error + WasmNotSendSync + 'static, + source: impl WebGpuError + WasmNotSendSync + 'static, fn_ident: &'static str, ) { - self.handle_error_inner(sink_mutex, Box::new(source), None, fn_ident) + let error_type = source.webgpu_error_type(); + self.handle_error_inner(sink_mutex, error_type, Box::new(source), None, fn_ident) } #[track_caller] @@ -372,17 +378,18 @@ impl ContextWgpuCore { format!("Validation Error\n\nCaused by:\n{output}") } - pub unsafe fn queue_as_hal) -> R, R>( + pub unsafe fn queue_as_hal( &self, queue: &CoreQueue, - hal_queue_callback: F, - ) -> R { - unsafe { self.0.queue_as_hal::(queue.id, hal_queue_callback) } + ) -> Option + WasmNotSendSync> { + unsafe { self.0.queue_as_hal::(queue.id) } } } -fn map_buffer_copy_view(view: crate::TexelCopyBufferInfo<'_>) -> wgc::command::TexelCopyBufferInfo { - wgc::command::TexelCopyBufferInfo { +fn map_buffer_copy_view( + view: crate::TexelCopyBufferInfo<'_>, +) -> wgt::TexelCopyBufferInfo { + wgt::TexelCopyBufferInfo { buffer: view.buffer.inner.as_core().id, layout: view.layout, } @@ -390,8 +397,8 @@ fn map_buffer_copy_view(view: crate::TexelCopyBufferInfo<'_>) -> wgc::command::T fn map_texture_copy_view( view: crate::TexelCopyTextureInfo<'_>, -) -> wgc::command::TexelCopyTextureInfo { - wgc::command::TexelCopyTextureInfo { +) -> wgt::TexelCopyTextureInfo { + wgt::TexelCopyTextureInfo { texture: view.texture.inner.as_core().id, mip_level: view.mip_level, origin: view.origin, @@ -399,14 +406,11 @@ fn map_texture_copy_view( } } -#[cfg_attr( - any(not(target_arch = "wasm32"), target_os = "emscripten"), - expect(unused) -)] +#[cfg_attr(not(webgl), expect(unused))] fn map_texture_tagged_copy_view( view: crate::CopyExternalImageDestInfo<&api::Texture>, -) -> wgc::command::CopyExternalImageDestInfo { - wgc::command::CopyExternalImageDestInfo { +) -> wgt::CopyExternalImageDestInfo { + wgt::CopyExternalImageDestInfo { texture: view.texture.inner.as_core().id, mip_level: view.mip_level, origin: view.origin, @@ -503,6 +507,12 @@ pub struct CoreTextureView { id: wgc::id::TextureViewId, } +#[derive(Debug)] +pub struct CoreExternalTexture { + pub(crate) context: ContextWgpuCore, + id: wgc::id::ExternalTextureId, +} + #[derive(Debug)] pub struct CoreSampler { pub(crate) context: ContextWgpuCore, @@ -587,14 +597,13 @@ pub struct CoreCommandEncoder { pub(crate) context: ContextWgpuCore, id: wgc::id::CommandEncoderId, error_sink: ErrorSink, - open: bool, } #[derive(Debug)] pub struct CoreBlas { pub(crate) context: ContextWgpuCore, id: wgc::id::BlasId, - // error_sink: ErrorSink, + error_sink: ErrorSink, } #[derive(Debug)] @@ -619,7 +628,7 @@ struct ErrorScope { struct ErrorSinkRaw { scopes: Vec, - uncaptured_handler: Option>, + uncaptured_handler: Option>, } impl ErrorSinkRaw { @@ -630,8 +639,18 @@ impl ErrorSinkRaw { } } + /// Deliver the error to + /// + /// * the innermost error scope, if any, or + /// * the uncaptured error handler, if there is one, or + /// * [`default_error_handler()`]. + /// + /// If a closure is returned, the caller should call it immediately after dropping the + /// [`ErrorSink`] mutex guard. This makes sure that the user callback is not called with + /// a wgpu mutex held. #[track_caller] - fn handle_error(&mut self, err: crate::Error) { + #[must_use] + fn handle_error_or_return_handler(&mut self, err: crate::Error) -> Option { let filter = match err { crate::Error::OutOfMemory { .. } => crate::ErrorFilter::OutOfMemory, crate::Error::Validation { .. } => crate::ErrorFilter::Validation, @@ -647,13 +666,15 @@ impl ErrorSinkRaw { if scope.error.is_none() { scope.error = Some(err); } + None } None => { - if let Some(custom_handler) = self.uncaptured_handler.as_ref() { - (custom_handler)(err); + if let Some(custom_handler) = &self.uncaptured_handler { + let custom_handler = Arc::clone(custom_handler); + Some(move || (custom_handler)(err)) } else { // direct call preserves #[track_caller] where dyn can't - default_error_handler(err); + default_error_handler(err) } } } @@ -667,7 +688,7 @@ impl fmt::Debug for ErrorSinkRaw { } #[track_caller] -fn default_error_handler(err: crate::Error) { +fn default_error_handler(err: crate::Error) -> ! { log::error!("Handling wgpu errors as fatal by default"); panic!("wgpu error: {err}\n"); } @@ -736,6 +757,7 @@ crate::cmp::impl_eq_ord_hash_proxy!(CoreTextureView => .id); crate::cmp::impl_eq_ord_hash_proxy!(CoreSampler => .id); crate::cmp::impl_eq_ord_hash_proxy!(CoreBuffer => .id); crate::cmp::impl_eq_ord_hash_proxy!(CoreTexture => .id); +crate::cmp::impl_eq_ord_hash_proxy!(CoreExternalTexture => .id); crate::cmp::impl_eq_ord_hash_proxy!(CoreBlas => .id); crate::cmp::impl_eq_ord_hash_proxy!(CoreTlas => .id); crate::cmp::impl_eq_ord_hash_proxy!(CoreQuerySet => .id); @@ -867,6 +889,12 @@ impl dispatch::InstanceInterface for ContextWgpuCore { crate::WgslLanguageFeatures::empty(), |acc, wle| { acc | match wle { + ImplementedLanguageExtension::ReadOnlyAndReadWriteStorageTextures => { + crate::WgslLanguageFeatures::ReadOnlyAndReadWriteStorageTextures + } + ImplementedLanguageExtension::Packed4x8IntegerDotProduct => { + crate::WgslLanguageFeatures::Packed4x8IntegerDotProduct + } ImplementedLanguageExtension::PointerCompositeAccess => { crate::WgslLanguageFeatures::PointerCompositeAccess } @@ -874,6 +902,24 @@ impl dispatch::InstanceInterface for ContextWgpuCore { }, ) } + + fn enumerate_adapters( + &self, + backends: crate::Backends, + ) -> Pin> { + let adapters: Vec = self + .enumerate_adapters(backends) + .into_iter() + .map(|adapter| { + let core = crate::backend::wgpu_core::CoreAdapter { + context: self.clone(), + id: adapter, + }; + core.into() + }) + .collect(); + Box::pin(ready(adapters)) + } } impl dispatch::AdapterInterface for CoreAdapter { @@ -1046,36 +1092,30 @@ impl dispatch::DeviceInterface for CoreDevice { .into() } - unsafe fn create_shader_module_spirv( + unsafe fn create_shader_module_passthrough( &self, - desc: &crate::ShaderModuleDescriptorSpirV<'_>, + desc: &crate::ShaderModuleDescriptorPassthrough<'_>, ) -> dispatch::DispatchShaderModule { - let descriptor = wgc::pipeline::ShaderModuleDescriptor { - label: desc.label.map(Borrowed), - // Doesn't matter the value since spirv shaders aren't mutated to include - // runtime checks - runtime_checks: wgt::ShaderRuntimeChecks::unchecked(), - }; + let desc = desc.map_label(|l| l.map(Cow::from)); let (id, error) = unsafe { - self.context.0.device_create_shader_module_spirv( - self.id, - &descriptor, - Borrowed(&desc.source), - None, - ) + self.context + .0 + .device_create_shader_module_passthrough(self.id, &desc, None) }; + let compilation_info = match error { Some(cause) => { self.context.handle_error( &self.error_sink, cause.clone(), - desc.label, - "Device::create_shader_module_spirv", + desc.label.as_deref(), + "Device::create_shader_module_passthrough", ); CompilationInfo::from(cause) } None => CompilationInfo { messages: vec![] }, }; + CoreShaderModule { context: self.context.clone(), id, @@ -1188,9 +1228,12 @@ impl dispatch::DeviceInterface for CoreDevice { } BindingResource::AccelerationStructure(acceleration_structure) => { bm::BindingResource::AccelerationStructure( - acceleration_structure.shared.inner.as_core().id, + acceleration_structure.inner.as_core().id, ) } + BindingResource::ExternalTexture(external_texture) => { + bm::BindingResource::ExternalTexture(external_texture.inner.as_core().id) + } }, }) .collect::>(); @@ -1324,17 +1367,113 @@ impl dispatch::DeviceInterface for CoreDevice { targets: Borrowed(frag.targets), } }), + multiview_mask: desc.multiview_mask, + cache: desc.cache.map(|cache| cache.inner.as_core().id), + }; + + let (id, error) = self + .context + .0 + .device_create_render_pipeline(self.id, &descriptor, None); + if let Some(cause) = error { + if let wgc::pipeline::CreateRenderPipelineError::Internal { stage, ref error } = cause { + log::error!("Shader translation error for stage {stage:?}: {error}"); + log::error!("Please report it to https://github.com/gfx-rs/wgpu"); + } + self.context.handle_error( + &self.error_sink, + cause, + desc.label, + "Device::create_render_pipeline", + ); + } + CoreRenderPipeline { + context: self.context.clone(), + id, + error_sink: Arc::clone(&self.error_sink), + } + .into() + } + + fn create_mesh_pipeline( + &self, + desc: &crate::MeshPipelineDescriptor<'_>, + ) -> dispatch::DispatchRenderPipeline { + use wgc::pipeline as pipe; + + let mesh_constants = desc + .mesh + .compilation_options + .constants + .iter() + .map(|&(key, value)| (String::from(key), value)) + .collect(); + let descriptor = pipe::MeshPipelineDescriptor { + label: desc.label.map(Borrowed), + task: desc.task.as_ref().map(|task| { + let task_constants = task + .compilation_options + .constants + .iter() + .map(|&(key, value)| (String::from(key), value)) + .collect(); + pipe::TaskState { + stage: pipe::ProgrammableStageDescriptor { + module: task.module.inner.as_core().id, + entry_point: task.entry_point.map(Borrowed), + constants: task_constants, + zero_initialize_workgroup_memory: desc + .mesh + .compilation_options + .zero_initialize_workgroup_memory, + }, + } + }), + mesh: pipe::MeshState { + stage: pipe::ProgrammableStageDescriptor { + module: desc.mesh.module.inner.as_core().id, + entry_point: desc.mesh.entry_point.map(Borrowed), + constants: mesh_constants, + zero_initialize_workgroup_memory: desc + .mesh + .compilation_options + .zero_initialize_workgroup_memory, + }, + }, + layout: desc.layout.map(|layout| layout.inner.as_core().id), + primitive: desc.primitive, + depth_stencil: desc.depth_stencil.clone(), + multisample: desc.multisample, + fragment: desc.fragment.as_ref().map(|frag| { + let frag_constants = frag + .compilation_options + .constants + .iter() + .map(|&(key, value)| (String::from(key), value)) + .collect(); + pipe::FragmentState { + stage: pipe::ProgrammableStageDescriptor { + module: frag.module.inner.as_core().id, + entry_point: frag.entry_point.map(Borrowed), + constants: frag_constants, + zero_initialize_workgroup_memory: frag + .compilation_options + .zero_initialize_workgroup_memory, + }, + targets: Borrowed(frag.targets), + } + }), multiview: desc.multiview, cache: desc.cache.map(|cache| cache.inner.as_core().id), }; - let (id, error) = - self.context - .0 - .device_create_render_pipeline(self.id, &descriptor, None, None); + let (id, error) = self + .context + .0 + .device_create_mesh_pipeline(self.id, &descriptor, None); if let Some(cause) = error { if let wgc::pipeline::CreateRenderPipelineError::Internal { stage, ref error } = cause { - log::error!("Shader translation error for stage {:?}: {}", stage, error); + log::error!("Shader translation error for stage {stage:?}: {error}"); log::error!("Please report it to https://github.com/gfx-rs/wgpu"); } self.context.handle_error( @@ -1379,10 +1518,10 @@ impl dispatch::DeviceInterface for CoreDevice { cache: desc.cache.map(|cache| cache.inner.as_core().id), }; - let (id, error) = - self.context - .0 - .device_create_compute_pipeline(self.id, &descriptor, None, None); + let (id, error) = self + .context + .0 + .device_create_compute_pipeline(self.id, &descriptor, None); if let Some(cause) = error { if let wgc::pipeline::CreateComputePipelineError::Internal(ref error) = cause { log::error!( @@ -1480,6 +1619,36 @@ impl dispatch::DeviceInterface for CoreDevice { .into() } + fn create_external_texture( + &self, + desc: &crate::ExternalTextureDescriptor<'_>, + planes: &[&crate::TextureView], + ) -> dispatch::DispatchExternalTexture { + let wgt_desc = desc.map_label(|l| l.map(Borrowed)); + let planes = planes + .iter() + .map(|plane| plane.inner.as_core().id) + .collect::>(); + let (id, error) = self + .context + .0 + .device_create_external_texture(self.id, &wgt_desc, &planes, None); + if let Some(cause) = error { + self.context.handle_error( + &self.error_sink, + cause, + desc.label, + "Device::create_external_texture", + ); + } + + CoreExternalTexture { + context: self.context.clone(), + id, + } + .into() + } + fn create_blas( &self, desc: &crate::CreateBlasDescriptor<'_>, @@ -1497,7 +1666,7 @@ impl dispatch::DeviceInterface for CoreDevice { CoreBlas { context: self.context.clone(), id, - // error_sink: Arc::clone(&self.error_sink), + error_sink: Arc::clone(&self.error_sink), } .into(), ) @@ -1595,7 +1764,6 @@ impl dispatch::DeviceInterface for CoreDevice { context: self.context.clone(), id, error_sink: Arc::clone(&self.error_sink), - open: true, } .into() } @@ -1611,7 +1779,7 @@ impl dispatch::DeviceInterface for CoreDevice { sample_count: desc.sample_count, multiview: desc.multiview, }; - let encoder = match wgc::command::RenderBundleEncoder::new(&descriptor, self.id, None) { + let encoder = match wgc::command::RenderBundleEncoder::new(&descriptor, self.id) { Ok(encoder) => encoder, Err(e) => panic!("Error in Device::create_render_bundle_encoder: {e}"), }; @@ -1630,7 +1798,7 @@ impl dispatch::DeviceInterface for CoreDevice { .device_set_device_lost_closure(self.id, device_lost_callback); } - fn on_uncaptured_error(&self, handler: Box) { + fn on_uncaptured_error(&self, handler: Arc) { let mut error_sink = self.error_sink.lock(); error_sink.uncaptured_handler = Some(handler); } @@ -1649,17 +1817,24 @@ impl dispatch::DeviceInterface for CoreDevice { Box::pin(ready(scope.error)) } - fn start_capture(&self) { - self.context.0.device_start_capture(self.id); + unsafe fn start_graphics_debugger_capture(&self) { + unsafe { + self.context + .0 + .device_start_graphics_debugger_capture(self.id) + }; } - fn stop_capture(&self) { - self.context.0.device_stop_capture(self.id); + unsafe fn stop_graphics_debugger_capture(&self) { + unsafe { + self.context + .0 + .device_stop_graphics_debugger_capture(self.id) + }; } - fn poll(&self, poll_type: crate::PollType) -> Result { - let maintain_inner = poll_type.map_index(|i| i.index); - match self.context.0.device_poll(self.id, maintain_inner) { + fn poll(&self, poll_type: wgt::PollType) -> Result { + match self.context.0.device_poll(self.id, poll_type) { Ok(status) => Ok(status), Err(err) => { if let Some(poll_error) = err.to_poll_error() { @@ -1815,13 +1990,17 @@ impl dispatch::QueueInterface for CoreQueue { } } - #[cfg(any(webgpu, webgl))] + // This method needs to exist if either webgpu or webgl is enabled, + // but we only actually have an implementation if webgl is enabled. + #[cfg(web)] + #[cfg_attr(not(webgl), expect(unused_variables))] fn copy_external_image_to_texture( &self, source: &crate::CopyExternalImageSourceInfo, dest: crate::CopyExternalImageDestInfo<&crate::api::Texture>, size: crate::Extent3d, ) { + #[cfg(webgl)] match self.context.0.queue_copy_external_image_to_texture( self.id, source, @@ -1870,6 +2049,27 @@ impl dispatch::QueueInterface for CoreQueue { .0 .queue_on_submitted_work_done(self.id, callback); } + + fn compact_blas(&self, blas: &dispatch::DispatchBlas) -> (Option, dispatch::DispatchBlas) { + let (id, handle, error) = + self.context + .0 + .queue_compact_blas(self.id, blas.as_core().id, None); + + if let Some(cause) = error { + self.context + .handle_error_nolabel(&self.error_sink, cause, "Queue::compact_blas"); + } + ( + handle, + CoreBlas { + context: self.context.clone(), + id, + error_sink: Arc::clone(&self.error_sink), + } + .into(), + ) + } } impl Drop for CoreQueue { @@ -1915,6 +2115,18 @@ impl Drop for CoreTextureView { } } +impl dispatch::ExternalTextureInterface for CoreExternalTexture { + fn destroy(&self) { + self.context.0.external_texture_destroy(self.id); + } +} + +impl Drop for CoreExternalTexture { + fn drop(&mut self) { + self.context.0.external_texture_drop(self.id); + } +} + impl dispatch::SamplerInterface for CoreSampler {} impl Drop for CoreSampler { @@ -1976,14 +2188,6 @@ impl dispatch::BufferInterface for CoreBuffer { } } - #[cfg(webgpu)] - fn get_mapped_range_as_array_buffer( - &self, - _sub_range: Range, - ) -> Option { - None - } - fn unmap(&self) { match self.context.0.buffer_unmap(self.id) { Ok(()) => (), @@ -1995,8 +2199,7 @@ impl dispatch::BufferInterface for CoreBuffer { } fn destroy(&self) { - // Per spec, no error to report. Even calling destroy multiple times is valid. - let _ = self.context.0.buffer_destroy(self.id); + self.context.0.buffer_destroy(self.id); } } @@ -2040,8 +2243,7 @@ impl dispatch::TextureInterface for CoreTexture { } fn destroy(&self) { - // Per spec, no error to report. Even calling destroy multiple times is valid. - let _ = self.context.0.texture_destroy(self.id); + self.context.0.texture_destroy(self.id); } } @@ -2051,7 +2253,39 @@ impl Drop for CoreTexture { } } -impl dispatch::BlasInterface for CoreBlas {} +impl dispatch::BlasInterface for CoreBlas { + fn prepare_compact_async(&self, callback: BlasCompactCallback) { + let callback: Option = + Some(Box::new(|status: BlasPrepareCompactResult| { + let res = status.map_err(|_| crate::BlasAsyncError); + callback(res); + })); + + match self.context.0.blas_prepare_compact_async(self.id, callback) { + Ok(_) => (), + Err(cause) => self.context.handle_error_nolabel( + &self.error_sink, + cause, + "Blas::prepare_compact_async", + ), + } + } + + fn ready_for_compaction(&self) -> bool { + match self.context.0.ready_for_compaction(self.id) { + Ok(ready) => ready, + Err(cause) => { + self.context.handle_error_nolabel( + &self.error_sink, + cause, + "Blas::ready_for_compaction", + ); + // A BLAS is definitely not ready for compaction if it's not valid + false + } + } + } +} impl Drop for CoreBlas { fn drop(&mut self) { @@ -2156,7 +2390,7 @@ impl dispatch::CommandEncoderInterface for CoreCommandEncoder { source_offset: crate::BufferAddress, destination: &dispatch::DispatchBuffer, destination_offset: crate::BufferAddress, - copy_size: crate::BufferAddress, + copy_size: Option, ) { let source = source.as_core(); let destination = destination.as_core(); @@ -2287,6 +2521,7 @@ impl dispatch::CommandEncoderInterface for CoreCommandEncoder { ca.as_ref() .map(|at| wgc::command::RenderPassColorAttachment { view: at.view.inner.as_core().id, + depth_slice: at.depth_slice, resolve_target: at.resolve_target.map(|view| view.inner.as_core().id), load_op: at.ops.load, store_op: at.ops.store, @@ -2319,6 +2554,7 @@ impl dispatch::CommandEncoderInterface for CoreCommandEncoder { color_attachments: Borrowed(&colors), depth_stencil_attachment: depth_stencil.as_ref(), occlusion_query_set: desc.occlusion_query_set.map(|qs| qs.inner.as_core().id), + multiview_mask: desc.multiview_mask, }, ); @@ -2342,11 +2578,13 @@ impl dispatch::CommandEncoderInterface for CoreCommandEncoder { fn finish(&mut self) -> dispatch::DispatchCommandBuffer { let descriptor = wgt::CommandBufferDescriptor::default(); - self.open = false; // prevent the drop - let (id, error) = self.context.0.command_encoder_finish(self.id, &descriptor); - if let Some(cause) = error { + let (id, opt_label_and_error) = self.context - .handle_error_nolabel(&self.error_sink, cause, "a CommandEncoder"); + .0 + .command_encoder_finish(self.id, &descriptor, None); + if let Some((label, cause)) = opt_label_and_error { + self.context + .handle_error(&self.error_sink, cause, Some(&label), "a CommandEncoder"); } CoreCommandBuffer { context: self.context.clone(), @@ -2477,47 +2715,21 @@ impl dispatch::CommandEncoderInterface for CoreCommandEncoder { } } - fn build_acceleration_structures_unsafe_tlas<'a>( + fn mark_acceleration_structures_built<'a>( &self, - blas: &mut dyn Iterator>, - tlas: &mut dyn Iterator>, + blas: &mut dyn Iterator, + tlas: &mut dyn Iterator, ) { - let blas = blas.map(|e: &crate::BlasBuildEntry<'_>| { - let geometries = match e.geometry { - crate::BlasGeometries::TriangleGeometries(ref triangle_geometries) => { - let iter = triangle_geometries.iter().map(|tg| { - wgc::ray_tracing::BlasTriangleGeometry { - vertex_buffer: tg.vertex_buffer.inner.as_core().id, - index_buffer: tg.index_buffer.map(|buf| buf.inner.as_core().id), - transform_buffer: tg.transform_buffer.map(|buf| buf.inner.as_core().id), - size: tg.size, - transform_buffer_offset: tg.transform_buffer_offset, - first_vertex: tg.first_vertex, - vertex_stride: tg.vertex_stride, - first_index: tg.first_index, - } - }); - wgc::ray_tracing::BlasGeometries::TriangleGeometries(Box::new(iter)) - } - }; - wgc::ray_tracing::BlasBuildEntry { - blas_id: e.blas.inner.as_core().id, - geometries, - } - }); - - let tlas = tlas.into_iter().map(|e: &crate::TlasBuildEntry<'a>| { - wgc::ray_tracing::TlasBuildEntry { - tlas_id: e.tlas.shared.inner.as_core().id, - instance_buffer_id: e.instance_buffer.inner.as_core().id, - instance_count: e.instance_count, - } - }); - + let blas = blas + .map(|b| b.inner.as_core().id) + .collect::>(); + let tlas = tlas + .map(|t| t.inner.as_core().id) + .collect::>(); if let Err(cause) = self .context .0 - .command_encoder_build_acceleration_structures_unsafe_tlas(self.id, blas, tlas) + .command_encoder_mark_acceleration_structures_built(self.id, &blas, &tlas) { self.context.handle_error_nolabel( &self.error_sink, @@ -2530,7 +2742,7 @@ impl dispatch::CommandEncoderInterface for CoreCommandEncoder { fn build_acceleration_structures<'a>( &self, blas: &mut dyn Iterator>, - tlas: &mut dyn Iterator, + tlas: &mut dyn Iterator, ) { let blas = blas.map(|e: &crate::BlasBuildEntry<'_>| { let geometries = match e.geometry { @@ -2571,7 +2783,7 @@ impl dispatch::CommandEncoderInterface for CoreCommandEncoder { }) }); wgc::ray_tracing::TlasPackage { - tlas_id: e.tlas.shared.inner.as_core().id, + tlas_id: e.inner.as_core().id, instances: Box::new(instances), lowest_unmodified: e.lowest_unmodified, } @@ -2624,9 +2836,7 @@ impl dispatch::CommandEncoderInterface for CoreCommandEncoder { impl Drop for CoreCommandEncoder { fn drop(&mut self) { - if self.open { - self.context.0.command_encoder_drop(self.id) - } + self.context.0.command_encoder_drop(self.id) } } @@ -3053,6 +3263,22 @@ impl dispatch::RenderPassInterface for CoreRenderPass { } } + fn draw_mesh_tasks(&mut self, group_count_x: u32, group_count_y: u32, group_count_z: u32) { + if let Err(cause) = self.context.0.render_pass_draw_mesh_tasks( + &mut self.pass, + group_count_x, + group_count_y, + group_count_z, + ) { + self.context.handle_error( + &self.error_sink, + cause, + self.pass.label(), + "RenderPass::draw_mesh_tasks", + ); + } + } + fn draw_indirect( &mut self, indirect_buffer: &dispatch::DispatchBuffer, @@ -3095,6 +3321,27 @@ impl dispatch::RenderPassInterface for CoreRenderPass { } } + fn draw_mesh_tasks_indirect( + &mut self, + indirect_buffer: &dispatch::DispatchBuffer, + indirect_offset: crate::BufferAddress, + ) { + let indirect_buffer = indirect_buffer.as_core(); + + if let Err(cause) = self.context.0.render_pass_draw_mesh_tasks_indirect( + &mut self.pass, + indirect_buffer.id, + indirect_offset, + ) { + self.context.handle_error( + &self.error_sink, + cause, + self.pass.label(), + "RenderPass::draw_mesh_tasks_indirect", + ); + } + } + fn multi_draw_indirect( &mut self, indirect_buffer: &dispatch::DispatchBuffer, @@ -3141,6 +3388,29 @@ impl dispatch::RenderPassInterface for CoreRenderPass { } } + fn multi_draw_mesh_tasks_indirect( + &mut self, + indirect_buffer: &dispatch::DispatchBuffer, + indirect_offset: crate::BufferAddress, + count: u32, + ) { + let indirect_buffer = indirect_buffer.as_core(); + + if let Err(cause) = self.context.0.render_pass_multi_draw_mesh_tasks_indirect( + &mut self.pass, + indirect_buffer.id, + indirect_offset, + count, + ) { + self.context.handle_error( + &self.error_sink, + cause, + self.pass.label(), + "RenderPass::multi_draw_mesh_tasks_indirect", + ); + } + } + fn multi_draw_indirect_count( &mut self, indirect_buffer: &dispatch::DispatchBuffer, @@ -3201,6 +3471,38 @@ impl dispatch::RenderPassInterface for CoreRenderPass { } } + fn multi_draw_mesh_tasks_indirect_count( + &mut self, + indirect_buffer: &dispatch::DispatchBuffer, + indirect_offset: crate::BufferAddress, + count_buffer: &dispatch::DispatchBuffer, + count_buffer_offset: crate::BufferAddress, + max_count: u32, + ) { + let indirect_buffer = indirect_buffer.as_core(); + let count_buffer = count_buffer.as_core(); + + if let Err(cause) = self + .context + .0 + .render_pass_multi_draw_mesh_tasks_indirect_count( + &mut self.pass, + indirect_buffer.id, + indirect_offset, + count_buffer.id, + count_buffer_offset, + max_count, + ) + { + self.context.handle_error( + &self.error_sink, + cause, + self.pass.label(), + "RenderPass::multi_draw_mesh_tasks_indirect_count", + ); + } + } + fn insert_debug_marker(&mut self, label: &str) { if let Err(cause) = self .context @@ -3621,4 +3923,9 @@ impl dispatch::BufferMappedRangeInterface for CoreBufferMappedRange { fn slice_mut(&mut self) -> &mut [u8] { unsafe { slice::from_raw_parts_mut(self.ptr.as_ptr(), self.size) } } + + #[cfg(webgpu)] + fn as_uint8array(&self) -> &js_sys::Uint8Array { + panic!("Only available on WebGPU") + } } diff --git a/wgpu/src/cmp.rs b/wgpu/src/cmp.rs index 07e05f49e..c2ec1265e 100644 --- a/wgpu/src/cmp.rs +++ b/wgpu/src/cmp.rs @@ -13,7 +13,7 @@ use core::{num::NonZeroU64, sync::atomic::Ordering}; static NEXT_ID: AtomicU64 = AtomicU64::new(1); -#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Identifier { inner: NonZeroU64, } diff --git a/wgpu/src/dispatch.rs b/wgpu/src/dispatch.rs index 07924d914..ed73932dd 100644 --- a/wgpu/src/dispatch.rs +++ b/wgpu/src/dispatch.rs @@ -12,7 +12,7 @@ #![allow(clippy::too_many_arguments)] // It's fine. #![allow(missing_docs, clippy::missing_safety_doc)] // Interfaces are not documented -use crate::{WasmNotSend, WasmNotSendSync}; +use crate::{Blas, Tlas, WasmNotSend, WasmNotSendSync}; use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec}; use core::{any::Any, fmt::Debug, future::Future, hash::Hash, ops::Range, pin::Pin}; @@ -39,6 +39,7 @@ trait_alias!(RequestAdapterFuture: Future> + WasmNotSend + 'static); trait_alias!(PopErrorScopeFuture: Future> + WasmNotSend + 'static); trait_alias!(ShaderCompilationInfoFuture: Future + WasmNotSend + 'static); +trait_alias!(EnumerateAdapterFuture: Future> + WasmNotSend + 'static); // We can't use trait aliases here, as you can't convert from a dyn Trait to dyn Supertrait _yet_. #[cfg(send_sync)] @@ -54,8 +55,25 @@ pub type BufferMapCallback = Box) #[cfg(not(send_sync))] pub type BufferMapCallback = Box) + 'static>; +#[cfg(send_sync)] +pub type BlasCompactCallback = Box) + Send + 'static>; +#[cfg(not(send_sync))] +pub type BlasCompactCallback = Box) + 'static>; + +// remove when rust 1.86 +#[cfg_attr(not(custom), expect(dead_code))] +pub trait AsAny { + fn as_any(&self) -> &dyn Any; +} + +impl AsAny for T { + fn as_any(&self) -> &dyn Any { + self + } +} + // Common traits on all the interface traits -trait_alias!(CommonTraits: Any + Debug + WasmNotSendSync); +trait_alias!(CommonTraits: AsAny + Any + Debug + WasmNotSendSync); pub trait InstanceInterface: CommonTraits { fn new(desc: &crate::InstanceDescriptor) -> Self @@ -76,6 +94,9 @@ pub trait InstanceInterface: CommonTraits { #[cfg(feature = "wgsl")] fn wgsl_language_features(&self) -> crate::WgslLanguageFeatures; + + fn enumerate_adapters(&self, backends: crate::Backends) + -> Pin>; } pub trait AdapterInterface: CommonTraits { @@ -111,10 +132,12 @@ pub trait DeviceInterface: CommonTraits { desc: crate::ShaderModuleDescriptor<'_>, shader_bound_checks: crate::ShaderRuntimeChecks, ) -> DispatchShaderModule; - unsafe fn create_shader_module_spirv( + + unsafe fn create_shader_module_passthrough( &self, - desc: &crate::ShaderModuleDescriptorSpirV<'_>, + desc: &crate::ShaderModuleDescriptorPassthrough<'_>, ) -> DispatchShaderModule; + fn create_bind_group_layout( &self, desc: &crate::BindGroupLayoutDescriptor<'_>, @@ -128,6 +151,10 @@ pub trait DeviceInterface: CommonTraits { &self, desc: &crate::RenderPipelineDescriptor<'_>, ) -> DispatchRenderPipeline; + fn create_mesh_pipeline( + &self, + desc: &crate::MeshPipelineDescriptor<'_>, + ) -> DispatchRenderPipeline; fn create_compute_pipeline( &self, desc: &crate::ComputePipelineDescriptor<'_>, @@ -138,6 +165,11 @@ pub trait DeviceInterface: CommonTraits { ) -> DispatchPipelineCache; fn create_buffer(&self, desc: &crate::BufferDescriptor<'_>) -> DispatchBuffer; fn create_texture(&self, desc: &crate::TextureDescriptor<'_>) -> DispatchTexture; + fn create_external_texture( + &self, + desc: &crate::ExternalTextureDescriptor<'_>, + planes: &[&crate::TextureView], + ) -> DispatchExternalTexture; fn create_blas( &self, desc: &crate::CreateBlasDescriptor<'_>, @@ -157,14 +189,14 @@ pub trait DeviceInterface: CommonTraits { fn set_device_lost_callback(&self, device_lost_callback: BoxDeviceLostCallback); - fn on_uncaptured_error(&self, handler: Box); + fn on_uncaptured_error(&self, handler: Arc); fn push_error_scope(&self, filter: crate::ErrorFilter); fn pop_error_scope(&self) -> Pin>; - fn start_capture(&self); - fn stop_capture(&self); + unsafe fn start_graphics_debugger_capture(&self); + unsafe fn stop_graphics_debugger_capture(&self); - fn poll(&self, poll_type: crate::PollType) -> Result; + fn poll(&self, poll_type: wgt::PollType) -> Result; fn get_internal_counters(&self) -> crate::InternalCounters; fn generate_allocator_report(&self) -> Option; @@ -196,7 +228,7 @@ pub trait QueueInterface: CommonTraits { data_layout: crate::TexelCopyBufferLayout, size: crate::Extent3d, ); - #[cfg(any(webgpu, webgl))] + #[cfg(web)] fn copy_external_image_to_texture( &self, source: &crate::CopyExternalImageSourceInfo, @@ -204,10 +236,13 @@ pub trait QueueInterface: CommonTraits { size: crate::Extent3d, ); + /// Submit must always drain the iterator, even in the case of error. fn submit(&self, command_buffers: &mut dyn Iterator) -> u64; fn get_timestamp_period(&self) -> f32; fn on_submitted_work_done(&self, callback: BoxSubmittedWorkDoneCallback); + + fn compact_blas(&self, blas: &DispatchBlas) -> (Option, DispatchBlas); } pub trait ShaderModuleInterface: CommonTraits { @@ -226,11 +261,6 @@ pub trait BufferInterface: CommonTraits { ); fn get_mapped_range(&self, sub_range: Range) -> DispatchBufferMappedRange; - #[cfg(webgpu)] - fn get_mapped_range_as_array_buffer( - &self, - sub_range: Range, - ) -> Option; fn unmap(&self); @@ -241,7 +271,13 @@ pub trait TextureInterface: CommonTraits { fn destroy(&self); } -pub trait BlasInterface: CommonTraits {} +pub trait ExternalTextureInterface: CommonTraits { + fn destroy(&self); +} +pub trait BlasInterface: CommonTraits { + fn prepare_compact_async(&self, callback: BlasCompactCallback); + fn ready_for_compaction(&self) -> bool; +} pub trait TlasInterface: CommonTraits {} pub trait QuerySetInterface: CommonTraits {} pub trait PipelineLayoutInterface: CommonTraits {} @@ -261,7 +297,7 @@ pub trait CommandEncoderInterface: CommonTraits { source_offset: crate::BufferAddress, destination: &DispatchBuffer, destination_offset: crate::BufferAddress, - copy_size: crate::BufferAddress, + copy_size: Option, ); fn copy_buffer_to_texture( &self, @@ -311,16 +347,16 @@ pub trait CommandEncoderInterface: CommonTraits { destination: &DispatchBuffer, destination_offset: crate::BufferAddress, ); - - fn build_acceleration_structures_unsafe_tlas<'a>( + fn mark_acceleration_structures_built<'a>( &self, - blas: &mut dyn Iterator>, - tlas: &mut dyn Iterator>, + blas: &mut dyn Iterator, + tlas: &mut dyn Iterator, ); + fn build_acceleration_structures<'a>( &self, blas: &mut dyn Iterator>, - tlas: &mut dyn Iterator, + tlas: &mut dyn Iterator, ); fn transition_resources<'a>( @@ -393,6 +429,7 @@ pub trait RenderPassInterface: CommonTraits { fn draw(&mut self, vertices: Range, instances: Range); fn draw_indexed(&mut self, indices: Range, base_vertex: i32, instances: Range); + fn draw_mesh_tasks(&mut self, group_count_x: u32, group_count_y: u32, group_count_z: u32); fn draw_indirect( &mut self, indirect_buffer: &DispatchBuffer, @@ -403,6 +440,11 @@ pub trait RenderPassInterface: CommonTraits { indirect_buffer: &DispatchBuffer, indirect_offset: crate::BufferAddress, ); + fn draw_mesh_tasks_indirect( + &mut self, + indirect_buffer: &DispatchBuffer, + indirect_offset: crate::BufferAddress, + ); fn multi_draw_indirect( &mut self, @@ -424,6 +466,12 @@ pub trait RenderPassInterface: CommonTraits { count_buffer_offset: crate::BufferAddress, max_count: u32, ); + fn multi_draw_mesh_tasks_indirect( + &mut self, + indirect_buffer: &DispatchBuffer, + indirect_offset: crate::BufferAddress, + count: u32, + ); fn multi_draw_indexed_indirect_count( &mut self, indirect_buffer: &DispatchBuffer, @@ -432,6 +480,14 @@ pub trait RenderPassInterface: CommonTraits { count_buffer_offset: crate::BufferAddress, max_count: u32, ); + fn multi_draw_mesh_tasks_indirect_count( + &mut self, + indirect_buffer: &DispatchBuffer, + indirect_offset: crate::BufferAddress, + count_buffer: &DispatchBuffer, + count_buffer_offset: crate::BufferAddress, + max_count: u32, + ); fn insert_debug_marker(&mut self, label: &str); fn push_debug_group(&mut self, group_label: &str); @@ -520,6 +576,9 @@ pub trait QueueWriteBufferInterface: CommonTraits { pub trait BufferMappedRangeInterface: CommonTraits { fn slice(&self) -> &[u8]; fn slice_mut(&mut self) -> &mut [u8]; + + #[cfg(webgpu)] + fn as_uint8array(&self) -> &js_sys::Uint8Array; } /// Generates Dispatch types for each of the interfaces. Each type is a wrapper around the @@ -541,7 +600,7 @@ macro_rules! dispatch_types { #[cfg(wgpu_core)] Core(Arc<$core_type>), #[cfg(webgpu)] - WebGPU(Arc<$webgpu_type>), + WebGPU($webgpu_type), #[allow(clippy::allow_attributes, private_interfaces)] #[cfg(custom)] Custom($custom_type), @@ -568,6 +627,16 @@ macro_rules! dispatch_types { } } + #[cfg(custom)] + #[inline] + #[allow(clippy::allow_attributes, unused)] + pub fn as_custom(&self) -> Option<&T> { + match self { + Self::Custom(value) => value.downcast(), + _ => None, + } + } + #[cfg(webgpu)] #[inline] #[allow(clippy::allow_attributes, unused)] @@ -607,7 +676,7 @@ macro_rules! dispatch_types { impl From<$webgpu_type> for $name { #[inline] fn from(value: $webgpu_type) -> Self { - Self::WebGPU(Arc::new(value)) + Self::WebGPU(value) } } @@ -620,7 +689,7 @@ macro_rules! dispatch_types { #[cfg(wgpu_core)] Self::Core(value) => value.as_ref(), #[cfg(webgpu)] - Self::WebGPU(value) => value.as_ref(), + Self::WebGPU(value) => value, #[cfg(custom)] Self::Custom(value) => value.deref(), #[cfg(not(any(wgpu_core, webgpu)))] @@ -686,6 +755,16 @@ macro_rules! dispatch_types { } } + #[cfg(custom)] + #[inline] + #[allow(clippy::allow_attributes, unused)] + pub fn as_custom(&self) -> Option<&T> { + match self { + Self::Custom(value) => value.downcast(), + _ => None, + } + } + #[cfg(webgpu)] #[inline] #[allow(clippy::allow_attributes, unused)] @@ -798,6 +877,7 @@ dispatch_types! {ref type DispatchTextureView: TextureViewInterface = CoreTextur dispatch_types! {ref type DispatchSampler: SamplerInterface = CoreSampler, WebSampler, DynSampler} dispatch_types! {ref type DispatchBuffer: BufferInterface = CoreBuffer, WebBuffer, DynBuffer} dispatch_types! {ref type DispatchTexture: TextureInterface = CoreTexture, WebTexture, DynTexture} +dispatch_types! {ref type DispatchExternalTexture: ExternalTextureInterface = CoreExternalTexture, WebExternalTexture, DynExternalTexture} dispatch_types! {ref type DispatchBlas: BlasInterface = CoreBlas, WebBlas, DynBlas} dispatch_types! {ref type DispatchTlas: TlasInterface = CoreTlas, WebTlas, DynTlas} dispatch_types! {ref type DispatchQuerySet: QuerySetInterface = CoreQuerySet, WebQuerySet, DynQuerySet} @@ -808,7 +888,7 @@ dispatch_types! {ref type DispatchPipelineCache: PipelineCacheInterface = CorePi dispatch_types! {mut type DispatchCommandEncoder: CommandEncoderInterface = CoreCommandEncoder, WebCommandEncoder, DynCommandEncoder} dispatch_types! {mut type DispatchComputePass: ComputePassInterface = CoreComputePass, WebComputePassEncoder, DynComputePass} dispatch_types! {mut type DispatchRenderPass: RenderPassInterface = CoreRenderPass, WebRenderPassEncoder, DynRenderPass} -dispatch_types! {ref type DispatchCommandBuffer: CommandBufferInterface = CoreCommandBuffer, WebCommandBuffer, DynCommandBuffer} +dispatch_types! {mut type DispatchCommandBuffer: CommandBufferInterface = CoreCommandBuffer, WebCommandBuffer, DynCommandBuffer} dispatch_types! {mut type DispatchRenderBundleEncoder: RenderBundleEncoderInterface = CoreRenderBundleEncoder, WebRenderBundleEncoder, DynRenderBundleEncoder} dispatch_types! {ref type DispatchRenderBundle: RenderBundleInterface = CoreRenderBundle, WebRenderBundle, DynRenderBundle} dispatch_types! {ref type DispatchSurface: SurfaceInterface = CoreSurface, WebSurface, DynSurface} diff --git a/wgpu/src/lib.rs b/wgpu/src/lib.rs index d1ec8a17f..248296c7a 100644 --- a/wgpu/src/lib.rs +++ b/wgpu/src/lib.rs @@ -1,6 +1,23 @@ -//! A cross-platform graphics and compute library based on [WebGPU](https://gpuweb.github.io/gpuweb/). +//! `wgpu` is a cross-platform, safe, pure-Rust graphics API. It runs natively on +//! Vulkan, Metal, D3D12, and OpenGL; and on top of WebGL2 and WebGPU on wasm. //! -//! To start using the API, create an [`Instance`]. +//! The API is based on the [WebGPU standard][webgpu]. It serves as the core of the +//! WebGPU integration in Firefox, Servo, and Deno. +//! +//! [webgpu]: https://gpuweb.github.io/gpuweb/ +//! +//! ## Getting Started +//! +//! The main entry point to the API is the [`Instance`] type, from which you can create [`Adapter`], [`Device`], and [`Surface`]. +//! +//! If you are new to `wgpu` and graphics programming, we recommend reading +//! and . The latter is a WebGPU +//! tutorial, but the concepts are nearly identical to `wgpu`. +//! +//! There are examples for this version [available on GitHub](https://github.com/gfx-rs/wgpu/tree/v27/examples#readme). +//! +//! The API is refcounted, so all handles are cloneable, and if you create a resource which references another, +//! it will automatically keep dependent resources alive. //! //! ## Feature flags #![doc = document_features::document_features!()] @@ -11,11 +28,11 @@ //! complicated cases. //! //! - **`wgpu_core`** --- Enabled when there is any non-webgpu backend enabled on the platform. -//! - **`naga`** ---- Enabled when any non-wgsl shader input is enabled. +//! - **`naga`** --- Enabled when target `glsl` or `spirv`` input is enabled, or when `wgpu_core` is enabled. //! #![no_std] -#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] +#![cfg_attr(docsrs, feature(doc_cfg))] #![doc(html_logo_url = "https://raw.githubusercontent.com/gfx-rs/wgpu/trunk/logo.png")] #![warn( clippy::alloc_instead_of_core, @@ -26,11 +43,19 @@ rust_2018_idioms, unsafe_op_in_unsafe_fn )] +#![allow( + // We need to investiagate these. + clippy::large_enum_variant, + // These degrade readability significantly. + clippy::bool_assert_comparison, + clippy::bool_comparison, +)] // NOTE: Keep this in sync with `wgpu-core`. #![cfg_attr(not(send_sync), allow(clippy::arc_with_non_send_sync))] #![cfg_attr(not(any(wgpu_core, webgpu)), allow(unused))] extern crate alloc; +#[cfg(std)] extern crate std; #[cfg(wgpu_core)] pub extern crate wgpu_core as wgc; @@ -51,12 +76,6 @@ mod dispatch; mod macros; pub mod util; -// -// -// Private re-exports -// -// - // // // Public re-exports @@ -70,34 +89,35 @@ pub use api::*; pub use wgt::{ AdapterInfo, AddressMode, AllocatorReport, AstcBlock, AstcChannel, Backend, BackendOptions, Backends, BindGroupLayoutEntry, BindingType, BlendComponent, BlendFactor, BlendOperation, - BlendState, BufferAddress, BufferBindingType, BufferSize, BufferTransition, BufferUsages, - BufferUses, Color, ColorTargetState, ColorWrites, CommandBufferDescriptor, CompareFunction, - CompositeAlphaMode, CopyExternalImageDestInfo, CoreCounters, DepthBiasState, DepthStencilState, - DeviceLostReason, DeviceType, DownlevelCapabilities, DownlevelFlags, DownlevelLimits, - Dx12BackendOptions, Dx12Compiler, DxcShaderModel, DynamicOffset, Extent3d, Face, Features, - FeaturesWGPU, FeaturesWebGPU, FilterMode, FrontFace, GlBackendOptions, GlFenceBehavior, - Gles3MinorVersion, HalCounters, ImageSubresourceRange, IndexFormat, InstanceDescriptor, - InstanceFlags, InternalCounters, Limits, MemoryHints, MultisampleState, NoopBackendOptions, - Origin2d, Origin3d, PipelineStatisticsTypes, PollError, PollStatus, PolygonMode, - PowerPreference, PredefinedColorSpace, PresentMode, PresentationTimestamp, PrimitiveState, - PrimitiveTopology, PushConstantRange, QueryType, RenderBundleDepthStencil, RequestAdapterError, - SamplerBindingType, SamplerBorderColor, ShaderLocation, ShaderModel, ShaderRuntimeChecks, - ShaderStages, StencilFaceState, StencilOperation, StencilState, StorageTextureAccess, - SurfaceCapabilities, SurfaceStatus, TexelCopyBufferLayout, TextureAspect, TextureDimension, - TextureFormat, TextureFormatFeatureFlags, TextureFormatFeatures, TextureSampleType, - TextureTransition, TextureUsages, TextureUses, TextureViewDimension, Trace, VertexAttribute, - VertexFormat, VertexStepMode, WasmNotSend, WasmNotSendSync, WasmNotSync, COPY_BUFFER_ALIGNMENT, - COPY_BYTES_PER_ROW_ALIGNMENT, MAP_ALIGNMENT, PUSH_CONSTANT_ALIGNMENT, - QUERY_RESOLVE_BUFFER_ALIGNMENT, QUERY_SET_MAX_QUERIES, QUERY_SIZE, VERTEX_STRIDE_ALIGNMENT, + BlendState, BufferAddress, BufferBindingType, BufferSize, BufferTextureCopyInfo, + BufferTransition, BufferUsages, BufferUses, Color, ColorTargetState, ColorWrites, + CommandBufferDescriptor, CompareFunction, CompositeAlphaMode, CopyExternalImageDestInfo, + CoreCounters, DepthBiasState, DepthStencilState, DeviceLostReason, DeviceType, + DownlevelCapabilities, DownlevelFlags, DownlevelLimits, Dx12BackendOptions, Dx12Compiler, + DxcShaderModel, DynamicOffset, ExperimentalFeatures, Extent3d, ExternalTextureFormat, + ExternalTextureTransferFunction, Face, Features, FeaturesWGPU, FeaturesWebGPU, FilterMode, + FrontFace, GlBackendOptions, GlFenceBehavior, Gles3MinorVersion, HalCounters, + ImageSubresourceRange, IndexFormat, InstanceDescriptor, InstanceFlags, InternalCounters, + Limits, MemoryBudgetThresholds, MemoryHints, MipmapFilterMode, MultisampleState, + NoopBackendOptions, Origin2d, Origin3d, PipelineStatisticsTypes, PollError, PollStatus, + PolygonMode, PowerPreference, PredefinedColorSpace, PresentMode, PresentationTimestamp, + PrimitiveState, PrimitiveTopology, PushConstantRange, QueryType, RenderBundleDepthStencil, + RequestAdapterError, SamplerBindingType, SamplerBorderColor, ShaderLocation, ShaderModel, + ShaderRuntimeChecks, ShaderStages, StencilFaceState, StencilOperation, StencilState, + StorageTextureAccess, SurfaceCapabilities, SurfaceStatus, TexelCopyBufferLayout, TextureAspect, + TextureDimension, TextureFormat, TextureFormatFeatureFlags, TextureFormatFeatures, + TextureSampleType, TextureTransition, TextureUsages, TextureUses, TextureViewDimension, Trace, + VertexAttribute, VertexFormat, VertexStepMode, WasmNotSend, WasmNotSendSync, WasmNotSync, + COPY_BUFFER_ALIGNMENT, COPY_BYTES_PER_ROW_ALIGNMENT, MAP_ALIGNMENT, PUSH_CONSTANT_ALIGNMENT, + QUERY_RESOLVE_BUFFER_ALIGNMENT, QUERY_SET_MAX_QUERIES, QUERY_SIZE, VERTEX_ALIGNMENT, }; + #[expect(deprecated)] -pub use wgt::{ImageCopyBuffer, ImageCopyTexture, ImageCopyTextureTagged, ImageDataLayout}; +pub use wgt::VERTEX_STRIDE_ALIGNMENT; + // wasm-only types, we try to keep as many types non-platform // specific, but these need to depend on web-sys. -#[cfg(any(webgpu, webgl))] -#[expect(deprecated)] -pub use wgt::ImageCopyExternalImage; -#[cfg(any(webgpu, webgl))] +#[cfg(web)] pub use wgt::{CopyExternalImageSourceInfo, ExternalImageSource}; /// Re-export of our `naga` dependency. @@ -119,7 +139,7 @@ pub use raw_window_handle as rwh; /// Re-export of our `web-sys` dependency. /// -#[cfg(any(webgl, webgpu))] +#[cfg(web)] pub use web_sys; #[doc(hidden)] diff --git a/wgpu/src/macros.rs b/wgpu/src/macros.rs deleted file mode 100644 index 85371ec57..000000000 --- a/wgpu/src/macros.rs +++ /dev/null @@ -1,145 +0,0 @@ -//! Convenience macros - -#[cfg(doc)] -use crate::{VertexAttribute, VertexBufferLayout, VertexFormat}; - -/// Macro to produce an array of [`VertexAttribute`]. -/// -/// The input is a sequence of pairs of shader locations (expression of type [`u32`]) and -/// variant names of [`VertexFormat`]. -/// -/// The return value has type `[VertexAttribute; N]`, where `N` is the number of inputs. -/// -/// Offsets are calculated automatically, -/// using the assumption that there is no padding or other data between attributes. -/// -/// # Example -/// -/// ``` -/// // Suppose that this is our vertex format: -/// #[repr(C, packed)] -/// struct Vertex { -/// foo: [f32; 2], -/// bar: f32, -/// baz: [u16; 4], -/// } -/// -/// // Then these attributes match it: -/// let attrs = wgpu::vertex_attr_array![ -/// 0 => Float32x2, -/// 1 => Float32, -/// 2 => Uint16x4, -/// ]; -/// -/// // Here's the full data structure the macro produced: -/// use wgpu::{VertexAttribute as A, VertexFormat as F}; -/// assert_eq!(attrs, [ -/// A { format: F::Float32x2, offset: 0, shader_location: 0, }, -/// A { format: F::Float32, offset: 8, shader_location: 1, }, -/// A { format: F::Uint16x4, offset: 12, shader_location: 2, }, -/// ]); -/// ``` -/// -/// See [`VertexBufferLayout`] for an example building on this one. -#[macro_export] -macro_rules! vertex_attr_array { - ($($location:expr => $format:ident),* $(,)?) => { - $crate::_vertex_attr_array_helper!([] ; 0; $($location => $format ,)*) - }; -} - -#[doc(hidden)] -#[macro_export] -macro_rules! _vertex_attr_array_helper { - ([$($t:expr,)*] ; $off:expr ;) => { [$($t,)*] }; - ([$($t:expr,)*] ; $off:expr ; $location:expr => $format:ident, $($ll:expr => $ii:ident ,)*) => { - $crate::_vertex_attr_array_helper!( - [$($t,)* - $crate::VertexAttribute { - format: $crate::VertexFormat :: $format, - offset: $off, - shader_location: $location, - },]; - $off + $crate::VertexFormat :: $format.size(); - $($ll => $ii ,)* - ) - }; -} - -#[test] -fn test_vertex_attr_array() { - let attrs = vertex_attr_array![0 => Float32x2, 3 => Uint16x4]; - // VertexAttribute does not support PartialEq, so we cannot test directly - assert_eq!(attrs.len(), 2); - assert_eq!(attrs[0].offset, 0); - assert_eq!(attrs[0].shader_location, 0); - assert_eq!(attrs[1].offset, size_of::<(f32, f32)>() as u64); - assert_eq!(attrs[1].shader_location, 3); -} - -/// Macro to load a SPIR-V module statically. -/// -/// It ensures the word alignment as well as the magic number. -/// -/// Return type: [`crate::ShaderModuleDescriptor`] -#[macro_export] -#[cfg(feature = "spirv")] -macro_rules! include_spirv { - ($($token:tt)*) => { - { - //log::info!("including '{}'", $($token)*); - $crate::ShaderModuleDescriptor { - label: Some($($token)*), - source: $crate::util::make_spirv(include_bytes!($($token)*)), - } - } - }; -} - -/// Macro to load raw SPIR-V data statically, for use with [`Features::SPIRV_SHADER_PASSTHROUGH`]. -/// -/// It ensures the word alignment as well as the magic number. -/// -/// [`Features::SPIRV_SHADER_PASSTHROUGH`]: crate::Features::SPIRV_SHADER_PASSTHROUGH -#[macro_export] -macro_rules! include_spirv_raw { - ($($token:tt)*) => { - { - //log::info!("including '{}'", $($token)*); - $crate::ShaderModuleDescriptorSpirV { - label: $crate::__macro_helpers::Some($($token)*), - source: $crate::util::make_spirv_raw($crate::__macro_helpers::include_bytes!($($token)*)), - } - } - }; -} - -/// Load WGSL source code from a file at compile time. -/// -/// The loaded path is relative to the path of the file containing the macro call, in the same way -/// as [`include_str!`] operates. -/// -/// ```ignore -/// fn main() { -/// let module: ShaderModuleDescriptor = include_wgsl!("shader.wgsl"); -/// } -/// ``` -#[macro_export] -macro_rules! include_wgsl { - ($($token:tt)*) => { - { - //log::info!("including '{}'", $($token)*); - $crate::ShaderModuleDescriptor { - label: $crate::__macro_helpers::Some($($token)*), - source: $crate::ShaderSource::Wgsl($crate::__macro_helpers::Cow::Borrowed($crate::__macro_helpers::include_str!($($token)*))), - } - } - }; -} - -#[doc(hidden)] -pub mod helpers { - pub use alloc::borrow::Cow; - pub use core::{include_bytes, include_str}; - pub use Some; -} diff --git a/wgpu/src/macros/be-aligned.spv b/wgpu/src/macros/be-aligned.spv new file mode 100644 index 000000000..0e2d06578 --- /dev/null +++ b/wgpu/src/macros/be-aligned.spv @@ -0,0 +1 @@ +#"3D \ No newline at end of file diff --git a/wgpu/src/macros/le-aligned.spv b/wgpu/src/macros/le-aligned.spv new file mode 100644 index 000000000..3f6aead06 --- /dev/null +++ b/wgpu/src/macros/le-aligned.spv @@ -0,0 +1 @@ +#D3" \ No newline at end of file diff --git a/wgpu/src/macros/mod.rs b/wgpu/src/macros/mod.rs new file mode 100644 index 000000000..b334ee003 --- /dev/null +++ b/wgpu/src/macros/mod.rs @@ -0,0 +1,276 @@ +//! Convenience macros + +#[cfg(doc)] +use crate::{VertexAttribute, VertexBufferLayout, VertexFormat}; + +/// Macro to produce an array of [`VertexAttribute`]. +/// +/// The input is a sequence of pairs of shader locations (expression of type [`u32`]) and +/// variant names of [`VertexFormat`]. +/// +/// The return value has type `[VertexAttribute; N]`, where `N` is the number of inputs. +/// +/// Offsets are calculated automatically, +/// using the assumption that there is no padding or other data between attributes. +/// +/// # Example +/// +/// ``` +/// // Suppose that this is our vertex format: +/// #[repr(C, packed)] +/// struct Vertex { +/// foo: [f32; 2], +/// bar: f32, +/// baz: [u16; 4], +/// } +/// +/// // Then these attributes match it: +/// let attrs = wgpu::vertex_attr_array![ +/// 0 => Float32x2, +/// 1 => Float32, +/// 2 => Uint16x4, +/// ]; +/// +/// // Here's the full data structure the macro produced: +/// use wgpu::{VertexAttribute as A, VertexFormat as F}; +/// assert_eq!(attrs, [ +/// A { format: F::Float32x2, offset: 0, shader_location: 0, }, +/// A { format: F::Float32, offset: 8, shader_location: 1, }, +/// A { format: F::Uint16x4, offset: 12, shader_location: 2, }, +/// ]); +/// ``` +/// +/// See [`VertexBufferLayout`] for an example building on this one. +#[macro_export] +macro_rules! vertex_attr_array { + ($($location:expr => $format:ident),* $(,)?) => { + $crate::_vertex_attr_array_helper!([] ; 0; $($location => $format ,)*) + }; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! _vertex_attr_array_helper { + ([$($t:expr,)*] ; $off:expr ;) => { [$($t,)*] }; + ([$($t:expr,)*] ; $off:expr ; $location:expr => $format:ident, $($ll:expr => $ii:ident ,)*) => { + $crate::_vertex_attr_array_helper!( + [$($t,)* + $crate::VertexAttribute { + format: $crate::VertexFormat :: $format, + offset: $off, + shader_location: $location, + },]; + $off + $crate::VertexFormat :: $format.size(); + $($ll => $ii ,)* + ) + }; +} + +#[test] +fn test_vertex_attr_array() { + let attrs = vertex_attr_array![0 => Float32x2, 3 => Uint16x4]; + // VertexAttribute does not support PartialEq, so we cannot test directly + assert_eq!(attrs.len(), 2); + assert_eq!(attrs[0].offset, 0); + assert_eq!(attrs[0].shader_location, 0); + assert_eq!(attrs[1].offset, size_of::<(f32, f32)>() as u64); + assert_eq!(attrs[1].shader_location, 3); +} + +#[macro_export] +#[doc(hidden)] +macro_rules! include_spirv_source { + ($($token:tt)*) => { + { + // FIXME(MSRV): when bumping to 1.89, use [u8; _] here + const SPIRV_SOURCE: [ + u8; + $crate::__macro_helpers::include_bytes!($($token)*).len() + ] = *$crate::__macro_helpers::include_bytes!($($token)*); + const SPIRV_LEN: usize = SPIRV_SOURCE.len() / 4; + const SPIRV_WORDS: [u32; SPIRV_LEN] = $crate::util::make_spirv_const(SPIRV_SOURCE); + &SPIRV_WORDS + } + } +} + +#[test] +fn make_spirv_le_pass() { + static SPIRV: &[u32] = include_spirv_source!("le-aligned.spv"); + assert_eq!(SPIRV, &[0x07230203, 0x11223344]); +} + +#[test] +fn make_spirv_be_pass() { + static SPIRV: &[u32] = include_spirv_source!("be-aligned.spv"); + assert_eq!(SPIRV, &[0x07230203, 0x11223344]); +} + +/// Macro to load a SPIR-V module statically. +/// +/// It ensures the word alignment as well as the magic number. +/// +/// Return type: [`crate::ShaderModuleDescriptor`] +#[macro_export] +#[cfg(feature = "spirv")] +macro_rules! include_spirv { + ($($token:tt)*) => { + { + //log::info!("including '{}'", $($token)*); + $crate::ShaderModuleDescriptor { + label: Some($($token)*), + source: $crate::ShaderSource::SpirV( + $crate::__macro_helpers::Cow::Borrowed($crate::include_spirv_source!($($token)*)) + ), + } + } + }; +} + +#[cfg(all(feature = "spirv", test))] +#[expect(dead_code)] +static SPIRV: crate::ShaderModuleDescriptor<'_> = include_spirv!("le-aligned.spv"); + +/// Macro to load raw SPIR-V data statically, for use with [`Features::EXPERIMENTAL_PASSTHROUGH_SHADERS`]. +/// +/// It ensures the word alignment as well as the magic number. +/// +/// [`Features::EXPERIMENTAL_PASSTHROUGH_SHADERS`]: crate::Features::EXPERIMENTAL_PASSTHROUGH_SHADERS +#[macro_export] +macro_rules! include_spirv_raw { + ($($token:tt)*) => { + { + //log::info!("including '{}'", $($token)*); + $crate::ShaderModuleDescriptorPassthrough { + label: $crate::__macro_helpers::Some($($token)*), + spirv: Some($crate::__macro_helpers::Cow::Borrowed($crate::include_spirv_source!($($token)*))), + entry_point: $crate::__macro_helpers::String::new(), + // This is unused for SPIR-V + num_workgroups: (0, 0, 0), + runtime_checks: $crate::ShaderRuntimeChecks::unchecked(), + dxil: None, + msl: None, + hlsl: None, + glsl: None, + wgsl: None, + } + } + }; +} + +#[cfg(test)] +#[expect(dead_code)] +static SPIRV_RAW: crate::ShaderModuleDescriptorPassthrough<'_> = + include_spirv_raw!("le-aligned.spv"); + +/// Load WGSL source code from a file at compile time. +/// +/// The loaded path is relative to the path of the file containing the macro call, in the same way +/// as [`include_str!`] operates. +/// +/// ```ignore +/// fn main() { +/// let module: ShaderModuleDescriptor = include_wgsl!("shader.wgsl"); +/// } +/// ``` +#[macro_export] +macro_rules! include_wgsl { + ($($token:tt)*) => { + { + //log::info!("including '{}'", $($token)*); + $crate::ShaderModuleDescriptor { + label: $crate::__macro_helpers::Some($($token)*), + source: $crate::ShaderSource::Wgsl($crate::__macro_helpers::Cow::Borrowed($crate::__macro_helpers::include_str!($($token)*))), + } + } + }; +} + +// Macros which help us generate the documentation of which hal types correspond to which backend. +// +// Because all backends are not compiled into the program, we cannot link to them in all situations, +// we need to only link to the types if the backend is compiled in. These are used in #[doc] attributes +// so cannot have more than one line, so cannot use internal cfgs. + +/// Helper macro to generate the documentation for dx12 hal methods, referencing the hal type. +#[macro_export] +#[doc(hidden)] +#[cfg(dx12)] +macro_rules! hal_type_dx12 { + ($ty: literal) => { + concat!("- [`hal::api::Dx12`] uses [`hal::dx12::", $ty, "`]") + }; +} +/// Helper macro to generate the documentation for dx12 hal methods, referencing the hal type. +#[macro_export] +#[doc(hidden)] +#[cfg(not(dx12))] +macro_rules! hal_type_dx12 { + ($ty: literal) => { + concat!("- `hal::api::Dx12` uses `hal::dx12::", $ty, "`") + }; +} + +/// Helper macro to generate the documentation for metal hal methods, referencing the hal type. +#[macro_export] +#[doc(hidden)] +#[cfg(metal)] +macro_rules! hal_type_metal { + ($ty: literal) => { + concat!("- [`hal::api::Metal`] uses [`hal::metal::", $ty, "`]") + }; +} +/// Helper macro to generate the documentation for metal hal methods, referencing the hal type. +#[macro_export] +#[doc(hidden)] +#[cfg(not(metal))] +macro_rules! hal_type_metal { + ($ty: literal) => { + concat!("- `hal::api::Metal` uses `hal::metal::", $ty, "`") + }; +} + +/// Helper macro to generate the documentation for vulkan hal methods, referencing the hal type. +#[macro_export] +#[doc(hidden)] +#[cfg(vulkan)] +macro_rules! hal_type_vulkan { + ($ty: literal) => { + concat!("- [`hal::api::Vulkan`] uses [`hal::vulkan::", $ty, "`]") + }; +} +/// Helper macro to generate the documentation for vulkan hal methods, referencing the hal type. +#[macro_export] +#[doc(hidden)] +#[cfg(not(vulkan))] +macro_rules! hal_type_vulkan { + ($ty: literal) => { + concat!("- `hal::api::Vulkan` uses `hal::vulkan::", $ty, "`") + }; +} + +/// Helper macro to generate the documentation for gles hal methods, referencing the hal type. +#[macro_export] +#[doc(hidden)] +#[cfg(gles)] +macro_rules! hal_type_gles { + ($ty: literal) => { + concat!("- [`hal::api::Gles`] uses [`hal::gles::", $ty, "`]") + }; +} +/// Helper macro to generate the documentation for gles hal methods, referencing the hal type. +#[macro_export] +#[doc(hidden)] +#[cfg(not(gles))] +macro_rules! hal_type_gles { + ($ty: literal) => { + concat!("- `hal::api::Gles` uses `hal::gles::", $ty, "`") + }; +} + +#[doc(hidden)] +pub mod helpers { + pub use alloc::{borrow::Cow, string::String}; + pub use core::{include_bytes, include_str}; + pub use Some; +} diff --git a/wgpu/src/util/be-unaligned.spv b/wgpu/src/util/be-unaligned.spv new file mode 100644 index 000000000..c484c20cc --- /dev/null +++ b/wgpu/src/util/be-unaligned.spv @@ -0,0 +1 @@ +#" \ No newline at end of file diff --git a/wgpu/src/util/belt.rs b/wgpu/src/util/belt.rs index 222a49f4c..808d7b5f6 100644 --- a/wgpu/src/util/belt.rs +++ b/wgpu/src/util/belt.rs @@ -6,6 +6,8 @@ use alloc::vec::Vec; use core::fmt; use std::sync::mpsc; +use crate::COPY_BUFFER_ALIGNMENT; + /// Efficiently performs many buffer writes by sharing and reusing temporary buffers. /// /// Internally it uses a ring-buffer of staging buffers that are sub-allocated. @@ -22,6 +24,7 @@ use std::sync::mpsc; /// /// [`Queue::write_buffer_with()`]: crate::Queue::write_buffer_with pub struct StagingBelt { + device: Device, chunk_size: BufferAddress, /// Chunks into which we are accumulating data to be transferred. active_chunks: Vec, @@ -48,9 +51,10 @@ impl StagingBelt { /// * 1-4 times less than the total amount of data uploaded per submission /// (per [`StagingBelt::finish()`]); and /// * bigger is better, within these bounds. - pub fn new(chunk_size: BufferAddress) -> Self { + pub fn new(device: Device, chunk_size: BufferAddress) -> Self { let (sender, receiver) = mpsc::channel(); StagingBelt { + device, chunk_size, active_chunks: Vec::new(), closed_chunks: Vec::new(), @@ -63,6 +67,9 @@ impl StagingBelt { /// Allocate a staging belt slice of `size` to be copied into the `target` buffer /// at the specified offset. /// + /// `offset` and `size` must be multiples of [`COPY_BUFFER_ALIGNMENT`] + /// (as is required by the underlying buffer operations). + /// /// The upload will be placed into the provided command encoder. This encoder /// must be submitted after [`StagingBelt::finish()`] is called and before /// [`StagingBelt::recall()`] is called. @@ -70,18 +77,25 @@ impl StagingBelt { /// If the `size` is greater than the size of any free internal buffer, a new buffer /// will be allocated for it. Therefore, the `chunk_size` passed to [`StagingBelt::new()`] /// should ideally be larger than every such size. + #[track_caller] pub fn write_buffer( &mut self, encoder: &mut CommandEncoder, target: &Buffer, offset: BufferAddress, size: BufferSize, - device: &Device, - ) -> BufferViewMut<'_> { + ) -> BufferViewMut { + // Asserting this explicitly gives a usefully more specific, and more prompt, error than + // leaving it to regular API validation. + // We check only `offset`, not `size`, because `self.allocate()` will check the size. + assert!( + offset.is_multiple_of(COPY_BUFFER_ALIGNMENT), + "StagingBelt::write_buffer() offset {offset} must be a multiple of `COPY_BUFFER_ALIGNMENT`" + ); + let slice_of_belt = self.allocate( size, const { BufferSize::new(crate::COPY_BUFFER_ALIGNMENT).unwrap() }, - device, ); encoder.copy_buffer_to_buffer( slice_of_belt.buffer(), @@ -95,6 +109,9 @@ impl StagingBelt { /// Allocate a staging belt slice with the given `size` and `alignment` and return it. /// + /// `size` must be a multiple of [`COPY_BUFFER_ALIGNMENT`] + /// (as is required by the underlying buffer operations). + /// /// To use this slice, call [`BufferSlice::get_mapped_range_mut()`] and write your data into /// that [`BufferViewMut`]. /// (The view must be dropped before [`StagingBelt::finish()`] is called.) @@ -112,12 +129,12 @@ impl StagingBelt { /// The chosen slice will be positioned within the buffer at a multiple of `alignment`, /// which may be used to meet alignment requirements for the operation you wish to perform /// with the slice. This does not necessarily affect the alignment of the [`BufferViewMut`]. - pub fn allocate( - &mut self, - size: BufferSize, - alignment: BufferSize, - device: &Device, - ) -> BufferSlice<'_> { + #[track_caller] + pub fn allocate(&mut self, size: BufferSize, alignment: BufferSize) -> BufferSlice<'_> { + assert!( + size.get().is_multiple_of(COPY_BUFFER_ALIGNMENT), + "StagingBelt allocation size {size} must be a multiple of `COPY_BUFFER_ALIGNMENT`" + ); assert!( alignment.get().is_power_of_two(), "alignment must be a power of two, not {alignment}" @@ -142,7 +159,7 @@ impl StagingBelt { self.free_chunks.swap_remove(index) } else { Chunk { - buffer: device.create_buffer(&BufferDescriptor { + buffer: self.device.create_buffer(&BufferDescriptor { label: Some("(wgpu internal) StagingBelt staging buffer"), size: self.chunk_size.max(size.get()), usage: BufferUsages::MAP_WRITE | BufferUsages::COPY_SRC, @@ -210,11 +227,21 @@ impl StagingBelt { impl fmt::Debug for StagingBelt { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let Self { + device, + chunk_size, + active_chunks, + closed_chunks, + free_chunks, + sender: _, + receiver: _, + } = self; f.debug_struct("StagingBelt") - .field("chunk_size", &self.chunk_size) - .field("active_chunks", &self.active_chunks.len()) - .field("closed_chunks", &self.closed_chunks.len()) - .field("free_chunks", &self.free_chunks.len()) + .field("device", device) + .field("chunk_size", chunk_size) + .field("active_chunks", &active_chunks.len()) + .field("closed_chunks", &closed_chunks.len()) + .field("free_chunks", &free_chunks.len()) .finish_non_exhaustive() } } diff --git a/wgpu/src/util/empty.spv b/wgpu/src/util/empty.spv new file mode 100644 index 000000000..e69de29bb diff --git a/wgpu/src/util/init.rs b/wgpu/src/util/init.rs index 5a22670c6..20b058ff8 100644 --- a/wgpu/src/util/init.rs +++ b/wgpu/src/util/init.rs @@ -5,16 +5,25 @@ use crate::Backends; /// Initialize the adapter obeying the `WGPU_ADAPTER_NAME` environment variable. #[cfg(wgpu_core)] -pub fn initialize_adapter_from_env( +#[cfg_attr(not(std), expect(unused_variables, unreachable_code))] +pub async fn initialize_adapter_from_env( instance: &Instance, compatible_surface: Option<&Surface<'_>>, ) -> Result { - let desired_adapter_name = std::env::var("WGPU_ADAPTER_NAME") - .as_deref() - .map(str::to_lowercase) - .map_err(|_| wgt::RequestAdapterError::EnvNotSet)?; + let desired_adapter_name: alloc::string::String = { + cfg_if::cfg_if! { + if #[cfg(std)] { + std::env::var("WGPU_ADAPTER_NAME") + .as_deref() + .map(str::to_lowercase) + .map_err(|_| wgt::RequestAdapterError::EnvNotSet)? + } else { + return Err(wgt::RequestAdapterError::EnvNotSet) + } + } + }; - let adapters = instance.enumerate_adapters(crate::Backends::all()); + let adapters = instance.enumerate_adapters(crate::Backends::all()).await; let mut chosen_adapter = None; for adapter in adapters { @@ -37,7 +46,7 @@ pub fn initialize_adapter_from_env( /// Initialize the adapter obeying the `WGPU_ADAPTER_NAME` environment variable. #[cfg(not(wgpu_core))] -pub fn initialize_adapter_from_env( +pub async fn initialize_adapter_from_env( _instance: &Instance, _compatible_surface: Option<&Surface<'_>>, ) -> Result { @@ -49,7 +58,7 @@ pub async fn initialize_adapter_from_env_or_default( instance: &Instance, compatible_surface: Option<&Surface<'_>>, ) -> Result { - match initialize_adapter_from_env(instance, compatible_surface) { + match initialize_adapter_from_env(instance, compatible_surface).await { Ok(a) => Ok(a), Err(_) => { instance diff --git a/wgpu/src/util/le-unaligned.spv b/wgpu/src/util/le-unaligned.spv new file mode 100644 index 000000000..80a5988bd --- /dev/null +++ b/wgpu/src/util/le-unaligned.spv @@ -0,0 +1 @@ +#" \ No newline at end of file diff --git a/wgpu/src/util/mod.rs b/wgpu/src/util/mod.rs index 7f7908053..2f524fc74 100644 --- a/wgpu/src/util/mod.rs +++ b/wgpu/src/util/mod.rs @@ -3,15 +3,20 @@ //! Nothing in this module is a part of the WebGPU API specification; //! they are unique to the `wgpu` library. +// TODO: For [`belt::StagingBelt`] to be available in `no_std` its usage of [`std::sync::mpsc`] +// must be replaced with an appropriate alternative. +#[cfg(std)] mod belt; mod device; mod encoder; mod init; +mod mutex; mod texture_blitter; use alloc::{borrow::Cow, format, string::String, vec}; -use core::ptr::copy_nonoverlapping; +use core::{mem, ptr::copy_nonoverlapping}; +#[cfg(std)] pub use belt::StagingBelt; pub use device::{BufferInitDescriptor, DeviceExt}; pub use encoder::RenderEncoder; @@ -22,6 +27,8 @@ pub use wgt::{ math::*, DispatchIndirectArgs, DrawIndexedIndirectArgs, DrawIndirectArgs, TextureDataOrder, }; +pub(crate) use mutex::Mutex; + use crate::dispatch; /// Treat the given byte slice as a SPIR-V module. @@ -39,18 +46,29 @@ pub fn make_spirv(data: &[u8]) -> super::ShaderSource<'_> { super::ShaderSource::SpirV(make_spirv_raw(data)) } -/// Version of `make_spirv` intended for use with [`Device::create_shader_module_spirv`]. +const SPIRV_MAGIC_NUMBER: u32 = 0x0723_0203; + +const fn check_spirv_len(data: &[u8]) { + assert!( + data.len() % size_of::() == 0, + "SPIRV data size must be a multiple of 4." + ); + assert!(!data.is_empty(), "SPIRV data must not be empty."); +} + +const fn verify_spirv_magic(words: &[u32]) { + assert!( + words[0] == SPIRV_MAGIC_NUMBER, + "Wrong magic word in data. Make sure you are using a binary SPIRV file.", + ); +} + +/// Version of `make_spirv` intended for use with [`Device::create_shader_module_passthrough`]. /// Returns a raw slice instead of [`ShaderSource`](super::ShaderSource). /// -/// [`Device::create_shader_module_spirv`]: crate::Device::create_shader_module_spirv +/// [`Device::create_shader_module_passthrough`]: crate::Device::create_shader_module_passthrough pub fn make_spirv_raw(data: &[u8]) -> Cow<'_, [u32]> { - const MAGIC_NUMBER: u32 = 0x0723_0203; - assert_eq!( - data.len() % size_of::(), - 0, - "data size is not a multiple of 4" - ); - assert_ne!(data.len(), 0, "data size must be larger than zero"); + check_spirv_len(data); // If the data happens to be aligned, directly use the byte array, // otherwise copy the byte array in an owned vector and use that instead. @@ -69,21 +87,68 @@ pub fn make_spirv_raw(data: &[u8]) -> Cow<'_, [u32]> { // Before checking if the data starts with the magic, check if it starts // with the magic in non-native endianness, own & swap the data if so. - if words[0] == MAGIC_NUMBER.swap_bytes() { + if words[0] == SPIRV_MAGIC_NUMBER.swap_bytes() { for word in Cow::to_mut(&mut words) { *word = word.swap_bytes(); } } - assert_eq!( - words[0], MAGIC_NUMBER, - "wrong magic word {:x}. Make sure you are using a binary SPIRV file.", - words[0] - ); + verify_spirv_magic(&words); words } +/// Version of `make_spirv_raw` used for implementing [`include_spirv!`] and [`include_spirv_raw!`] macros. +/// +/// Not public API. Also, don't even try calling at runtime; you'll get a stack overflow. +/// +/// [`include_spirv!`]: crate::include_spirv +#[doc(hidden)] +pub const fn make_spirv_const(data: [u8; IN]) -> [u32; OUT] { + #[repr(align(4))] + struct Aligned(T); + + check_spirv_len(&data); + + // NOTE: to get around lack of generic const expressions + assert!(IN / 4 == OUT); + + let aligned = Aligned(data); + let mut words: [u32; OUT] = unsafe { mem::transmute_copy(&aligned) }; + + // Before checking if the data starts with the magic, check if it starts + // with the magic in non-native endianness, own & swap the data if so. + if words[0] == SPIRV_MAGIC_NUMBER.swap_bytes() { + let mut idx = 0; + while idx < words.len() { + words[idx] = words[idx].swap_bytes(); + idx += 1; + } + } + + verify_spirv_magic(&words); + + words +} + +#[should_panic = "multiple of 4"] +#[test] +fn make_spirv_le_fail() { + let _: [u32; 1] = make_spirv_const([0x03, 0x02, 0x23, 0x07, 0x44, 0x33]); +} + +#[should_panic = "multiple of 4"] +#[test] +fn make_spirv_be_fail() { + let _: [u32; 1] = make_spirv_const([0x07, 0x23, 0x02, 0x03, 0x11, 0x22]); +} + +#[should_panic = "empty"] +#[test] +fn make_spirv_empty() { + let _: [u32; 0] = make_spirv_const([]); +} + /// CPU accessible buffer used to download data back from the GPU. pub struct DownloadBuffer { _gpu_buffer: super::Buffer, @@ -98,10 +163,7 @@ impl DownloadBuffer { buffer: &super::BufferSlice<'_>, callback: impl FnOnce(Result) + Send + 'static, ) { - let size = match buffer.size { - Some(size) => size.into(), - None => buffer.buffer.map_context.lock().total_size - buffer.offset, - }; + let size = buffer.size.into(); let download = device.create_buffer(&super::BufferDescriptor { size, diff --git a/wgpu/src/util/mutex.rs b/wgpu/src/util/mutex.rs new file mode 100644 index 000000000..86dff533d --- /dev/null +++ b/wgpu/src/util/mutex.rs @@ -0,0 +1,60 @@ +//! Provides a [`Mutex`] for internal use based on what features are available. + +cfg_if::cfg_if! { + if #[cfg(feature = "parking_lot")] { + use parking_lot::Mutex as MutexInner; + } else if #[cfg(std)] { + use std::sync::Mutex as MutexInner; + } else { + use core::cell::RefCell as MutexInner; + } +} + +pub(crate) struct Mutex { + inner: MutexInner, +} + +impl core::fmt::Debug for Mutex +where + MutexInner: core::fmt::Debug, +{ + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + as core::fmt::Debug>::fmt(&self.inner, f) + } +} + +impl Default for Mutex { + fn default() -> Self { + Self::new(::default()) + } +} + +impl Mutex { + pub const fn new(value: T) -> Self { + Self { + inner: MutexInner::new(value), + } + } +} + +impl Mutex { + pub fn lock(&self) -> impl core::ops::DerefMut + '_ { + cfg_if::cfg_if! { + if #[cfg(feature = "parking_lot")] { + self.inner.lock() + } else if #[cfg(std)] { + self.inner.lock().unwrap_or_else(std::sync::PoisonError::into_inner) + } else { + loop { + let Ok(lock) = self.inner.try_borrow_mut() else { + // Without `std` all we can do is spin until the current lock is released + core::hint::spin_loop(); + continue; + }; + + break lock; + } + } + } + } +} diff --git a/wgpu/src/util/texture_blitter.rs b/wgpu/src/util/texture_blitter.rs index 2ee6c85d5..f05ea1512 100644 --- a/wgpu/src/util/texture_blitter.rs +++ b/wgpu/src/util/texture_blitter.rs @@ -130,7 +130,7 @@ impl<'a> TextureBlitterBuilder<'a> { write_mask: ColorWrites::ALL, })], }), - multiview: None, + multiview_mask: None, cache: None, }); @@ -199,6 +199,7 @@ impl TextureBlitter { label: Some("wgpu::util::TextureBlitter::pass"), color_attachments: &[Some(crate::RenderPassColorAttachment { view: target, + depth_slice: None, resolve_target: None, ops: wgt::Operations { load: LoadOp::Load, @@ -208,6 +209,7 @@ impl TextureBlitter { depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, }); pass.set_pipeline(&self.pipeline); pass.set_bind_group(0, &bind_group, &[]); diff --git a/xtask/Cargo.lock b/xtask/Cargo.lock deleted file mode 100644 index da50a58f9..000000000 --- a/xtask/Cargo.lock +++ /dev/null @@ -1,63 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "anyhow" -version = "1.0.75" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6" - -[[package]] -name = "env_logger" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85cdab6a89accf66733ad5a1693a4dcced6aeff64602b634530dd73c1f3ee9f0" -dependencies = [ - "log", -] - -[[package]] -name = "log" -version = "0.4.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" - -[[package]] -name = "pico-args" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" - -[[package]] -name = "regex-lite" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30b661b2f27137bdbc16f00eda72866a92bb28af1753ffbd56744fb6e2e9cd8e" - -[[package]] -name = "xshell" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce2107fe03e558353b4c71ad7626d58ed82efaf56c54134228608893c77023ad" -dependencies = [ - "xshell-macros", -] - -[[package]] -name = "xshell-macros" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e2c411759b501fb9501aac2b1b2d287a6e93e5bdcf13c25306b23e1b716dd0e" - -[[package]] -name = "xtask" -version = "0.1.0" -dependencies = [ - "anyhow", - "env_logger", - "log", - "pico-args", - "regex-lite", - "xshell", -] diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index cc22def43..330949337 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -1,8 +1,8 @@ [package] -name = "xtask" +name = "wgpu-xtask" version = "0.1.0" edition = "2021" -rust-version = "1.84" +rust-version.workspace = true publish = false [lints.rust] @@ -11,17 +11,11 @@ unexpected_cfgs = { level = "warn", check-cfg = [ 'cfg(trick_rust_analyzer_into_highlighting_interpolated_bits)', ] } -[dependencies] +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] # The dependencies in this config have no transitive dependencies. -anyhow = "1.0.71" -env_logger = { version = "0.10.0", default-features = false } -regex-lite = "0.1.5" -log = "0.4.18" -pico-args = { version = "0.5.0", features = [ - "eq-separator", - "short-space-opt", - "combined-flags", -] } -xshell = "0.2.3" - -[workspace] +anyhow.workspace = true +env_logger.workspace = true +regex-lite.workspace = true +log.workspace = true +pico-args.workspace = true +xshell.workspace = true diff --git a/xtask/src/cts.rs b/xtask/src/cts.rs new file mode 100644 index 000000000..e23952fcd --- /dev/null +++ b/xtask/src/cts.rs @@ -0,0 +1,284 @@ +//! Interface for running the WebGPU CTS (Conformance Test Suite) against wgpu. +//! +//! To run the default set of tests from `cts_runner/test.lst`: +//! +//! ```sh +//! cargo xtask cts +//! ``` +//! +//! To run a specific test selector: +//! +//! ```sh +//! cargo xtask cts 'webgpu:api,operation,command_buffer,basic:*' +//! ``` +//! +//! You can also supply your own test list in a file: +//! +//! ```sh +//! cargo xtask cts -f your_tests.lst +//! ``` +//! +//! Each line in a test list file is a test selector that will be passed to the +//! CTS's own command line runner. Note that wildcards may only be used to specify +//! running all tests in a file, or all subtests in a test. +//! +//! A test line may optionally contain a `fails-if(backend)` clause. This +//! indicates that the test should be skipped on that backend, however, the +//! runner will only do so if the `--backend` flag is passed to tell it where +//! it is running. +//! +//! Lines starting with `//` or `#` in the test list are treated as comments and +//! ignored. + +use anyhow::{bail, Context}; +use pico_args::Arguments; +use regex_lite::{Regex, RegexBuilder}; +use std::{ffi::OsString, sync::LazyLock}; +use xshell::Shell; + +use crate::util::git_version_at_least; + +/// Path within the repository where the CTS will be checked out. +const CTS_CHECKOUT_PATH: &str = "cts"; + +/// Path within the repository to a file containing the git revision of the CTS to check out. +const CTS_REVISION_PATH: &str = "cts_runner/revision.txt"; + +/// URL of the CTS git repository. +const CTS_GIT_URL: &str = "https://github.com/gpuweb/cts.git"; + +/// Path to default CTS test list. +const CTS_DEFAULT_TEST_LIST: &str = "cts_runner/test.lst"; + +#[derive(Default)] +struct TestLine { + pub selector: OsString, + pub fails_if: Vec, +} + +pub fn run_cts( + shell: Shell, + mut args: Arguments, + passthrough_args: Option>, +) -> anyhow::Result<()> { + let skip_checkout = args.contains("--skip-checkout"); + let llvm_cov = args.contains("--llvm-cov"); + let release = args.contains("--release"); + let running_on_backend = args.opt_value_from_str::<_, String>("--backend")?; + + if running_on_backend.is_none() { + log::warn!( + "fails-if conditions are only evaluated if a backend is specified with --backend" + ); + } + + let mut list_files = Vec::::new(); + while let Some(file) = args.opt_value_from_str("-f")? { + list_files.push(file); + } + + let mut tests = args + .finish() + .into_iter() + .map(|selector| TestLine { + selector, + ..Default::default() + }) + .collect::>(); + + if tests.is_empty() && list_files.is_empty() { + if passthrough_args.is_none() { + log::info!("Reading default test list from {CTS_DEFAULT_TEST_LIST}"); + list_files.push(OsString::from(CTS_DEFAULT_TEST_LIST)); + } + } else if passthrough_args.is_some() { + bail!("Test(s) and test list(s) are incompatible with passthrough arguments."); + } + + for file in list_files { + tests.extend(shell.read_file(file)?.lines().filter_map(|line| { + static TEST_LINE_REGEX: LazyLock = LazyLock::new(|| { + RegexBuilder::new( + r#"(?:fails-if\s*\(\s*(?\w+(?:,\w+)*?)\s*\)\s+)?(?.*)"#, + ) + .build() + .unwrap() + }); + + let trimmed = line.trim(); + let is_comment = trimmed.starts_with("//") || trimmed.starts_with("#"); + let captures = TEST_LINE_REGEX + .captures(trimmed) + .expect("Invalid test line: {trimmed}"); + (!trimmed.is_empty() && !is_comment).then(|| TestLine { + selector: OsString::from(&captures["selector"]), + fails_if: captures + .name("fails_if") + .map(|m| { + m.as_str() + .split_terminator(',') + .map(|m| m.to_string()) + .collect() + }) + .unwrap_or_default(), + }) + })) + } + + let wgpu_cargo_toml = std::path::absolute(shell.current_dir().join("Cargo.toml")) + .context("Failed to get path to Cargo.toml")?; + + let cts_revision = shell + .read_file(CTS_REVISION_PATH) + .context(format!( + "Failed to read CTS git SHA from {CTS_REVISION_PATH}" + ))? + .trim() + .to_string(); + + if !shell.path_exists(CTS_CHECKOUT_PATH) { + if skip_checkout { + bail!("Skipping CTS checkout doesn't make sense when CTS is not present"); + } + let mut cmd = shell + .cmd("git") + .args(["clone", CTS_GIT_URL, CTS_CHECKOUT_PATH]) + .quiet(); + + if git_version_at_least(&shell, [2, 49, 0])? { + log::info!("Cloning CTS shallowly with revision {cts_revision}"); + cmd = cmd.args(["--depth=1", "--revision", &cts_revision]); + cmd = cmd.args([ + "-c", + "remote.origin.fetch=+refs/heads/gh-pages:refs/remotes/origin/gh-pages", + ]); + } else { + log::info!("Cloning full checkout of CTS with revision {cts_revision}"); + cmd = cmd.args(["-b", "gh-pages", "--single-branch"]); + } + + cmd.run().context("Failed to clone CTS")?; + + shell.change_dir(CTS_CHECKOUT_PATH); + } else if !skip_checkout { + shell.change_dir(CTS_CHECKOUT_PATH); + + // For new clones, this is set by the cloning commands above, but older + // clones may not have it. Eventually this can be removed. + if shell + .cmd("git") + .args(["config", "--get", "remote.origin.fetch"]) + .quiet() + .ignore_stdout() + .ignore_stderr() + .run() + .is_err() + { + shell + .cmd("git") + .args([ + "config", + "remote.origin.fetch", + "+refs/heads/gh-pages:refs/remotes/origin/gh-pages", + ]) + .quiet() + .run() + .context("Failed setting git config")?; + } + + // If we don't have the CTS commit we want, try to fetch it. + if shell + .cmd("git") + .args(["cat-file", "commit", &cts_revision]) + .quiet() + .ignore_stdout() + .ignore_stderr() + .run() + .is_err() + { + log::info!("Fetching CTS"); + shell + .cmd("git") + .args(["fetch", "--quiet"]) + .quiet() + .run() + .context("Failed to fetch CTS")?; + } + } else { + shell.change_dir(CTS_CHECKOUT_PATH); + } + + if !skip_checkout { + log::info!("Checking out CTS"); + shell + .cmd("git") + .args(["checkout", "--quiet", &cts_revision]) + .quiet() + .run() + .context("Failed to check out CTS")?; + } else { + log::info!("Skipping CTS checkout because --skip-checkout was specified"); + } + + let run_flags = if llvm_cov { + &["llvm-cov", "--no-cfg-coverage", "--no-report", "run"][..] + } else { + &["run"][..] + }; + + if let Some(passthrough_args) = passthrough_args { + let mut cmd = shell + .cmd("cargo") + .args(run_flags) + .args(["--manifest-path".as_ref(), wgpu_cargo_toml.as_os_str()]) + .args(["-p", "cts_runner"]) + .args(["--bin", "cts_runner"]); + + if release { + cmd = cmd.arg("--release") + } + + cmd.args(["--", "./tools/run_deno", "--verbose"]) + .args(&passthrough_args) + .run()?; + + return Ok(()); + } + + log::info!("Running CTS"); + for test in &tests { + if let Some(running_on_backend) = &running_on_backend { + if test.fails_if.contains(running_on_backend) { + log::info!( + "Skipping {} on {} backend", + test.selector.to_string_lossy(), + running_on_backend, + ); + continue; + } + } + + log::info!("Running {}", test.selector.to_string_lossy()); + let mut cmd = shell + .cmd("cargo") + .args(run_flags) + .args(["--manifest-path".as_ref(), wgpu_cargo_toml.as_os_str()]) + .args(["-p", "cts_runner"]) + .args(["--bin", "cts_runner"]); + + if release { + cmd = cmd.arg("--release") + } + + cmd.args(["--", "./tools/run_deno", "--verbose"]) + .args([&test.selector]) + .run() + .context("CTS failed")?; + } + + if tests.len() > 1 { + log::info!("Summary reflects only tests from the last selector, not the entire run."); + } + + Ok(()) +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index a87c68ebd..81e0b6db5 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1,8 +1,13 @@ +#![cfg_attr(target_arch = "wasm32", no_main)] +#![cfg(not(target_arch = "wasm32"))] + use std::process::ExitCode; use anyhow::Context; use pico_args::Arguments; +mod cts; +mod miri; mod run_wasm; mod test; mod util; @@ -12,6 +17,16 @@ const HELP: &str = "\ Usage: xtask Commands: + cts [] [ | -f | -- ] + Check out, build, and run CTS tests + + --skip-checkout Don't check out the pinned CTS version, use whatever + is already checked out. + --release Build and run in release mode + --llvm-cov Run with LLVM code coverage + --backend Specify the backend (metal, dx12, or vulkan). Used + to evaluate `fails-if` conditions in the test list. + run-wasm Build and run web examples @@ -27,6 +42,14 @@ Commands: All extra arguments will be forwarded to cargo-nextest (NOT wgpu-info) + miri + Run all miri-compatible tests under miri. Requires a nightly toolchain + with the x86_64-unknown-linux-gnu target and miri component installed. + + --toolchain The toolchain to use for miri tests. + Must be a nightly toolchain. + Defaults to `nightly`. + vendor-web-sys Re-vendor the WebGPU web-sys bindings. @@ -44,7 +67,7 @@ Options: #[macro_export] macro_rules! bad_arguments { ($($arg:tt)*) => {{ - eprintln!("{}", crate::HELP); + eprintln!("{}", $crate::HELP); anyhow::bail!($($arg)*) }}; } @@ -56,9 +79,14 @@ fn main() -> anyhow::Result { .format_indent(Some(0)) .init(); - let mut args = Arguments::from_env(); + let mut args = std::env::args_os().skip(1).collect::>(); + let passthrough_args = args + .iter() + .position(|arg| arg == "--") + .map(|pos| args.drain(pos..).skip(1).collect()); + let mut args = Arguments::from_vec(args); - if args.contains("--help") { + if args.contains(["-h", "--help"]) { eprint!("{HELP}"); return Ok(ExitCode::FAILURE); } @@ -73,8 +101,10 @@ fn main() -> anyhow::Result { shell.change_dir(String::from(env!("CARGO_MANIFEST_DIR")) + "/.."); match subcommand.as_deref() { - Some("run-wasm") => run_wasm::run_wasm(shell, args)?, - Some("test") => test::run_tests(shell, args)?, + Some("cts") => cts::run_cts(shell, args, passthrough_args)?, + Some("run-wasm") => run_wasm::run_wasm(shell, args, passthrough_args)?, + Some("miri") => miri::run_miri(shell, args)?, + Some("test") => test::run_tests(shell, args, passthrough_args)?, Some("vendor-web-sys") => vendor_web_sys::run_vendor_web_sys(shell, args)?, Some(subcommand) => { bad_arguments!("Unknown subcommand: {}", subcommand) diff --git a/xtask/src/miri.rs b/xtask/src/miri.rs new file mode 100644 index 000000000..075b115fd --- /dev/null +++ b/xtask/src/miri.rs @@ -0,0 +1,30 @@ +use pico_args::Arguments; +use xshell::Shell; + +pub fn run_miri(shell: Shell, mut args: Arguments) -> anyhow::Result<()> { + let toolchain: String = args + .opt_value_from_str("--toolchain")? + .unwrap_or_else(|| String::from("nightly")); + + shell + .cmd("rustup") + .args([ + "run", + &toolchain, + "cargo", + "miri", + "nextest", + "run", + "--target", + "x86_64-unknown-linux-gnu", + ]) + .env( + "MIRIFLAGS", + "-Zmiri-disable-isolation -Zmiri-deterministic-floats", + ) + .env("WGPU_GPU_TESTS_USE_NOOP_BACKEND", "1") + .quiet() + .run()?; + + Ok(()) +} diff --git a/xtask/src/run_wasm.rs b/xtask/src/run_wasm.rs index d8048b3ca..8c556895d 100644 --- a/xtask/src/run_wasm.rs +++ b/xtask/src/run_wasm.rs @@ -1,13 +1,19 @@ -use anyhow::Context; +use std::ffi::OsString; +use anyhow::Context; use pico_args::Arguments; use xshell::Shell; -use crate::util::{check_all_programs, Program}; +use crate::util::{check_all_programs, flatten_args, Program}; -pub(crate) fn run_wasm(shell: Shell, mut args: Arguments) -> anyhow::Result<()> { +pub(crate) fn run_wasm( + shell: Shell, + mut args: Arguments, + passthrough_args: Option>, +) -> anyhow::Result<()> { let should_serve = !args.contains("--no-serve"); let release = args.contains("--release"); + let cargo_args = flatten_args(args, passthrough_args); let mut programs_needed = vec![Program { crate_name: "wasm-bindgen-cli", @@ -28,11 +34,9 @@ pub(crate) fn run_wasm(shell: Shell, mut args: Arguments) -> anyhow::Result<()> log::info!("building webgpu examples"); - let cargo_args = args.finish(); - xshell::cmd!( shell, - "cargo build --target wasm32-unknown-unknown --bin wgpu-examples --no-default-features --features webgpu {release_flag...}" + "cargo build --target wasm32-unknown-unknown -p wgpu-examples --no-default-features --features webgpu {release_flag...}" ) .args(&cargo_args) .quiet() @@ -53,7 +57,7 @@ pub(crate) fn run_wasm(shell: Shell, mut args: Arguments) -> anyhow::Result<()> xshell::cmd!( shell, - "cargo build --target wasm32-unknown-unknown --bin wgpu-examples --no-default-features --features webgl {release_flag...}" + "cargo build --target wasm32-unknown-unknown -p wgpu-examples --no-default-features --features webgl {release_flag...}" ) .args(&cargo_args) .quiet() diff --git a/xtask/src/test.rs b/xtask/src/test.rs index f1bce2c07..58516fb1b 100644 --- a/xtask/src/test.rs +++ b/xtask/src/test.rs @@ -1,10 +1,19 @@ +use std::ffi::OsString; + use anyhow::Context; use pico_args::Arguments; use xshell::Shell; -pub fn run_tests(shell: Shell, mut args: Arguments) -> anyhow::Result<()> { +use crate::util::flatten_args; + +pub fn run_tests( + shell: Shell, + mut args: Arguments, + passthrough_args: Option>, +) -> anyhow::Result<()> { let llvm_cov = args.contains("--llvm-cov"); let list = args.contains("--list"); + let cargo_args = flatten_args(args, passthrough_args); // Retries handled by cargo nextest natively // These needs to match the command in "run wgpu-info" in `.github/workflows/ci.yml` @@ -58,7 +67,7 @@ pub fn run_tests(shell: Shell, mut args: Arguments) -> anyhow::Result<()> { .cmd("cargo") .args(llvm_cov_nextest_flags) .args(["-v", "--benches", "--tests", "--all-features"]) - .args(args.finish()) + .args(cargo_args) .run() .context("Failed to list tests")?; return Ok(()); @@ -69,7 +78,7 @@ pub fn run_tests(shell: Shell, mut args: Arguments) -> anyhow::Result<()> { .cmd("cargo") .args(llvm_cov_nextest_flags) .args(["--benches", "--tests", "--all-features"]) - .args(args.finish()) + .args(cargo_args) .quiet() .run() .context("Tests failed")?; diff --git a/xtask/src/util.rs b/xtask/src/util.rs index 186426971..aaece549a 100644 --- a/xtask/src/util.rs +++ b/xtask/src/util.rs @@ -1,10 +1,38 @@ -use std::{io, process::Command}; +use std::{ffi::OsString, io, process::Command}; + +use anyhow::Context; +use pico_args::Arguments; +use xshell::Shell; pub(crate) struct Program { pub crate_name: &'static str, pub binary_name: &'static str, } +pub(crate) fn looks_like_git_sha(input: &str) -> bool { + input.len() == 40 && input.chars().all(|c| c.is_ascii_hexdigit()) +} + +pub(crate) fn flatten_args( + args: Arguments, + passthrough_args: Option>, +) -> Vec { + if let Some(passthrough_args) = passthrough_args { + let mut args = args.finish(); + // The following matches the historical behavior of our xtasks, however, + // it would be more general not to re-insert the terminator here, so + // that arguments can be passed either to cargo or to tests. i.e., with + // the next line, the args are interpreted as `xtask test + // -- `, without it the args would be interpreted as `xtask + // test -- -- `. + args.push(OsString::from("--")); + args.extend(passthrough_args); + args + } else { + args.finish() + } +} + pub(crate) fn check_all_programs(programs: &[Program]) -> anyhow::Result<()> { let mut failed_crates = Vec::new(); for &Program { @@ -25,7 +53,7 @@ pub(crate) fn check_all_programs(programs: &[Program]) -> anyhow::Result<()> { } Err(e) => { log::error!("Checking for {binary_name} in PATH: ❌"); - panic!("Unknown IO error: {:?}", e); + panic!("Unknown IO error: {e:?}"); } } } @@ -41,3 +69,119 @@ pub(crate) fn check_all_programs(programs: &[Program]) -> anyhow::Result<()> { Ok(()) } + +pub(crate) fn git_version_at_least(shell: &Shell, version: GitVersion) -> anyhow::Result { + let output = shell + .cmd("git") + .args(["--version"]) + .output() + .context("Failed to invoke `git --version`")?; + + let Some(code) = output.status.code() else { + anyhow::bail!("`git --version` failed to return an exit code; interrupt via signal, maybe?") + }; + + anyhow::ensure!(code == 0, "`git --version` returned a nonzero exit code"); + + let fmt_err_msg = "`git --version` did not have the expected structure"; + + let stdout = String::from_utf8(output.stdout).expect(fmt_err_msg); + + let parsed = parse_git_version_output(&stdout).expect(fmt_err_msg); + + Ok(parsed >= version) +} + +pub(crate) type GitVersion = [u8; 3]; + +fn parse_git_version_output(output: &str) -> anyhow::Result { + const PREFIX: &str = "git version "; + + let raw_version = output + .strip_prefix(PREFIX) + .with_context(|| format!("missing `{PREFIX}` prefix"))?; + + let raw_version = raw_version.trim_end(); // There should always be a newline at the end, but + // we don't care if it's missing. + + // Git for Windows suffixes the version with ".windows.". + // Strip it if present. + let raw_version = raw_version + .split_once(".windows") + .map_or(raw_version, |(before, _after)| before); + + let parsed = GitVersion::try_from( + raw_version + .splitn(3, '.') + .enumerate() + .map(|(idx, s)| { + s.parse().with_context(|| { + format!("failed to parse version number {idx} ({s:?}) as `u8`") + }) + }) + .collect::, _>>()?, + ) + .map_err(|vec| anyhow::Error::msg(format!("less than 3 version numbers found: {vec:?}")))?; + + log::debug!("detected Git version {raw_version}"); + + Ok(parsed) +} + +#[test] +fn test_git_version_parsing() { + macro_rules! test_ok { + ($input:expr, $expected:expr) => { + assert_eq!(parse_git_version_output($input).unwrap(), $expected); + }; + } + test_ok!("git version 2.3.0", [2, 3, 0]); + test_ok!("git version 0.255.0", [0, 255, 0]); + test_ok!("git version 4.5.6", [4, 5, 6]); + test_ok!("git version 2.3.0.windows.1", [2, 3, 0]); + + macro_rules! test_err { + ($input:expr, $msg:expr) => { + assert_eq!( + parse_git_version_output($input).unwrap_err().to_string(), + $msg + ) + }; + } + test_err!("2.3.0", "missing `git version ` prefix"); + test_err!("", "missing `git version ` prefix"); + + test_err!( + "git version 1.2", + "less than 3 version numbers found: [1, 2]" + ); + + test_err!( + "git version 9001", + "failed to parse version number 0 (\"9001\") as `u8`" + ); + test_err!( + "git version ", + "failed to parse version number 0 (\"\") as `u8`" + ); + test_err!( + "git version asdf", + "failed to parse version number 0 (\"asdf\") as `u8`" + ); + test_err!( + "git version 23.beta", + "failed to parse version number 1 (\"beta\") as `u8`" + ); + test_err!( + "git version 1.2.wat", + "failed to parse version number 2 (\"wat\") as `u8`" + ); + test_err!( + "git version 1.2.3.", + "failed to parse version number 2 (\"3.\") as `u8`" + ); + test_err!( + "git version 1.2.3.4", + "failed to parse version number 2 (\"3.4\") as `u8`" + ); +} diff --git a/xtask/src/vendor_web_sys.rs b/xtask/src/vendor_web_sys.rs index 451e95465..15f25f452 100644 --- a/xtask/src/vendor_web_sys.rs +++ b/xtask/src/vendor_web_sys.rs @@ -1,8 +1,12 @@ use anyhow::Context; use pico_args::Arguments; +use std::fmt::Write; use xshell::Shell; -use crate::bad_arguments; +use crate::{ + bad_arguments, + util::{git_version_at_least, looks_like_git_sha}, +}; /// Path to the webgpu_sys folder relative to the root of the repository const WEBGPU_SYS_PATH: &str = "wgpu/src/backend/webgpu/webgpu_sys"; @@ -157,7 +161,7 @@ pub(crate) fn run_vendor_web_sys(shell: Shell, mut args: Arguments) -> anyhow::R let path_to_checkout_arg: Option = args.opt_value_from_str("--path-to-checkout")?; // Plain text of the command that was run. - let argument_description; + let mut argument_description; // Path to the checkout we're using let path_to_wasm_bindgen_checkout; match (path_to_checkout_arg.as_deref(), version.as_deref()) { @@ -177,6 +181,11 @@ pub(crate) fn run_vendor_web_sys(shell: Shell, mut args: Arguments) -> anyhow::R } }; + let git_url: Option = args.opt_value_from_str("--git-url")?; + if let Some(url) = &git_url { + write!(&mut argument_description, " --git-url {url}")?; + } + let unknown_args = args.finish(); if !unknown_args.is_empty() { bad_arguments!( @@ -192,22 +201,31 @@ pub(crate) fn run_vendor_web_sys(shell: Shell, mut args: Arguments) -> anyhow::R .remove_path(WEBGPU_SYS_PATH) .context("could not remove webgpu_sys")?; - if let Some(ref version) = version { + if let Some(version) = version.as_deref() { eprintln!("# Cloning wasm-bindgen repository with version {version}"); - shell - .cmd("git") - .args([ - "clone", - "-b", - version, - "--depth", - "1", - "https://github.com/rustwasm/wasm-bindgen.git", - WASM_BINDGEN_TEMP_CLONE_PATH, - ]) - .ignore_stderr() - .run() - .context("Could not clone wasm-bindgen repository")?; + let mut cmd = shell.cmd("git").args(["clone"]); + + if looks_like_git_sha(version) { + if git_version_at_least(&shell, [2, 49, 0])? { + cmd = cmd.args(["--revision", version]); + } else { + bad_arguments!("Must have git >= 2.49 to clone a SHA with --revision"); + } + } else { + cmd = cmd.args(["-b", version]); + } + + cmd.args([ + "--depth", + "1", + git_url + .as_deref() + .unwrap_or("https://github.com/wasm-bindgen/wasm-bindgen.git"), + WASM_BINDGEN_TEMP_CLONE_PATH, + ]) + .ignore_stderr() + .run() + .context("Could not clone wasm-bindgen repository")?; } if let Some(ref path) = path_to_checkout_arg { @@ -221,7 +239,7 @@ pub(crate) fn run_vendor_web_sys(shell: Shell, mut args: Arguments) -> anyhow::R // The indentation here does not matter, as rustfmt will normalize it. let file_prefix = format!("\ // DO NOT EDIT THIS FILE! - // + // // This module part of a subset of web-sys that is used by wgpu's webgpu backend. // // These bindings are vendored into wgpu for the sole purpose of letting @@ -238,8 +256,8 @@ pub(crate) fn run_vendor_web_sys(shell: Shell, mut args: Arguments) -> anyhow::R // Vendoring also allows us to avoid building `web-sys` with // `--cfg=web_sys_unstable_apis`, needed to get the WebGPU bindings. // - // If you want to improve the generated code, please submit a PR to the https://github.com/rustwasm/wasm-bindgen repository. - // + // If you want to improve the generated code, please submit a PR to the https://github.com/wasm-bindgen/wasm-bindgen repository. + // // This file was generated by the `cargo xtask vendor-web-sys {argument_description}` command.\n" ); @@ -278,7 +296,7 @@ pub(crate) fn run_vendor_web_sys(shell: Shell, mut args: Arguments) -> anyhow::R let mut module_file_contents = format!( "\ //! Bindings to the WebGPU API. - //! + //! //! Internally vendored from the `web-sys` crate until the WebGPU binding are stabilized. {file_prefix} #![allow(unused_imports, non_snake_case)]\n" @@ -287,11 +305,11 @@ pub(crate) fn run_vendor_web_sys(shell: Shell, mut args: Arguments) -> anyhow::R module_file_contents.push_str("use web_sys::{Event, EventTarget};\n"); for &feature in WEB_SYS_FEATURES_NEEDED { - module_file_contents.push_str(&format!("mod gen_{};\n", feature)); - module_file_contents.push_str(&format!("pub use gen_{}::*;\n", feature)); + module_file_contents.push_str(&format!("mod gen_{feature};\n")); + module_file_contents.push_str(&format!("pub use gen_{feature}::*;\n")); } - shell.write_file(format!("{}/mod.rs", WEBGPU_SYS_PATH), module_file_contents)?; + shell.write_file(format!("{WEBGPU_SYS_PATH}/mod.rs"), module_file_contents)?; eprintln!("# Formatting files");