owned this note
owned this note
Published
Linked with GitHub
# Changelog for WebGPU in Chromium / Dawn 94
Chromium's WebGPU implementation and Dawn's API try to closely follow changes to the WebGPU specification. When the WebGPU IDL changes, Chromium and Dawn will try to support both the deprecated and the new version of the IDL at the same time so prototypes can be updated. In JavaScript, uses of the deprecated path will result in a console warning, while when using Dawn directly, the deprecated path will print a warning to stderr.
Note that all changes to Dawn's API make it closer to [`webgpu.h`](https://github.com/webgpu-native/webgpu-headers/blob/master/webgpu.h) that we hope will allow applications to target both [Dawn](https://dawn.googlesource.com/dawn), and [wgpu](https://github.com/gfx-rs/wgpu/) in native before being compiled in WASM. Emscripten will also be updated from the "old" to the "new" API but won't have the smooth transition since developers control which version of emscripten they use.
Items deprecated in this changelog will be removed in the next branched version of Chromium. They will also be removed in Chromium Canary and top of tree Dawn two weeks after this changelog is published in Canary and top of tree Dawn (so starting 2021-09-03).
Previous PSAs / changelogs:
- [PSA for Chromium / Dawn WebGPU API updates 2021-04-07](https://hackmd.io/BtRPZXulQICjbcZi4tLCdg)
- [PSA for Chromium / Dawn WebGPU API updates 2020-10-19](https://hackmd.io/uH1MI9cnQBG9GGOZG20COw)
- [PSA for Chromium / Dawn WebGPU API updates 2020-07-28](https://hackmd.io/szV68rOVQ56GYzPJMBko8A)
- [PSA for Chromium / Dawn WebGPU API updates 2020-04-28](https://hackmd.io/Et7xlhoaThmi8dEX_s-xSw)
## New deprecations
### `GPUComputePipelineDescriptor.computeStage` → `.compute`
WebGPU [PR](https://github.com/gpuweb/gpuweb/pull/1352)
The `computeStage` value in `ComputePipelineDescriptor` was renamed to `compute` for simplicity and consistency with the other programmable stages (`vertex` and `fragment`).
An example of the change needed in JavaScript:
```diff=
device.createComputePipeline({
- computeStage: {
+ compute: {
module: device.createShaderModule({ code: computeSrc }),
entryPoint: 'main',
}
});
```
Likewise when using Dawn’s API, changes are needed:
```diff=
wgpu::ComputePipelineDescriptor pipelineDescriptor;
-pipelineDescriptor.computeStage.module = module;
-pipelineDescriptor.computeStage.entryPoint = "main";
+pipelineDescriptor.compute.module = module;
+pipelineDescriptor.compute.entryPoint = "main";
wgpu::ComputePipeline pipeline = device.CreateComputePipeline(&pipelineDescriptor);
```
### Attachment descriptor `.attachment` → `.view`
WebGPU [PR](https://github.com/gpuweb/gpuweb/pull/1352)
The `attachment` value in `RenderPassColorAttachment` and `RenderPassDepthStencilAttachment` was renamed to `view` to emphasize the fact that it requires a `TextureView` rather than a `Texture`.
An example of the change needed in JavaScript:
```diff=
commandEncoder.beginRenderPass({
colorAttachments: [{
- attachment: colorTarget.createView(),
+ view: colorTarget.createView(),
loadValue: { r: 0.0, g: 0.0, b: 0.0, a: 1.0 },
storeOp: 'discard'
}]
});
```
Likewise when using Dawn’s API, changes are needed:
```diff=
wgpu::RenderPassColorAttachment colorAttachment;
-colorAttachment.attachment = colorView;
+colorAttachment.view = colorView;
colorAttachment.loadOp = wgpu::LoadOp::Load;
colorAttachment.storeOp = wgpu::StoreOp::Store;
```
### `BlendFactor` and `setBlendColor` changes
WebGPU [PR1](https://github.com/gpuweb/gpuweb/pull/1614) [PR2](https://github.com/gpuweb/gpuweb/pull/1627) [PR3](https://github.com/gpuweb/gpuweb/pull/1633)
The use of "color" and "blend-color" in the blend related names was confusing. Instead "blend-color" becomes the blend "constant" and "color" is removed to make names simpler. See the table below for the correspondance in JavaScript and Dawn.
| Old Javascript | New JavaScript | Old Dawn | New Dawn |
|-|-|-|-|
|`"src-color"` | `"src"` | `SrcColor` | `Src` |
|`"one-minus-src-color"` | `"one-minus-src"` | `OneMinusSrcColor` | `OneMinusSrc` |
|`"dst-color"` | `"dst"` | `DstColor` | `Dst` |
|`"one-minus-dst-color"` | `"one-minus-dst"` | `OneMinusDstColor` | `OneMinusDst` |
|`"blend-color"` | `"constant"` | `BlendColor` | `Constant` |
|`"one-minus-blend-color"` | `"one-minus-constant"` | `OneMinusBlendColor` | `OneMinusConstant` |
Likewise `setBlendColor` was renamed to `setBlendConstant`.
An example of the change needed in JavaScript:
```diff=
-pass.setBlendColor(1.0, 0.0, 0.0, 1.0);
+pass.setBlendConstant(1.0, 0.0, 0.0, 1.0);
```
Likewise when using Dawn’s API, changes are needed:
```diff=
-pass.SetBlendColor(1.0, 0.0, 0.0, 1.0);
+pass.SetBlendConstant(1.0, 0.0, 0.0, 1.0);
```
### CopyImageBitmapToTexture → CopyExternalTextureToTexture (Web only)
WebGPU [PR](https://github.com/gpuweb/gpuweb/pull/1581) (and [related changes](https://github.com/gpuweb/gpuweb/pulls?q=copyExternalImageToTexture))
`copyImageBitmapToTexture` has been generalized to `copyExternalImageToTexture`, which also accepts `HTMLCanvasElement` and `OffscreenCanvas` inputs.
An example of the change needed in JavaScript:
```diff=
-device.queue.copyImageBitmapToTexture(
- { imageBitmap: imageBitmap },
+device.queue.copyExternalImageToTexture(
+ { source: imageBitmap },
{ texture: destinationTexture },
[imageBitmap.width, imageBitmap.height]
);
```
This change does not affect Dawn’s API.
### `GPUStoreOp` `"clear"` → `"discard"`
WebGPU [PR](https://github.com/gpuweb/gpuweb/pull/1815)
To clarify the expected storeOp cost, the `GPUStoreOp` mode discarding the data from an attachment at the end of a render pass was renamed to `"discard"`. It still results in a lazy clear if needed, but when correctly used allows optimizing render passes.
An example of the change needed in JavaScript:
```diff=
commandEncoder.beginRenderPass({
colorAttachments: [{
view: colorTarget.createView(),
loadValue: { r: 0.0, g: 0.0, b: 0.0, a: 1.0 },
- storeOp: 'clear'
+ storeOp: 'discard'
}]
});
```
Likewise when using Dawn’s API, changes are needed:
```diff=
wgpu::RenderPassDepthStencilAttachment dsAttachment;
dsAttachment.view = depthView;
dsAttachment.depthLoadOp = wgpu::LoadOp::Load;
-dsAttachment.depthStoreOp = wgpu::StoreOp::Clear;
+dsAttachment.depthStoreOp = wgpu::StoreOp::Discard;
```
### `"gpupresent"` → `"webgpu"`
WebGPU [PR](https://github.com/gpuweb/gpuweb/pull/1930)
After consulting with members of the WHATWG, it was determined that the context type of `'webgpu'` would be more consistent with the other existing canvas context types.
An example of the change needed in JavaScript:
```diff=
-const context = canvas.getContext('gpupresent');
+const context = canvas.getContext('webgpu');
```
This change does not affect Dawn’s API.
### SwapChains merged into the CanvasContext (Web only)
WebGPU [PR](https://github.com/gpuweb/gpuweb/pull/1810)
Previously a `GPUSwapChain` object was created from the `GPUCanvasContext` in order to get the current texture for each frame. To simplify the API surface, the functionality of `GPUSwapChain` has been merged into `GPUCanvasContext`, with method names being adjusted accordingly.
An example of the change needed in JavaScript:
```diff=
const context = canvas.getContext('webgpu');
-const colorFormat = context.getSwapChainPreferredFormat(adapter);
+const colorFormat = context.getPreferredFormat(adapter);
const configuration = {
device: device,
format: colorFormat,
};
-const swapChain = context.configureSwapChain(configuration);
+context.configure(configuration);
// In your rAF loop:
-const colorTexture = swapChain.getCurrentTexture();
+const colorTexture = context.getCurrentTexture();
```
This change does not affect Dawn’s API.
### Changes to how CanvasContext handles resizing (Web only)
WebGPU [PR](https://github.com/gpuweb/gpuweb/pull/1738)
In addition to the above change, `GPUCanvasContext`s have also changed how they handle resizing in order to offer more predictability to developers.
Previously when the `width` or `height` was changed on a `HTMLCanvasElement` with a `GPUCanvasContext` the width and height of the textures returned by `getCurrentTexture()` would be resized to match. The timing of when that change took effect and what would happen to previously fetched textures was ambiguous, however. As a result the `GPUCanvasContext` was changed to only resize the textures it returns on calls to `configure()`.
An explicit `size` can be passed to `configure()`, or, if no `size` is given, the `width` and `height` attributes of the `HTMLCanvasElement` **at the time the `configure()` call was made** will be used.
An example of the how to handle the canvas resizing in JavaScript:
```js=
const context = canvas.getContext('webgpu');
const colorFormat = context.getPreferredFormat(adapter);
window.addEventListener('resize', () => {
context.configure({
device: device,
format: colorFormat,
size: {
width: canvas.clientWidth * window.devicePixelRatio,
height: canvas.clientHeight * window.devicePixelRatio,
}
});
});
```
(For more precise sizing, [use the ResizeObserver API](https://webglfundamentals.org/webgl/lessons/webgl-resizing-the-canvas.html).)
This change does not affect Dawn’s API.
### Read-only storage textures will be removed
WebGPU [PR](https://github.com/gpuweb/gpuweb/pull/1794)
Read-only storage textures had severe limitations and had barely any advantage compared to regular sampled textures. A future optional feature will introduce read-write storage textures and will impact the design or read-only storage textures (or make them obselete). For these reasons read-only have been completely removed and code must be updated to use "sampled" (non-storage) textures instead. There is no simple diff to apply to make this change unfortunately.
### `GPUDeviceDescriptor.nonGuaranteedFeatures`+`Limits` → `.required*`
WebGPU [PR](https://github.com/gpuweb/gpuweb/pull/1804)
To clarify the meaning of these arguments to `requestDevice()`, `nonGuaranteedFeatures` and `nonGuaranteedLimits` have been renamed to `requiredFeatures` and `requiredLimits`.
This only affects the JavaScript API and the following changes are needed:
```diff=
const device = await adapter.requestDevice({
- nonGuaranteedFeatures: [
+ requiredFeatures: [
'texture-compression-bc',
],
- nonGuaranteedLimits: {
+ requiredLimits: {
maxStorageBufferBindingSize: 256 * 1024 * 1024,
}
});
```
### Texture usage flags
WebGPU [PR](https://github.com/gpuweb/gpuweb/pull/1989)
The `GPUTextureUsage.SAMPLED` flag was confusing because it didn't necessarily mean the texture could be used with `textureSample` in WGSL (for example for integer textures). For that reason the `SAMPLED` and `STORAGE` texture usage flags have been renamed to `TEXTURE_BINDING` and `STORAGE_BINDING`.
An example of the change needed in JavaScript:
```diff=
const sampledTexture = device.createTexture({
format: 'rgba8unorm',
size: [16, 16],
- usage: GPUTextureUsage.SAMPLED,
+ usage: GPUTextureUsage.TEXTURE_BINDING,
});
const storageTexture = device.createTexture({
format: 'rgba8unorm',
size: [16, 16],
- usage: GPUTextureUsage.STORAGE,
+ usage: GPUTextureUsage.STORAGE_BINDING,
});
```
Likewise when using Dawn’s API, changes are needed:
```diff=
wgpu::TextureDescriptor sampledDesc;
sampledDesc.format = wgpu::TextureFormat::RGBA8Unorm;
sampledDesc.size = {16, 16};
-sampledDesc.usage = wgpu::TextureUsage::Sampled;
+sampledDesc.usage = wgpu::TextureUsage::TextureBinding;
wgpu::Texture sampledTexture = device.CreateTexture(&sampledDesc);
wgpu::TextureDescriptor storageDesc;
storageDesc.format = wgpu::TextureFormat::RGBA8Unorm;
storageDesc.size = {16, 16};
-storageDesc.usage = wgpu::TextureUsage::Storage;
+storageDesc.usage = wgpu::TextureUsage::StorageBinding;
wgpu::Texture storageTexture = device.CreateTexture(&storageDesc);
```
### `wgpu::InputStepMode` → `VertexStepMode`
WebGPU [PR](https://github.com/gpuweb/gpuweb/pull/1927)
`GPUInputStepMode` was renamed to `GPUVertexStepMode` because it wasn't very clear what "input" was a reference to in that name.
When using Dawn's API the following changes are needed:
```diff=
wgpu::VertexBufferLayout buffer;
buffer.arrayStride = 16;
-buffer.stepMode = wgpu::InputStepMode::Instance;
+buffer.stepMode = wgpu::VertexStepMode::Instance;
buffer.attributeCount = 2;
buffer.attributes = &attributes;
```
No new changes are necessary in JavaScript.
### Attachment descriptor type rename
The types for the sub-descriptor of `GPURenderPassDescriptor` were renamed to not include `Descriptor` since they directly describe one attachment.
When using Dawn's API the following changes are needed:
```diff=
-wgpu::RenderPassColorAttachmentDescriptor colorAttachment;
+wgpu::RenderPassColorAttachment colorAttachment;
colorAttachment.view = colorView;
colorAttachment.loadOp = wgpu::LoadOp::Load;
colorAttachment.storeOp = wgpu::StoreOp::Store;
-wgpu::RenderPassDepthStencilAttachmentDescriptor dsAttachment;
+wgpu::RenderPassDepthStencilAttachment dsAttachment;
dsAttachment.view = depthView;
dsAttachment.depthLoadOp = wgpu::LoadOp::Load;
dsAttachment.depthStoreOp = wgpu::StoreOp::Store;
wgpu::RenderPassDescriptor rpDesc;
rpDesc.colorAttachmentCount = 1;
rpDesc.colorAttachments = &colorAttachment;
rpDesc.depthStencilAttachment = &dsAttachment;
wgpu::RenderPassEncoder pass = encoder.BeginRenderPass(&rpDesc);
```
No new changes are necessary in JavaScript.
### `RenderPipeline2` → `RenderPipeline`
[Dawn tracking bug](https://bugs.chromium.org/p/dawn/issues/detail?id=642)
This is the last step of the big change to the `RenderPipelineDescriptor`. Now that the previous pipeline descriptor structure has been removed, the new pipeline descriptor can be renamed from `RenderPipelineDescriptor2` to `RenderPipelineDescriptor` and likewise `CreateRenderPipeline2` to `CreateRenderPipeline`.
When using Dawn's API the following changes are needed:
```diff=
-wgpu::RenderPipelineDescriptor2 desc;
+wgpu::RenderPipelineDescriptor desc;
//...
-wgpu::RenderPipeline pipeline = device.CreateRenderPipeline2(&desc);
+wgpu::RenderPipeline pipeline = device.CreateRenderPipeline(&desc);
```
No new changes are necessary in JavaScript.
## New features and improvements
### Security hardening
In preparation for letting WebGPU be used in the wild without flags (as part of the Origin Trial), the implementation was made robust in a lot of ways. Here's a non-exhaustive list of improvements:
- The SPIRV-Cross shader translator was completely replaced with [Tint](https://dawn.googlesource.com/tint) a new shader translator made specifically for WebGPU and developped to be robust from day one.
- Code transformations were implemented in Tint to zero-initialize all shader variables, including efficient zero-initialization of workgroup variables.
- Access to out-of-bounds vertex data was made robust through a combination of hardware runtime checks, CPU side validation and emulation of the vertex fetching when needed.
- All the validation checks for WebGPU were implemented.
### 3D textures
3D textures are now available! They can be used for sampling, storage texture, copying from/to texture and buffers but not for rendering. They take advantage of `GPUExtent3D.depthOrArrayLayers` that will be used as the "depth" when the texture dimension is `"3d"`, while it is used as the number of layers when the texture dimension is `"2d"`.
For example, creating a 3D texture in JavaScript is done like the following:
```js=
const texture = device.createTexture({
dimension: "3d",
format: "r32float",
usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.TEXTURE_BINDING,
size: [16, 16, 16],
});
```
Likewise when using Dawn's API:
```cpp=
wgpu::TextureDesriptor desc;
desc.dimension = wgpu::TextureDimension::e3D;
desc.format = wgpu::TextureFormat::R32Float;
desc.usage = wgpu::TextureUsage::CopyDst | wgpu::TextureUsage::TextureBinding;
desc.size = {16, 16, 16};
wgpu::Texture texture = device.CreateTexture(&desc);
```
### `GPUCompilationInfo`
It is now possible to get messages from the compiler after creating a shader module. These messages contain spans of the shader source they apply to, helping create online editors that surface errors and warnings. Because the shader compiler is running asynchronously, `GPUShaderModule.compilationInfo()` returns a `Promise` that will resolve asynchronously.
Using compilation info in JavaScript is done like the following:
```js=
const module = device.createShaderModule({ code : sourceCode });
const compilationInfo = await module.compilationInfo();
for (const message of compilationInfo.messages) {
// Handle compilation message:
// - message.type describes if it is "error", "warning" or "info"
// - message.message is the content of the message
// - message.(lineNum, linePos, offset, length) give an indication
// of which range of the `sourceCode` the message applies to.
}
```
Similarly compilation messages can be queried asynchronously when using Dawn's API:
```cpp=
wgpu::ShaderModule module = device.CreateShaderModule(...);
auto OnCompilationInfo = [] (WGPUCompilationInfoRequestStatus status,
const WGPUCompilationInfo* info,
void* userdata) {
for (int i = 0; i < info->messageCount) {
// Do something with info->messages[i];
}
};
module.GetCompilationInfo(OnCompilationInfo, nullptr);
```
### Occlusion queries
Boolean occlusion queries can now be used to check whether any fragment shader was run during the query. Unlike WebGL, the `GPUQuerySet` that will receive the results must be passed during the creation of the render pass.
Using occlusion queries in JavaScript is done like below (the Dawn equivalent is left as an exercise):
```js=
// Create the querySet
const querySet = device.createQuerySet({
count: numObjects,
type: "occlusion",
});
// Record for each object whether any fragment shader was run
const passEncoder = encoder.beginRenderPass({
occlusionQuerySet: querySet,
// ...
});
for (var i = 0; i < numObjects; i++) {
passEncoder.beginOcclusionQuery(i);
// `drawObject()` is a helper function that draw the i-th object
drawObject(passEncoder, i);
passEncoder.endOcclusionQuery();
}
passEncoder.endPass();
// Now resolve the queries in a buffer as usual.
```
### Offscreen Canvas (Web only)
`OffscreenCanvas` is now fully supported with WebGPU, created from either [`new OffscreenCanvas()`](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas/OffscreenCanvas) or [`HTMLCanvasElement.transferControlToOffscreen()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/transferControlToOffscreen). This allows running WebGPU in a Web Worker while still presenting rendering results on the page.
Note that, currently, WebGPU devices can still only be used from one "thread" (similar to WebGL).
### `GPUExternalTexture` (Web only)
[`GPUExternalTexture`](https://gpuweb.github.io/gpuweb/#gpu-external-texture) is an object that wraps a frame of an external video object such as `HTMLVideoElement` and provides optimized access to it. The internals are a bit involved since video frames are often stored with YUV formats instead of RGBA formats. That's why the `GPUExternalTexture` is considered an opaque texture object that can only be used with special WGSL builtins.
Using `GPUExternalTexture` in a page in Javascript is done like the following:
```js=
const shaderUsingExternalTexture = device.createShaderModule({
code: `
[[group(0), binding(0)]] var video : texture_external;
[[group(0), binding(1)]] var s : sampler;
fn sampleVideo(texcoords : vec2<f32>) -> vec4<f32> {
return textureSampleLevel(video, s, texcoords);
}
`
});
const bgl = device.createBindGroupLayout({
entries: [{
binding: 0,
visibility: GPUShaderStage.FRAGMENT,
externalTexture: {},
}, {
binding: 1,
visibility: GPUShaderStage.FRAGMENT,
sampler: {},
}]
});
// Create a `pipeline` using `shaderUsingExternalTexture` and `bgl`.
function frame() {
const texture = device.importExternalTexture({
source : document.querySelector("video")
});
const bindGroup = device.createBindGroup({
entries: [{
binding: 0,
resource: texture,
}, {
binding: 1,
resource: device.createSampler(),
}],
});
// Draw with the video using `bindGroup` and `pipeline`
}
```
Please note that the implementation of `GPUExternalTexture` is still being optimized and expected to improve significantly in the future. This aspect of the specification is also less mature and more subject to changes, for example around the lifetime of the result of `importExternalTexture()`.