Convert wiki and api-specs into documentation modules (#9779)

This commit is contained in:
Connor Fitzgerald authored and GitHub committed 2026-08-29 18:59:58 -04:00
1 parent 855ead0745
commit fae070bf21
68 files changed
+3461 -273

No files matched your search

+1 -1
View File
@@ -6,7 +6,7 @@ labels: bug
assignees: ""
---
<!-- Thank you for filing this! Please read the [debugging tips](https://github.com/gfx-rs/wgpu/wiki/Debugging-wgpu-Applications).
<!-- Thank you for filing this! Please read the [debugging tips](https://docs.rs/wgpu/latest/wgpu/documentation/debugging/debugging_applications/index.html).
That may let you investigate on your own, or provide additional information that helps us to assist.-->
**Description**
+2 -2
View File
@@ -88,7 +88,7 @@ behavior in the WebGPU or WGSL specification.
# Overview of the Code
See `docs/big-picture.png` for an overview of the system.
See `wgpu/src/documentation/images/big-picture.webp` for an overview of the system.
The major components are:
@@ -116,7 +116,7 @@ The major components are:
apply to other clients, the issue should probably be fixed in `wgpu-core`.
For a more detailed discussion of the `wgpu` architecture, refer to
<https://github.com/gfx-rs/wgpu/wiki/Architecture>.
wgpu/src/documentation/internals/architecture.rs
## Naga
+4 -4
View File
@@ -24,9 +24,9 @@ Additionally, [WebGPU Fundamentals] is a tutorial for WebGPU which is very simil
[Learn Wgpu]: https://sotrh.github.io/learn-wgpu/
[WebGPU Fundamentals]: https://webgpufundamentals.org/
### Wiki
### Documentation Guides
We have a [wiki](https://github.com/gfx-rs/wgpu/wiki) which has information on useful architecture patterns, debugging tips, and more getting started information.
We ship a set of [documentation modules](https://docs.rs/wgpu/latest/wgpu/documentation/index.html) with information on useful architecture patterns, debugging tips, and more getting started information.
### Need Help? Want to Contribute?
@@ -75,7 +75,7 @@ Contributors are welcome! See [CONTRIBUTING.md][contrib] for more information.
✅ = First Class Support
🆗 = Downlevel/Best Effort Support
📐 = Requires the [ANGLE](https://github.com/gfx-rs/wgpu/wiki/Running-on-ANGLE) translation layer (GL ES 3.0 only). On macOS/iOS, use the `angle` feature. On Windows, `gles` uses WGL by default; build with `cfg(windows_angle)` to use ANGLE instead.
📐 = Requires the [ANGLE](https://docs.rs/wgpu/latest/wgpu/documentation/platforms/angle/index.html) translation layer (GL ES 3.0 only). On macOS/iOS, use the `angle` feature. On Windows, `gles` uses WGL by default; build with `cfg(windows_angle)` to use ANGLE instead.
🌋 = Requires the [MoltenVK](https://vulkan.lunarg.com/sdk/home#mac) translation layer
🛠️ = Unsupported, though open to contributions
@@ -93,7 +93,7 @@ When running the CTS, use the variables `DENO_WEBGPU_ADAPTER_NAME`, `DENO_WEBGPU
## Repo Overview
For an overview of all the components in the gfx-rs ecosystem, see [the big picture](./docs/big-picture.png).
For an overview of all the components in the gfx-rs ecosystem, see [the big picture](./wgpu/src/documentation/images/big-picture.webp).
## MSRV policy
+1 -1
View File
@@ -11,7 +11,7 @@ spec becomes more concrete, we will implement to follow the spec more closely.
In addition, setting the `DENO_WEBGPU_TRACE` environmental variable will output
a
[wgpu trace](https://github.com/gfx-rs/wgpu/wiki/Debugging-wgpu-Applications#tracing-infrastructure)
[wgpu trace](https://docs.rs/wgpu/latest/wgpu/documentation/debugging/debugging_applications/index.html#tracing-infrastructure)
to the specified directory.
This op crate is tested primarily by running the
+3
View File
@@ -0,0 +1,3 @@
# `wgpu` Contributor Documentation
This folder contains documentation for contributors of wgpu. If you're looking for user facing documentation, look at <https://wgpu.rs/doc/wgpu/documentation/index.html> for documentation on `trunk` and <https://docs.rs/wgpu/latest/wgpu/documentation/index.html> for the latest release.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 146 KiB

+65
View File
@@ -0,0 +1,65 @@
# Managing Cargo dependencies
In general, `wgpu` tries to stay up-to-date with the current Rust ecosystem; we are interested in keeping the version of dependency crates we use up-to-date. However, there are some considerations to keep in mind when upgrading or adding dependencies to `wgpu`.
## Adding or upgrading dependencies may cause dependency duplication downstream
Some crates in the Rust ecosystem are useful for both `wgpu` and its downstream consumers. Popular crates—like those in the `serde` ecosystem, for example—are often used in multiple places in a Rust crate's dependency tree. Normally, Cargo can unify dependencies behind a single SemVer-compatible version. When one or more, but not all, of these places consume a [SemVer-incompatible upgrade][semver-summary], Cargo uses both in the new dependency tree (see The Cargo Book's section titled [`Version-incompatibility hazards`](https://doc.rust-lang.org/cargo/reference/resolver.html#version-incompatibility-hazards)). These are often referred to as "duplicate dependencies"[^1].
[semver-summary]: https://semver.org/spec/v2.0.0.html#summary
[^1]: One can detect such duplicates with [`cargo tree --duplicates`](https://doc.rust-lang.org/cargo/commands/cargo-tree.html#option-cargo-tree---duplicates).
There exist many Rust projects that, for some reason or another, are sensitive to duplicate dependencies. The most common reason for this is to minimize the number of built dependencies, but there are other reasons for doing so, like projects that prefer to [vendor in their dependencies' source code](https://doc.rust-lang.org/cargo/commands/cargo-vendor.html) and keep diffs easy to inspect. **When a dependency of `wgpu` releases a SemVer-incompatible change and `wgpu` consumes it (even if it's new _to `wgpu`_), it may cause conflicts for projects that avoid duplicate dependencies.**
> [!TIP]
> Downstreams like Firefox can and do work around Cargo's (well-motivated) refusal to unify SemVer-incompatible versions of crates, but this happens only on a case-by-case basis. In general, this requires source compatibility for the APIs actually consumed between both versions.
## Firefox needs to audit every dependency
In addition to the above, Firefox has unusual sensitivities to updates because of required auditing via [`cargo-vet`](https://github.com/mozilla/cargo-vet). **Firefox contributors _cannot_ bring in a Rust dependency—including new versions of dependencies already in use—without an audit indicating that the dependency meets [`safe-to-deploy`] criteria for _all_ of its feature combinations.** One can ask the following questions to determine whether an upgrade is feasible for Firefox; "yes" answers are significantly easier cases to deal with:
1. If the dependency had to be audited for [`safe-to-deploy`], would it take less than an hour to review?
<sup>One can use <https://diff.rs/> to quickly gauge the answer to this question for upgrades. Example: [`serde` 1.0.218 → 1.0.219](https://diff.rs/serde/1.0.218/1.0.219/src%2Flib.rs)</sup>
1. Does the same code work between the two dependency's versions without needing to be changed (viz., are they "source-compatible")?
<sup>NOTE: This is somewhat different from [SemVer compatibility][semver-summary], because it deals with code already written, rather than SemVer's dealing with code that _might_ be written.</sup>
1. Does the dependency already have an audit in Mozilla's [`supply-chain/audits.toml`](https://searchfox.org/mozilla-central/source/supply-chain/audits.toml) or in the other audit databases it `import`s in [`supply-chain/config.toml`](https://searchfox.org/mozilla-central/source/supply-chain/config.toml)?
[`safe-to-deploy`]: https://mozilla.github.io/cargo-vet/built-in-criteria.html#safe-to-deploy
> [!TIP]
> [Searchfox](https://searchfox.org) can be used to answer question (3) and other simple questions with just a web browser. For example:
>
> - "Does Firefox use the `itertools` crate?" can be answered by a case-sensitive search scoped to files with the `rs` extension: https://searchfox.org/mozilla-central/search?q=itertools&path=*.rs&case=true&regexp=false
> - "Is `serde` 1.0.143 already audited?" can be answered by examining `supply-chain/audits.toml` ([permalink](https://searchfox.org/mozilla-central/rev/f3c8c63a097b61bb1f01e13629b9514e09395947/supply-chain/audits.toml#4730-4733)).
> [!TIP]
> For more complicated questions like, "What features does Mozilla use in the `hashbrown` crate?" the best known way to satisfy the question is using Cargo's CLI, i.e., `cargo tree` or `cargo metadata`, in tandem with editing Cargo manifests directly. A Git mirror of Firefox's source code can be found at [`mozilla/gecko-dev`](https://github.com/mozilla/gecko-dev).
>
> A full checkout of `gecko-dev` fills multiple gigabytes, and is not recommended to make one locally unless you plan on doing work directly on Firefox. However, we can optimize to somewhat less than 1 GiB of storage, and speed up the checkout process by using `git sparse-checkout`:
>
> ```sh
> git clone --sparse --depth=1 'https://github.com/mozilla/gecko-dev.git'
> cd gecko-dev
> git sparse-checkout set --no-cone
> git sparse-checkout add \
> '**/Cargo.toml' \
> '**/lib.rs' \
> '**/main.rs' \
> '**/src/bin/*.rs' \
> ;
> ```
>
> From here, you can invoke Cargo with the `--locked` flag, i.e:
>
> ```sh
> cargo --locked tree -i itertools
> ```
>
> ```sh
> cargo --locked metadata --format-version=1
> ```
Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.2 KiB

+165
View File
@@ -0,0 +1,165 @@
# Running the tests on Android and iOS
An approach of cross-compiling the binaries on a host, then using various tools such as `adb` and `ssh` to transfer the test binaries over to run them, can be used.
Below are example configuration and runner scripts that can be used to perform this yourself.
## Android
<details>
<summary>.cargo/config.toml</summary>
```toml
[target.aarch64-linux-android]
# Runner script is written in powershell
runner = ["pwsh", "-File", "<runner location>run-on-android.ps1"]
rustflags = [
"-C", "linker=clang",
"-C", "link-arg=-fuse-ld=lld",
"-C", "link-arg=--target=aarch64-linux-android",
"-C", "link-arg=--sysroot=<ndk/sysroot location>",
"-C", "link-arg=-B<ndk/sysroot location>/usr/lib/aarch64-linux-android/<version>",
"-C", "link-arg=-L<ndk/sysroot location>/usr/lib/aarch64-linux-android/<version>",
"-C", "link-arg=-L<ndk/sysroot location>/usr/lib/aarch64-linux-android",
"-C", "link-arg=-L<ndk location>/toolchains/llvm/prebuilt/<host>/lib/clang/20/lib/linux/aarch64"
]
```
</details>
<details>
<summary>run-on-android.ps1</summary>
```powershell
param(
[string]$BinaryPath
)
$ErrorActionPreference = "Stop"
# /data/local/tmp is the most common directory where arbitrary binaries can be run
$RemoteDir = "/data/local/tmp/runner"
$BinaryName = Split-Path -Leaf $BinaryPath
$RemotePath = "$RemoteDir/$BinaryName"
adb push --sync "$BinaryPath" "$RemotePath" *>$null
adb shell "chmod 755 $RemotePath"
$EscapedArgs = $args | ForEach-Object {
if ($_ -match " ") {
"`"$_`""
} else {
$_
}
}
$LinuxArgs = $EscapedArgs -join " "
# Set LD_LIBRARY_PATH to the location of libc++_shared.so
$DeviceCmd = "cd $RemoteDir && LD_LIBRARY_PATH=$RemoteDir ./$BinaryName $LinuxArgs"
adb shell "$DeviceCmd"
exit $LASTEXITCODE
```
</details>
All Android binaries link to `libc++_shared.so`. Remember to put a copy alongside the binaries.
## iOS
Apple does not normally provide shell access and `sshd` on their operating system, so jailbreaking the system is required.
Only a copy of the iOS sysroot is required to cross-compile, so Linux and Windows can also try this.
<details>
<summary>.cargo/config.toml</summary>
```toml
[target.aarch64-apple-ios]
# Runner script is written in powershell
runner = ["pwsh", "-File", "<runner location>run-on-ios.ps1"]
rustflags = [
"-C", "linker=clang",
"-C", "link-arg=-fuse-ld=lld",
"-C", "link-arg=--target=aarch64-apple-ios",
"-C", "link-arg=--sysroot=<sysroot location>",
"-C", "link-arg=-miphoneos-version-min=<minversion>",
"-C", "link-arg=-rpath",
"-C", "link-arg=@executable_path/Frameworks",
"-Lnative=<sysroot location>/usr/lib",
"-Lframework=<sysroot location>/System/Library/Frameworks",
]
```
</details>
If you're on a platform other than macOS, set an environment variable of `SDKROOT` to your sysroot location.
This avoids `cc-rs` trying to run `xcrun`.
<details>
<summary>run-on-ios.ps1</summary>
```powershell
param(
[string]$BinaryPath
)
$SshTarget = "<target user>@<target host>"
$BinaryName = Split-Path -Leaf $BinaryPath
# Select one of the following paths depending on rootless or rootful jailbreak
$RemoteDir = "/var/jb/var/mobile/runner"
#$RemoteDir = "/var/root/runner"
$RemotePath = "$RemoteDir/$BinaryName"
$EscapedArgs = $args | ForEach-Object {
if ($_ -match " ") {
"`"$_`""
} else {
$_
}
}
$LinuxArgs = $EscapedArgs -join " "
$DeviceCmd = "./$BinaryName $LinuxArgs"
ssh $SshTarget "test -f $RemotePath"
if ($LASTEXITCODE -ne 0) {
scp -q "$BinaryPath" "$SshTarget`:$RemotePath"
$DeviceCmd = "chmod 755 $BinaryName && ldid -Sent.xml $BinaryName && $DeviceCmd"
}
ssh $SshTarget "cd $RemoteDir && $DeviceCmd"
exit $LASTEXITCODE
```
</details>
Due to iOS security measures, a binary needs to contain specific entitlements to run without a container and access IOKit, so it is required to have the `ldid` tool installed on your target device to set the entitlements with `ent.xml`. It should be placed in your runner directory.
<details>
<summary>ent.xml</summary>
```xml
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>platform-application</key>
<true/>
<key>com.apple.private.security.container-required</key>
<false/>
<key>com.apple.security.iokit-user-client-class</key>
<array>
<string>AGXCommandQueue</string>
<string>AGXDevice</string>
<string>AGXDeviceUserClient</string>
<string>AGXSharedUserClient</string>
<string>IOSurfaceRootUserClient</string>
</array>
</dict>
</plist>
```
</details>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

@@ -4,7 +4,7 @@ This example demonstrates how to use cooperative matrix operations (also known a
For the full description of the cooperative matrix feature (supported configurations, WGSL types and operations, validation rules, and backend support), see the central API spec:
- `docs/api-specs/cooperative_matrix.md`
- [`wgpu::documentation::extensions::cooperative_matrices`](https://docs.rs/wgpu/latest/wgpu/documentation/extensions/cooperative_matrices/index.html)
## Example specifics
@@ -23,7 +23,7 @@ The example:
- A GPU and backend that expose `Features::EXPERIMENTAL_COOPERATIVE_MATRIX`
- A configuration returned from `adapter.cooperative_matrix_properties()` that matches the tile size and element types used by this example
- See `docs/api-specs/cooperative_matrix.md` for details on hardware / backend support
- See [`wgpu::documentation::extensions::cooperative_matrices`](https://docs.rs/wgpu/latest/wgpu/documentation/extensions/cooperative_matrices/index.html) for details on hardware / backend support
## Running
+3 -1
View File
@@ -5,9 +5,10 @@ extend-exclude = [
'/.git',
# spirv-asm isn't real source code
'*.spvasm',
'docs/big-picture.xml',
'wgpu/src/documentation/images/big-picture.xml',
# This test has weird pattern-derived variable names.
'naga/tests/in/wgsl/abstract-types-builtins.wgsl',
'*.excalidraw',
]
# Corrections take the form of a key/value pair. The key is the incorrect word
@@ -40,6 +41,7 @@ D3DCOLORtoUBYTE4 = "D3DCOLORtoUBYTE4"
Derivate = "Derivate"
inout = "inout"
Ect = "Ect"
bve = "bve"
[type.wgsl]
extend-glob = ["*.wgsl"]
+4 -4
View File
@@ -112,8 +112,8 @@ secondary backends, so the latter may impose more overhead.
## Debugging
Most of the information on the wiki [Debugging wgpu Applications][wiki-debug]
page still applies to this API, with the exception of API tracing/replay
functionality, which is only available in `wgpu-core`.
Most of the information in the [Debugging wgpu Applications][debug-docs]
documentation still applies to this API, with the exception of API
tracing/replay functionality, which is only available in `wgpu-core`.
[wiki-debug]: https://github.com/gfx-rs/wgpu/wiki/Debugging-wgpu-Applications
[debug-docs]: https://docs.rs/wgpu/latest/wgpu/documentation/debugging/debugging_applications/index.html
+4 -4
View File
@@ -196,11 +196,11 @@
//!
//! ## Debugging
//!
//! Most of the information on the wiki [Debugging wgpu Applications][wiki-debug]
//! page still applies to this API, with the exception of API tracing/replay
//! functionality, which is only available in `wgpu-core`.
//! Most of the information in the [Debugging wgpu Applications][debug-docs]
//! documentation still applies to this API, with the exception of API
//! tracing/replay functionality, which is only available in `wgpu-core`.
//!
//! [wiki-debug]: https://github.com/gfx-rs/wgpu/wiki/Debugging-wgpu-Applications
//! [debug-docs]: https://docs.rs/wgpu/latest/wgpu/documentation/debugging/debugging_applications/index.html
#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]
+3 -3
View File
@@ -1,6 +1,6 @@
use macro_rules_attribute::derive;
use crate::{link_to_wgpu_item, ConstDefault};
use crate::{link_to_wgpu_docs, link_to_wgpu_item, ConstDefault};
/// Token of the user agreeing to access experimental features.
#[derive(Debug, ConstDefault!, Copy, Clone, Eq, PartialEq)]
@@ -25,7 +25,7 @@ impl ExperimentalFeatures {
/// access to newer technology sooner, and we can work with users
/// to fix bugs quicker.
///
/// Look inside our repo at the [`api-specs`] for more information
/// See the [extension documentation][extensions] for more information
/// on various experimental apis.
///
/// # Safety
@@ -35,7 +35,7 @@ impl ExperimentalFeatures {
/// - You agree to report any such bugs to us, if you find them.
///
#[doc = link_to_wgpu_item!(struct Features)]
/// [`api-specs`]: https://github.com/gfx-rs/wgpu/tree/trunk/docs/api-specs
#[doc = link_to_wgpu_docs!(["extensions"]: "documentation/extensions/index.html")]
pub const unsafe fn enabled() -> Self {
Self { enabled: true }
}
+73
View File
@@ -62,4 +62,77 @@ fn main() {
) },
no_std: { not(std) }
}
// Expose a `file://` base URL pointing at the crate's
// `src/documentation/images/` directory so that local documentation builds
// resolve images from disk. Because these images live inside the crate, they
// are packaged on publish and this path also resolves when a downstream user
// builds the docs of `wgpu` as a dependency. `docsrs` builds ignore this and
// use an HTTP URL instead; see the `doc_image!` macro in `src/macros/mod.rs`.
// Resolving the path here lets us normalize to forward slashes and pick the
// right number of leading slashes for the host.
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
let docs_dir = std::path::Path::new(&manifest_dir)
.join("src")
.join("documentation")
.join("images");
let docs_dir = docs_dir.to_string_lossy().replace('\\', "/");
let docs_url = if docs_dir.starts_with('/') {
format!("file://{docs_dir}")
} else {
format!("file:///{docs_dir}")
};
println!("cargo::rustc-env=WGPU_DOCS_URL_BASE={docs_url}");
// Pin hosted documentation image URLs (docs.rs and the self-hosted trunk
// docs) to the exact commit being built rather than the moving `trunk`
// branch, so the images never drift from the prose. Only the `docsrs` arm of
// the `doc_image!` macro reads this; local builds use the on-disk path above
// and ignore it, so we deliberately don't add a `rerun-if-changed` on the
// git HEAD — recomputing it on the build script's normal re-runs is enough.
println!(
"cargo::rustc-env=WGPU_DOCS_COMMIT={}",
docs_commit(&manifest_dir)
);
}
/// Best-effort lookup of the commit this build corresponds to, for pinning
/// documentation image URLs.
///
/// Tries `git` first (a local checkout, and the self-hosted trunk docs CI), then
/// the `.cargo_vcs_info.json` that `cargo publish` embeds in the packaged crate
/// (the docs.rs case, where there is no `.git`), and finally falls back to
/// `trunk` so the URLs still resolve.
fn docs_commit(manifest_dir: &str) -> String {
commit_from_git(manifest_dir)
.or_else(|| commit_from_vcs_info(manifest_dir))
.unwrap_or_else(|| "trunk".to_owned())
}
fn commit_from_git(manifest_dir: &str) -> Option<String> {
let output = std::process::Command::new("git")
.args(["rev-parse", "HEAD"])
.current_dir(manifest_dir)
.output()
.ok()?;
if !output.status.success() {
return None;
}
let sha = String::from_utf8(output.stdout).ok()?.trim().to_owned();
(!sha.is_empty()).then_some(sha)
}
fn commit_from_vcs_info(manifest_dir: &str) -> Option<String> {
let path = std::path::Path::new(manifest_dir).join(".cargo_vcs_info.json");
let contents = std::fs::read_to_string(path).ok()?;
// Minimal extraction of `"sha1": "<hex>"`, to avoid pulling a JSON parser
// into the build script.
let sha = contents
.split_once("\"sha1\"")?
.1
.split_once('"')?
.1
.split_once('"')?
.0;
(!sha.is_empty()).then(|| sha.to_owned())
}
@@ -0,0 +1,36 @@
/*!
# Dos and Don'ts
A short list of common performance pitfalls and the patterns that avoid
them.
### Don't: create temporary mapped buffers when updating data
Instead, [`Queue::write_buffer`] and [`Queue::write_texture`] can be used
conveniently. If you are uploading a lot of data that is generated (as
opposed to already sitting in a data vector), it may be more efficient to
recycle staging buffers in a pool.
### Do: group resource bindings by change frequency, starting from the lowest
For example, put per-frame resources into bind group 0, per-pass resources
into bind group 1, and per-material resources into bind group 2. This allows
the WebGPU implementation to keep the other bindings intact, reducing state
changes.
### Don't: create many resources (buffers or textures) per frame
This puts pressure on the WebGPU memory allocator and tracker. Prefer
coalescing smaller resources into larger ones. For buffers, you can create a
large buffer and use different parts of it for different purposes. For
textures, consider texture atlases and arrays.
### Don't: submit many times per frame
There is a visible CPU cost per submission, and resources are tracked per
submission by the implementation. It is fine to have multiple
[`CommandBuffer`]s per submission, but the number of [`Queue::submit`] calls
should be limited to a few per frame (e.g. 1–5).
*/
use crate::{CommandBuffer, Queue};
@@ -0,0 +1,104 @@
/*!
# Encapsulating Graphics Work: the Middleware Pattern
Whether you are designing a library to be used by others or modularizing
your own code, it is important to be able to encapsulate graphics code in a
way that offers the calling code as much flexibility as possible.
The following pattern is called the "middleware pattern" and works well both
in separate libraries and in regular modules.
## Middleware libraries
Middleware is a piece of software that fits unobtrusively into an existing
application, giving it some extra functionality. In the case of `wgpu`,
middleware are libraries that use the `wgpu` context the user provides to do
their work. If a library creates the `wgpu` adapter, device, etc. for you,
it isn't middleware — it would more likely be called a framework.
## API design
This does not have to be the extent of the API; you may have more (or
different) arguments or more functions, but this is the gist of the
interactions with `wgpu`.
```ignore
impl MiddlewareRenderer {
/// Create all unchanging resources here.
pub fn new(device: &Device, format: &TextureFormat, ..) -> Self;
/// Prepare for rendering this frame; create all resources that will be
/// used during the next render that do not already exist.
pub fn prepare(&mut self, ..);
/// Render using a caller-provided render pass.
pub fn render(&self, render_pass: &mut RenderPass<'_>);
}
```
The goal of this API is to use as few render passes and submissions as
possible.
- On GPUs that use _tiled rendering_, there is significant cost to ending a
render pass. Therefore, the middleware should accept an existing
[`RenderPass`] (presuming it is rendering to a surface/texture provided by
the user).
- [`Queue::submit`] is expensive for `wgpu` to execute. Therefore, if the
middleware generates a [`CommandBuffer`] when preparing, it should hand
that buffer back to the caller to become part of a larger submission,
instead of submitting it alone.
## Functions
### New
```ignore
fn new(device: &Device, format: &TextureFormat, ..) -> Self;
```
This is where you create your renderer and set up all the static resources.
Things like pipelines, buffers, or textures should be created and uploaded
here. When the middleware needs to know the parameters of what it is
rendering to, favor accepting a [`TextureFormat`], `width`, and `height`
over a [`SurfaceConfiguration`], as the user may not be rendering to the
surface but to another texture.
### Prepare
```ignore
fn prepare(&mut self, ..);
```
Ideally there should be a minimal amount of resources created per frame, but
that is often hard to avoid. `prepare()` should create those resources and
do any other computation required to be ready to render.
### Render
```ignore
fn render(&self, render_pass: &mut RenderPass<'_>);
```
This is where the magic happens! Using the resources created during `new()`
and `prepare()`, render everything using the provided render pass.
The split between `prepare()` and `render()` is not critical but improves
flexibility. By avoiding borrowing the middleware object exclusively
(`&mut`) during `render()`, the user has more options for organizing their
code; for example, they might want to perform command encoding — including
the middleware's `render()` — in parallel into multiple command buffers, and
this may be easier if the middleware (and therefore whatever owns it) does
not have to be exclusively borrowed. It also means that the order of calls
to `prepare()` of different middleware can be independent of the order of
drawing.
## Multiple render targets
If your piece of middleware has to render to multiple targets, it is pretty
unavoidable to have multiple render passes. As much as possible, this
pattern should be used as a guideline for the design of your API, but it
doesn't work for every possible piece of middleware out there.
*/
use crate::{CommandBuffer, Queue, RenderPass, SurfaceConfiguration, TextureFormat};
@@ -0,0 +1,8 @@
/*!
Best Practices
Patterns and pitfalls for writing efficient, well-structured `wgpu` code.
*/
pub mod dos_and_donts;
pub mod middleware;
@@ -0,0 +1,149 @@
/*!
# HDR Surfaces
A surface can present in different color spaces to get HDR or wide-gamut
output onto the screen. This is configured through
[`SurfaceConfiguration::color_space`], and the rest of this section is a
concept primer on how it works.
### HDR output in a nutshell
By default a surface is standard dynamic range (SDR) with the sRGB gamut: the
value `1.0` is the brightest white, anything above it clips, and only colors
within sRGB are expressible. Other [`SurfaceColorSpace`]s opt into a **wider
gamut** (for example [`DisplayP3`](SurfaceColorSpace::DisplayP3), still SDR
but with more saturated colors than sRGB), **high dynamic range** (values
above `1.0` drive brighter-than-white output), or both (for example
[`Bt2100Pq`](SurfaceColorSpace::Bt2100Pq), aka HDR10), on platforms that
support it.
Three ideas carry most of the weight:
* **Reference white and headroom.** Brightness is measured in *nits*
(cd/m²). On HDR-capable monitors, SDR reference white (plain white, `(1.0, 1.0, 1.0)` in the
extended color spaces) sits *below* the display's peak output on purpose, so
highlights have room above it. That gap is the display's *headroom*.
* **The transfer function is a round-trip.** Your shader applies an
encoding transfer function (the OETF) to turn the light it computed into a
stored signal, and the display applies the inverse decoding transfer
function (the EOTF) to turn it back into light. Choosing a color space
chooses which transfer functions both ends use.
* **Who applies the encoding transfer function.** wgpu applies it for you
**only** when you render to an `*Srgb` texture view format, where the GPU
runs the sRGB OETF when a value is stored to a texture. For every other
color space (linear extended sRGB, encoded extended sRGB or P3, PQ, HLG)
**the values your shader writes to the surface texture must already be
encoded by you**, along with any gamut conversion; in a typical renderer
this happens in a final tone-mapping or post-processing pass. wgpu hands
the signal to the compositor unchanged; getting this wrong produces a
wrong image with no error.
wgpu does **not** tonemap or gamut-map for you. It gives you the surface
and, through [`DisplayHdrInfo`], the display's advisory capabilities;
*choosing* and *applying* a tone curve is your application's job.
### The practical path
1. **Query capabilities.** Call [`Surface::get_capabilities`]. To use HDR or
wide-gamut output, read [`SurfaceCapabilities::format_capabilities`] (each
format and the [`SurfaceColorSpaces`] it supports), **not**
[`SurfaceCapabilities::formats`]: the latter lists only formats usable
with [`Auto`](SurfaceColorSpace::Auto), which never selects HDR.
[`SurfaceCapabilities::color_spaces`] is a convenience lookup for one
format.
2. **Optionally query the display.** Call [`Surface::display_hdr_info`] for the
current [`DisplayHdrInfo`] (peak and SDR-white nits, EDR headroom,
primaries, and a coarse dynamic-range/gamut bucket). Use it to pick a
tone-map target ([`DisplayHdrInfo::tone_map_headroom`]); *whether* HDR is
worthwhile is the capability question from step 1, not this live value.
Every field is advisory and optional; `None` means "cannot tell here",
never "SDR".
3. **Choose a format and color space.** Intersect what you want with what
step 1 advertises, in your own preference order (for example HDR10, then
linear extended sRGB, then encoded extended sRGB, then SDR
[`Srgb`](SurfaceColorSpace::Srgb)). Keep an SDR fallback for when nothing
HDR is advertised, such as when OS HDR is off.
4. **Configure the surface.** Set [`SurfaceConfiguration::color_space`] and
`format`. [`Auto`](SurfaceColorSpace::Auto) (the default) reproduces
wgpu's historical behavior and never picks HDR; any other value must be in
that format's advertised set or configuration fails validation.
5. **Encode what you write to the surface texture.** For an `*Srgb` format,
output linear and the hardware encodes for you. Otherwise the values your
shader writes to the surface texture must already carry the encoding the
chosen color space expects (sRGB, extended sRGB, PQ, or HLG) **and** any
gamut conversion (for example outputting in the BT.2020 gamut for HDR10);
in a typical renderer you do this in a final tone-mapping or
post-processing pass. See the table below.
6. **Present** as usual. If OS HDR is toggled mid-run, you'll see it on the
next [`Surface::display_hdr_info`] poll; re-query [`Surface::get_capabilities`]
and re-run the steps above.
The standalone [HDR surface example] implements every step, including the
encoding transfer function for each color space.
### What to output from your fragment shader
What the values your shader writes to the surface texture must contain for
each color space, and whether wgpu applies the transfer function for you:
| Color space | Typical format | You write | wgpu encodes? |
| ----------- | -------------- | --------- | ------------- |
| `Srgb`, `*Srgb` format | `{Rgba,Bgra}8UnormSrgb` | linear | **yes** (hardware sRGB OETF on store) |
| `Srgb`, non-srgb format | `{Rgba,Bgra}8Unorm` | sRGB-encoded | no; apply the sRGB OETF yourself or use `*Srgb` instead |
| `ExtendedSrgbLinear` (scRGB) | `Rgba16Float` | linear, `1.0` = SDR white | no, but no encoding is necessary |
| `ExtendedSrgb` | `Rgba16Float` | extended sRGB-encoded | no; apply the extended sRGB OETF yourself |
| `DisplayP3` | `Bgra8Unorm` | sRGB-encoded, P3 primaries | no; apply the sRGB OETF (after gamut-mapping to P3) |
| `ExtendedDisplayP3` | `Rgba16Float` | extended sRGB-encoded, P3 primaries | no; apply the extended sRGB OETF (after gamut-mapping to P3) |
| `Bt2100Pq` (HDR10) | `Rgb10a2Unorm` | PQ-encoded, BT.2020 primaries | no; apply the PQ OETF (after gamut-mapping to BT.2020) |
| `Bt2100Hlg` | `Rgb10a2Unorm` | HLG-encoded, BT.2020 primaries | no; apply the HLG OETF (after gamut-mapping to BT.2020) |
In short, wgpu applies the transfer function for you only when you render to
an `*Srgb` format. In every other case the values your shader writes to the
surface texture must already carry both the transfer function and any gamut
conversion. The [HDR surface example] implements every encoder in WGSL.
### Glossary
* **Chromaticity** --- a color's hue and saturation independent of its
brightness, given as an `(x, y)` coordinate on the CIE 1931 diagram.
* **Primaries / gamut** --- the chromaticities of the red, green, and blue a
color space addresses, and so the range of colors it can express. [BT.709]
is the sRGB gamut, [Display P3] is wider, and [BT.2020] is wider still.
* **White point** --- the chromaticity of `R = G = B` (what "white" looks
like). Every color space here uses [D65], standard daylight.
* **Transfer function (OETF / EOTF)** --- how stored values map to light. The
*OETF* is the encoding transfer function your application applies; the
*EOTF* is the inverse decoding transfer function the display applies.
* **SDR / HDR** --- standard dynamic range clips at `1.0` (reference white);
high dynamic range lets values above `1.0` drive brighter-than-white
output.
* **Nits and reference white** --- a *nit* (cd/m²) is a unit of brightness;
*reference white* (also called *paper white*, especially on Windows) is the
brightness of SDR plain white, set below the panel's peak so highlights have
room above it.
* **Headroom (EDR)** --- how much brighter than current SDR white the display
can go right now, as a multiplier (`1.0` means none). Dynamic; see
[`DisplayHdrInfo::tone_map_headroom`].
* **PQ / HLG** --- the two HDR transfer functions: [PQ] (SMPTE ST 2084,
HDR10) encodes absolute luminance, [HLG] (BT.2100) encodes relative
luminance.
* **scRGB / extended-range sRGB** --- sRGB extended past 0.0..=1.0 for
HDR: [scRGB] is *linear*
([`ExtendedSrgbLinear`](SurfaceColorSpace::ExtendedSrgbLinear)), while
[`ExtendedSrgb`](SurfaceColorSpace::ExtendedSrgb) is the same range but
sRGB-*encoded* (gamma), the web's HDR path.
[HDR surface example]: https://github.com/gfx-rs/wgpu/tree/v29/examples/standalone/03_hdr_surface
[BT.709]: https://www.itu.int/rec/R-REC-BT.709
[BT.2020]: https://www.itu.int/rec/R-REC-BT.2020
[Display P3]: https://en.wikipedia.org/wiki/DCI-P3#Display_P3
[D65]: https://en.wikipedia.org/wiki/Standard_illuminant#D65_values
[PQ]: https://en.wikipedia.org/wiki/Perceptual_quantizer
[HLG]: https://www.itu.int/rec/R-REC-BT.2100
[scRGB]: https://en.wikipedia.org/wiki/ScRGB
*/
use crate::{
DisplayHdrInfo, Surface, SurfaceCapabilities, SurfaceColorSpace, SurfaceColorSpaces,
SurfaceConfiguration,
};
+6
View File
@@ -0,0 +1,6 @@
/*!
Articles about HDR, color, and color spaces.
*/
pub mod hdr_surfaces;
pub mod srgb;
+119
View File
@@ -0,0 +1,119 @@
/*!
# Texture Color Formats and sRGB Conversions
Tips and common misconceptions about color formats. For surface output,
wide-gamut, and high-dynamic-range color, see
[HDR and Wide-Gamut Color Spaces](crate::documentation::color::hdr_surfaces).
_(The following is adapted from conversations on the `wgpu` users Matrix
channel, saved here as a useful resource for future `wgpu` developers.)_
Digital color can be an extremely confusing topic, and the resources in
common circulation aren't always great. Modern low-level graphics APIs (such
as those under the hood of `wgpu`) give us powerful tools to manipulate color
data, though this comes at the cost of having to understand several low-level
principles in how digital color works.
The best place to start is to have an understanding of the problems and
history of gamma correction. This page won't go deeply into the topic, but
some useful links can be found here:
- [What every coder should know about gamma](https://blog.johnnovak.net/2016/09/21/what-every-coder-should-know-about-gamma/)
- [Hitchhiker's Guide to Digital Color](https://hg2dc.com/)
- [Learn OpenGL — Gamma Correction](https://learnopengl.com/Advanced-Lighting/Gamma-Correction)
## What do `TextureFormat`s do?
There are many different texture formats you can specify for the format of
your color data. This can be image data you upload from the CPU, shaded
geometry rendered to intermediate textures (what we used to call frame
buffers in OpenGL), compute shader targets, or geometry shaded to the window
surface itself.
We won't go into all the different formats here, but it's useful to talk
about two of the most commonly used formats and some misconceptions about
what they do (and don't) do.
## What are Unorm and UnormSrgb?
Some of the most common formats you will see used for texture data, render
targets, etc. are [`Rgba8Unorm`](TextureFormat::Rgba8Unorm) and
[`Rgba8UnormSrgb`](TextureFormat::Rgba8UnormSrgb). So what are they, and how
do they relate to the issues of gamma correction, perceptually-linear "sRGB"
space, and physically-accurate "linear" space (as described in detail in the
links above)?
First of all, it will be useful to clarify some terminology, as the words
"linear" and "sRGB" can be overloaded and lead to confusion:
- **sRGB space** is a set of color primaries — this defines what red, green,
and blue are.
In this sense (and perhaps counter-intuitively), texture formats ending in
"Unorm" and "UnormSrgb" are BOTH in the sRGB color space, and encode their
data in the same way without losing precision (as might be implied by some
descriptions of "linear" vs. "sRGB"); more on this later.
Here is some useful terminology to help avoid "linear" and "sRGB" confusion:
- What we traditionally called "linear space" is more accurately called
"scene-referred color".
- What we traditionally called "sRGB space" is more accurately called
"monitor-referred color".
- The conversion from scene-referred color to monitor-referred color is done
by the sRGB OETF (opto-electrical transfer function \[light → bits\]).
- The conversion from monitor-referred color to scene-referred color is done
by the sRGB EOTF (electro-optical transfer function \[bits → light\]).
Let's walk our way up the color pipeline. The OS assumes that the bits you
are sending to the screen are monitor-referred and in the sRGB space (unless
otherwise specified). It will interpret the bits this way no matter what.
- If you write/shade to a texture which is in a **Unorm** format, it will
take the output of your shader and do a float → int conversion, and that's
it (Unorm floats are written as ints under the hood, though you don't need
to worry about this).
This means that if you're using this **Unorm** texture as a surface, *the
floats you are writing from your shader need to be **monitor-referred*** (i.e.
numbers that the OS can safely assume are already in sRGB space).
- If you write/shade to a texture which is in a **UnormSrgb** format, it will
take the output of your shader and then apply the sRGB OETF to it, then
afterwards do the float → int conversion to store the data.
This means that if you're using this **UnormSrgb** texture as a surface,
*the floats you are writing from your shader need to be **scene-referred***,
as the GPU will do the conversion to monitor-referred as part of the write!
The inverse happens when you read from a texture:
- a **Unorm** texture just does int → float on read.
- a **UnormSrgb** texture applies the sRGB EOTF to do monitor → scene and
then does the int → float read.
## Common misconceptions
**Q: So Unorm textures are in "linear" space and UnormSrgb textures are in
"sRGB" space?**
**A:** No. Despite the naming, you are responsible for whether the outputs of
your shader represent "scene"- or "monitor"-referred values. The "Srgb" tag on
the texture format just lets the shader know that you want it to do a
conversion from sRGB to linear (or, more specifically, "monitor" to "scene")
when you sample it, or the inverse when you write to it.
## Tips
- Think of texture formats as a combination of data resolution and data
conversion functions. For example:
[`Rgba8UnormSrgb`](TextureFormat::Rgba8UnormSrgb) = `Rgba8` data +
`UnormSrgb` conversion step.
- Let the GPU do the conversion work for you. Historically in WebGL, for
example, if you wanted to do physically-accurate lighting you would need to
convert from linear to sRGB manually (often with an approximation like
`pow(col, 2.2)`). By being aware of the textures you are sampling and
writing to, you should be able to avoid manual conversions.
*/
use crate::TextureFormat;
@@ -0,0 +1,178 @@
/*!
# Debugging wgpu Applications
This page describes the tricks and tools aimed at investigating issues
related to `wgpu`.
## Native API validation
`wgpu`'s goal is to guarantee that only valid workloads reach the low-level
APIs under the hood. If anything is not correct, we are going to complain
about it. You should never need to listen to the low-level API's complaints.
This is a big [work-in-progress](https://github.com/gfx-rs/wgpu/labels/area%3A%20validation),
however. So in the meantime, it's useful to hear what the low-level
validation has to say.
### Vulkan and OpenGL
On Khronos APIs we redirect all the validation output to the console. You
will see it as long as:
1. you run a debug build,
2. you have the validation layers installed (i.e. the LunarG SDK), and
3. you capture logging (with something like
[`env_logger`](https://crates.io/crates/env_logger)).
To enable the validation layers in non-debug builds, manually turn on
validation in the [`InstanceDescriptor`] with [`InstanceFlags::VALIDATION`].
See also [Enabling Vulkan Validation Layers](crate::documentation::debugging::vulkan_validation_layers).
### D3D
#### COM
The refcount of a COM object is 9 32-bit words behind the pointer's
destination and is 4 bytes. As such, subtract 36 from the pointer's address
to get a pointer to that object's refcount. This allows you to use data
breakpoints to see all changes to the object's refcount, useful for
detecting leaks and other such things.
### Metal
You can either set `METAL_DEVICE_WRAPPER_TYPE=1` in the environment, or
launch from Xcode, where validation options are configurable in the project
menus (and enabled by default). To launch from Xcode, you can create a
project of "External Build System" type, picking `cargo` or any other
command as the build system. Then you'd need to edit the target
configuration and select the executable.
A full guide that explains how to launch from Xcode is available in
[Debugging with Xcode](crate::documentation::debugging::xcode).
#### Mac leaks
To look for leaks using "Instruments", you need to add a special entitlement
to your executable's signature. Write the following to `entitle.xml`:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.get-task-allow</key>
<true/>
</dict>
</plist>
```
Then run `codesign -s - -v -f --entitlements=entitle.xml /path/to/my/app`.
([Source](https://stackoverflow.com/questions/74262518/why-required-kernel-recording-resources-are-in-use-by-another-document-error-i).)
## GPU debugging
If the validation is clean, and you are getting incorrect rendering or
computing, it's time to dive into GPU debugging. Many tools exist today:
- RenderDoc can be used on Windows and Linux to capture Vulkan, D3D, and
OpenGL.
- If RenderDoc is used with a compute shader without any normal rendering
components, wrap the work in [`Device::start_graphics_debugger_capture`]
and [`Device::stop_graphics_debugger_capture`] so RenderDoc picks up the
pipeline.
- Vulkan initialization may fail in RenderDoc under Wayland (see
[issue 3889](https://github.com/gfx-rs/wgpu/issues/3889)). To work around
it, force winit to use X11 by setting the `WAYLAND_DISPLAY` environment
variable to an empty string for winit versions `0.28.2` and onward, or
the `WINIT_UNIX_BACKEND` environment variable to `"x11"` for winit
versions up to `0.29.1`. When in doubt, do both.
- PIX can be used on Windows to capture D3D12.
- Xcode has powerful Metal GPU capture support with full shader debugging.
In order to run your application from Xcode, you can create an empty project,
select your executable binary, and provide the command-line parameters in
the project settings.
### Capturing WebGPU in Chrome with PIX
<https://gist.github.com/Popov72/41f71cbf8d55f2cb8cae93f439eee347>
### Capturing WebGPU in Chrome with Xcode
<https://ced.quest/chromium-metal-debugger.html>
## CPU debugging
As `wgpu` is a Rust project, all the regular methods of debugging work. It's
convenient to launch an application from Xcode (e.g. as an "External Build
System" type project), or Visual Studio (just go to "Open Project" and
select the executable, adjusting the path and parameters).
When looking at a crash/panic, the first step is typically enabling
`RUST_BACKTRACE=1` in the environment. This will spew out the stack trace,
which helps you locate the problem.
## Rubber-duck debugging
Hop on to [`#wgpu:matrix.org`](https://matrix.to/#/#wgpu:matrix.org) and try
to explain what happens and why. Maybe we listen. Maybe you'll figure out
the answer by then ;)
## Tracing infrastructure
API tracing is built into `wgpu-core` under the `trace` feature. To record a
trace, first make sure this feature is enabled, then set the `trace` field
of the [`DeviceDescriptor`] to [`Trace::Directory`](crate::Trace) with an existing folder
path when calling [`Adapter::request_device`]. The device will then record a
trace of everything that's going on to that folder.
Once the trace is recorded, you can zip the folder and attach it to an
issue. This should allow anyone, including the developers, to reproduce the
issue on their machines, using the `player`:
```bash
cd player
cargo run --features winit -- <trace_folder_path>
```
If the program crashed or was interrupted in the midst of recording, you may
need to edit the trace folder's `trace.ron` file and add a closing `]`
bracket to the end. When that bracket is missing, the player exits with a
message like:
```text
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value:
Error { code: Eof, position: Position { line: 96233, col: 1 } }', player/src/bin/play.rs:28:70
```
### Running in Gecko
If you encounter a problem with something that runs fine outside of Gecko
but fails to run in Gecko, there is a way to trace the API use by the
browser. Simply run Firefox Nightly (with prefs enabled for WebGPU,
obviously) under `WGPU_TRACE` pointing to a writable folder, and it will
record the API trace. Setting `MOZ_DISABLE_GPU_SANDBOX=1` might also be
required if the GPU process is sandboxed by default. This trace can be
replayed as usual, or even compared to a trace you get by running the same
application natively, to find out what the browser doesn't do right.
To replay a capture from Firefox and inspect it in RenderDoc or similar
tools, it is best not to build the player with the `winit` cargo feature.
When Firefox renders a WebGPU canvas, the result is done in a texture rather
than a window's swapchain, and that texture is then shared and put onto the
screen via other means that aren't part of the `wgpu` trace. Since there is
no window swapchain involved, RenderDoc can't guess when a frame starts and
ends, so it has to be helped by manually inserting begin/end capture
markers. When built without the `winit` feature, the player replays the
commands without rendering them into a window, and adds these markers at the
beginning and end of the trace; it doesn't when the `winit` feature is
enabled, since it then assumes the trace will eventually render into the
winit window's swapchain.
This applies to Firefox as well as any other software using `wgpu` to render
content into a texture but not to present that texture into a window.
*/
use crate::{Adapter, Device, DeviceDescriptor, InstanceDescriptor, InstanceFlags, Trace};
+11
View File
@@ -0,0 +1,11 @@
/*!
Debugging
Tools and techniques for investigating correctness, validation, and
performance problems in `wgpu` applications.
*/
pub mod debugging_applications;
pub mod performance;
pub mod vulkan_validation_layers;
pub mod xcode;
@@ -0,0 +1,16 @@
/*!
# Debugging Performance Issues
If you're encountering performance problems, here's a checklist:
- Are you building with `--release`? (Don't laugh!) Development-profile
builds trade overhead for diagnostic ability:
- [`InstanceFlags::DEBUG`] is set by default in development builds, which
enables platform-level validation, like the Vulkan validation layers.
- The Rust compiler doesn't optimize the generated machine code.
- Development builds have more assertions enabled.
Please add more checklist items, based on your experience.
*/
use crate::InstanceFlags;
@@ -0,0 +1,57 @@
/*!
# Enabling Vulkan Validation Layers
When developing an application it is often useful to enable Vulkan's
validation layers. They can catch errors when you are using the API
incorrectly or exceeding device limits. You can read more about validation
layers here: <https://gpuopen.com/using-the-vulkan-validation-layers/>.
Validation layers are a Vulkan-only feature, so they cannot be used with
other backends. You can restrict which backends `wgpu` uses via
[`InstanceDescriptor`] and [`Backends`].
## Installation
For validation layers to work you need to install the Vulkan SDK:
### Linux
Visit <https://packages.lunarg.com/> to install the Vulkan SDK along with
some validation layers. Click the "Latest Supported Release" button (which
looks like it's just a header, but it is in fact a button) and follow the
instructions.
### Other operating systems
TODO.
## Enabling validation layers
`wgpu` enables validation layers automatically in most cases when the
application is compiled in debug mode (that is, if the `--release` flag is
*not* passed to `cargo`), because [`InstanceFlags::DEBUG`] is set by default
in development builds. You can also enable them explicitly with
[`InstanceFlags::VALIDATION`], or by setting the environment variable
`VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation`.
The validation layers use normal Rust logging functionality, which also
needs to be enabled. The `wgpu` examples use the
[`env_logger`](https://crates.io/crates/env_logger) crate for logging, which
means you can enable validation-layer logging by setting an environment
variable:
```bash
env RUST_LOG=trace cargo run --bin wgpu-examples cube
```
There are several logging levels (see <https://docs.rs/log/latest/log/> for
more info), with `trace` being the highest. If you choose a lower level such
as `info`, then fewer messages will be logged.
If you want to enable validation layers in your own application, make sure
it has logging configured. The
[`env_logger`](https://crates.io/crates/env_logger) crate is one possible
way to do this.
*/
use crate::{Backends, InstanceDescriptor, InstanceFlags};
+80
View File
@@ -0,0 +1,80 @@
#![doc = crate::macros::doc_image!("xcode-new-project.webp")]
#![doc = crate::macros::doc_image!("xcode-project-type.webp")]
#![doc = crate::macros::doc_image!("xcode-build-tool.webp")]
#![doc = crate::macros::doc_image!("xcode-edit-scheme.webp")]
#![doc = crate::macros::doc_image!("xcode-scheme-options.webp")]
#![doc = crate::macros::doc_image!("xcode-scheme-arguments.webp")]
#![doc = crate::macros::doc_image!("xcode-select-binary.webp")]
#![doc = crate::macros::doc_image!("xcode-play-button.webp")]
#![doc = crate::macros::doc_image!("xcode-attached.webp")]
#![doc = crate::macros::doc_image!("xcode-start-capture.webp")]
/*!
# Debugging with Xcode (Metal GPU Capture)
Xcode provides powerful Metal GPU capture and shader debugging tools. This
page walks through attaching Xcode to a `wgpu` application so you can enable
Metal validation and capture frames.
A Chinese version is also available:
[使用 Xcode 调试 wgpu 程序](https://jinleili.github.io/learn-wgpu-zh/integration-and-debugging/ios/#xcode-%E4%B8%8E-metal).
First we'll start by opening Xcode and creating a new project using the menu
or "Create a new Xcode project" in the startup dialog.
![Xcode startup dialog][xcode-new-project.webp]
Select "External Build System" as the project type.
![Xcode project type][xcode-project-type.webp]
Choose which build tool to use in the "Build Tool" field. This will be
called whenever we build in Xcode.
We can write our `cargo` build command here if we'd like Xcode to run it,
but we could also skip the build step to avoid Xcode building the project
for us.
It's possible to skip the build step by specifying our build command as
`ls`, `echo`, or anything else that exits successfully (note: `:` doesn't
appear to work here).
The rest of the fields don't actually matter to us, so we can put any values
there.
![Xcode build tool][xcode-build-tool.webp]
Click on the project name and then click "Edit Scheme".
![Xcode edit scheme][xcode-edit-scheme.webp]
Under the "Options" tab we can choose the level of validation for Metal and
whether to enable GPU frame capture.
![Xcode scheme options][xcode-scheme-options.webp]
Under the "Arguments" tab we'll choose which executable to run. We want this
to be the binary created by `cargo`. We'll select "Other" and then find the
binary in the target directory.
![Xcode scheme arguments][xcode-scheme-arguments.webp]
![Xcode select binary][xcode-select-binary.webp]
Next we'll click the play button to run our binary and attach Xcode to it.
![Xcode play button][xcode-play-button.webp]
Now we should see our application running and some output telling us that
Metal validation has been enabled.
![Xcode attached][xcode-attached.webp]
To start a GPU capture, click the camera button while Xcode is attached to
our running application.
![Xcode start capture][xcode-start-capture.webp]
After a frame has been captured, we will be able to use all the regular
Metal tools (e.g. shader debugging, GPU statistics, etc.).
*/
@@ -1,8 +1,7 @@
# Cooperative Matrix Extensions
/*!
# 🧪Experimental🧪 Cooperative Matrix Extensions
🧪Experimental🧪
`wgpu` supports an experimental cooperative matrix feature when `Features::EXPERIMENTAL_COOPERATIVE_MATRIX` is enabled.
`wgpu` supports an experimental cooperative matrix feature when [`Features::EXPERIMENTAL_COOPERATIVE_MATRIX`] is enabled.
This exposes hardware-accelerated matrix multiply-accumulate (MMA) operations (for example, NVIDIA tensor cores,
Metal SIMD-group matrices, and Vulkan `VK_KHR_cooperative_matrix`).
@@ -63,7 +62,7 @@ Each `CooperativeMatrixProperties` describes a single supported configuration. F
Example usage:
```/dev/null/cooperative-matrix-host.rs#L1-40
```ignore
let coop_props = adapter.cooperative_matrix_properties();
for prop in &coop_props {
println!(
@@ -77,7 +76,7 @@ for prop in &coop_props {
You **must**:
1. Enable `Features::EXPERIMENTAL_COOPERATIVE_MATRIX` on the `Device`.
1. Enable [`Features::EXPERIMENTAL_COOPERATIVE_MATRIX`] on the `Device`.
2. Query `adapter.cooperative_matrix_properties()` and ensure that the configuration(s) you intend
to use in WGSL are actually available on the running adapter/backend.
3. Treat the sizes and types as a contract between your shaders and the underlying hardware implementation.
@@ -90,7 +89,7 @@ You **must**:
### `wgpu` feature
- Using cooperative matrices requires enabling:
- `Features::EXPERIMENTAL_COOPERATIVE_MATRIX`
- [`Features::EXPERIMENTAL_COOPERATIVE_MATRIX`]
This feature may be restricted to certain backends and hardware.
@@ -107,7 +106,7 @@ These are general guidelines, not a complete compatibility matrix:
- Requires the `VK_KHR_cooperative_matrix` extension.
- Many NVIDIA and AMD GPUs support `f16` at 16×16 tile sizes and similar.
- 8×8 `f32` support is hardware-dependent.
- Exact configurations are enumerated by `Adapter::cooperative_matrix_properties()`.
- Exact configurations are enumerated by [`Adapter::cooperative_matrix_properties()`].
- **Other backends**:
- May not support cooperative matrices at all. In that case the feature will not be exposed, and
@@ -156,7 +155,7 @@ may change; the details below describe the intended semantics.
Any WGSL program using cooperative matrices must declare an extension at the top of the shader, for example:
```/dev/null/example.wgsl#L1-3
```wgsl
enable wgpu_cooperative_matrix;
```
@@ -175,7 +174,7 @@ A cooperative matrix is a value type parameterized by:
Conceptually:
```/dev/null/example.wgsl#L1-8
```wgsl
// A: MxK, B: KxN, C: MxN
type coop_matMxN<T, A>;
type coop_matMxN<T, B>;
@@ -185,7 +184,7 @@ type coop_matMxN<T, C>;
Concrete examples (sizes and types must match a supported configuration from
`Adapter::cooperative_matrix_properties`):
```/dev/null/example.wgsl#L10-20
```wgsl
// 8x8 single-precision tiles
alias CoopMatA = coop_mat8x8<f32, A>;
alias CoopMatB = coop_mat8x8<f32, B>;
@@ -233,7 +232,7 @@ select the memory layout:
`stride` is the number of elements between adjacent rows. This is the
natural fit for C-style `ptr[i * num_cols + j]` storage.
```/dev/null/example.wgsl#L1-10
```wgsl
fn coopLoad<T, R>(
ptr: ptr<STORAGE_CLASS, T>, // base pointer to scalar or vector elements
stride: u32 // elements between adjacent columns
@@ -260,7 +259,7 @@ selection mirrors the load builtins:
- `coopStore` — writes **column-major**; `stride` between columns.
- `coopStoreT` — writes **row-major**; `stride` between rows.
```/dev/null/example.wgsl#L12-23
```wgsl
fn coopStore<T, R>(
value: coop_matMxN<T, R>,
ptr: ptr<STORAGE_CLASS, T>,
@@ -282,7 +281,7 @@ fn coopStoreT<T, R>(
Perform a matrix multiply-accumulate operation on cooperative matrices:
```/dev/null/example.wgsl#L15-23
```wgsl
fn coopMultiplyAdd<Tab, Tcr, MA, KA, KB, NB>(
a: coop_matMAxKA<Tab, A>, // A: MAxKA tile
b: coop_matKBxNB<Tab, B>, // B: KBxNB tile (KB == KA)
@@ -302,7 +301,7 @@ Semantics:
For example, with a supported configuration:
```/dev/null/example.wgsl#L25-39
```wgsl
enable wgpu_cooperative_matrix;
alias MatA = coop_mat8x8<f32, A>;
@@ -354,7 +353,7 @@ For portable code:
Example:
```/dev/null/example.wgsl#L1-42
```wgsl
enable wgpu_cooperative_matrix;
struct Matrices {
@@ -405,7 +404,7 @@ Implementations must validate the following where possible:
- The `wgpu_cooperative_matrix` WGSL extension is enabled if any cooperative matrix types
or builtins are used.
- Tile sizes `(M, N, K)` and scalar types `(ab_type, cr_type)` match at least one
`CooperativeMatrixProperties` entry for the current adapter/backend.
[`CooperativeMatrixProperties`] entry for the current adapter/backend.
- Workgroup size, shader stage, and other pipeline configuration constraints required
by the backend are satisfied.
@@ -413,7 +412,7 @@ The following are examples of **undefined behavior** (non-exhaustive):
- Using cooperative matrix operations without enabling the WGSL extension.
- Using a cooperative matrix type `(M, N, T, R)` not supported by
`Adapter::cooperative_matrix_properties()`.
[`Adapter::cooperative_matrix_properties()`].
- Mismatching sizes or roles in `coopMultiplyAdd` (e.g. incompatible M/N/K, or incorrect roles).
- Executing `coopLoad` / `coopLoadT`, `coopStore` / `coopStoreT`, or `coopMultiplyAdd` in divergent
control flow within the cooperating execution group.
@@ -451,7 +450,7 @@ Key points from the example:
- Workgroup size is chosen so that all cooperative operations are well-defined and efficient for 8×8 tiles.
- Host-side code:
- Enables `Features::EXPERIMENTAL_COOPERATIVE_MATRIX`.
- Enables [`Features::EXPERIMENTAL_COOPERATIVE_MATRIX`].
- Queries `cooperative_matrix_properties` and verifies that 8×8 `f32` or chosen configuration is supported.
- Dispatches the compute pipeline with appropriate grid dimensions.
@@ -466,3 +465,7 @@ Key points from the example:
- Avoid divergent control flow around cooperative operations.
- Consider providing a fallback non-cooperative implementation for devices that do not support the feature.
- This is an experimental extension; API and semantics may change across versions of `wgpu` and `naga`.
*/
use crate::{Adapter, CooperativeMatrixProperties, Features};
@@ -1,8 +1,7 @@
# Mesh Shader Extensions
/*!
# 🧪Experimental🧪 Mesh Shading
🧪Experimental🧪
`wgpu` supports an experimental version of mesh shading when `Features::EXPERIMENTAL_MESH_SHADER` is enabled.
`wgpu` supports an experimental version of mesh shading when [`Features::EXPERIMENTAL_MESH_SHADER`] is enabled.
The status of the implementation is documented in [the mesh-shading issue](https://github.com/gfx-rs/wgpu/issues/7197).
**Note**: The features documented here may have major bugs in them and are expected to be subject
@@ -69,19 +68,20 @@ With the current pipeline set to a mesh pipeline, a draw command like
### 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.
[`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`] - 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.
[`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).
An example of using mesh shaders to render a single triangle can be seen
[here](https://github.com/gfx-rs/wgpu/tree/trunk/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`.
- Using mesh shaders with point primitives requires enabling `Features::EXPERIMENTAL_MESH_SHADER_POINTS`.
- Using mesh shaders requires enabling [`Features::EXPERIMENTAL_MESH_SHADER`].
- Using mesh shaders with multiview requires enabling [`Features::EXPERIMENTAL_MESH_SHADER_MULTIVIEW`].
- Using mesh shaders with point primitives requires enabling [`Features::EXPERIMENTAL_MESH_SHADER_POINTS`].
- Queries are unsupported
- Primitive index support will be added once support lands in for them in general.
@@ -280,3 +280,7 @@ fn fs_main(vertex: VertexOutput, primitive: PrimitiveInput) -> @location(0) vec4
return vertex.color * primitive.colorMask;
}
```
*/
use crate::{Device, Features, RenderPass};
+7
View File
@@ -0,0 +1,7 @@
/*!
Extensions to the WebGPU API
*/
pub mod cooperative_matrices;
pub mod mesh_shading;
pub mod ray_tracing;
@@ -1,10 +1,9 @@
# Ray Tracing Extensions
🧪Experimental🧪
/*!
# 🧪Experimental🧪 Ray Tracing
`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_QUERY` enabled) and interacted with in shaders. Currently `naga` only supports ray queries
(accessible with `Features::EXPERIMENTAL_RAY_QUERY` enabled in wgpu).
[`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
to breaking changes, suggestions for the API exposed by this should be posted on [the ray-tracing issue](https://github.com/gfx-rs/wgpu/issues/1040).
@@ -18,7 +17,7 @@ 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.
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`].
@@ -72,7 +71,7 @@ Some memory is allocated when building to be "scratch" data (a temporary buffer
the build) and instance staging memory (to copy the instances to the GPU). The some of this can be reused for between
the [`Blas`] and [`Tlas`] builds so in general it is advisable to try and integrate the builds together. Because
building is slow, it should be done as few times as possible. For moving geometry (players, particles, etc.), use
[`PREFER_FAST_BUILD`](https://wgpu.rs/doc/wgpu_hal/struct.AccelerationStructureBuildFlags.html#associatedconstant.PREFER_FAST_BUILD)
[`AccelerationStructureFlags::PREFER_FAST_BUILD`](wgt::AccelerationStructureFlags::PREFER_FAST_BUILD)
to speed up builds. Updating (performing a partial rebuild) is currently unsupported, but may be implemented in the
future. You should compact any geometry which will not change (e.g. static level geometry) once it has been built.
@@ -80,7 +79,7 @@ future. You should compact any geometry which will not change (e.g. static level
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
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
@@ -95,44 +94,38 @@ An example of compaction being run when [`Blas`]es are ready, this would be in a
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
```no_run
# let queue: wgpu::Queue = unimplemented!();
# let device: wgpu::Device = unimplemented!();
# let mut tlas: wgpu::Tlas = unimplemented!();
use std::iter;
use wgpu::Blas;
struct BlasToBeCompacted {
blas: Blas,
/// The index into the TlasInstance this BLAS is used in.
/// The index into the TLAS instance 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 {
// An iterator over whatever BLASes you have called `prepare_compaction_async` on.
let blas_s_pending_compaction = iter::empty::<BlasToBeCompacted>();
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);
tlas[blas_to_be_compacted.tlas_index]
.as_mut()
.unwrap()
.set_blas(&compacted_blas);
}
}
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
/* do other preparations on the TlasInstance.*/
encoder.build_acceleration_structures(iter::empty(), iter::once(&tlas_package));
/* more render code */
queue.submit([encoder.finish()]);
}
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
// do any other preparations on the TLAS here
encoder.build_acceleration_structures(iter::empty(), iter::once(&tlas));
// more render code
queue.submit([encoder.finish()]);
```
[`Device::create_blas`]: https://wgpu.rs/doc/wgpu/struct.Device.html#method.create_blas
[`CommandEncoder::build_acceleration_structures`]: https://wgpu.rs/doc/wgpu/struct.CommandEncoder.html#method.build_acceleration_structures
[`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
[`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:
@@ -409,3 +402,7 @@ These are tags that can be added to a acceleration structure (`acceleration_stru
| Tag | Requirements | Description |
| --------------- | ------------------------------------- | ---------------------------------------------------------------------- |
| `vertex_return` | `enable wgpu_ray_query_vertex_return` | Allows getting the vertices of the hit triangle when using ray queries |
*/
use crate::{Blas, CommandEncoder, Device, Features, Queue, Tlas, TlasInstance};
+16
View File
@@ -0,0 +1,16 @@
/*!
## Feature flags
*/
#![doc = document_features::document_features!()]
/*!
### Feature Aliases
These features aren't actually features on the crate itself, but a convenient shorthand for
complicated cases.
- **`wgpu_core`** --- Enabled when there is any non-webgpu backend enabled on the platform.
- **`naga`** --- Enabled when target `glsl` or `spirv` input is enabled, or when `wgpu_core` is enabled.
*/
use crate::Adapter;
@@ -0,0 +1,80 @@
/*!
# Learning wgpu: Key Concepts and Resources
If you are new to `wgpu` and graphics programming, this page collects
external learning resources and a primer on the core concepts of the API.
## External resources
Learning materials:
- [Learn Wgpu tutorial](https://sotrh.github.io/learn-wgpu/)
- [Draw You a Triangle for Great Good](https://github.com/dwbrite/wgpu-rendering-project/wiki/Draw-You-a-Triangle-for-Great-Good)
- Chinese version of [学习 wgpu](https://jinleili.github.io/learn-wgpu-zh/)
- [GPU Architecture](https://docs.google.com/presentation/d/1qi2j-SZuzew7Rrf5VKEPDZAQQEitV40k9fKvwJNyicM/edit),
a presentation by Kangz on how GPUs work under the hood.
Reference material:
- The `wgpu` examples; see
[Running the Examples](crate::documentation::getting_started::running_the_examples).
- The [WebGPU specification](https://www.w3.org/TR/webgpu/), which `wgpu`
follows closely.
Runtimes:
- The [Deno](https://deno.land/) JS/TS runtime.
## Important concepts
### Device and Queue
- [`Device`]
- All resource creation.
- All of its methods take `&self` (no `&mut`!).
- [`Queue`]
- All GPU work submission.
_Typically_ both are created once on startup, one of each. A [`Device`] is
created with a set of [`Features`] and [`Limits`], which are enforced
independently of the underlying hardware's actual capabilities (e.g. texture
size and formats, number of bound resources, native extensions, …).
### Relationship of [`RenderPipeline`]s and resource binding
A slightly simplified overview of what you need to set up before rendering a
frame.
*/
#![doc = include_str!("../images/render-pipeline-and-resource-binding.svg")]
/*!
- _Round boxes:_ temporary descriptor structs.
- _Cornered boxes:_ resources created from a [`Device`].
- _Bold:_ what you deal with on a per-frame basis.
Each [`BindGroupLayoutEntry`] has a (mostly) corresponding
[`BindingResource`]. Compute pipelines follow a similar pattern.
### Drawing a "frame"
A simplified overview of what you need to do to draw a frame.
*/
#![doc = include_str!("../images/life-of-a-frame.svg")]
/*!
- _Full lines:_ needed for creation.
- _Dashed lines:_ provided as "information".
[`CommandEncoder::finish`] consumes a [`CommandEncoder`] and produces a
[`CommandBuffer`]; [`Queue::submit`] consumes [`CommandBuffer`]s. The
[`TextureView`] on a [`RenderPassColorAttachment`] can come from a
[`Surface`] — a special target for the final output.
*/
use crate::{
BindGroupLayoutEntry, BindingResource, CommandBuffer, CommandEncoder, Device, Features, Limits,
Queue, RenderPassColorAttachment, RenderPipeline, Surface, TextureView,
};
@@ -0,0 +1,9 @@
/*!
Getting Started
First steps for new `wgpu` users: running the bundled examples and learning
the core concepts of the API.
*/
pub mod learning_wgpu;
pub mod running_the_examples;
@@ -0,0 +1,39 @@
/*!
# Running the Examples
This section shows you how to get the dependencies needed to run the
examples included in the `wgpu` repository.
## Dependencies
The examples require:
- The Rust compiler ([installation instructions](https://www.rust-lang.org/)).
- Drivers for your graphics card. Note that some platforms have multiple
possible driver backends (e.g. D3D12 or Vulkan on Windows).
- Git ([installation instructions](https://git-scm.com/downloads)).
## Cloning
Once you have the tools above, clone the repository:
```bash
git clone --depth 1 https://github.com/gfx-rs/wgpu.git
cd wgpu
```
## Running the examples
You can run the examples using the `wgpu-examples` binary:
```bash
# Show a list of all examples
cargo run --bin wgpu-examples
# Run the cube example
cargo run --bin wgpu-examples cube
```
To run an example in a browser, see
[Running on the Web](crate::documentation::platforms::web).
*/
File diff suppressed because it is too large. Load diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

File renamed without changes.
@@ -0,0 +1 @@
<svg version="1.1" viewBox="0.0 0.0 960.0 540.0" fill="none" stroke="none" stroke-linecap="square" stroke-miterlimit="10" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg"><clipPath id="g162162e116a_0_56.0"><path d="m0 0l960.0 0l0 540.0l-960.0 0l0 -540.0z" clip-rule="nonzero"/></clipPath><g clip-path="url(#g162162e116a_0_56.0)"><path fill="#212121" d="m0 0l960.0 0l0 540.0l-960.0 0z" fill-rule="evenodd"/><path fill="#000000" fill-opacity="0.0" d="m893.7507 15.569553l56.02356 0l0 60.64284l-56.02356 0z" fill-rule="evenodd"/><g transform="matrix(0.029610761154855645 0.0 0.0 0.029610761154855645 893.7506435695539 15.569553805774278)"><clipPath id="g162162e116a_0_56.1"><path d="m0 0l1892.0 0l0 2048.0l-1892.0 0z" clip-rule="evenodd"/></clipPath></g><path fill="#000000" fill-opacity="0.0" d="m31.485565 48.46194l894.55115 0l0 60.125988l-894.55115 0z" fill-rule="evenodd"/><path fill="#ffffff" d="m42.93869 89.71794l0 -24.046875l3.1875 0l0 21.203125l11.84375 0l0 2.84375l-15.03125 0zm18.464493 -20.65625l0 -3.390625l2.953125 0l0 3.390625l-2.953125 0zm0 20.65625l0 -17.421875l2.953125 0l0 17.421875l-2.953125 0zm8.150955 0l0 -15.125l-2.609375 0l0 -2.296875l2.609375 0l0 -1.859375q0 -1.75 0.3125 -2.59375q0.421875 -1.15625 1.5 -1.859375q1.078125 -0.71875 3.015625 -0.71875q1.234375 0 2.75 0.296875l-0.4375 2.5625q-0.921875 -0.15625 -1.75 -0.15625q-1.34375 0 -1.90625 0.578125q-0.546875 0.5625 -0.546875 2.140625l0 1.609375l3.390625 0l0 2.296875l-3.390625 0l0 15.125l-2.9375 0zm20.55217 -5.609375l3.046875 0.375q-0.71875 2.671875 -2.671875 4.15625q-1.953125 1.46875 -4.984375 1.46875q-3.828125 0 -6.0625 -2.34375q-2.234375 -2.359375 -2.234375 -6.609375q0 -4.390625 2.25 -6.8125q2.265625 -2.4375 5.875 -2.4375q3.5 0 5.703125 2.375q2.21875 2.375 2.21875 6.6875q0 0.265625 -0.015625 0.796875l-12.984375 0q0.15625 2.875 1.609375 4.40625q1.46875 1.515625 3.65625 1.515625q1.625 0 2.765625 -0.84375q1.15625 -0.859375 1.828125 -2.734375zm-9.703125 -4.78125l9.734375 0q-0.203125 -2.1875 -1.109375 -3.296875q-1.421875 -1.703125 -3.65625 -1.703125q-2.046875 0 -3.4375 1.375q-1.375 1.359375 -1.53125 3.625zm24.688538 1.6875q0 -4.84375 2.703125 -7.171875q2.234375 -1.9375 5.46875 -1.9375q3.59375 0 5.875 2.359375q2.28125 2.34375 2.28125 6.5q0 3.359375 -1.015625 5.296875q-1.0 1.921875 -2.9375 2.984375q-1.921875 1.0625 -4.203125 1.0625q-3.65625 0 -5.921875 -2.34375q-2.25 -2.34375 -2.25 -6.75zm3.046875 0q0 3.34375 1.453125 5.015625q1.453125 1.65625 3.671875 1.65625q2.203125 0 3.65625 -1.671875q1.46875 -1.671875 1.46875 -5.109375q0 -3.234375 -1.46875 -4.890625q-1.46875 -1.671875 -3.65625 -1.671875q-2.21875 0 -3.671875 1.65625q-1.453125 1.65625 -1.453125 5.015625zm17.448868 8.703125l0 -15.125l-2.609375 0l0 -2.296875l2.609375 0l0 -1.859375q0 -1.75 0.3125 -2.59375q0.421875 -1.15625 1.5 -1.859375q1.078125 -0.71875 3.015625 -0.71875q1.234375 0 2.75 0.296875l-0.4375 2.5625q-0.921875 -0.15625 -1.75 -0.15625q-1.34375 0 -1.90625 0.578125q-0.546875 0.5625 -0.546875 2.140625l0 1.609375l3.390625 0l0 2.296875l-3.390625 0l0 15.125l-2.9375 0zm29.32309 -2.15625q-1.640625 1.40625 -3.15625 1.984375q-1.515625 0.5625 -3.25 0.5625q-2.875 0 -4.421875 -1.390625q-1.53125 -1.40625 -1.53125 -3.59375q0 -1.28125 0.578125 -2.328125q0.578125 -1.0625 1.515625 -1.703125q0.953125 -0.640625 2.140625 -0.96875q0.859375 -0.234375 2.625 -0.4375q3.5625 -0.4375 5.25 -1.03125q0.03125 -0.59375 0.03125 -0.765625q0 -1.796875 -0.84375 -2.546875q-1.125 -1.0 -3.359375 -1.0q-2.09375 0 -3.09375 0.734375q-0.984375 0.734375 -1.453125 2.578125l-2.890625 -0.390625q0.390625 -1.84375 1.296875 -2.984375q0.90625 -1.140625 2.609375 -1.75q1.703125 -0.625 3.953125 -0.625q2.234375 0 3.625 0.53125q1.390625 0.515625 2.046875 1.3125q0.65625 0.796875 0.921875 2.015625q0.15625 0.75 0.15625 2.71875l0 3.9375q0 4.109375 0.1875 5.203125q0.1875 1.09375 0.734375 2.09375l-3.078125 0q-0.453125 -0.921875 -0.59375 -2.15625zm-0.25 -6.59375q-1.59375 0.65625 -4.8125 1.125q-1.828125 0.265625 -2.578125 0.59375q-0.75 0.328125 -1.171875 0.953125q-0.40625 0.625 -0.40625 1.40625q0 1.171875 0.890625 1.96875q0.90625 0.78125 2.625 0.78125q1.703125 0 3.03125 -0.734375q1.328125 -0.75 1.953125 -2.046875q0.46875 -1.0 0.46875 -2.953125l0 -1.09375zm17.047913 -6.78125l-0.8125 -4.578125l0 -3.9375l3.359375 0l0 3.9375l-0.734375 4.578125l-1.8125 0zm5.4375 0l-0.8125 -4.578125l0 -3.9375l3.359375 0l0 3.9375l-0.78125 4.578125l-1.765625 0zm6.87825 15.53125l0 -24.046875l16.234375 0l0 2.84375l-13.046875 0l0 7.4375l11.28125 0l0 2.84375l-11.28125 0l0 10.921875l-3.1875 0zm19.957901 0l0 -17.421875l2.65625 0l0 2.640625q1.015625 -1.859375 1.875 -2.4375q0.859375 -0.59375 1.890625 -0.59375q1.5 0 3.03125 0.953125l-1.015625 2.734375q-1.078125 -0.640625 -2.15625 -0.640625q-0.96875 0 -1.75 0.59375q-0.765625 0.578125 -1.09375 1.609375q-0.484375 1.578125 -0.484375 3.4375l0 9.125l-2.953125 0zm22.577606 -2.15625q-1.640625 1.40625 -3.15625 1.984375q-1.515625 0.5625 -3.25 0.5625q-2.875 0 -4.421875 -1.390625q-1.53125 -1.40625 -1.53125 -3.59375q0 -1.28125 0.Line truncated

After

Width:  |  Height:  |  Size: 211 KiB

@@ -0,0 +1 @@
<svg version="1.1" viewBox="0.0 0.0 960.0 540.0" fill="none" stroke="none" stroke-linecap="square" stroke-miterlimit="10" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg"><clipPath id="g162162e116a_0_87.0"><path d="m0 0l960.0 0l0 540.0l-960.0 0l0 -540.0z" clip-rule="nonzero"/></clipPath><g clip-path="url(#g162162e116a_0_87.0)"><path fill="#212121" d="m0 0l960.0 0l0 540.0l-960.0 0z" fill-rule="evenodd"/><path fill="#000000" fill-opacity="0.0" d="m893.7507 15.569553l56.02356 0l0 60.64284l-56.02356 0z" fill-rule="evenodd"/><g transform="matrix(0.029610761154855645 0.0 0.0 0.029610761154855645 893.7506435695539 15.569553805774278)"><clipPath id="g162162e116a_0_87.1"><path d="m0 0l1892.0 0l0 2048.0l-1892.0 0z" clip-rule="evenodd"/></clipPath></g><path fill="#adadad" d="m31.509186 356.11356l0 0c0 -19.308594 15.652721 -34.961334 34.961327 -34.961334l591.36865 0c9.272339 0 18.164917 3.6834106 24.721436 10.23996c6.5565186 6.5565186 10.239929 15.449066 10.239929 24.721375l0 139.84113c0 19.308624 -15.65271 34.961334 -34.961365 34.961334l-591.36865 0c-19.308605 0 -34.961327 -15.65271 -34.961327 -34.961334z" fill-rule="evenodd"/><path stroke="#ffffff" stroke-width="3.0" stroke-linejoin="round" stroke-linecap="butt" d="m31.509186 356.11356l0 0c0 -19.308594 15.652721 -34.961334 34.961327 -34.961334l591.36865 0c9.272339 0 18.164917 3.6834106 24.721436 10.23996c6.5565186 6.5565186 10.239929 15.449066 10.239929 24.721375l0 139.84113c0 19.308624 -15.65271 34.961334 -34.961365 34.961334l-591.36865 0c-19.308605 0 -34.961327 -15.65271 -34.961327 -34.961334z" fill-rule="evenodd"/><path fill="#000000" d="m242.91884 515.1429l2.421875 5.03125l1.65625 0l0 -0.09375l-2.609375 -5.265625q0.5 -0.21875 0.921875 -0.53125q0.4375 -0.3125 0.734375 -0.71875q0.3125 -0.40625 0.484375 -0.90625q0.171875 -0.5 0.171875 -1.1094055q0 -0.921875 -0.328125 -1.609375q-0.328125 -0.703125 -0.890625 -1.15625q-0.578125 -0.453125 -1.34375 -0.671875q-0.765625 -0.234375 -1.625 -0.25l-3.609375 0l0 12.3125305l1.5625 0l0 -5.03125l2.453125 0zm-2.453125 -1.28125l0 -4.7187805l2.046875 0q0.578125 0 1.046875 0.15625q0.484375 0.15625 0.828125 0.453125q0.34375 0.296875 0.53125 0.75q0.203125 0.4375 0.203125 1.03125q0 0.5625305 -0.203125 1.0000305q-0.203125 0.421875 -0.546875 0.71875q-0.359375 0.28125 -0.828125 0.4375q-0.453125 0.15625 -0.984375 0.171875l-2.09375 0zm12.82045 6.484375q1.34375 0 2.25 -0.53125q0.90625 -0.546875 1.359375 -1.234375l-0.953125 -0.75q-0.4375 0.5625 -1.09375 0.90625q-0.640625 0.328125 -1.484375 0.328125q-0.625 0 -1.15625 -0.234375q-0.515625 -0.234375 -0.890625 -0.65625q-0.359375 -0.390625 -0.578125 -0.890625q-0.203125 -0.515625 -0.265625 -1.171875l0 -0.0625l6.546875 0l0 -0.703125q0 -0.953125 -0.25 -1.765625q-0.234375 -0.828125 -0.71875 -1.4375q-0.5 -0.6094055 -1.25 -0.9531555q-0.734375 -0.34375 -1.71875 -0.34375q-0.78125 0 -1.53125 0.328125q-0.75 0.3125 -1.34375 0.9219055q-0.578125 0.609375 -0.9375 1.484375q-0.359375 0.875 -0.359375 1.984375l0 0.359375q0 0.953125 0.3125 1.765625q0.328125 0.8125 0.90625 1.40625q0.578125 0.59375 1.375 0.921875q0.8125 0.328125 1.78125 0.328125zm-0.203125 -8.203125q0.609375 0 1.03125 0.21875q0.4375 0.21875 0.734375 0.5625q0.28125 0.359375 0.4375 0.84375q0.171875 0.484375 0.171875 0.921875l0 0.0625l-4.921875 0q0.078125 -0.625 0.3125 -1.109375q0.234375 -0.484375 0.578125 -0.828125q0.34375 -0.328125 0.765625 -0.5q0.421875 -0.171875 0.890625 -0.171875zm6.55484 8.03125l1.5625 0l0 -6.5625q0.171875 -0.296875 0.375 -0.546875q0.21875 -0.25 0.484375 -0.421875q0.3125 -0.21875 0.671875 -0.34375q0.375 -0.125 0.8125 -0.125q0.5 0 0.875 0.125q0.390625 0.109375 0.65625 0.375q0.265625 0.265625 0.40625 0.6875q0.140625 0.421875 0.140625 1.03125l0 5.78125l1.5625 0l0 -5.8125q0 -0.90625 -0.234375 -1.578125q-0.21875 -0.671875 -0.640625 -1.0937805q-0.40625 -0.4375 -1.0 -0.640625q-0.578125 -0.203125 -1.296875 -0.203125q-0.53125 0.015625 -1.015625 0.171875q-0.484375 0.140625 -0.890625 0.40625q-0.265625 0.171875 -0.515625 0.421875q-0.234375 0.23440552 -0.4375 0.5312805l-0.109375 -1.3594055l-1.40625 0l0 9.1562805zm10.101685 -4.65625l0 0.1875q0 0.96875 0.265625 1.828125q0.265625 0.84375 0.734375 1.46875q0.46875 0.625 1.140625 0.984375q0.6875 0.359375 1.515625 0.359375q0.84375 0 1.46875 -0.28125q0.640625 -0.296875 1.09375 -0.859375l0.078125 0.96875l1.4375 0l0 -13.0000305l-1.578125 0l0 4.75q-0.4375 -0.53125 -1.0625 -0.796875q-0.609375 -0.28125 -1.421875 -0.28125q-0.84375 0 -1.53125 0.359375q-0.671875 0.34375 -1.140625 0.9531555q-0.484375 0.625 -0.75 1.484375q-0.25 0.859375 -0.25 1.875zm1.5625 0.1875l0 -0.1875q0 -0.671875 0.140625 -1.265625q0.15625 -0.609375 0.453125 -1.078125q0.296875 -0.453125 0.765625 -0.71875q0.46875 -0.28125 1.140625 -0.28125q0.765625 0 1.28125 0.359375q0.515625 0.359375 0.8125 0.921875l0 4.25q-0.296875 0.59375 -0.8125 0.953125q-0.515625 0.359375 -1.296875 0.359375q-0.65625 0 -1.125 -0.265625q-0.46875 -0.265625 -0.765625 -0.734375q-0.296875 -0.453125 -0.453125 -1.046875q-0.140625 -0.609375 -0.140625 -1Line truncated

After

Width:  |  Height:  |  Size: 274 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

@@ -0,0 +1,269 @@
#![doc = crate::macros::doc_image!("architecture.webp")]
#![doc = crate::macros::doc_image!("big-picture.webp")]
/*!
# Architecture: wgpu, wgpu-core, and wgpu-hal
Here's an overview of `wgpu`'s architecture.
![wgpu architecture][architecture.webp]
Working through this diagram from the bottom up:
- Each operating system provides its own API (or APIs) for getting at the
GPU:
- On Windows, [Direct3D] is the primary GPU programming API, but [Vulkan]
and [OpenGL] are often also available.
- On macOS, [Metal] is the official GPU programming API, although OpenGL is
still around for legacy programs, and the [MoltenVK] open-source project
implements the Vulkan API on top of Metal.
- On Linux, the [Mesa] library supports Vulkan and OpenGL.
If you want to write an application that runs on all three of these
platforms, you have a few options:
- You could target Vulkan, and for macOS support embed MoltenVK, or
require your users to install it.
- You could target OpenGL, which is no longer being developed and is
missing many modern features, and worry that macOS will drop support for
it altogether.
- You could port it to all three native platform APIs: Direct3D, Vulkan,
and Metal. This would be a lot of code.
- Or, you could just use `wgpu`!
- The [`wgpu_hal`] crate implements a portable Rust API that can use any of
the platform-specific APIs mentioned above as a backend: a program that
uses `wgpu_hal` correctly should behave consistently regardless of what
platform you're running on.
However, `wgpu_hal`'s interface is completely unsafe; you must follow all
of its safety requirements to the letter to avoid provoking undefined
behavior from the underlying platforms. These requirements are complex,
and not well documented. And `wgpu_hal` performs almost no validation
beyond the minimum necessary to ensure portability.
- The [`wgpu_core`] crate builds on `wgpu_hal` to provide an API with a
similar flavor, preserving its portability, and adding full bullet-proof
validation. By "bullet-proof", we mean that `wgpu_core` is intended to be
driven by untrusted code, like web content using the [WebGPU] API.
`wgpu_core` only assumes that Rust's safety rules are respected. Safe Rust
code should not be able to cause a crash using `wgpu_core`.
This means that `wgpu_core` is fully responsible for things like tracking
resource lifetimes, generating barriers for usage transitions, checking
parameters, and so on. We cover its duties in more detail below.
The `wgpu_core` crate's API is designed to be easy to use from other
languages via foreign function interfaces (FFI). This restricts the Rust
features we can use in the API somewhat. But this makes `wgpu_core` the
best dependency for crates like `wgpu_native` and applications like Deno
and Firefox that have their own binding systems.
- The [`wgpu`](crate) crate provides an idiomatic Rust API on top of
`wgpu_core`, inheriting its validation and portability. This is what most
users in the Rust ecosystem will want.
You can also compile `wgpu` to WebAssembly and run it in a web browser,
having it drive the browser's [WebGPU] implementation. In this mode of use,
`wgpu_core` and `wgpu_hal` are not present. This can help you share code
between in-browser and native versions of your app, by providing a single
API for both versions to use.
[WebGPU]: https://www.w3.org/TR/webgpu/
[Direct3D]: https://learn.microsoft.com/en-us/windows/win32/direct3d
[Vulkan]: https://www.vulkan.org/
[Metal]: https://developer.apple.com/metal/
[OpenGL]: https://www.opengl.org/
[MoltenVK]: https://github.com/KhronosGroup/MoltenVK
[Mesa]: https://mesa3d.org/
[`wgpu_hal`]: https://docs.rs/wgpu-hal/latest/wgpu_hal/
[`wgpu_core`]: https://docs.rs/wgpu-core/latest/wgpu_core/
## wgpu
The `wgpu` crate provides an idiomatic Rust API for cross-platform GPU-based
graphics and computation, modeled after the [WebGPU] JavaScript API.
The `wgpu` crate itself doesn't contain much interesting graphics-related
code. It is mostly concerned with providing a consistent, idiomatic API that
applications can use to drive any one of several implementations:
- The [`wgpu::backend::wgpu_core`][w:cwc] module is available in native or
Emscripten environments. It forwards all operations to `wgpu_core`. Most
[`Backend`] values, like `Vulkan` or `Metal`, go through this module.
- The [`wgpu::backend::webgpu`][w:cwg] module, available when `wgpu` has been
compiled to WebAssembly, forwards calls to a browser's WebGPU
implementation. The [`Backend::BrowserWebGpu`] backend selects this module.
- The [`wgpu::backend::custom`][w:cc] module uses dynamic dispatch to let the
user supply their own implementation. These are created via a separate
mechanism, so they don't use any [`Backend`] value.
[w:cwc]: https://github.com/gfx-rs/wgpu/blob/trunk/wgpu/src/backend/wgpu_core.rs
[w:cwg]: https://github.com/gfx-rs/wgpu/blob/trunk/wgpu/src/backend/webgpu.rs
[w:cc]: https://github.com/gfx-rs/wgpu/blob/trunk/wgpu/src/backend/custom.rs
## wgpu_core
The `wgpu_core` crate implements a safe, cross-platform API on top of
`wgpu_hal`'s unsafe, cross-platform API. Almost every method in `wgpu_hal`'s
API is marked `unsafe`; it is `wgpu_core`'s job to satisfy or enforce every
requirement in `wgpu_hal`'s safety contracts. Then, `wgpu_hal`'s only
responsibility is to get consistent behavior across all its backends. This
relationship is explained more in
[`wgpu_hal`'s documentation][hal safety].
Beyond safety, `wgpu_core` also implements a few convenience APIs (for
example, mapped-at-creation buffers) on top of `wgpu_hal`'s more primitive
features.
[hal safety]: https://docs.rs/wgpu-hal/latest/wgpu_hal/#validation-is-the-calling-codes-responsibility-not-wgpu-hals
### Lifetime tracking
The `wgpu_hal` API requires some objects to outlive others. For example, a
[`wgpu_hal::Device`] must outlive all resources (`wgpu_hal::Buffer`,
`wgpu_hal::CommandEncoder`, etc.) created from it. The `wgpu_core` types
ensure that these requirements are upheld, mostly just by using `Arc`.
TODO: Command-buffer resource usage through submission probably counts as
"lifetime tracking" too.
This `wgpu_hal` requirement arises mostly from the Vulkan backend. Direct3D
and Metal both use reference counting internally for most operations, but
Vulkan foists the entire problem off on its users.
[`wgpu_hal::Device`]: https://docs.rs/wgpu-hal/latest/wgpu_hal/trait.Device.html
### Synchronization
Some types in the `wgpu_hal` API cannot be accessed simultaneously by
multiple threads. For example, most [`wgpu_hal::CommandEncoder`] methods take
`&mut self`. `wgpu_core` protects these hal types with `Mutex` as
appropriate.
There are a few other interesting requirements; for example, calls to
[`wgpu_hal::Queue::submit`] on a given `Queue` that could occur
simultaneously must use different `Fence`s. `wgpu_core` addresses this by
simply wrapping `wgpu_hal::Queue` in a `Mutex`.
[`wgpu_hal::CommandEncoder`]: https://docs.rs/wgpu-hal/latest/wgpu_hal/trait.CommandEncoder.html
[`wgpu_hal::Queue::submit`]: https://docs.rs/wgpu-hal/latest/wgpu_hal/trait.Queue.html#tymethod.submit
### Barrier generation
Vulkan and Direct3D require the user to include barriers in the command
stream to notify the driver when a particular buffer or texture is
transitioning from one kind of use to another. For example, if a texture is
used as a render target and then sampled by a shader, Direct3D 12 requires a
[ResourceBarrier] command between the two uses. Similarly, Vulkan requires
[VkCmdPipelineBarrier] commands in some cases to ensure that values written
to a resource by one operation will be seen by reads in a subsequent
operation.
The `wgpu_hal` API passes these backends' requirements through to its own
users, requiring calls to [`transition_buffers`] and [`transition_textures`]
between different kinds of access to such resources. But, following the lead
of [WebGPU], the `wgpu` API does not require its users to record barriers.
This means that `wgpu_core` must track how each resource was last used, and
generate the barriers itself.
Since `wgpu` encourages users to record `CommandBuffer`s in advance (ideally
in multiple threads), and then submit them in whatever order they please,
`wgpu_core` cannot know what states the resources that a `CommandBuffer` uses
will be in until it is actually submitted. Thus, each
`wgpu_core::CommandBuffer` merely records what states it expects the
resources it uses to be in initially, and which states it will leave those
resources in when it is done. Submission is then responsible for comparing
resources' actual states with those expected by each
`wgpu_core::CommandBuffer`, and recording the necessary barriers in a fresh
`wgpu_hal::CommandBuffer` submitted ahead of it.
When recording a command buffer, since the commands are only being recorded
for later execution, and not executed immediately, a `CommandEncoder` tracks
the state each resource *will be in* when the given commands are executed,
and adds barriers to the recorded stream as appropriate. Naturally, the
`CommandEncoder` must treat each resource's initial state as unknown, as it
has no way to know what other commands will be submitted ahead of it.
Note that, within a single `wgpu_hal::Texture`, individual array elements and
mip levels can be in different states. `wgpu_hal::Buffer`s, however, have only
a single state.
Within `wgpu_core`, the `Tracker` type records a set of resources, their
current states, and (for command buffers being recorded) the initial state
they should be in. `Tracker` also notes which stateless resources (samplers;
render pipelines) a `CommandBuffer` uses, in order to keep them alive until
the commands have been submitted and finished running.
[ResourceBarrier]: https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12graphicscommandlist-resourcebarrier
[VkCmdPipelineBarrier]: https://docs.vulkan.org/refpages/latest/refpages/source/vkCmdPipelineBarrier.html
[`transition_buffers`]: https://docs.rs/wgpu-hal/latest/wgpu_hal/trait.DynCommandEncoder.html#tymethod.transition_buffers
[`transition_textures`]: https://docs.rs/wgpu-hal/latest/wgpu_hal/trait.DynCommandEncoder.html#tymethod.transition_textures
### MemoryInitTracker
Tracks the memory-initialization state of buffer resources, i.e. whether
they have been written to either by the user or by `wgpu` previously
zero-initializing them (WebGPU requires all buffers to behave *as if* they
are zero-initialized). A `MemoryInitTracker` tracks a single buffer and
allows inserting zero-initialization lazily on use. Zero-init is inserted if
necessary at:
- memory mapping, and
- `queue_submit` (for all bindings).
### Device maintain
TODO (what/why).
### Cross-device use
The `wgpu_hal` API requires that a resource created with one
[`wgpu_hal::Device`] may not be used with a different `Device`. `wgpu_core`
tracks the `Device` to which each resource belongs, and checks for
cross-device use where necessary.
### General parameter validation
The `wgpu_core` crate is responsible for all the usual parameter validation
for graphics operations: a texture's format must be supported by the device;
copies must not exceed the bounds of the buffers or textures involved; bind
groups need to have the right layout for the pipeline; and so on.
## API tracing
Enabled via a feature flag. Allows recording all usage (WebGPU API functions,
essentially) to a `.ron` file. Any additional data (data uploaded to a
buffer, etc.) is stored in additional files. A trace can be replayed with the
`player` compiled from the same `wgpu` revision. Used for testing and bug
reporting. See
[Debugging wgpu Applications](crate::documentation::debugging::debugging_applications#tracing-infrastructure).
## Other WebGPU implementations
Note that `wgpu` represents only one possible way to implement the
[WebGPU][WebGPU API] API; Google's [Dawn] and
[WebKit's WebGPU module][webkit] are other WebGPU implementations used in
production.
[WebGPU API]: https://www.w3.org/TR/webgpu/
[Dawn]: https://dawn.googlesource.com/dawn
[webkit]: https://github.com/WebKit/WebKit/tree/main/Source/WebCore/Modules/WebGPU
## The wider gfx-rs ecosystem
`wgpu` is one piece of the larger gfx-rs ecosystem. For a map of all the
components and how they fit together, see the big picture:
![The gfx-rs big picture][big-picture.webp]
*/
use crate::Backend;
@@ -0,0 +1,194 @@
/*!
# Known Driver Issues
This page lists known issues with drivers that are not, or cannot, be worked
around by `wgpu`.
Issues are categorized by GPU vendor and backend. Where details such as
"driver version" are recorded, they are not intended to be exhaustive: these
are just the values where the issue has been observed. Just because your
combination is not explicitly listed does not mean you aren't susceptible to
the same issue.
## WGSL / All
- **WGSL draft spec compliance**
As outlined in the README, section
[Tracking the WebGPU and WGSL draft specifications](https://github.com/gfx-rs/wgpu#tracking-the-webgpu-and-wgsl-draft-specifications),
the version of WGSL implemented by `wgpu` will likely differ from what is
in the up-to-date spec.
## Intel / Vulkan
- **Integrated GPU not visible to programs named `cube`**
| Property | Values observed |
| ---------------- | ----------------- |
| Operating System | Windows 10 64-bit |
| Driver OEM | Intel, Microsoft |
| Driver Version | 27.20.100.8935 |
In a dual-GPU system, the driver for the Intel GPU will hide itself from
programs named `cube`. The issue can be worked around by disabling the
discrete GPU or by renaming the program to something other than `cube`.
- **Hangs when the same semaphore is signaled and waited upon**
| Property | Values observed |
| ---------------- | --------------- |
| Operating System | Linux 5.14 |
| Driver OEM | Intel |
| Driver Version | Mesa 21.2.3 |
Using a "relay" semaphore confuses the Intel driver in Mesa. Reported in
<https://gitlab.freedesktop.org/mesa/mesa/-/issues/5508>. Can be worked
around by only doing one submission per frame.
- **`cmd_begin_debug_utils_label_ext` pointer is NULL**
| Property | Values observed |
| ---------------- | ------------------- |
| Operating System | Windows 10 Pro 21H1 |
| Driver OEM | UHD Graphics 630 |
| Driver Version | 24.20.100.6287 |
The extension is supported, but the pointer to the function is NULL.
Escalated in <https://github.com/MaikKlein/ash/issues/484>. Still needs an
upstream report.
## Intel / DirectX 12
- **Offset after resizing window** —
[wgpu-rs#647](https://github.com/gfx-rs/wgpu-rs/issues/647)
| Property | Values observed |
| ---------------- | ----------------- |
| Operating System | Windows 10 64-bit |
| Driver OEM | Microsoft |
| Driver Version | 26.20.100.7639 |
This issue affects programs running on any GPU if the Intel GPU is being
used by the compositor. This would typically be the case in dual-GPU
systems. It can be worked around by replacing the Microsoft OEM driver with
the generic Intel driver.
- **`CreatePlacedResource` TDRs** —
[wgpu#1319](https://github.com/gfx-rs/wgpu/issues/1319)
| Property | Values observed |
| ---------------- | ------------------------------ |
| Operating System | Windows 10 64-bit, build 19042 |
| GPU | HD Graphics 4600 |
| Driver Version | 20.19.15.5171 |
Reported in
<https://github.com/IGCIT/Intel-GPU-Community-Issue-Tracker-IGCIT/issues/44>.
## Intel / DX11
- **Buffer write not synchronized with draw** —
[wgpu#1060](https://github.com/gfx-rs/wgpu/issues/1060)
| Property | Values observed |
| ---------------- | --------------- |
| Operating System | Windows |
Buffer upload isn't being properly synchronized with the draw call that is
using it. This is entirely on the driver to get right; there is no way to
do manual sync.
## Intel / All
- **Cannot combine MSAA with sRGB resolve** —
[wgpu#725](https://github.com/gfx-rs/wgpu/issues/725)
| Property | Values observed |
| ---------------- | --------------- |
| Operating System | Linux |
Attempting to do MSAA resolve at the same time as sRGB resolve will cause
MSAA to not work and the clear color to not be properly converted into
sRGB.
## Nvidia / Vulkan
- **Hang/panic/device loss after specific render sequence** —
[wgpu#983](https://github.com/gfx-rs/wgpu/issues/983)
| Property | Values observed |
| ---------------- | ------------------------- |
| Operating System | Windows 10 64-bit |
| GPU | GeForce RTX 2080 Ti |
| Driver Name | GeForce Game Ready Driver |
| Driver Version | 456.38, 457.09, 457.30 |
Does not occur on driver version 452.06. After submitting a frame to
`wgpu`, Vulkan seems to become unstable and this manifests itself in a few
ways.
- **`write_buffer` only works when aligned to 16** —
[wgpu#1323](https://github.com/gfx-rs/wgpu/issues/1323)
| Property | Values observed |
| ---------------- | ---------------------------- |
| Operating System | Windows 10 64-bit |
| GPU | GeForce GTX 1050, 1070 |
| Driver Version | 27.21.14.5256, 27.21.14.6589 |
We issue `vkCmdFillBuffer` for the uninitialized area of a buffer. If only
the first 40 bytes were filled, the fill buffer is called with an offset of
40, but the driver ends up erasing all the data starting with offset 32.
Issue reported directly to the NVIDIA level-2 support team, ticket
210412-000661.
- **Flat-interpolated integers come out as zeroes** —
[wgpu#1775](https://github.com/gfx-rs/wgpu/issues/1775)
| Property | Values observed |
| ---------------- | ---------------- |
| Operating System | Linux |
| GPU | GeForce GTX 1050 |
| Driver Version | 390 |
Fragment shader sees interpolated values as 0. Issue reported to NVIDIA
Vulkan support.
## WARP / D3D12
- **CPU descriptors are used after `CopyDescriptors`** —
[wgpu#1002](https://github.com/gfx-rs/wgpu/issues/1002)
| Property | Values observed |
| ---------------- | ----------------- |
| Operating System | Windows 10 64-bit |
## AMD / D3D12
- **Updating partial texture data doesn't show up** —
[wgpu#1306](https://github.com/gfx-rs/wgpu/issues/1306)
| Property | Values observed |
| ---------------- | ----------------- |
| Operating System | Windows 10 64-bit |
| GPU | Ryzen 3500U |
| Driver Name | ? |
| Driver Version | ? |
When a texture only gets partially updated, sampling from it returns
zeroes. Issue has been reported directly to AMD.
## Mesa / Vulkan
- **Integer overflow with very large buffers** —
[wgpu#2796](https://github.com/gfx-rs/wgpu/pull/2796)
| Property | Values observed |
| ---------------- | ----------------- |
| Operating System | Linux |
| Driver Name | Mesa/lavapipe |
When a buffer size or range parameter does not fit a 32-bit signed integer,
Mesa runs into integer overflows.
*/
+10
View File
@@ -0,0 +1,10 @@
/*!
Internals and Architecture
How `wgpu` is put together internally, and the driver-level issues it has to
contend with.
*/
pub mod architecture;
pub mod known_driver_issues;
pub mod reporting_driver_bugs;
@@ -0,0 +1,35 @@
/*!
# Reporting Driver Bugs
It can sometimes be hard to figure out where to report driver bugs to the
vendor. Here is a collection of known places for issues to go, and whether
reports have been successful.
Proprietary:
- NVIDIA Windows/Linux:
[forum](https://forums.developer.nvidia.com/c/gaming-and-visualization-technologies/apis/489)
(success)
- AMD (Windows — GL/VK):
[forum](https://community.amd.com/t5/opengl-vulkan/bd-p/opengl-and-vulkan-discussions)
(unknown)
- Intel (Windows):
[GitHub](https://github.com/IGCIT/Intel-GPU-Community-Issue-Tracker-IGCIT)
(unknown)
- Qualcomm:
[forum](https://developer.qualcomm.com/forums/software/adreno-gpu-sdk)
(success)
- WARP: ping `@soldieroflight` in `#dx12-developers` on the
[DX12 Discord](https://discord.gg/directx)
Open source:
- AMDVLK (Linux): [GitHub](https://github.com/GPUOpen-Drivers/AMDVLK)
- Mesa: [GitLab](https://gitlab.freedesktop.org/mesa/mesa)
- AMD (Linux) RADV
- Intel (Linux)
- Raspberry Pi
- llvmpipe
- lavapipe
- MoltenVK: [GitHub](https://github.com/KhronosGroup/MoltenVK)
*/
+19
View File
@@ -0,0 +1,19 @@
#![cfg_attr(not(doc), expect(unused_imports))]
/*!
General documentation and guides for the `wgpu` crate.
Each module here is documentation only (it contains no runtime code) and
collects concept primers, best practices, debugging tips, platform notes,
and explanations of `wgpu`'s internals that don't belong on any single API item.
*/
pub mod best_practices;
pub mod color;
pub mod debugging;
pub mod extensions;
pub mod features;
pub mod getting_started;
pub mod internals;
pub mod platforms;
pub mod shaders;
@@ -0,0 +1,24 @@
/*!
# Running on Android
## Surface creation
On Android, surface creation should happen on the resume event of the
window, and surface cleanup on the suspend event. A valid surface cannot be
created beforehand. This means that, when using `winit`, `sdl2`, or anything
similar, surface creation should happen in the resume handler, roughly like
this:
```ignore
// winit's `ApplicationHandler::resumed`:
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
let window = event_loop.create_window(Window::default_attributes()).unwrap();
let surface = instance.create_surface(window).unwrap();
// ...
}
```
Correspondingly, drop the [`Surface`] when the window is suspended.
*/
use crate::Surface;
+20
View File
@@ -0,0 +1,20 @@
/*!
# Running on ANGLE
[ANGLE](https://angleproject.org) is a translation layer from GLES to other
backends, developed by Google. We support running our GLES3 backend over it
in order to reach platforms with D3D11 support, which aren't accessible
otherwise.
In order to run with ANGLE, the `angle` feature has to be enabled, and ANGLE
libraries placed in a location visible to the application. These binaries
can be downloaded from
[gfbuild-angle](https://github.com/DileSoft/gfbuild-angle) artifacts;
[manual compilation](https://github.com/google/angle/blob/main/doc/DevSetup.md)
may be required on Macs with Apple silicon.
On Windows, you generally need to copy the libraries into the working
directory, into the same directory as the executable, or somewhere in your
`PATH`. On Linux, you can point to them using the `LD_LIBRARY_PATH`
environment variable.
*/
@@ -0,0 +1,33 @@
/*!
# Running on the Web with Emscripten
At the moment `wgpu` has one example meant to run under Emscripten:
`wgpu-hal/examples/raw-gles.rs`.
In the workspace's top directory, build the example as follows:
```bash
cargo clean
EMCC_CFLAGS="-g -s ERROR_ON_UNDEFINED_SYMBOLS=0 --no-entry -s FULL_ES3=1" \
cargo build --example raw-gles --target wasm32-unknown-emscripten --features gles,emscripten,webgl
```
Then copy the HTML page that loads the compiled example into the target
directory alongside the WebAssembly:
```bash
cp wgpu-hal/examples/raw-gles.em.html target/wasm32-unknown-emscripten/debug/examples/
```
Finally, start an HTTP server publishing the contents of that directory:
```bash
cd target/wasm32-unknown-emscripten/debug/examples/
python -m http.server
```
Then visit `localhost:8000/` in your browser.
If you get other, more interesting examples working with Emscripten, please
update this page!
*/
@@ -0,0 +1,29 @@
/*!
# Integrating wgpu into Existing iOS and Android Apps
`wgpu` does not depend on any windowing library, so it does not provide
window creation and management functions. Only when creating a window-based
[`Surface`] may an argument that implements the
[`raw-window-handle`](https://github.com/rust-windowing/raw-window-handle)
abstract interface be required. The
[`winit`](https://github.com/rust-windowing/winit) crate used by the `wgpu`
examples is a cross-platform window creation and management crate that
implements that interface; it takes over the window management and event
loop of the entire app.
There is no doubt that, for game apps, the combination of `wgpu` + `winit`
is very suitable. However, a large number of non-game apps also often need
to use graphics APIs (for charts, image filters, etc.). These apps need to
use a lot of system UI components and interactions, and `winit`'s way of
taking over the entire app window is not suitable. So, it would be very
useful to integrate `wgpu` into existing iOS and Android apps without using
third-party window-management libraries.
[wgpu-in-app](https://github.com/jinleili/wgpu-in-app) is a complete doc and
example of how to do it. The doc section also has two Chinese versions:
[与 iOS App 集成](https://jinleili.github.io/learn-wgpu-zh/integration-and-debugging/ios/)
and
[与 Android App 集成](https://jinleili.github.io/learn-wgpu-zh/integration-and-debugging/android/).
*/
use crate::Surface;
+13
View File
@@ -0,0 +1,13 @@
/*!
Platform-Specific Guides
Notes on running `wgpu` on specific platforms and targets: the web, mobile,
ANGLE, and the requirements `wgpu` places on the Vulkan backend.
*/
pub mod android;
pub mod angle;
pub mod emscripten;
pub mod mobile_app_integration;
pub mod vulkan_requirements;
pub mod web;
@@ -0,0 +1,12 @@
/*!
# Vulkan Requirements
`wgpu`'s Vulkan backend requires the following from a physical device:
- `fragmentStoresAndAtomics` must be enabled (see
<https://github.com/gpuweb/gpuweb/issues/639>).
- `independentBlending` must be enabled (see
[wgpu#2498](https://github.com/gfx-rs/wgpu/pull/2498)).
- The `maxDrawIndexedIndexValue` limit must be 32-bit.
- `VK_KHR_storage_buffer_storage_class` must be supported.
*/
+111
View File
@@ -0,0 +1,111 @@
/*!
# Running on the Web (WebGPU and WebGL)
`wgpu` can run in the browser by compiling to WebAssembly, targeting either
WebGPU (where available) or the WebGL2 backend as a fallback. The WebGL2
backend is still missing some features compared to the native and WebGPU
backends.
## Running the examples
### Installing the Rust WebAssembly target
To build the `wgpu` examples for execution in a browser, you must first
install the Rust toolchain for the `wasm32-unknown-unknown` target. Using
`rustup`:
```bash
rustup target add wasm32-unknown-unknown
```
### Using `cargo xtask run-wasm`
The simplest way to run the examples on the web is the `run-wasm` xtask:
```bash
cargo xtask run-wasm
```
This builds the `wgpu-examples` crate for `wasm32-unknown-unknown` (both the
WebGPU and WebGL2 variants), runs `wasm-bindgen` on the output, and serves
the result. It requires
[`wasm-bindgen-cli`](https://crates.io/crates/wasm-bindgen-cli) and
[`simple-http-server`](https://crates.io/crates/simple-http-server) to be
installed. Once it's running, open <http://127.0.0.1:8000> in your browser
and pick an example.
> **Note:** the server binds to `127.0.0.1` on purpose. WebGPU requires a
> [secure context](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts),
> which `127.0.0.1` satisfies but `0.0.0.0` does not.
### WebGPU browser support
WebGPU is available in current versions of Chrome and other Chromium-based
browsers, and is shipping or in progress elsewhere. For up-to-date
implementation status, check [webgpu.io](https://webgpu.io) or
[caniuse.com/webgpu](https://caniuse.com/webgpu). Note that `wgpu` is often
ahead of browsers in catching up with upstream WebGPU API changes.
## Manual compilation with `wasm-bindgen-cli`
If you'd rather not use the xtask, you can reproduce what it does by hand.
First install the version of `wasm-bindgen-cli` that matches the version
used by `wgpu` (check the workspace `Cargo.lock`):
```bash
cargo install -f wasm-bindgen-cli --version <matching version>
```
Then build the examples for `wasm32-unknown-unknown` and run `wasm-bindgen`
on the output. For WebGPU:
```bash
cargo build --target wasm32-unknown-unknown -p wgpu-examples --no-default-features --features webgpu
wasm-bindgen target/wasm32-unknown-unknown/debug/wgpu-examples.wasm \
--target web --no-typescript --out-dir target/generated --out-name webgpu
```
For WebGL2, swap the `webgpu` feature for `webgl` and the `--out-name`
accordingly:
```bash
cargo build --target wasm32-unknown-unknown -p wgpu-examples --no-default-features --features webgl
wasm-bindgen target/wasm32-unknown-unknown/debug/wgpu-examples.wasm \
--target web --no-typescript --out-dir target/generated --out-name webgl2
```
### Setting up the page
Create an `index.html` file in the `target/generated` directory that loads
the generated module:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<script type="module">
import init from "./webgpu.js"; // or "./webgl2.js"
init();
</script>
</body>
</html>
```
### Running the code
Now run a web server locally inside the `target/generated` directory to view
the example in the browser. A secure context is required for WebGPU, so
serve from `127.0.0.1` (or `localhost`), for example with
[`simple-http-server`](https://crates.io/crates/simple-http-server):
```bash
simple-http-server target/generated -c wasm,html,js -i --coep --coop --ip 127.0.0.1
```
The `--coep` and `--coop` flags set the cross-origin isolation headers some
features require.
*/
+16
View File
@@ -0,0 +1,16 @@
/*!
## Shader Support
`wgpu` can consume shaders in [WGSL](https://gpuweb.github.io/gpuweb/wgsl/), SPIR-V, and GLSL.
Both [HLSL](https://github.com/Microsoft/DirectXShaderCompiler) and [GLSL](https://github.com/KhronosGroup/glslang)
have compilers to target SPIR-V. All of these shader languages can be used with any backend as we handle all of the conversions. Additionally, support for these shader inputs is not going away.
While WebGPU does not support any shading language other than WGSL, we will automatically convert your
non-WGSL shaders if you're running on WebGPU.
WGSL is always supported by default, but GLSL and SPIR-V need features enabled to compile in support.
To enable WGSL shaders, enable the `wgsl` feature of `wgpu` (enabled by default).
To enable SPIR-V shaders, enable the `spirv` feature of `wgpu`.
To enable GLSL shaders, enable the `glsl` feature of `wgpu`.
*/
+10 -189
View File
@@ -1,8 +1,9 @@
//! `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.
//!
//! The API is based on the [WebGPU standard][webgpu], but is a fully native Rust library.
//! It serves as the core of the WebGPU integration in Firefox, Servo, and Deno.
//! The API is based on the [WebGPU standard][webgpu], but is a fully native Rust library
//! and includes many extensions specific to the native backends. It serves as the core of
//! the WebGPU integration in Firefox, Servo, and Deno.
//!
//! [webgpu]: https://gpuweb.github.io/gpuweb/
//!
@@ -15,7 +16,7 @@
//!
//! Additionally, [WebGPU Fundamentals] is a tutorial for WebGPU which is very similar to our API, minus differences between Rust and Javascript.
//!
//! We have a [wiki](https://github.com/gfx-rs/wgpu/wiki) which has information on useful architecture patterns, debugging tips, and more getting started information.
//! Most types and functions are documented, but for more general guides and explanations, see the [documentation modules][documentation].
//!
//! There are examples for this version [available on GitHub](https://github.com/gfx-rs/wgpu/tree/v30/examples#readme).
//!
@@ -24,197 +25,16 @@
//!
//! `wgpu` uses the coordinate systems of D3D and Metal. Depth ranges from [0, 1].
//!
//! | Render | Texture |
//! | --------------------- | ---------------------- |
//! | ![render_coordinates] | ![texture_coordinates] |
//! | Render | Texture |
//! | --- | --- |
//! | ![Render coordinates][render_coordinates.webp] | ![Texture coordinates][texture_coordinates.webp] |
//!
//! `wgpu`'s MSRV is **1.87**.
//!
//! [Learn Wgpu]: https://sotrh.github.io/learn-wgpu/
//! [WebGPU Fundamentals]: https://webgpufundamentals.org/
//! [render_coordinates]: https://raw.githubusercontent.com/gfx-rs/wgpu/refs/heads/v30/docs/render_coordinates.png
//! [texture_coordinates]: https://raw.githubusercontent.com/gfx-rs/wgpu/refs/heads/v30/docs/texture_coordinates.png
//!
//! ## Extension Specifications
//!
//! While the core of `wgpu` is based on the WebGPU standard, we also support extensions that allow for features that the standard does not have yet.
//! For high-level documentation on how to use these extensions, see documentation on [`Features`] or the relevant specification:
//!
//! 🧪EXPERIMENTAL🧪 APIs are subject to change and may allow undefined behavior if used incorrectly.
//!
//! - 🧪EXPERIMENTAL🧪 [Ray Tracing](https://github.com/gfx-rs/wgpu/blob/v30/docs/api-specs/ray_tracing.md).
//! - 🧪EXPERIMENTAL🧪 [Mesh Shading](https://github.com/gfx-rs/wgpu/blob/v30/docs/api-specs/mesh_shading.md).
//!
//! ## Shader Support
//!
//! `wgpu` can consume shaders in [WGSL](https://gpuweb.github.io/gpuweb/wgsl/), SPIR-V, and GLSL.
//! Both [HLSL](https://github.com/Microsoft/DirectXShaderCompiler) and [GLSL](https://github.com/KhronosGroup/glslang)
//! have compilers to target SPIR-V. All of these shader languages can be used with any backend as we handle all of the conversions. Additionally, support for these shader inputs is not going away.
//!
//! While WebGPU does not support any shading language other than WGSL, we will automatically convert your
//! non-WGSL shaders if you're running on WebGPU.
//!
//! WGSL is always supported by default, but GLSL and SPIR-V need features enabled to compile in support.
//!
//! To enable WGSL shaders, enable the `wgsl` feature of `wgpu` (enabled by default).
//! To enable SPIR-V shaders, enable the `spirv` feature of `wgpu`.
//! To enable GLSL shaders, enable the `glsl` feature of `wgpu`.
//!
//! ## Feature flags
#![doc = document_features::document_features!()]
//!
//! ### Feature Aliases
//!
//! These features aren't actually features on the crate itself, but a convenient shorthand for
//! complicated cases.
//!
//! - **`wgpu_core`** --- Enabled when there is any non-webgpu backend enabled on the platform.
//! - **`naga`** --- Enabled when target `glsl` or `spirv` input is enabled, or when `wgpu_core` is enabled.
//!
//! ## Surface color spaces and HDR output
//!
//! A surface can present in different color spaces to get HDR or wide-gamut
//! output onto the screen. This is configured through
//! [`SurfaceConfiguration::color_space`], and the rest of this section is a
//! concept primer on how it works.
//!
//! ### HDR output in a nutshell
//!
//! By default a surface is standard dynamic range (SDR) with the sRGB gamut: the
//! value `1.0` is the brightest white, anything above it clips, and only colors
//! within sRGB are expressible. Other [`SurfaceColorSpace`]s opt into a **wider
//! gamut** (for example [`DisplayP3`](SurfaceColorSpace::DisplayP3), still SDR
//! but with more saturated colors than sRGB), **high dynamic range** (values
//! above `1.0` drive brighter-than-white output), or both (for example
//! [`Bt2100Pq`](SurfaceColorSpace::Bt2100Pq), aka HDR10), on platforms that
//! support it.
//!
//! Three ideas carry most of the weight:
//!
//! * **Reference white and headroom.** Brightness is measured in *nits*
//! (cd/m²). On HDR-capable monitors, SDR reference white (plain white, `(1.0, 1.0, 1.0)` in the
//! extended color spaces) sits *below* the display's peak output on purpose, so
//! highlights have room above it. That gap is the display's *headroom*.
//! * **The transfer function is a round-trip.** Your shader applies an
//! encoding transfer function (the OETF) to turn the light it computed into a
//! stored signal, and the display applies the inverse decoding transfer
//! function (the EOTF) to turn it back into light. Choosing a color space
//! chooses which transfer functions both ends use.
//! * **Who applies the encoding transfer function.** wgpu applies it for you
//! **only** when you render to an `*Srgb` texture view format, where the GPU
//! runs the sRGB OETF when a value is stored to a texture. For every other
//! color space (linear extended sRGB, encoded extended sRGB or P3, PQ, HLG)
//! **the values your shader writes to the surface texture must already be
//! encoded by you**, along with any gamut conversion; in a typical renderer
//! this happens in a final tone-mapping or post-processing pass. wgpu hands
//! the signal to the compositor unchanged; getting this wrong produces a
//! wrong image with no error.
//!
//! wgpu does **not** tonemap or gamut-map for you. It gives you the surface
//! and, through [`DisplayHdrInfo`], the display's advisory capabilities;
//! *choosing* and *applying* a tone curve is your application's job.
//!
//! ### The practical path
//!
//! 1. **Query capabilities.** Call `Surface::get_capabilities`. To use HDR or
//! wide-gamut output, read [`SurfaceCapabilities::format_capabilities`] (each
//! format and the [`SurfaceColorSpaces`] it supports), **not**
//! [`SurfaceCapabilities::formats`]: the latter lists only formats usable
//! with [`Auto`](SurfaceColorSpace::Auto), which never selects HDR.
//! [`SurfaceCapabilities::color_spaces`] is a convenience lookup for one
//! format.
//! 2. **Optionally query the display.** Call `Surface::display_hdr_info` for the
//! current [`DisplayHdrInfo`] (peak and SDR-white nits, EDR headroom,
//! primaries, and a coarse dynamic-range/gamut bucket). Use it to pick a
//! tone-map target ([`DisplayHdrInfo::tone_map_headroom`]); *whether* HDR is
//! worthwhile is the capability question from step 1, not this live value.
//! Every field is advisory and optional; `None` means "cannot tell here",
//! never "SDR".
//! 3. **Choose a format and color space.** Intersect what you want with what
//! step 1 advertises, in your own preference order (for example HDR10, then
//! linear extended sRGB, then encoded extended sRGB, then SDR
//! [`Srgb`](SurfaceColorSpace::Srgb)). Keep an SDR fallback for when nothing
//! HDR is advertised, such as when OS HDR is off.
//! 4. **Configure the surface.** Set [`SurfaceConfiguration::color_space`] and
//! `format`. [`Auto`](SurfaceColorSpace::Auto) (the default) reproduces
//! wgpu's historical behavior and never picks HDR; any other value must be in
//! that format's advertised set or configuration fails validation.
//! 5. **Encode what you write to the surface texture.** For an `*Srgb` format,
//! output linear and the hardware encodes for you. Otherwise the values your
//! shader writes to the surface texture must already carry the encoding the
//! chosen color space expects (sRGB, extended sRGB, PQ, or HLG) **and** any
//! gamut conversion (for example outputting in the BT.2020 gamut for HDR10);
//! in a typical renderer you do this in a final tone-mapping or
//! post-processing pass. See the table below.
//! 6. **Present** as usual. If OS HDR is toggled mid-run, you'll see it on the
//! next `Surface::display_hdr_info` poll; re-query `Surface::get_capabilities`
//! and re-run the steps above.
//!
//! The standalone [HDR surface example] implements every step, including the
//! encoding transfer function for each color space.
//!
//! ### What to output from your fragment shader
//!
//! What the values your shader writes to the surface texture must contain for
//! each color space, and whether wgpu applies the transfer function for you:
//!
//! | Color space | Typical format | You write | wgpu encodes? |
//! | ----------- | -------------- | --------- | ------------- |
//! | `Srgb`, `*Srgb` format | `{Rgba,Bgra}8UnormSrgb` | linear | **yes** (hardware sRGB OETF on store) |
//! | `Srgb`, non-srgb format | `{Rgba,Bgra}8Unorm` | sRGB-encoded | no; apply the sRGB OETF yourself or use `*Srgb` instead |
//! | `ExtendedSrgbLinear` (scRGB) | `Rgba16Float` | linear, `1.0` = SDR white | no, but no encoding is necessary |
//! | `ExtendedSrgb` | `Rgba16Float` | extended sRGB-encoded | no; apply the extended sRGB OETF yourself |
//! | `DisplayP3` | `Bgra8Unorm` | sRGB-encoded, P3 primaries | no; apply the sRGB OETF (after gamut-mapping to P3) |
//! | `ExtendedDisplayP3` | `Rgba16Float` | extended sRGB-encoded, P3 primaries | no; apply the extended sRGB OETF (after gamut-mapping to P3) |
//! | `Bt2100Pq` (HDR10) | `Rgb10a2Unorm` | PQ-encoded, BT.2020 primaries | no; apply the PQ OETF (after gamut-mapping to BT.2020) |
//! | `Bt2100Hlg` | `Rgb10a2Unorm` | HLG-encoded, BT.2020 primaries | no; apply the HLG OETF (after gamut-mapping to BT.2020) |
//!
//! In short, wgpu applies the transfer function for you only when you render to
//! an `*Srgb` format. In every other case the values your shader writes to the
//! surface texture must already carry both the transfer function and any gamut
//! conversion. The [HDR surface example] implements every encoder in WGSL.
//!
//! ### Glossary
//!
//! * **Chromaticity** --- a color's hue and saturation independent of its
//! brightness, given as an `(x, y)` coordinate on the CIE 1931 diagram.
//! * **Primaries / gamut** --- the chromaticities of the red, green, and blue a
//! color space addresses, and so the range of colors it can express. [BT.709]
//! is the sRGB gamut, [Display P3] is wider, and [BT.2020] is wider still.
//! * **White point** --- the chromaticity of `R = G = B` (what "white" looks
//! like). Every color space here uses [D65], standard daylight.
//! * **Transfer function (OETF / EOTF)** --- how stored values map to light. The
//! *OETF* is the encoding transfer function your application applies; the
//! *EOTF* is the inverse decoding transfer function the display applies.
//! * **SDR / HDR** --- standard dynamic range clips at `1.0` (reference white);
//! high dynamic range lets values above `1.0` drive brighter-than-white
//! output.
//! * **Nits and reference white** --- a *nit* (cd/m²) is a unit of brightness;
//! *reference white* (also called *paper white*, especially on Windows) is the
//! brightness of SDR plain white, set below the panel's peak so highlights have
//! room above it.
//! * **Headroom (EDR)** --- how much brighter than current SDR white the display
//! can go right now, as a multiplier (`1.0` means none). Dynamic; see
//! [`DisplayHdrInfo::tone_map_headroom`].
//! * **PQ / HLG** --- the two HDR transfer functions: [PQ] (SMPTE ST 2084,
//! HDR10) encodes absolute luminance, [HLG] (BT.2100) encodes relative
//! luminance.
//! * **scRGB / extended-range sRGB** --- sRGB extended past 0.0..=1.0 for
//! HDR: [scRGB] is *linear*
//! ([`ExtendedSrgbLinear`](SurfaceColorSpace::ExtendedSrgbLinear)), while
//! [`ExtendedSrgb`](SurfaceColorSpace::ExtendedSrgb) is the same range but
//! sRGB-*encoded* (gamma), the web's HDR path.
//!
//! [HDR surface example]: https://github.com/gfx-rs/wgpu/tree/v30/examples/standalone/03_hdr_surface
//! [BT.709]: https://www.itu.int/rec/R-REC-BT.709
//! [BT.2020]: https://www.itu.int/rec/R-REC-BT.2020
//! [Display P3]: https://en.wikipedia.org/wiki/DCI-P3#Display_P3
//! [D65]: https://en.wikipedia.org/wiki/Standard_illuminant#D65_values
//! [PQ]: https://en.wikipedia.org/wiki/Perceptual_quantizer
//! [HLG]: https://www.itu.int/rec/R-REC-BT.2100
//! [scRGB]: https://en.wikipedia.org/wiki/ScRGB
//!
#![doc = crate::macros::doc_image!("render_coordinates.webp")]
#![doc = crate::macros::doc_image!("texture_coordinates.webp")]
#![no_std]
// `-Znext-solver` requires deeper recursion limits (at least for now) to prove Send/Sync
#![recursion_limit = "256"]
@@ -259,6 +79,7 @@ mod api;
mod backend;
mod cmp;
mod dispatch;
pub mod documentation;
mod macros;
pub mod util;
+44
View File
@@ -255,6 +255,50 @@ macro_rules! hal_type_gles {
}
pub(crate) use hal_type_gles;
// Reference an image from the crate's `src/documentation/images/` directory. Put
// the expansion in a `#[doc]` attribute and reference the image by file name
// elsewhere in the same docs:
//
// #![doc = crate::macros::doc_image!("foo.png")]
// //! ![alt text][foo.png]
//
// Local builds resolve the image from the on-disk `src/documentation/images/`
// directory (which, because it lives inside the crate, is also present when a
// downstream user builds `wgpu`'s docs as a dependency); `docsrs` builds resolve
// it from the repository over HTTP, pinned to the commit being built. Both base
// URLs are set in `build.rs`. The expansion must be a single line, as it is used
// in a `#[doc]` attribute.
//
// Place these attributes *before* the module's doc comment, as shown above.
// rustdoc strips trailing blank lines from each doc fragment and joins the
// fragments with a single newline, so a definition placed after a doc comment
// that ends in a paragraph is swallowed by that paragraph as a lazy
// continuation, and every image reference in the module silently fails to
// resolve.
/// Expands to a Markdown reference-style link definition for a `src/documentation/images/` image.
#[cfg(docsrs)]
macro_rules! doc_image {
($name:literal) => {
concat!(
"[",
$name,
"]: https://raw.githubusercontent.com/gfx-rs/wgpu/",
env!("WGPU_DOCS_COMMIT"),
"/wgpu/src/documentation/images/",
$name
)
};
}
/// Expands to a Markdown reference-style link definition for a `src/documentation/images/` image.
#[cfg(not(docsrs))]
macro_rules! doc_image {
($name:literal) => {
concat!("[", $name, "]: ", env!("WGPU_DOCS_URL_BASE"), "/", $name)
};
}
pub(crate) use doc_image;
#[doc(hidden)]
pub mod helpers {
pub use alloc::{borrow::Cow, string::String};