Reset firefox to trunk commit ccc650fd

This commit is contained in:
Andy Leiserson committed 2025-11-13 13:59:39 -08:00
commit cf508f8454
1654 files changed
+98115 -43218

No files matched your search

+5 -1
View File
@@ -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\""]
+23 -1
View File
@@ -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)'
+32 -19
View File
@@ -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 = []
-1
View File
@@ -1 +0,0 @@
use nix
-17
View File
@@ -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
+1 -1
View File
@@ -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.
+17
View File
@@ -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"
+61
View File
@@ -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"
@@ -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"
+25
View File
@@ -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
-27
View File
@@ -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
+119 -184
View File
@@ -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 }}
+119
View File
@@ -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 <<EOF >> .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 }}
+9 -2
View File
@@ -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
+17 -4
View File
@@ -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.
+55 -48
View File
@@ -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
+9 -2
View File
@@ -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
+17 -49
View File
@@ -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
+10 -3
View File
@@ -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
wgpu/src/backend/webgpu/webgpu_sys/wasm_bindgen_clone_tmp
+4
View File
@@ -0,0 +1,4 @@
**/*.frag
**/*.vert
naga/tests/in/
naga/tests/out/
+951 -118
View File
File diff suppressed because it is too large. Load diff
+26 -26
View File
@@ -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
Generated
+1347 -944
View File
File diff suppressed because it is too large. Load diff
+118 -76
View File
@@ -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]
+11 -11
View File
@@ -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.
+1 -1
View File
@@ -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
+34 -27
View File
@@ -2,10 +2,10 @@
<img align="right" width="20%" src="logo.png">
[![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 "<test string>"
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
+84
View File
@@ -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.
+2 -3
View File
@@ -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
@@ -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();
}
@@ -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();
}
@@ -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,
}))
@@ -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();
}
@@ -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
@@ -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<u8>,
string: Option<String>,
options: Parameters,
module: Option<naga::Module>,
module_info: Option<naga::valid::ModuleInfo>,
}
impl From<Input> 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<Input>,
inner: Vec<InputWithInfo>,
}
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<InputWithInfo> = 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<InputWithInfo> = 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::<Vec<_>>();
b.iter(move || {
for input in inputs_bin.iter() {
bincode::deserialize::<naga::Module>(input).unwrap();
bincode::serde::decode_from_slice::<naga::Module, _>(
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::<Vec<u32>>::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);
-2
View File
@@ -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" },
]
+8 -1
View File
@@ -1,20 +1,27 @@
[package]
name = "cts_runner"
version = "0.1.0"
version.workspace = true
authors = ["Luca Casonato <hello@lcas.dev>"]
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
+17
View File
@@ -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`.
+2 -2
View File
@@ -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!");
+1 -1
View File
@@ -1 +1 @@
7ea73ba6f44c9f6fedfffc06f14c73ea9f2eaa11
964a0b43f1505f75ea62acf88674adf3962a5218
+25 -4
View File
@@ -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),
+131 -143
View File
@@ -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::<Permissions>(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::<Vec<String>>();
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::<v8::Function>::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::<Permissions>(
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::<Vec<String>>();
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::<v8::Function>::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<Vec<u8>, 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<Vec<u8>, 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<T>(result: Result<T, AnyError>) -> T {
match result {
Ok(value) => value,
Err(error) => {
eprintln!("{}: {:?}", red_bold("error"), error);
std::process::exit(1);
}
}
}
fn style<S: AsRef<str>>(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: AsRef<str>>(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<T>(result: Result<T, AnyError>) -> 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: AsRef<str>>(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: AsRef<str>>(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)
}
+169 -3
View File
@@ -1,10 +1,176 @@
// The following may be useful to generate lists of tests for this file:
// ```
// cargo xtask cts -- --list <selector>
// ```
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 <https://github.com/gfx-rs/wgpu/issues/4507>.
// - Fails with `vec3` & `f16` cases on macOS because of <https://github.com/gfx-rs/wgpu/issues/5262>.
//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<f32>";*
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:*
+78 -8
View File
@@ -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<OsStr>) -> Output {
Command::new(cts_runner_exe_path())
.arg(script_file)
.output()
.unwrap()
}
fn exec_js_file(script_file: impl AsRef<OsStr>) {
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",
);
}
+191 -58
View File
@@ -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,
+2 -2
View File
@@ -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
+8 -6
View File
@@ -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
+369 -348
View File
@@ -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<GPUPowerPreference>,
#[webidl(default = false)]
pub force_fallback_adapter: bool,
pub power_preference: Option<GPUPowerPreference>,
#[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<GPUFeatureName>,
#[webidl(default = Default::default())]
#[options(enforce_range = true)]
required_limits: indexmap::IndexMap<String, Option<u64>>,
#[webidl(default = vec![])]
required_features: Vec<GPUFeatureName>,
#[webidl(default = Default::default())]
#[options(enforce_range = true)]
required_limits: indexmap::IndexMap<String, Option<u64>>,
}
pub struct GPUAdapter {
pub instance: Instance,
pub id: wgpu_core::id::AdapterId,
pub instance: Instance,
pub id: wgpu_core::id::AdapterId,
pub features: SameObject<GPUSupportedFeatures>,
pub limits: SameObject<GPUSupportedLimits>,
pub info: Rc<SameObject<GPUAdapterInfo>>,
pub features: SameObject<GPUSupportedFeatures>,
pub limits: SameObject<GPUSupportedLimits>,
pub info: Rc<SameObject<GPUAdapterInfo>>,
}
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<v8::Object> {
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<GPUAdapter, GPUGenericError> {
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<v8::Object> {
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<v8::Object> {
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<v8::Object> {
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<v8::Global<v8::Value>, 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::<HashSet<_>>();
if !required_features.is_subset(&supported_features) {
return Err(CreateDeviceError::RequiredFeaturesNotASubset);
}
#[getter]
#[global]
fn features(&self, scope: &mut v8::HandleScope) -> v8::Global<v8::Object> {
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<v8::Object> {
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::<wgpu_types::Limits>(
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<v8::Global<v8::Value>, 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::<HashSet<_>>();
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::<V8TaskSpawner>().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::<crate::EventTargetSetup>();
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::<v8::Function>();
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::<v8::Value>();
deno_core::cppgc::try_unwrap_cppgc_object::<GPUDevice>(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::<crate::EventTargetSetup>();
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::<v8::Function>();
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::<v8::Function>().unwrap());
let device = v8::Global::new(scope, device.cast::<v8::Value>());
let error_event_class = state.borrow::<crate::ErrorEventClass>().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::<v8::Function>::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<GPUSupportedLimits, GPUGenericError> {
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<v8::Value>);
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<GPUFeatureName>) -> Self {
let set = v8::Set::new(scope);
#[allow(clippy::disallowed_types)]
pub fn new(
scope: &mut v8::HandleScope,
features: HashSet<GPUFeatureName>,
) -> 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, <v8::Local<v8::Value>>::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, <v8::Local<v8::Value>>::from(set)))
}
}
#[op2]
impl GPUSupportedFeatures {
#[global]
#[symbol("setlike_set")]
fn set(&self) -> v8::Global<v8::Value> {
self.0.clone()
}
#[constructor]
#[cppgc]
fn constructor(_: bool) -> Result<GPUSupportedFeatures, GPUGenericError> {
Err(GPUGenericError::InvalidConstructor)
}
#[global]
#[symbol("setlike_set")]
fn set(&self) -> v8::Global<v8::Value> {
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<GPUAdapterInfo, GPUGenericError> {
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
}
}
+99 -59
View File
@@ -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<GPUBindGroup, GPUGenericError> {
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<super::bind_group_layout::GPUBindGroupLayout>,
pub entries: Vec<GPUBindGroupEntry>,
pub layout: Ptr<super::bind_group_layout::GPUBindGroupLayout>,
pub entries: Vec<GPUBindGroupEntry>,
}
#[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<GPUBuffer>,
#[webidl(default = 0)]
#[options(enforce_range = true)]
pub offset: u64,
#[options(enforce_range = true)]
pub size: Option<u64>,
pub buffer: Ptr<GPUBuffer>,
#[webidl(default = 0)]
#[options(enforce_range = true)]
pub offset: u64,
#[options(enforce_range = true)]
pub size: Option<u64>,
}
pub(crate) enum GPUBindingResource {
Sampler(Ptr<GPUSampler>),
TextureView(Ptr<GPUTextureView>),
BufferBinding(GPUBufferBinding),
Sampler(Ptr<GPUSampler>),
Texture(Ptr<GPUTexture>),
TextureView(Ptr<GPUTextureView>),
Buffer(Ptr<GPUBuffer>),
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<Self, WebIdlError> {
<Ptr<GPUSampler>>::convert(scope, value, prefix.clone(), context.borrowed(), options)
.map(Self::Sampler)
.or_else(|_| {
<Ptr<GPUTextureView>>::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<Self, WebIdlError> {
<Ptr<GPUSampler>>::convert(
scope,
value,
prefix.clone(),
context.borrowed(),
options,
)
.map(Self::Sampler)
.or_else(|_| {
<Ptr<GPUTexture>>::convert(
scope,
value,
prefix.clone(),
context.borrowed(),
options,
)
.map(Self::Texture)
})
.or_else(|_| {
<Ptr<GPUTextureView>>::convert(
scope,
value,
prefix.clone(),
context.borrowed(),
options,
)
.map(Self::TextureView)
})
.or_else(|_| {
<Ptr<GPUBuffer>>::convert(
scope,
value,
prefix.clone(),
context.borrowed(),
options,
)
.map(Self::Buffer)
})
.or_else(|_| {
GPUBufferBinding::convert(scope, value, prefix, context, options)
.map(Self::BufferBinding)
})
}
}
+103 -88
View File
@@ -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<GPUBindGroupLayout, GPUGenericError> {
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<GPUBindGroupLayoutEntry>,
#[webidl(default = String::new())]
pub label: String,
pub entries: Vec<GPUBindGroupLayoutEntry>,
}
#[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<GPUBufferBindingLayout>,
pub sampler: Option<GPUSamplerBindingLayout>,
pub texture: Option<GPUTextureBindingLayout>,
pub storage_texture: Option<GPUStorageTextureBindingLayout>,
#[options(enforce_range = true)]
pub binding: u32,
#[options(enforce_range = true)]
pub visibility: u32,
pub buffer: Option<GPUBufferBindingLayout>,
pub sampler: Option<GPUSamplerBindingLayout>,
pub texture: Option<GPUTextureBindingLayout>,
pub storage_texture: Option<GPUStorageTextureBindingLayout>,
}
#[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<GPUBufferBindingType> 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<GPUSamplerBindingType> 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<GPUTextureSampleType> 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<GPUStorageTextureAccess> 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,
}
}
}
+218 -199
View File
@@ -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<Option<MapMode>>,
pub map_state: RefCell<&'static str>,
pub map_mode: RefCell<Option<MapMode>>,
pub mapped_js_buffers: RefCell<Vec<v8::Global<v8::ArrayBuffer>>>,
pub mapped_js_buffers: RefCell<Vec<v8::Global<v8::ArrayBuffer>>>,
}
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<GPUBuffer, GPUGenericError> {
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<u64>,
) -> 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::<wgpu_core::resource::BufferAccessResult>();
{
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<u64>,
) -> 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::<wgpu_core::resource::BufferAccessResult>();
{
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<u64>,
) -> Result<v8::Local<'s, v8::ArrayBuffer>, 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<u64>,
) -> Result<v8::Local<'s, v8::ArrayBuffer>, 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);
}
}
+345 -298
View File
@@ -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<u32>,
pub height: RefCell<u32>,
pub context: SameObject<GPUCanvasContext>,
}
impl GarbageCollected for UnsafeWindowSurface {}
#[op2]
impl UnsafeWindowSurface {
#[constructor]
#[cppgc]
fn new(
state: &mut OpState,
#[from_v8] options: UnsafeWindowSurfaceOptions,
) -> Result<UnsafeWindowSurface, ByowError> {
let instance = state
.try_borrow::<super::Instance>()
.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<v8::Object>,
scope: &mut v8::HandleScope,
) -> v8::Global<v8::Object> {
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<Self, Self::Error> {
let obj = value
.try_cast::<v8::Object>()
.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::<u32>::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::<u32>::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<RawHandles, ByowError> {
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<RawHandles, ByowError> {
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<RawHandles, ByowError> {
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<u32>,
pub height: RefCell<u32>,
pub context: SameObject<GPUCanvasContext>,
}
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<UnsafeWindowSurface, ByowError> {
let instance = state
.try_borrow::<super::Instance>()
.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<v8::Object>,
scope: &mut v8::HandleScope,
) -> v8::Global<v8::Object> {
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<Self, Self::Error> {
let obj = value
.try_cast::<v8::Object>()
.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::<u32>::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::<u32>::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<RawHandles, ByowError> {
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<RawHandles, ByowError> {
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<RawHandles, ByowError> {
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<RawHandles, deno_error::JsErrorBox> {
Err(deno_error::JsErrorBox::type_error("Unsupported platform"))
_system: UnsafeWindowSurfaceSystem,
_window: *const c_void,
_display: *const c_void,
) -> Result<RawHandles, ByowError> {
Err(ByowError::Unsupported)
}
+31 -26
View File
@@ -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<GPUCommandBuffer, GPUGenericError> {
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,
}
+411 -314
View File
@@ -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<GPUCommandEncoder, GPUGenericError> {
Err(GPUGenericError::InvalidConstructor)
}
#[required(1)]
#[cppgc]
fn begin_render_pass(
&self,
#[webidl] descriptor: crate::render_pass::GPURenderPassDescriptor,
) -> Result<GPURenderPassEncoder, JsErrorBox> {
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::<Vec<_>>(),
);
#[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<GPURenderPassEncoder, JsErrorBox> {
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::<Vec<_>>(),
);
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<GPUBuffer>,
#[webidl(options(enforce_range = true))] source_offset: u64,
#[webidl] destination: Ptr<GPUBuffer>,
#[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,
&copy_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,
&copy_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,
&copy_size.into(),
)
.err();
self.error_handler.push_error(err);
}
#[required(1)]
fn clear_buffer(
&self,
#[webidl] buffer: Ptr<GPUBuffer>,
#[webidl(default = 0, options(enforce_range = true))] offset: u64,
#[webidl(options(enforce_range = true))] size: Option<u64>,
) {
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<super::query_set::GPUQuerySet>,
#[webidl(options(enforce_range = true))] first_query: u32,
#[webidl(options(enforce_range = true))] query_count: u32,
#[webidl] destination: Ptr<GPUBuffer>,
#[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<GPUBuffer>,
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<GPUBuffer>;
let destination_offset: BufferAddress;
let size: Option<BufferAddress>;
// 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::<GPUBuffer>::convert(
scope,
arg2,
Cow::Borrowed(prefix),
(|| Cow::Borrowed("destination")).into(),
&(),
)?;
destination_offset = 0;
size = <Option<u64>>::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::<GPUBuffer>::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 = <Option<u64>>::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,
&copy_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,
&copy_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,
&copy_size.into(),
)
.err();
self.error_handler.push_error(err);
}
#[required(1)]
#[undefined]
fn clear_buffer(
&self,
#[webidl] buffer: Ptr<GPUBuffer>,
#[webidl(default = 0, options(enforce_range = true))] offset: u64,
#[webidl(options(enforce_range = true))] size: Option<u64>,
) {
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<super::query_set::GPUQuerySet>,
#[webidl(options(enforce_range = true))] first_query: u32,
#[webidl(options(enforce_range = true))] query_count: u32,
#[webidl] destination: Ptr<GPUBuffer>,
#[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<GPUBuffer>,
#[webidl(default = 0)]
#[options(enforce_range = true)]
offset: u64,
#[options(enforce_range = true)]
bytes_per_row: Option<u32>,
#[options(enforce_range = true)]
rows_per_image: Option<u32>,
pub buffer: Ptr<GPUBuffer>,
#[webidl(default = 0)]
#[options(enforce_range = true)]
offset: u64,
#[options(enforce_range = true)]
bytes_per_row: Option<u32>,
#[options(enforce_range = true)]
rows_per_image: Option<u32>,
}
+201 -169
View File
@@ -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<wgpu_core::command::ComputePass>,
pub label: String,
pub compute_pass: RefCell<wgpu_core::command::ComputePass>,
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<GPUComputePassEncoder, GPUGenericError> {
Err(GPUGenericError::InvalidConstructor)
}
fn set_pipeline(&self, #[webidl] pipeline: Ptr<crate::compute_pipeline::GPUComputePipeline>) {
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<crate::compute_pipeline::GPUComputePipeline>,
) {
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<crate::buffer::GPUBuffer>,
#[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<crate::buffer::GPUBuffer>,
#[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<Ptr<crate::bind_group::GPUBindGroup>>,
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::<v8::Uint32Array>() {
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<Ptr<crate::bind_group::GPUBindGroup>>,
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::<v8::Uint32Array>()
{
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 = <Option<Vec<u32>>>::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 = <Option<Vec<u32>>>::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<GPUComputePassTimestampWrites>,
pub timestamp_writes: Option<GPUComputePassTimestampWrites>,
}
#[derive(WebIDL)]
#[webidl(dictionary)]
pub(crate) struct GPUComputePassTimestampWrites {
pub query_set: Ptr<crate::query_set::GPUQuerySet>,
#[options(enforce_range = true)]
pub beginning_of_pass_write_index: Option<u32>,
#[options(enforce_range = true)]
pub end_of_pass_write_index: Option<u32>,
pub query_set: Ptr<crate::query_set::GPUQuerySet>,
#[options(enforce_range = true)]
pub beginning_of_pass_write_index: Option<u32>,
#[options(enforce_range = true)]
pub end_of_pass_write_index: Option<u32>,
}
+50 -39
View File
@@ -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<GPUComputePipeline, GPUGenericError> {
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<GPUShaderModule>,
pub entry_point: Option<String>,
#[webidl(default = Default::default())]
pub constants: IndexMap<String, f64>,
pub module: Ptr<GPUShaderModule>,
pub entry_point: Option<String>,
#[webidl(default = Default::default())]
pub constants: IndexMap<String, f64>,
}
+860 -736
View File
File diff suppressed because it is too large. Load diff
+244 -215
View File
@@ -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<DeviceErrorHandler>;
use crate::device::GPUDeviceLostInfo;
use crate::device::GPUDeviceLostReason;
pub type ErrorHandler = std::rc::Rc<DeviceErrorHandler>;
pub struct DeviceErrorHandler {
pub is_lost: OnceLock<()>,
lost_sender: Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
uncaptured_sender_is_closed: Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
pub is_lost: OnceLock<()>,
pub scopes: Mutex<Vec<(GPUErrorFilter, Vec<GPUError>)>>,
lost_resolver: Mutex<Option<v8::Global<v8::PromiseResolver>>>,
spawner: V8TaskSpawner,
pub uncaptured_sender: tokio::sync::mpsc::UnboundedSender<GPUError>,
pub scopes: Mutex<Vec<(GPUErrorFilter, Vec<GPUError>)>>,
}
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<v8::Weak<v8::Object>>,
}
impl DeviceErrorHandler {
pub fn new(
lost_sender: tokio::sync::oneshot::Sender<()>,
uncaptured_sender: tokio::sync::mpsc::UnboundedSender<GPUError>,
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<v8::PromiseResolver>,
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<v8::Object>) {
self.device.set(device).unwrap()
}
pub fn push_error<E: Into<GPUError>>(&self, err: Option<E>) {
let Some(err) = err else {
return;
};
if self.is_lost.get().is_some() {
return;
}
pub fn push_error<E: Into<GPUError>>(&self, err: Option<E>) {
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::<v8::Function>().unwrap());
let device = v8::Global::new(scope, device.cast::<v8::Value>());
let error_event_class =
state.borrow().borrow::<crate::ErrorEventClass>().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::<v8::Function>::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<EncoderStateError> for GPUError {
fn from(err: EncoderStateError) -> Self {
GPUError::from_webgpu(err)
}
}
impl From<PassStateError> for GPUError {
fn from(err: PassStateError) -> Self {
GPUError::Validation(fmt_err(&err))
}
}
impl From<CreateBufferError> 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<DeviceError> 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<BufferAccessError> 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<CreateBindGroupLayoutError> 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<CreatePipelineLayoutError> 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<CreateBindGroupError> 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<RenderBundleError> for GPUError {
fn from(err: RenderBundleError) -> Self {
GPUError::Validation(fmt_err(&err))
}
fn from(err: RenderBundleError) -> Self {
GPUError::from_webgpu(err)
}
}
impl From<CreateRenderBundleError> for GPUError {
fn from(err: CreateRenderBundleError) -> Self {
GPUError::Validation(fmt_err(&err))
}
}
impl From<CopyError> for GPUError {
fn from(err: CopyError) -> Self {
GPUError::Validation(fmt_err(&err))
}
fn from(err: CreateRenderBundleError) -> Self {
GPUError::from_webgpu(err)
}
}
impl From<CommandEncoderError> for GPUError {
fn from(err: CommandEncoderError) -> Self {
GPUError::Validation(fmt_err(&err))
}
fn from(err: CommandEncoderError) -> Self {
GPUError::from_webgpu(err)
}
}
impl From<QueryError> for GPUError {
fn from(err: QueryError) -> Self {
GPUError::Validation(fmt_err(&err))
}
fn from(err: QueryError) -> Self {
GPUError::from_webgpu(err)
}
}
impl From<ComputePassError> for GPUError {
fn from(err: ComputePassError) -> Self {
GPUError::Validation(fmt_err(&err))
}
fn from(err: ComputePassError) -> Self {
GPUError::from_webgpu(err)
}
}
impl From<CreateComputePipelineError> 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<GetBindGroupLayoutError> for GPUError {
fn from(err: GetBindGroupLayoutError) -> Self {
GPUError::Validation(fmt_err(&err))
}
fn from(err: GetBindGroupLayoutError) -> Self {
GPUError::from_webgpu(err)
}
}
impl From<CreateRenderPipelineError> 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<RenderPassError> for GPUError {
fn from(err: RenderPassError) -> Self {
GPUError::Validation(fmt_err(&err))
}
fn from(err: RenderPassError) -> Self {
GPUError::from_webgpu(err)
}
}
impl From<CreateSamplerError> 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<CreateShaderModuleError> 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<CreateTextureError> 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<CreateTextureViewError> for GPUError {
fn from(err: CreateTextureViewError) -> Self {
GPUError::Validation(fmt_err(&err))
}
fn from(err: CreateTextureViewError) -> Self {
GPUError::from_webgpu(err)
}
}
impl From<CreateQuerySetError> 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<QueueSubmitError> 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<QueueWriteError> 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<ClearError> for GPUError {
fn from(err: ClearError) -> Self {
GPUError::Validation(fmt_err(&err))
}
fn from(err: ClearError) -> Self {
GPUError::from_webgpu(err)
}
}
impl From<ConfigureSurfaceError> 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,
}
+151 -127
View File
@@ -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<wgpu_core::global::Global>;
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<v8::Value>,
set_event_target_data: v8::Local<v8::Value>,
error_event_class: v8::Local<v8::Value>,
state: &mut OpState,
scope: &mut v8::HandleScope,
webidl_brand: v8::Local<v8::Value>,
set_event_target_data: v8::Local<v8::Value>,
error_event_class: v8::Local<v8::Value>,
) -> 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<v8::Value>,
set_event_target_data: v8::Global<v8::Value>,
brand: v8::Global<v8::Value>,
set_event_target_data: v8::Global<v8::Value>,
}
struct ErrorEventClass(v8::Global<v8::Value>);
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<RefCell<OpState>>,
#[webidl] options: adapter::GPURequestAdapterOptions,
) -> Option<adapter::GPUAdapter> {
let mut state = state.borrow_mut();
#[constructor]
#[cppgc]
fn constructor(_: bool) -> Result<GPU, GPUGenericError> {
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>() {
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::<Instance>()
};
#[async_method]
#[cppgc]
async fn request_adapter(
&self,
state: Rc<RefCell<OpState>>,
#[webidl] options: adapter::GPURequestAdapterOptions,
) -> Option<adapter::GPUAdapter> {
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>() {
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::<Instance>()
};
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<std::borrow::Cow<'a, str>> {
if label.is_empty() {
None
} else {
Some(std::borrow::Cow::Owned(label))
}
if label.is_empty() {
None
} else {
Some(std::borrow::Cow::Owned(label))
}
}
+33 -21
View File
@@ -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<GPUPipelineLayout, GPUGenericError> {
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<Ptr<super::bind_group_layout::GPUBindGroupLayout>>,
pub bind_group_layouts:
Vec<Ptr<super::bind_group_layout::GPUBindGroupLayout>>,
}
+61 -47
View File
@@ -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<GPUQuerySet, GPUGenericError> {
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<GPUQueryType> 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,
}
}
}
+161 -105
View File
@@ -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<GPUQueue, GPUGenericError> {
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<Ptr<GPUCommandBuffer>>,
) -> Result<(), JsErrorBox> {
let ids = command_buffers
.into_iter()
.map(|cb| cb.id)
.collect::<Vec<_>>();
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<Ptr<GPUCommandBuffer>>,
) -> 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::<Result<Vec<_>, _>>()?;
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<GPUBuffer>,
#[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<u64>,
) {
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<GPUBuffer>,
#[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<u64>,
) {
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<GPUTexture>,
#[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<GPUTexture>,
#[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<u32>,
#[options(enforce_range = true)]
rows_per_image: Option<u32>,
#[webidl(default = 0)]
#[options(enforce_range = true)]
offset: u64,
#[options(enforce_range = true)]
bytes_per_row: Option<u32>,
#[options(enforce_range = true)]
rows_per_image: Option<u32>,
}
+387 -333
View File
@@ -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<Option<wgpu_core::command::RenderBundleEncoder>>,
pub label: String,
fn c_string_truncated_at_first_nul<T: Into<Vec<u8>>>(
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<Option<wgpu_core::command::RenderBundleEncoder>>,
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<GPURenderBundleEncoder, GPUGenericError> {
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<Ptr<crate::bind_group::GPUBindGroup>>,
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::<v8::Uint32Array>() {
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 = <Option<Vec<u32>>>::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<Ptr<crate::bind_group::GPUBindGroup>>,
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::<v8::Uint32Array>() {
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 = <Option<Vec<u32>>>::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<crate::render_pipeline::GPURenderPipeline>,
) -> 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<GPUBuffer>,
#[webidl] index_format: crate::render_pipeline::GPUIndexFormat,
#[webidl(default = 0, options(enforce_range = true))] offset: u64,
#[webidl(options(enforce_range = true))] size: Option<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"))?;
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<GPUBuffer>, // TODO(wgpu): support nullable buffer
#[webidl(default = 0, options(enforce_range = true))] offset: u64,
#[webidl(options(enforce_range = true))] size: Option<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"))?;
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<crate::render_pipeline::GPURenderPipeline>,
) -> 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<GPUBuffer>,
#[webidl] index_format: crate::render_pipeline::GPUIndexFormat,
#[webidl(default = 0, options(enforce_range = true))] offset: u64,
#[webidl(options(enforce_range = true))] size: Option<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")
})?;
#[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<GPUBuffer>, // TODO(wgpu): support nullable buffer
#[webidl(default = 0, options(enforce_range = true))] offset: u64,
#[webidl(options(enforce_range = true))] size: Option<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")
})?;
#[required(2)]
fn draw_indirect(
&self,
#[webidl] indirect_buffer: Ptr<GPUBuffer>,
#[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<GPUBuffer>,
#[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<GPUBuffer>,
#[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<GPUBuffer>,
#[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<Nullable<GPUTextureFormat>>,
pub depth_stencil_format: Option<GPUTextureFormat>,
#[webidl(default = 1)]
#[options(enforce_range = true)]
pub sample_count: u32,
pub color_formats: Vec<Nullable<GPUTextureFormat>>,
pub depth_stencil_format: Option<GPUTextureFormat>,
#[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<GPURenderBundle, GPUGenericError> {
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,
}
+497 -380
View File
@@ -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<wgpu_core::command::RenderPass>,
pub label: String,
pub render_pass: RefCell<wgpu_core::command::RenderPass>,
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<GPURenderPassEncoder, GPUGenericError> {
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<Ptr<GPURenderBundle>>) {
let err = self
.instance
.render_pass_execute_bundles(
&mut self.render_pass.borrow_mut(),
&bundles
.into_iter()
.map(|bundle| bundle.id)
.collect::<Vec<_>>(),
)
.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<Ptr<GPURenderBundle>>) {
let err = self
.instance
.render_pass_execute_bundles(
&mut self.render_pass.borrow_mut(),
&bundles
.into_iter()
.map(|bundle| bundle.id)
.collect::<Vec<_>>(),
)
.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<Ptr<crate::bind_group::GPUBindGroup>>,
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::<v8::Uint32Array>() {
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<Ptr<crate::bind_group::GPUBindGroup>>,
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::<v8::Uint32Array>()
{
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 = <Option<Vec<u32>>>::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 = <Option<Vec<u32>>>::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<crate::render_pipeline::GPURenderPipeline>) {
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<GPUBuffer>,
#[webidl] index_format: crate::render_pipeline::GPUIndexFormat,
#[webidl(default = 0, options(enforce_range = true))] offset: u64,
#[webidl(options(enforce_range = true))] size: Option<u64>,
) {
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<crate::render_pipeline::GPURenderPipeline>,
) {
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<GPUBuffer>, // TODO(wgpu): support nullable buffer
#[webidl(default = 0, options(enforce_range = true))] offset: u64,
#[webidl(options(enforce_range = true))] size: Option<u64>,
) {
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<GPUBuffer>,
#[webidl] index_format: crate::render_pipeline::GPUIndexFormat,
#[webidl(default = 0, options(enforce_range = true))] offset: u64,
#[webidl(options(enforce_range = true))] size: Option<u64>,
) {
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<GPUBuffer>, // TODO(wgpu): support nullable buffer
#[webidl(default = 0, options(enforce_range = true))] offset: u64,
#[webidl(options(enforce_range = true))] size: Option<u64>,
) {
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<GPUBuffer>,
#[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<GPUBuffer>,
#[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<GPUBuffer>,
#[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<GPUBuffer>,
#[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<Nullable<GPURenderPassColorAttachment>>,
pub depth_stencil_attachment: Option<GPURenderPassDepthStencilAttachment>,
pub occlusion_query_set: Option<Ptr<crate::query_set::GPUQuerySet>>,
pub timestamp_writes: Option<GPURenderPassTimestampWrites>,
/*#[webidl(default = 50000000)]
#[options(enforce_range = true)]
pub max_draw_count: u64,*/
pub color_attachments: Vec<Nullable<GPURenderPassColorAttachment>>,
pub depth_stencil_attachment: Option<GPURenderPassDepthStencilAttachment>,
pub occlusion_query_set: Option<Ptr<crate::query_set::GPUQuerySet>>,
pub timestamp_writes: Option<GPURenderPassTimestampWrites>,
/*#[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<GPUTextureView>,
/*#[options(enforce_range = true)]
pub depth_slice: Option<u32>,*/
pub resolve_target: Option<Ptr<GPUTextureView>>,
pub clear_value: Option<GPUColor>,
pub load_op: GPULoadOp,
pub store_op: GPUStoreOp,
pub view: GPUTextureOrView,
#[options(enforce_range = true)]
pub depth_slice: Option<u32>,
pub resolve_target: Option<GPUTextureOrView>,
pub clear_value: Option<GPUColor>,
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<V: Default>(self, val: Option<V>) -> wgpu_core::command::LoadOp<V> {
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<V: Default>(
self,
val: Option<V>,
) -> wgpu_core::command::LoadOp<V> {
match self {
GPULoadOp::Load => wgpu_core::command::LoadOp::Load,
GPULoadOp::Clear => {
wgpu_core::command::LoadOp::Clear(val.unwrap_or_default())
}
}
}
pub fn with_value<V>(self, val: V) -> wgpu_core::command::LoadOp<V> {
match self {
GPULoadOp::Load => wgpu_core::command::LoadOp::Load,
GPULoadOp::Clear => wgpu_core::command::LoadOp::Clear(val),
}
pub fn with_value<V>(self, val: V) -> wgpu_core::command::LoadOp<V> {
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<GPUStoreOp> 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<GPUTextureView>,
pub depth_clear_value: Option<f32>,
pub depth_load_op: Option<GPULoadOp>,
pub depth_store_op: Option<GPUStoreOp>,
#[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<GPULoadOp>,
pub stencil_store_op: Option<GPUStoreOp>,
#[webidl(default = false)]
pub stencil_read_only: bool,
pub view: GPUTextureOrView,
pub depth_clear_value: Option<f32>,
pub depth_load_op: Option<GPULoadOp>,
pub depth_store_op: Option<GPUStoreOp>,
#[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<GPULoadOp>,
pub stencil_store_op: Option<GPUStoreOp>,
#[webidl(default = false)]
pub stencil_read_only: bool,
}
#[derive(WebIDL)]
#[webidl(dictionary)]
pub(crate) struct GPURenderPassTimestampWrites {
pub query_set: Ptr<crate::query_set::GPUQuerySet>,
#[options(enforce_range = true)]
pub beginning_of_pass_write_index: Option<u32>,
#[options(enforce_range = true)]
pub end_of_pass_write_index: Option<u32>,
pub query_set: Ptr<crate::query_set::GPUQuerySet>,
#[options(enforce_range = true)]
pub beginning_of_pass_write_index: Option<u32>,
#[options(enforce_range = true)]
pub end_of_pass_write_index: Option<u32>,
}
pub(crate) enum GPUTextureOrView {
Texture(Ptr<GPUTexture>),
TextureView(Ptr<GPUTextureView>),
}
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<Self, WebIdlError> {
<Ptr<GPUTexture>>::convert(
scope,
value,
prefix.clone(),
context.borrowed(),
options,
)
.map(Self::Texture)
.or_else(|_| {
<Ptr<GPUTextureView>>::convert(
scope,
value,
prefix.clone(),
context.borrowed(),
options,
)
.map(Self::TextureView)
})
}
}
+384 -373
View File
@@ -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<GPURenderPipeline, GPUGenericError> {
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<GPUDepthStencilState>,
pub multisample: GPUMultisampleState,
pub fragment: Option<GPUFragmentState>,
pub layout: GPUPipelineLayoutOrGPUAutoLayoutMode,
pub vertex: GPUVertexState,
pub primitive: GPUPrimitiveState,
pub depth_stencil: Option<GPUDepthStencilState>,
pub multisample: GPUMultisampleState,
pub fragment: Option<GPUFragmentState>,
}
#[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<bool>,
pub depth_compare: Option<GPUCompareFunction>,
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<bool>,
pub depth_compare: Option<GPUCompareFunction>,
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<GPUStencilOperation> 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<GPUShaderModule>,
pub entry_point: Option<String>,
#[webidl(default = Default::default())]
pub constants: IndexMap<String, f64>,
#[webidl(default = vec![])]
pub buffers: Vec<Nullable<GPUVertexBufferLayout>>,
pub module: Ptr<GPUShaderModule>,
pub entry_point: Option<String>,
#[webidl(default = Default::default())]
pub constants: IndexMap<String, f64>,
#[webidl(default = vec![])]
pub buffers: Vec<Nullable<GPUVertexBufferLayout>>,
}
#[derive(WebIDL)]
#[webidl(dictionary)]
pub(crate) struct GPUFragmentState {
pub module: Ptr<GPUShaderModule>,
pub entry_point: Option<String>,
#[webidl(default = Default::default())]
pub constants: IndexMap<String, f64>,
pub targets: Vec<Nullable<GPUColorTargetState>>,
pub module: Ptr<GPUShaderModule>,
pub entry_point: Option<String>,
#[webidl(default = Default::default())]
pub constants: IndexMap<String, f64>,
pub targets: Vec<Nullable<GPUColorTargetState>>,
}
#[derive(WebIDL)]
#[webidl(dictionary)]
pub(crate) struct GPUColorTargetState {
pub format: GPUTextureFormat,
pub blend: Option<GPUBlendState>,
#[webidl(default = 0xF)]
#[options(enforce_range = true)]
pub write_mask: u32,
pub format: GPUTextureFormat,
pub blend: Option<GPUBlendState>,
#[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<GPUBlendOperation> 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<GPUBlendFactor> 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<GPUIndexFormat>,
#[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<GPUIndexFormat>,
#[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<GPUPrimitiveTopology> 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<GPUIndexFormat> 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<GPUFrontFace> 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<GPUCullMode> for Option<wgpu_types::Face> {
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<GPUVertexAttribute>,
#[options(enforce_range = true)]
pub array_stride: u64,
#[webidl(default = GPUVertexStepMode::Vertex)]
pub step_mode: GPUVertexStepMode,
pub attributes: Vec<GPUVertexAttribute>,
}
#[derive(WebIDL)]
#[webidl(enum)]
pub(crate) enum GPUVertexStepMode {
Vertex,
Instance,
Vertex,
Instance,
}
impl From<GPUVertexStepMode> 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<GPUVertexFormat> 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,
}
}
}
+3
View File
@@ -0,0 +1,3 @@
max_width = 80
tab_spaces = 2
edition = "2021"
+102 -76
View File
@@ -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<GPUSampler, GPUGenericError> {
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<GPUCompareFunction>,
pub compare: Option<GPUCompareFunction>,
#[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<GPUAddressMode> 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<GPUFilterMode> 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<GPUMipmapFilterMode> 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<GPUCompareFunction> 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,
}
}
}
+198 -21
View File
@@ -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<v8::Object>,
}
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<GPUShaderModule, GPUGenericError> {
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<v8::Object>,
}
impl GarbageCollected for GPUCompilationInfo {
fn get_name(&self) -> &'static std::ffi::CStr {
c"GPUCompilationInfo"
}
}
#[op2]
impl GPUCompilationInfo {
#[getter]
#[global]
fn messages(&self) -> v8::Global<v8::Object> {
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<v8::Object> = 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,
}
+206 -161
View File
@@ -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<GPUDevice>,
pub usage: u32,
pub format: GPUTextureFormat,
pub device: Ptr<GPUDevice>,
pub usage: u32,
pub format: GPUTextureFormat,
pub surface_config:
wgpu_types::SurfaceConfiguration<Vec<wgpu_types::TextureFormat>>,
}
pub struct GPUCanvasContext {
pub surface_id: wgpu_core::id::SurfaceId,
pub width: RefCell<u32>,
pub height: RefCell<u32>,
pub surface_id: wgpu_core::id::SurfaceId,
pub width: RefCell<u32>,
pub height: RefCell<u32>,
pub config: RefCell<Option<Configuration>>,
pub texture: RefCell<Option<v8::Global<v8::Object>>>,
pub config: RefCell<Option<Configuration>>,
pub texture: RefCell<Option<v8::Global<v8::Object>>>,
pub canvas: v8::Global<v8::Object>,
pub canvas: v8::Global<v8::Object>,
}
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<v8::Object> {
self.canvas.clone()
#[constructor]
#[cppgc]
fn constructor(_: bool) -> Result<GPUCanvasContext, GPUGenericError> {
Err(GPUGenericError::InvalidConstructor)
}
#[getter]
#[global]
fn canvas(&self) -> v8::Global<v8::Object> {
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<v8::Global<v8::Object>, 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<v8::Global<v8::Object>, 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<GPUDevice>,
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<GPUDevice>,
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<GPUPresentMode>,
#[webidl(default = vec![])]
view_formats: Vec<GPUTextureFormat>,
// Extended from spec
present_mode: Option<GPUPresentMode>,
#[webidl(default = vec![])]
view_formats: Vec<GPUTextureFormat>,
}
#[derive(WebIDL)]
#[webidl(enum)]
enum GPUCanvasAlphaMode {
Opaque,
Premultiplied,
Opaque,
Premultiplied,
}
impl From<GPUCanvasAlphaMode> 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<GPUPresentMode> 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,
}
}
}
+628 -562
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+533 -495
View File
File diff suppressed because it is too large. Load diff
+270
View File
@@ -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<u32>` 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<u32>`, `vec2<u32>`, 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<f32>`, 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<f32>,
visible: bool,
}
var<task_payload> taskPayload: TaskPayload;
var<workgroup> workgroupData: f32;
struct VertexOutput {
@builtin(position) position: vec4<f32>,
@location(0) color: vec4<f32>,
}
struct PrimitiveOutput {
@builtin(triangle_indices) index: vec3<u32>,
@builtin(cull_primitive) cull: bool,
@per_primitive @location(1) colorMask: vec4<f32>,
}
struct PrimitiveInput {
@per_primitive @location(1) colorMask: vec4<f32>,
}
@task
@payload(taskPayload)
@workgroup_size(1)
fn ts_main() -> @builtin(mesh_task_size) vec3<u32> {
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<u32>) {
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<u32>(0, 1, 2);
p.cull = !taskPayload.visible;
p.colorMask = vec4<f32>(1.0, 0.0, 1.0, 1.0);
setPrimitive(0, p);
}
@fragment
fn fs_main(vertex: VertexOutput, primitive: PrimitiveInput) -> @location(0) vec4<f32> {
return vertex.color * primitive.colorMask;
}
```
+55 -6
View File
@@ -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<Item = BlasToBeCompacted> = 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:
+23
View File
@@ -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)/"
}
+29 -24
View File
@@ -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.
+1 -1
View File
@@ -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`?
+24 -24
View File
@@ -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.
+6 -5
View File
@@ -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
+10 -4
View File
@@ -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",
@@ -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<wgpu::B
.enumerate()
.map(|(e, seg)| {
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(&format!("Storage Buffer-{}", e)),
label: Some(&format!("Storage Buffer-{e}")),
contents: bytemuck::cast_slice(seg),
usage: wgpu::BufferUsages::STORAGE
| wgpu::BufferUsages::COPY_DST
@@ -211,7 +211,7 @@ fn create_staging_buffers(device: &wgpu::Device, numbers: &[f32]) -> Vec<wgpu::B
let size = std::mem::size_of_val(chunks[e]) as u64;
device.create_buffer(&wgpu::BufferDescriptor {
label: Some(&format!("staging buffer-{}", e)),
label: Some(&format!("staging buffer-{e}")),
size,
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
@@ -248,4 +248,4 @@ pub fn main() {
#[cfg(test)]
#[cfg(not(target_arch = "wasm32"))]
mod tests;
pub mod tests;
@@ -2,7 +2,7 @@ use super::*;
use wgpu_test::{gpu_test, GpuTestConfiguration, TestParameters};
#[gpu_test]
static TWO_BUFFERS: GpuTestConfiguration = GpuTestConfiguration::new()
pub static TWO_BUFFERS: GpuTestConfiguration = GpuTestConfiguration::new()
.parameters(
TestParameters::default()
.features(
+5 -5
View File
@@ -148,7 +148,7 @@ impl crate::framework::Example for Example {
primitive: wgpu::PrimitiveState::default(),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview: None,
multiview_mask: None,
cache: None,
});
@@ -263,11 +263,10 @@ impl crate::framework::Example for Example {
// create render pass descriptor and its color attachments
let color_attachments = [Some(wgpu::RenderPassColorAttachment {
view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
// Not clearing here in order to test wgpu's zero texture initialization on a surface texture.
// Users should avoid loading uninitialized memory since this can cause additional overhead.
load: wgpu::LoadOp::Load,
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: wgpu::StoreOp::Store,
},
})];
@@ -277,6 +276,7 @@ impl crate::framework::Example for Example {
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
};
// get command encoder
@@ -324,7 +324,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: "boids",
// Generated on 1080ti on Vk/Windows
image_path: "/examples/features/src/boids/screenshot.png",
+9 -4
View File
@@ -112,6 +112,7 @@ impl Example {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(clear_color),
@@ -121,6 +122,7 @@ impl Example {
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.global_group, &[]);
@@ -228,7 +230,7 @@ impl crate::framework::Example for Example {
},
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview: None,
multiview_mask: None,
cache: None,
});
@@ -236,7 +238,10 @@ impl crate::framework::Example for Example {
let img_data = include_bytes!("../../../../logo.png");
let decoder = png::Decoder::new(std::io::Cursor::new(img_data));
let mut reader = decoder.read_info().unwrap();
let mut buf = vec![0; reader.output_buffer_size()];
let buf_len = reader
.output_buffer_size()
.expect("output buffer would not fit in memory");
let mut buf = vec![0; buf_len];
let info = reader.next_frame(&mut buf).unwrap();
let size = wgpu::Extent3d {
@@ -274,7 +279,7 @@ impl crate::framework::Example for Example {
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Nearest,
mipmap_filter: wgpu::FilterMode::Nearest,
mipmap_filter: wgpu::MipmapFilterMode::Nearest,
..Default::default()
});
@@ -433,7 +438,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: "bunnymark",
image_path: "/examples/features/src/bunnymark/screenshot.png",
width: 1024,
@@ -106,7 +106,7 @@ impl crate::framework::Example for Example {
},
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview: None,
multiview_mask: None,
cache: None,
});
@@ -129,7 +129,7 @@ impl crate::framework::Example for Example {
primitive: wgpu::PrimitiveState::default(),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview: None,
multiview_mask: None,
cache: None,
});
@@ -160,7 +160,7 @@ impl crate::framework::Example for Example {
},
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview: None,
multiview_mask: None,
cache: None,
}),
)
@@ -217,7 +217,7 @@ impl crate::framework::Example for Example {
primitive: wgpu::PrimitiveState::default(),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview: None,
multiview_mask: None,
cache: None,
}),
bind_group_layout,
@@ -263,6 +263,7 @@ impl crate::framework::Example for Example {
label: Some("low resolution"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &self.low_res_target,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
@@ -272,6 +273,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_triangle_conservative);
@@ -284,6 +286,7 @@ impl crate::framework::Example for Example {
label: Some("full resolution"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
@@ -293,6 +296,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_upscale);
@@ -315,7 +319,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: "conservative-raster",
image_path: "/examples/features/src/conservative_raster/screenshot.png",
width: 1024,
+6 -4
View File
@@ -256,7 +256,7 @@ impl crate::framework::Example for Example {
},
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview: None,
multiview_mask: None,
cache: None,
});
@@ -298,7 +298,7 @@ impl crate::framework::Example for Example {
},
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview: None,
multiview_mask: None,
cache: None,
});
Some(pipeline_wire)
@@ -341,6 +341,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 {
@@ -355,6 +356,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);
@@ -380,7 +382,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: "cube",
// Generated on 1080ti on Vk/Windows
image_path: "/examples/features/src/cube/screenshot.png",
@@ -396,7 +398,7 @@ static TEST: crate::framework::ExampleTestParams = crate::framework::ExampleTest
#[cfg(test)]
#[wgpu_test::gpu_test]
static TEST_LINES: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams {
pub static TEST_LINES: crate::framework::ExampleTestParams = crate::framework::ExampleTestParams {
name: "cube-lines",
// Generated on 1080ti on Vk/Windows
image_path: "/examples/features/src/cube/screenshot-lines.png",
+10 -5
View File
@@ -196,6 +196,8 @@ impl SurfaceWrapper {
config.format = format;
config.view_formats.push(format);
};
config.present_mode = wgpu::PresentMode::Immediate;
config.desired_maximum_frame_latency = 3;
surface.configure(&context.device, &config);
self.config = Some(config);
@@ -247,7 +249,7 @@ impl SurfaceWrapper {
}
}
fn get(&self) -> Option<&Surface> {
fn get(&self) -> Option<&'_ Surface<'static>> {
self.surface.as_ref()
}
@@ -268,9 +270,9 @@ impl ExampleContext {
async fn init_async<E: Example>(surface: &mut SurfaceWrapper, window: Arc<Window>) -> 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<E: Example + wgpu::WasmNotSendSync> From<ExampleTestParams<E>>
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(
@@ -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<T: bytemuck::Pod>(
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;
@@ -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()
+4 -1
View File
@@ -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);
@@ -74,6 +74,7 @@ async fn run(event_loop: EventLoop<()>, viewports: Vec<(Arc<Window>, 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<Window>, 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<Window>, wgpu::Color
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
}
@@ -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<T: bytemuck::Pod>(
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();
+51 -1
View File
@@ -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<wgpu_test::GpuTestInitializer> {
#[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());
+12
View File
@@ -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<String> {
@@ -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
```
+181
View File
@@ -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::<Example>("mesh_shader");
}
Loaded 100 of 1654 files, more files were not shown because too many files have changed in this diff. Show more