1. Introduction
This section is non-normative.
Graphics Processing Units , or GPUs for short, have been essential in enabling rich rendering and computational applications in personal computing. WebGPU is an API that exposes the capabilities of GPU hardware for the Web. The API is designed from the ground up to efficiently map to the Vulkan , Direct3D 12 , and Metal native GPU APIs. WebGPU is not related to WebGL and does not explicitly target OpenGL ES.
WebGPU
sees
physical
GPU
hardware
as
GPUAdapter
s.
It
provides
a
connection
to
an
adapter
via
GPUDevice
,
which
manages
resources,
and
the
device’s
GPUQueue
s,
which
execute
commands.
GPUDevice
may
have
its
own
memory
with
high-speed
access
to
the
processing
units.
GPUBuffer
and
GPUTexture
are
the
physical
resources
backed
by
GPU
memory.
GPUCommandBuffer
and
GPURenderBundle
are
containers
for
user-recorded
commands.
GPUShaderModule
contains
shader
code.
The
other
resources,
such
as
GPUSampler
or
GPUBindGroup
,
configure
the
way
physical
resources
are
used
by
the
GPU.
GPUs
execute
commands
encoded
in
GPUCommandBuffer
s
by
feeding
data
through
a
pipeline
,
which
is
a
mix
of
fixed-function
and
programmable
stages.
Programmable
stages
execute
shaders
,
which
are
special
programs
designed
to
run
on
GPU
hardware.
Most
of
the
state
of
a
pipeline
is
defined
by
a
GPURenderPipeline
or
a
GPUComputePipeline
object.
The
state
not
included
in
these
pipeline
objects
is
set
during
encoding
with
commands,
such
as
beginRenderPass()
or
setBlendColor()
.
2. Malicious use considerations
This section is non-normative. It describes the risks associated with exposing this API on the Web.
2.1. Security
The security requirements for WebGPU are the same as ever for the web, and are likewise non-negotiable. The general approach is strictly validating all the commands before they reach GPU, ensuring that a page can only work with its own data.
2.1.1. CPU-based undefined behavior
A WebGPU implementation translates the workloads issued by the user into API commands specific to the target platform. Native APIs specify the valid usage for the commands (for example, see vkCreateDescriptorSetLayout ) and generally don’t guarantee any outcome if the valid usage rules are not followed. This is called "undefined behavior", and it can be exploited by an attacker to access memory they don’t own, or force the driver to execute arbitrary code.
In
order
to
disallow
insecure
usage,
the
range
of
allowed
WebGPU
behaviors
is
defined
for
any
input.
An
implementation
has
to
validate
all
the
input
from
the
user
and
only
reach
the
driver
with
the
valid
workloads.
This
document
specifies
all
the
error
conditions
and
handling
semantics.
For
example,
specifying
the
same
buffer
with
intersecting
ranges
in
both
"source"
and
"destination"
of
copyBufferToBuffer()
results
in
GPUCommandEncoder
generating
an
error,
and
no
other
operation
occurring.
See § 20 Errors & Debugging for more information about error handling.
2.2. GPU-based undefined behavior
WebGPU
shader
s
are
executed
by
the
compute
units
inside
GPU
hardware.
In
native
APIs,
some
of
the
shader
instructions
may
result
in
undefined
behavior
on
the
GPU.
In
order
to
address
that,
the
shader
instruction
set
and
its
defined
behaviors
are
strictly
defined
by
WebGPU.
When
a
shader
is
provided
to
createShaderModule()
,
the
WebGPU
implementation
has
to
validate
it
before
doing
any
translation
(to
platform-specific
shaders)
or
transformation
passes.
2.3. Uninitialized data
Generally, allocating new memory may expose the leftover data of other applications running on the system. In order to address that, WebGPU conceptually initializes all the resources to zero, although in practice an implementation may skip this step if it sees the developer initializing the contents manually. This includes variables and shared workgroup memory inside shaders.
The precise mechanism of clearing the workgroup memory can differ between platforms. If the native API does not provide facilities to clear it, the WebGPU implementation transforms the compute shader to first do a clear across all invocations, synchronize them, and continue executing developer’s code.
2.4. Out-of-bounds access in shaders
Shader
s
can
access
physical
resource
s
either
directly
(for
example,
as
a
"uniform-buffer"
),
or
via
texture
unit
s,
which
are
fixed-function
hardware
blocks
that
handle
texture
coordinate
conversions.
Validation
on
the
API
side
can
only
guarantee
that
all
the
inputs
to
the
shader
are
provided
and
they
have
the
correct
usage
and
types.
The
host
API
side
can
not
guarantee
that
the
data
is
accessed
within
bounds
if
the
texture
unit
s
are
not
involved.
define the host API distinct from the shader API
In order to prevent the shaders from accessing GPU memory an application doesn’t own, the WebGPU implementation may enable a special mode (called "robust buffer access") in the driver that guarantees that the access is limited to buffer bounds.
Alternatively,
an
implementation
may
transform
the
shader
code
by
inserting
manual
bounds
checks.
When
this
path
is
taken,
the
out-of-bound
checks
only
apply
to
array
indexing.
They
aren’t
needed
for
plain
field
access
of
shader
structures
due
to
the
minBufferBindingSize
validation
on
the
host
side.
If the shader attempts to load data outside of physical resource bounds, the implementation is allowed to:
-
return a value at a different location within the resource bounds
-
return a value vector of "(0, 0, 0, X)" with any "X"
-
partially discard the draw or dispatch call
If the shader attempts to write data outside of physical resource bounds, the implementation is allowed to:
-
write the value to a different location within the resource bounds
-
discard the write operation
-
partially discard the draw or dispatch call
2.5. Invalid data
When uploading floating-point data from CPU to GPU, or generating it on the GPU, we may end up with a binary representation that doesn’t correspond to a valid number, such as infinity or NaN (not-a-number). The GPU behavior in this case is subject to the accuracy of the GPU hardware implementation of the IEEE-754 standard. WebGPU guarantees that introducing invalid floating-point numbers would only affect the results of arithmetic computations and will not have other side effects.
2.5.1. Driver bugs
GPU drivers are subject to bugs like any other software. If a bug occurs, an attacker could possibly exploit the incorrect behavior of the driver to get access to unprivileged data. In order to reduce the risk, the WebGPU working group will coordinate with GPU vendors to integrate the WebGPU Conformance Test Suite (CTS) as part of their driver testing process, like it was done for WebGL. WebGPU implementations are expected to have workarounds for some of the discovered bugs, and disable WebGPU on drivers with known bugs that can’t be worked around.
2.5.2. Timing attacks
WebGPU
is
designed
for
multi-threaded
use
via
Web
Workers.
As
such,
it
is
designed
not
to
open
the
users
to
modern
high-precision
timing
attacks.
Some
of
the
objects,
like
GPUBuffer
or
GPUQueue
,
have
shared
state
which
can
be
simultaneously
accessed.
This
allows
race
conditions
to
occur,
similar
to
those
of
accessing
a
SharedArrayBuffer
from
multiple
Web
Workers,
which
makes
the
thread
scheduling
observable.
WebGPU
addresses
this
by
limiting
the
ability
to
deserialize
(or
share)
objects
only
to
the
agents
inside
the
agent
cluster
,
and
only
if
the
cross-origin
isolated
policies
are
in
place.
This
restriction
matches
the
mitigations
against
the
malicious
SharedArrayBuffer
use.
Similarly,
the
user
agent
may
also
serialize
the
agents
sharing
any
handles
to
prevent
any
concurrency
entirely.
In
the
end,
the
attack
surface
for
races
on
shared
state
in
WebGPU
will
be
a
small
subset
of
the
SharedArrayBuffer
attacks.
WebGPU
also
specifies
the
"timestamp-query"
feature,
which
provides
high
precision
timing
of
GPU
operations.
The
feature
is
optional,
and
a
WebGPU
implementation
may
limit
its
exposure
only
to
those
scenarios
that
are
trusted.
Alternatively,
the
timing
query
results
could
be
processed
by
a
compute
shader
and
aligned
to
a
lower
precision.
2.5.3. Row hammer attacks
Row hammer is a class of attacks that exploit the leaking of states in DRAM cells. It could be used on GPU . WebGPU does not have any specific mitigations in place, and relies on platform-level solutions, such as reduced memory refresh intervals.
2.6. Denial of service
WebGPU applications have access to GPU memory and compute units. A WebGPU implementation may limit the available GPU memory to an application, in order to keep other applications responsive. For GPU processing time, a WebGPU implementation may set up "watchdog" timer that makes sure an application doesn’t cause GPU unresponsiveness for more than a few seconds. These measures are similar to those used in WebGL.
2.7. Workload identification
WebGPU provides access to constrained global resources shared between different programs (and web pages) running on the same machine. An application can try to indirectly probe how constrained these global resources are, in order to reason about workloads performed by other open web pages, based on the patterns of usage of these shared resources. These issues are generally analogous to issues with Javascript, such as system memory and CPU execution throughput. WebGPU does not provide any additional mitigations for this.
2.7.1. Memory resources
WebGPU exposes fallible allocations from machine-global memory heaps, such as VRAM. This allows for probing the size of the system’s remaining available memory (for a given heap type) by attempting to allocate and watching for allocation failures.
GPUs internally have one or more (typically only two) heaps of memory shared by all running applications. When a heap is depleted, WebGPU would fail to create a resource. This is observable, which may allow a malicious application to guess what heaps are used by other applications, and how much they allocate from them.
2.7.2. Computation resources
If one site uses WebGPU at the same time as another, it may observe the increase in time it takes to process some work. For example, if a site constantly submits compute workloads and tracks fences for their completion, it may observe that something else also started using the GPU.
A GPU has many parts that can be tested independently, such as the arithmetic units, texture sampling units, atomic units, etc. A malicious application may sense when some of these units are stressed, and attempt to guess the workload of another application by analyzing the stress patterns. This is analogous to the realities of CPU execution of Javascript.
2.8. Privacy
2.8.1. Machine-specific limits
WebGPU can expose a lot of detail on the underlying GPU architecture and the device geometry. This includes available physical adapters, many limits on the GPU and CPU resources that could be used (such as the maximum texture size), and any optional hardware-specific capabilities that are available.
User agents are not obligated to expose the real hardware limits, they are in full contol of how much the machine specifics are exposed. One strategy to reduce fingeprinting is binning all the target platforms into a few number of bins. In general, the privacy impact of exposing the hardware limits matches the one of WebGL.
The baseline (guaranteed) limits are also deliberately high enough to allow most application to work without requesting higher limits. All the usage of the API is validated according to the requested limits, so the actual hardware capabilities are not exposed to the users by accident.
2.8.2. Machine-specific artifacts
There are some machine-specific rasterization/precision artifacts and performance differences that can be observed roughly in the same way as in WebGL. This applies to rasterization coverage and patterns, interpolation precision of the varyings between shader stages, compute unit scheduling, and more aspects of execution.
Generally, rasterization and precision fingerprints are identical across most or all of the devices of each vendor. Performance differences are relatively intractable, but also relatively low-signal (as with JS execution performance).
Privacy-critical applications and user agents should utilize software implementations to eliminate such artifacts.
2.8.3. Machine-specific performance
Another factor for differentiating users is measuring the performance of specific operations on the GPU. Even with low precision timing, repeated execution of an operation can show if the user’s machine is fast at specific workloads. This is a fairly common vector (present in both WebGL and Javascript), but it’s also low-signal and relatively intractable to truly normalize.
WebGPU compute pipelines expose access to GPU unobstructed by the fixed-function hardware. This poses an additional risk for unique device fingerprinting. User agents can take steps to dissociate logical GPU invocations with actual compute units to reduce this risk.
3. Fundamentals
3.1. Conventions
3.1.1. Dot Syntax
In
this
specification,
the
.
("dot")
syntax,
common
in
programming
languages,
is
used.
The
phrasing
"
Foo.Bar
"
means
"the
Bar
member
of
the
value
(or
interface)
Foo
."
For
example,
where
buffer
is
a
GPUBuffer
,
buffer.[[device]].[[adapter]]
means
"the
[[adapter]]
internal
slot
of
the
[[device]]
internal
slot
of
buffer
.
3.1.2. Internal Objects
An internal object is a conceptual, non-exposed WebGPU object. Internal objects track the state of an API object and hold any underlying implementation. If the state of a particular internal object can change in parallel from multiple agents , those changes are always atomic with respect to all agents .
Note: An " agent " refers to a JavaScript "thread" (i.e. main thread, or Web Worker).
3.1.3. WebGPU Interfaces
A WebGPU interface is an exposed interface which encapsulates an internal object . It provides the interface through which the internal object 's state is changed.
As a matter of convention, if a WebGPU interface is referred to as invalid , it means that the internal object it encapsulates is invalid .
Any
interface
which
includes
GPUObjectBase
is
a
WebGPU
interface
.
interface mixin {GPUObjectBase attribute USVString ?label ; };
GPUObjectBase
has
the
following
attributes:
-
label, of type USVString , nullable -
A label which can be used by development tools (such as error/warning messages, browser developer tools, or platform debugging utilities) to identify the underlying internal object to the developer. It has no specified format, and therefore cannot be reliably machine-parsed.
In any given situation, the user agent may or may not choose to use this label.
GPUObjectBase
has
the
following
internal
slots:
-
[[device]], of type device , readonly -
An internal slot holding the device which owns the internal object .
3.1.4. Object Descriptors
An
object
descriptor
holds
the
information
needed
to
create
an
object,
which
is
typically
done
via
one
of
the
create*
methods
of
GPUDevice
.
dictionary {GPUObjectDescriptorBase USVString label ; };
GPUObjectDescriptorBase
has
the
following
members:
-
label, of type USVString -
The initial value of
GPUObjectBase.label.
3.2. Invalid Internal Objects & Contagious Invalidity
If an object is successfully created, it is valid at that moment. An internal object may be invalid . It may become invalid during its lifetime, but it will never become valid again.
-
If there is an error in the creation of an object, it is immediately invalid. This can happen, for example, if the object descriptor doesn’t describe a valid object, or if there is not enough memory to allocate a resource.
-
If an object is explicitly destroyed (e.g.
GPUBuffer.destroy()), it becomes invalid. -
If the device that owns an object is lost, the object becomes invalid.
GPUObjectBase
object
is
valid
to
use
with
a
targetObject
,
run
the
following
steps:
-
If any of the following conditions are unsatisfied return
false:-
object is valid
-
If targetObject is a
GPUDeviceobject .[[device]]is targetObject . -
Otherwise object .
[[device]]is targetObject .[[device]].
-
-
Return
true.
3.3. Coordinate Systems
WebGPU’s coordinate systems match DirectX and Metal’s coordinate systems in a graphics pipeline.
-
Y-axis is up in normalized device coordinate (NDC): point(-1.0, -1.0) in NDC is located at the bottom-left corner of NDC. In addition, x and y in NDC should be between -1.0 and 1.0 inclusive, while z in NDC should be between 0.0 and 1.0 inclusive. Vertices out of this range in NDC will not introduce any errors, but they will be clipped.
-
Y-axis is down in framebuffer coordinate, viewport coordinate and fragment/pixel coordinate: origin(0, 0) is located at the top-left corner in these coordinate systems.
-
Window/present coordinate matches framebuffer coordinate.
-
UV of origin(0, 0) in texture coordinate represents the first texel (the lowest byte) in texture memory.
3.4. Programming Model
3.4.1. Timelines
This section is non-normative.
A computer system with a user agent at the front-end and GPU at the back-end has components working on different timelines in parallel:
- Content timeline
-
Associated with the execution of the Web script. It includes calling all methods described by this specification.
Steps executed on the content timeline look like this. - Device timeline
-
Associated with the GPU device operations that are issued by the user agent. It includes creation of adapters, devices, and GPU resources and state objects, which are typically synchronous operations from the point of view of the user agent part that controls the GPU, but can live in a separate OS process.
Steps executed on the device timeline look like this. - Queue timeline
-
Associated with the execution of operations on the compute units of the GPU. It includes actual draw, copy, and compute jobs that run on the GPU.
Steps executed on the queue timeline look like this.
In this specification, asynchronous operations are used when the result value depends on work that happens on any timeline other than the Content timeline . They are represented by callbacks and promises in JavaScript.
GPUComputePassEncoder.dispatch()
:
-
User encodes a
dispatchcommand by calling a method of theGPUComputePassEncoderwhich happens on the Content timeline . -
User issues
GPUQueue.submit()that hands over theGPUCommandBufferto the user agent, which processes it on the Device timeline by calling the OS driver to do a low-level submission. -
The submit gets dispatched by the GPU invocation scheduler onto the actual compute units for execution, which happens on the Queue timeline .
GPUDevice.createBuffer()
:
-
User fills out a
GPUBufferDescriptorand creates aGPUBufferwith it, which happens on the Content timeline . -
User agent creates a low-level buffer on the Device timeline .
GPUBuffer.mapAsync()
:
-
User requests to map a
GPUBufferon the Content timeline and gets a promise in return. -
User agent checks if the buffer is currently used by the GPU and makes a reminder to itself to check back when this usage is over.
-
After the GPU operating on Queue timeline is done using the buffer, the user agent maps it to memory and resolves the promise.
3.4.2. Memory Model
This section is non-normative.
Once
a
GPUDevice
has
been
obtained
during
an
application
initialization
routine,
we
can
describe
the
WebGPU
platform
as
consisting
of
the
following
layers:
-
User agent implementing the specification.
-
Operating system with low-level native API drivers for this device.
-
Actual CPU and GPU hardware.
Each layer of the WebGPU platform may have different memory types that the user agent needs to consider when implementing the specification:
-
The script-owned memory, such as an
ArrayBuffercreated by the script, is generally not accessible by a GPU driver. -
A user agent may have different processes responsible for running the content and communication to the GPU driver. In this case, it uses inter-process shared memory to transfer data.
-
Dedicated GPUs have their own memory with high bandwidth, while integrated GPUs typically share memory with the system.
Most physical resources are allocated in the memory of type that is efficient for computation or rendering by the GPU. When the user needs to provide new data to the GPU, the data may first need to cross the process boundary in order to reach the user agent part that communicates with the GPU driver. Then it may need to be made visible to the driver, which sometimes requires a copy into driver-allocated staging memory. Finally, it may need to be transferred to the dedicated GPU memory, potentially changing the internal layout into one that is most efficient for GPUs to operate on.
All of these transitions are done by the WebGPU implementation of the user agent.
Note:
This
example
describes
the
worst
case,
while
in
practice
the
implementation
may
not
need
to
cross
the
process
boundary,
or
may
be
able
to
expose
the
driver-managed
memory
directly
to
the
user
behind
an
ArrayBuffer
,
thus
avoiding
any
data
copies.
3.4.3. Multi-Threading
3.4.4. Resource Usages
A
physical
resource
can
be
used
on
GPU
in
one
of
the
following
with
an
internal
usage
s:
:
- input
-
Buffer with input data for draw or dispatch calls. Preserves the contents. Allowed by
INDEX,VERTEX, orINDIRECT. - constant
-
Resource bindings that are constant from the shader point of view. Preserves the contents. Allowed by
UNIFORMorSAMPLED. - storage
-
Read-write storage resource binding. Allowed by
STORAGE. - storage-read
-
Read-only storage resource bindings. Preserves the contents. Allowed by
STORAGEorSTORAGE. - storage-write
-
Write-only storage resource bindings. Allowed by
STORAGE. - attachment
-
Texture used as an output attachment in a render pass. Allowed by
RENDER_ATTACHMENT. - attachment-read
-
Texture used as a read-only attachment in a render pass. Preserves the contents. Allowed by
RENDER_ATTACHMENT.
Textures
may
consist
of
separate
mipmap
levels
and
array
layers
,
which
can
be
used
differently
at
any
given
time.
Each
such
texture
subresource
is
uniquely
identified
by
a
texture
,
mipmap
level
,
and
(for
2d
textures
only)
array
layer
,
and
aspect
.
We define subresource to be either a whole buffer, or a texture subresource .
-
Each usage in U is input , constant , storage-read , or attachment-read .
-
Each usage in U is storage .
-
Each usage in U is storage-write .
-
U contains exactly one element: attachment .
Enforcing that the usages are only combined into a compatible usage list allows the API to limit when data races can occur in working with memory. That property makes applications written against WebGPU more likely to run without modification on different platforms.
Generally,
when
an
implementation
processes
an
operation
that
uses
a
subresource
in
a
different
way
than
its
current
usage
allows,
it
schedules
a
transition
of
the
resource
into
the
new
state.
In
some
cases,
like
within
an
open
GPURenderPassEncoder
,
such
a
transition
is
impossible
due
to
the
hardware
limitations.
We
define
these
places
as
usage
scopes
.
The main usage rule is, for any one subresource , its list of internal usages within one usage scope must be a compatible usage list .
For
example,
binding
the
same
buffer
for
storage
as
well
as
for
input
within
the
same
GPURenderPassEncoder
would
put
the
encoder
as
well
as
the
owning
GPUCommandEncoder
into
the
error
state.
This
combination
of
usages
does
not
make
a
compatible
usage
list
.
Note: race condition of multiple writable storage buffer/texture usages in a single usage scope is allowed.
The
subresources
of
textures
included
in
the
views
provided
to
GPURenderPassColorAttachmentDescriptor.attachment
and
GPURenderPassColorAttachmentDescriptor.resolveTarget
are
considered
to
be
used
as
attachment
for
the
usage
scope
of
this
render
pass.
The physical size of a texture subresource is the dimension of the texture subresource in texels that includes the possible extra paddings to form complete texel blocks in the subresource .
-
For pixel-based
, the physical size is always equal to the size of the texture subresource used in the sampling hardwares.GPUTextureFormatGPUTextureFormatss, -
GPUTextureTexturessin block-based compressedGPUTextureFormatGPUTextureFormatssalways have a mipmap level 0 whose[[textureSize]]is a multiple of the texel block size , but the lower mipmap levels might not be the multiple of the texel block size and can have paddings.
GPUTexture
in
BC
format
whose
[[textureSize]]
is
{60,
60,
1},
when
sampling
the
GPUTexture
at
mipmap
level
2,
the
sampling
hardware
uses
{15,
15,
1}
as
the
size
of
the
texture
subresource
,
while
its
physical
size
is
{16,
16,
1}
as
the
block-compression
algorithm
can
only
operate
on
4x4
texel
blocks
.
3.4.5. Synchronization
For each subresource of a physical resource , its set of internal usage flags is tracked on the Queue timeline .
This section will need to be revised to support multiple queues.
On the Queue timeline , there is an ordered sequence of usage scopes . Each item on the timeline is contained within exactly one scope. For the duration of each scope, the set of internal usage flags of any given subresource is constant. A subresource may transition to new usages at the boundaries between usage scope s.
This specification defines the following usage scopes :
-
an individual command on a
GPUCommandEncoder, such asGPUCommandEncoder.copyBufferToTexture. -
an individual command on a
GPUComputePassEncoder, such asGPUProgrammablePassEncoder.setBindGroup. -
the whole
GPURenderPassEncoder.
-
Resources used in every
GPUProgrammablePassEncoder.setBindGroupregardless of whether the shader orGPUPipelineLayoutactually depends on these bindings, or the bind group is shadowed by another 'set' call. -
Vertex buffer used in every
GPURenderEncoderBase.setVertexBufferregardless of whether draw call depends on this buffer, or this buffer is shadowed by another 'set' call. -
Index buffer used in every
GPURenderEncoderBase.setIndexBufferregardless of whether draw call depends on this buffer, or this buffer is shadowed by another 'set' call. -
Textures used as color attachments, resolve attachments or depth/stencil attachment in
GPURenderPassDescriptorbyGPUCommandEncoder.beginRenderPass()regardless of whether the shader actually depends on these attachments. -
Resources used in bind group entries with visibility 0, or visible only to the the compute stage but used in a render pass or vice versa.
The
usage
scopes
are
validated
at
GPUCommandEncoder.finish
time.
The
implementation
performs
the
usage
scope
validation
by
composing
the
list
of
all
internal
usage
flags
of
each
subresource
used
in
the
usage
scope
.
A
GPUValidationError
is
generated
in
the
current
scope
with
an
appropriate
error
message
if
that
list
is
not
a
compatible
usage
list
.
3.5. Core Internal Objects
3.5.1. Adapters
An adapter represents an implementation of WebGPU on the system. Each adapter identifies both an instance of a hardware accelerator (e.g. GPU or CPU) and an instance of a browser’s implementation of WebGPU on top of that accelerator.
If an adapter becomes unavailable, it becomes invalid . Once invalid, it never becomes valid again. Any devices on the adapter, and internal objects owned by those devices, also become invalid.
Note:
An
adapter
may
be
a
physical
display
adapter
(GPU),
but
it
could
also
be
a
software
renderer.
A
returned
adapter
could
refer
to
different
physical
adapters,
or
to
different
browser
codepaths
or
system
drivers
on
the
same
physical
adapters.
Applications
can
hold
onto
multiple
adapters
at
once
(via
GPUAdapter
)
(even
if
some
are
invalid
),
and
two
of
these
could
refer
to
different
instances
of
the
same
physical
configuration
(e.g.
if
the
GPU
was
reset
or
disconnected
and
reconnected).
An adapter has the following internal slots:
-
[[features]], of type list <GPUFeatureName>, readonly -
The features which can be used to create devices on this adapter.
-
[[limits]], of typeGPULimits, readonly -
The best limits which can be used to create devices on this adapter.
Each adapter limit must be the same or better than its default value in
GPULimits.
Adapters
are
exposed
via
GPUAdapter
.
3.5.2. Devices
A device is the logical instantiation of an adapter , through which internal objects are created. It can be shared across multiple agents (e.g. dedicated workers).
A
device
is
the
exclusive
owner
of
all
internal
objects
created
from
it:
when
the
device
is
lost,
it
and
all
objects
created
on
it
(directly,
e.g.
createTexture()
,
or
indirectly,
e.g.
createView()
)
become
invalid
.
A device has the following internal slots:
-
[[adapter]], of type adapter , readonly -
The adapter from which this device was created.
-
[[features]], of type list <GPUFeatureName>, readonly -
The features which can be used on this device. No additional features can be used, even if the underlying adapter can support them.
-
[[limits]], of typeGPULimits, readonly -
The limits which can be used on this device. No better limits can be used, even if the underlying adapter can support them.
GPUDeviceDescriptor
descriptor
:
-
Set device .
[[adapter]]to adapter . -
Set device .
[[features]]to descriptor .features. -
Set device .
[[limits]]to descriptor .limits.
Devices
are
exposed
via
GPUDevice
.
3.6. Optional Capabilities
WebGPU adapters and devices have capabilities , which describe WebGPU functionality that differs between different implementations, typically due to hardware or system software constraints. A capability is either a feature or a limit .
3.6.1. Features
A feature is a set of optional WebGPU functionality that is not supported on all implementations, typically due to hardware or system software constraints.
Each
GPUAdapter
exposes
a
set
of
available
features.
Only
those
features
may
be
requested
in
requestDevice()
.
Functionality that is part of an feature may only be used if the feature was requested at device creation. See the Feature Index for a description of the functionality each feature enables.
3.6.2. Limits
Each limit is a numeric limit on the usage of WebGPU on a device. Each adapter has a set of supported limits, and devices are created with specific limits in place. The device limits are enforced regardless of the adapter’s limits.
One limit value may be better than another. A better limit value always relaxes validation, enabling strictly more programs to be valid. For each limit, "better" is defined.
Note: Setting "better" limits may not necessarily be desirable, as they may have a performance impact. Because of this, and to improve portability across devices and implementations, applications should generally request the "worst" limits that work for their content (ideally, the default values).
Each
limit
also
has
a
baseline
value.
Every
adapter
is
guaranteed
to
support
the
baseline
value
or
better
.
The
baseline
value
is
also
the
default
value
for
the
limit
in
GPULimits
if
a
better
limit
is
not
specified.
GPULimits
member
| Type | Better | Baseline |
|---|---|---|---|
maxBindGroups
|
GPUSize32
| Higher | 4 |
The
maximum
number
of
GPUBindGroupLayouts
allowed
in
bindGroupLayouts
when
creating
a
GPUPipelineLayout
.
| |||
maxDynamicUniformBuffersPerPipelineLayout
|
GPUSize32
| Higher | 8 |
The
maximum
number
of
entries
for
which:
across
all
| |||
maxDynamicStorageBuffersPerPipelineLayout
|
GPUSize32
| Higher | 4 |
The
maximum
number
of
entries
for
which:
across
all
| |||
maxSampledTexturesPerShaderStage
|
GPUSize32
| Higher | 16 |
For
each
possible
GPUShaderStage
stage
,
the
maximum
number
of
entries
for
which:
across
all
| |||
maxSamplersPerShaderStage
|
GPUSize32
| Higher | 16 |
For
each
possible
GPUShaderStage
stage
,
the
maximum
number
of
entries
for
which:
across
all
| |||
maxStorageBuffersPerShaderStage
|
GPUSize32
| Higher | 4 |
For
each
possible
GPUShaderStage
stage
,
the
maximum
number
of
entries
for
which:
across
all
| |||
maxStorageTexturesPerShaderStage
|
GPUSize32
| Higher | 4 |
For
each
possible
GPUShaderStage
stage
,
the
maximum
number
of
entries
for
which:
across
all
| |||
maxUniformBuffersPerShaderStage
|
GPUSize32
| Higher | 12 |
For
each
possible
GPUShaderStage
stage
,
the
maximum
number
of
entries
for
which:
across
all
| |||
maxUniformBufferBindingSize
|
GPUSize32
| Higher | 16384 |
The
maximum
GPUBufferBinding
.
size
for
bindings
of
type
uniform-buffer
.
| |||
maxStorageBufferBindingSize
|
GPUSize32
| Higher | 134217728 (128 MiB) |
The
maximum
GPUBufferBinding
.
size
for
bindings
of
types
storage-buffer
and
readonly-storage-buffer
.
| |||
3.6.2.1.
GPULimits
GPULimits
describes
the
limits
with
which
a
device
should
be
created.
See
GPUDeviceDescriptor.limits
.
dictionary GPULimits {GPUSize32 maxBindGroups = 4;GPUSize32 maxDynamicUniformBuffersPerPipelineLayout = 8;GPUSize32 maxDynamicStorageBuffersPerPipelineLayout = 4;GPUSize32 maxSampledTexturesPerShaderStage = 16;GPUSize32 maxSamplersPerShaderStage = 16;GPUSize32 maxStorageBuffersPerShaderStage = 4;GPUSize32 maxStorageTexturesPerShaderStage = 4;GPUSize32 maxUniformBuffersPerShaderStage = 12;GPUSize32 maxUniformBufferBindingSize = 16384;GPUSize32 maxStorageBufferBindingSize = 134217728; };
3.6.2.2.
GPUAdapterFeatures
GPUAdapterFeatures
is
a
setlike
interface.
Its
set
entries
are
the
GPUFeatureName
values
of
the
features
supported
by
an
adapter.
interface GPUAdapterFeatures {readonly setlike <GPUFeatureName >; };
4. Initialization
4.1. Examples
Need a robust example like the one in ErrorHandling.md, which handles all situations. Possibly also include a simple example with no handling.
4.2. navigator.gpu
A
GPU
object
is
available
via
navigator.gpu
on
the
Window
:
[Exposed =Window ]partial interface Navigator { [SameObject ]readonly attribute GPU ; };gpu
... as well as on dedicated workers:
[Exposed =DedicatedWorker ]partial interface WorkerNavigator { [SameObject ]readonly attribute GPU ; };gpu
4.3. GPU
GPU
is
the
entry
point
to
WebGPU.
[Exposed =(Window ,DedicatedWorker )]interface GPU {Promise <GPUAdapter ?>requestAdapter (optional GPURequestAdapterOptions options = {}); };
GPU
has
the
following
methods:
-
requestAdapter(options) -
Requests an adapter from the user agent. The user agent chooses whether to return an adapter, and, if so, chooses according to the provided options.
Called on:GPUthis .Arguments:
Arguments for the GPU.requestAdapter(options) method. Parameter Type Nullable Optional Description optionsGPURequestAdapterOptions ✘ ✔ Criteria used to select the adapter. Returns:
Promise<GPUAdapter?>-
Let promise be a new promise .
-
Issue the following steps on the Device timeline of this :
-
If the user agent chooses to return an adapter:
-
The user agent chooses an adapter adapter according to the rules in § 4.3.1 Adapter Selection and the criteria in options .
-
promise resolves with a new
GPUAdapterencapsulating adapter .
-
-
Otherwise, promise resolves with
null.
-
-
Return promise .
-
4.3.1. Adapter Selection
GPURequestAdapterOptions
provides
hints
to
the
user
agent
indicating
what
configuration
is
suitable
for
the
application.
dictionary GPURequestAdapterOptions {GPUPowerPreference powerPreference ; };
enum {GPUPowerPreference "low-power" ,"high-performance" };
GPURequestAdapterOptions
has
the
following
members:
-
powerPreference, of type GPUPowerPreference -
Optionally provides a hint indicating what class of adapter should be selected from the system’s available adapters.
The value of this hint may influence which adapter is chosen, but it must not influence whether an adapter is returned or not.
Note: The primary utility of this hint is to influence which GPU is used in a multi-GPU system. For instance, some laptops have a low-power integrated GPU and a high-performance discrete GPU.
Note: Depending on the exact hardware configuration, such as battery status and attached displays or removable GPUs, the user agent may select different adapters given the same power preference. Typically, given the same hardware configuration and state and
powerPreference, the user agent is likely to select the same adapter.It must be one of the following values:
-
undefined(or not present) -
Provides no hint to the user agent.
-
"low-power" -
Indicates a request to prioritize power savings over performance.
Note: Generally, content should use this if it is unlikely to be constrained by drawing performance; for example, if it renders only one frame per second, draws only relatively simple geometry with simple shaders, or uses a small HTML canvas element. Developers are encouraged to use this value if their content allows, since it may significantly improve battery life on portable devices.
-
"high-performance" -
Indicates a request to prioritize performance over power consumption.
Note: By choosing this value, developers should be aware that, for devices created on the resulting adapter, user agents are more likely to force device loss, in order to save power by switching to a lower-power adapter. Developers are encouraged to only specify this value if they believe it is absolutely necessary, since it may significantly decrease battery life on portable devices.
-
4.4.
GPUAdapter
A
GPUAdapter
encapsulates
an
adapter
,
and
describes
its
capabilities
(
features
and
limits
).
To
get
a
GPUAdapter
,
use
requestAdapter()
.
interface GPUAdapter {readonly attribute DOMString name ; [SameObject ]readonly attribute GPUAdapterFeatures features ; //readonly attribute GPULimits limits; Don’t expose higher limits for now.Promise <GPUDevice ?>requestDevice (optional GPUDeviceDescriptor descriptor = {}); };
GPUAdapter
has
the
following
attributes:
-
name, of type DOMString , readonly -
A human-readable name identifying the adapter. The contents are implementation-defined.
-
features, of type GPUAdapterFeatures , readonly -
Accessor for
this.[[adapter]].[[features]].
GPUAdapter
has
the
following
internal
slots:
-
[[adapter]], of type adapter , readonly -
The adapter to which this
GPUAdapterrefers.
GPUAdapter
has
the
following
methods:
-
requestDevice(descriptor) -
Requests a device from the adapter .
Called on:GPUAdapterthis .Arguments:
Arguments for the GPUAdapter.requestDevice(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUDeviceDescriptor ✘ ✔ Description of the GPUDeviceto request.Returns:
Promise<GPUDevice?>-
Let promise be a new promise .
-
Issue the following steps to the Device timeline :
-
If any of the following conditions are unsatisfied, reject promise with an
OperationErrorand stop.-
The set of
GPUFeatureNamevalues in descriptor .featuresis a subset of those in adapter .[[features]]. -
For each type of limit in
GPULimits, the value of that limit in descriptor .limitsis no better than the value of that limit in adapter .[[limits]].
where adapter is this .
[[adapter]]. -
-
If the user agent cannot fulfill the request, resolve promise to
nulland stop. -
Resolve promise to a new
GPUDeviceobject encapsulating a new device with the capabilities described by descriptor .
-
-
Return promise .
-
4.4.1.
GPUDeviceDescriptor
GPUDeviceDescriptor
describes
a
device
request.
dictionary GPUDeviceDescriptor :GPUObjectDescriptorBase {sequence <GPUFeatureName >features = [];GPULimits limits = {}; };
GPUDeviceDescriptor
has
the
following
members:
-
features, of type sequence< GPUFeatureName >, defaulting to[] -
The set of
GPUFeatureNamevalues in this sequence defines the exact set of features that must be enabled on the device. -
limits, of type GPULimits , defaulting to{} -
Defines the exact limits that must be enabled on the device.
4.4.1.1.
GPUFeatureName
Each
GPUFeatureName
identifies
a
set
of
functionality
which,
if
available,
allows
additional
usages
of
WebGPU
that
would
have
otherwise
been
invalid.
enum GPUFeatureName {"depth-clamping" ,"depth24unorm-stencil8" ,"depth32float-stencil8" ,"pipeline-statistics-query" ,"texture-compression-bc" ,"timestamp-query" , };
4.5.
GPUDevice
A
GPUDevice
encapsulates
a
device
and
exposes
the
functionality
of
that
device.
GPUDevice
is
the
top-level
interface
through
which
WebGPU
interfaces
are
created.
To
get
a
GPUDevice
,
use
requestDevice()
.
[Exposed =(Window ,DedicatedWorker ),Serializable ]interface GPUDevice :EventTarget { [SameObject ]readonly attribute GPUAdapter adapter ;readonly attribute FrozenArray <GPUFeatureName >features ;readonly attribute object limits ; [SameObject ]readonly attribute GPUQueue defaultQueue ;GPUBuffer createBuffer (GPUBufferDescriptor descriptor ););GPUTexture createTexture (GPUTextureDescriptor descriptor );GPUSampler createSampler (optional GPUSamplerDescriptor descriptor = {});GPUBindGroupLayout createBindGroupLayout (GPUBindGroupLayoutDescriptor descriptor );GPUPipelineLayout createPipelineLayout (GPUPipelineLayoutDescriptor descriptor );GPUBindGroup createBindGroup (GPUBindGroupDescriptor descriptor );GPUShaderModule createShaderModule (GPUShaderModuleDescriptor descriptor );GPUComputePipeline createComputePipeline (GPUComputePipelineDescriptor descriptor );GPURenderPipeline createRenderPipeline (GPURenderPipelineDescriptor descriptor );Promise <GPUComputePipeline >createReadyComputePipeline (GPUComputePipelineDescriptor descriptor );Promise <GPURenderPipeline >createReadyRenderPipeline (GPURenderPipelineDescriptor descriptor );GPUCommandEncoder createCommandEncoder (optional GPUCommandEncoderDescriptor descriptor = {});GPURenderBundleEncoder createRenderBundleEncoder (GPURenderBundleEncoderDescriptor descriptor );GPUQuerySet createQuerySet (GPUQuerySetDescriptor descriptor ); };GPUDevice includes GPUObjectBase ;
GPUDevice
has
the
following
attributes:
-
adapter, of type GPUAdapter , readonly -
The
GPUAdapterfrom which this device was created. -
features, of type FrozenArray< GPUFeatureName >, readonly -
A sequence containing the
GPUFeatureNamevalues of the features supported by the device (i.e. the ones with which it was created). -
limits, of type object , readonly -
A
GPULimitsobject exposing the limits supported by the device (i.e. the ones with which it was created). -
defaultQueue, of type GPUQueue , readonly -
The default
GPUQueuefor this device.
GPUDevice
has
the
following
internal
slots:
GPUDevice
has
the
methods
listed
in
its
WebIDL
definition
above,
which
are
defined
elsewhere
in
this
document.
GPUDevice
objects
are
serializable
objects
.
-
Set serialized .agentCluster to be the surrounding agent 's agent cluster .
-
If serialized .agentCluster’s cross-origin isolated is false, throw a "
DataCloneError". -
If forStorage is
true, throw a "DataCloneError". -
Set serialized .device to the value of value .
[[device]].
-
If serialized .agentCluster is not the surrounding agent 's agent cluster , throw a "
DataCloneError". -
Set value .
[[device]]to serialized .device.
GPUDevice
doesn’t
really
need
the
cross-origin
policy
restriction.
It
should
be
usable
from
multiple
agents
regardless.
Once
we
describe
the
serialization
of
buffers,
textures,
and
queues
-
the
COOP+COEP
logic
should
be
moved
in
there.
5. Buffers
5.1.
GPUBuffer
define buffer (internal object)
A
GPUBuffer
represents
a
block
of
memory
that
can
be
used
in
GPU
operations.
Data
is
stored
in
linear
layout,
meaning
that
each
byte
of
the
allocation
can
be
addressed
by
its
offset
from
the
start
of
the
GPUBuffer
,
subject
to
alignment
restrictions
depending
on
the
operation.
Some
GPUBuffers
can
be
mapped
which
makes
the
block
of
memory
accessible
via
an
ArrayBuffer
called
its
mapping.
GPUBuffers
are
created
via
GPUDevice.createBuffer(descriptor)
that
returns
a
new
buffer
in
the
mapped
or
unmapped
state.
[Serializable ]interface GPUBuffer {Promise <undefined >mapAsync (GPUMapModeFlags mode ,optional GPUSize64 offset = 0,optional GPUSize64 size );ArrayBuffer getMappedRange (optional GPUSize64 offset = 0,optional GPUSize64 size );undefined unmap ();undefined destroy (); };GPUBuffer includes GPUObjectBase ;
GPUBuffer
has
the
following
internal
slots:
-
[[size]]of typeGPUSize64. -
The length of the
GPUBufferallocation in bytes. -
[[usage]]of typeGPUBufferUsageFlags. -
The allowed usages for this
GPUBuffer. -
[[state]]of type buffer state . -
The current state of the
GPUBuffer. -
[[mapping]]of typeArrayBufferorPromiseornull. -
The mapping for this
GPUBuffer. TheArrayBufferisn’t directly accessible and is instead accessed through views into it, called the mapped ranges, that are stored in[[mapped_ranges]]Specify
[[mapping]]in term ofDataBlocksimilarly toAllocateArrayBuffer? <https://github.com/gpuweb/gpuweb/issues/605> -
[[mapping_range]]of type list < Number > ornull. -
The range of this
GPUBufferthat is mapped. -
[[mapped_ranges]]of type list <ArrayBuffer> ornull. -
The
ArrayBuffers returned viagetMappedRangeto the application. They are tracked so they can be detached whenunmapis called. -
[[map_mode]]of typeGPUMapModeFlags. -
The
GPUMapModeFlagsof the last call tomapAsync()(if any).
[[usage]]
is
differently
named
from
[[textureUsage]]
.
We
should
make
it
consistent.
Each
GPUBuffer
has
a
current
buffer
state
on
the
Content
timeline
which
is
one
of
the
following:
-
" mapped " where the
GPUBufferis available for CPU operations on its content. -
" mapped at creation " where the
GPUBufferwas just created and is available for CPU operations on its content. -
" mapping pending " where the
GPUBufferis being made available for CPU operations on its content. -
" unmapped " where the
GPUBufferis available for GPU operations. -
" destroyed " where the
GPUBufferis no longer available for any operations exceptdestroy.
Note:
[[size]]
and
[[usage]]
are
immutable
once
the
GPUBuffer
has
been
created.
GPUBuffer
has
a
state
machine
with
the
following
states.
(
[[mapping]]
,
[[mapping_range]]
,
and
[[mapped_ranges]]
are
null
when
not
specified.)
-
mapped or mapped at creation with an
ArrayBuffertyped[[mapping]], a sequence of two numbers in[[mapping_range]]and a sequence ofArrayBufferin[[mapped_ranges]] -
mapping pending with a
Promisetyped[[mapping]].
GPUBuffer
is
Serializable
.
It
is
a
reference
to
an
internal
buffer
object,
and
Serializable
means
that
the
reference
can
be
copied
between
realms
(threads/workers),
allowing
multiple
realms
to
access
it
concurrently.
Since
GPUBuffer
has
internal
state
(mapped,
destroyed),
that
state
is
internally-synchronized
-
these
state
changes
occur
atomically
across
realms.
5.2. Buffer Creation
5.2.1.
GPUBufferDescriptor
This
specifies
the
options
to
use
in
creating
a
GPUBuffer
.
dictionary :GPUBufferDescriptor GPUObjectDescriptorBase {required GPUSize64 ;size required GPUBufferUsageFlags ;usage boolean =mappedAtCreation false ; };
5.3. Buffer Usage
typedef [EnforceRange ]unsigned long ;GPUBufferUsageFlags interface {GPUBufferUsage const GPUFlagsConstant = 0x0001;MAP_READ const GPUFlagsConstant = 0x0002;MAP_WRITE const GPUFlagsConstant = 0x0004;COPY_SRC const GPUFlagsConstant = 0x0008;COPY_DST const GPUFlagsConstant = 0x0010;INDEX const GPUFlagsConstant = 0x0020;VERTEX const GPUFlagsConstant = 0x0040;UNIFORM const GPUFlagsConstant = 0x0080;STORAGE const GPUFlagsConstant = 0x0100;INDIRECT const GPUFlagsConstant = 0x0200; };QUERY_RESOLVE
-
createBuffer(descriptor) -
Creates a
GPUBuffer.Called on:GPUDevicethis .Arguments:
Arguments for the GPUDevice.createBuffer(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUBufferDescriptor ✘ ✘ Description of the GPUBufferto create.Returns:
GPUBuffer-
If any of the following conditions are unsatisfied, return an error buffer and stop.
-
descriptor .
usageis a subset of this .[[allowed buffer usages]]. -
If descriptor .
mappedAtCreationistrue:-
descriptor .
sizeis a multiple of 4.
-
Explain that the resulting error buffer can still be mapped at creation. <https://github.com/gpuweb/gpuweb/issues/605>
Explain what are a
GPUDevice's[[allowed buffer usages]]. <https://github.com/gpuweb/gpuweb/issues/605> -
Let b be a new
GPUBufferobject. -
If descriptor .
mappedAtCreationistrue:-
Set b .
[[mapping]]to a newArrayBufferof size b .[[size]]. -
Set b .
[[mapping_range]]to[0, descriptor.size]. -
Set b .
[[mapped_ranges]]to[]. -
Set b .
[[state]]to mapped at creation .
Else:
-
Set b .
[[mapping]]tonull. -
Set b .
[[mapping_range]]tonull. -
Set b .
[[mapped_ranges]]tonull.
-
-
Set each byte of b ’s allocation to zero.
-
Return b .
Note: it is valid to set
mappedAtCreationtotruewithoutMAP_READorMAP_WRITEinusage. This can be used to set the buffer’s initial data. -
5.4. Buffer Destruction
An
application
that
no
longer
requires
a
GPUBuffer
can
choose
to
lose
access
to
it
before
garbage
collection
by
calling
destroy()
.
Note:
This
allows
the
user
agent
to
reclaim
the
GPU
memory
associated
with
the
GPUBuffer
once
all
previously
submitted
operations
using
it
are
complete.
-
destroy() -
Destroys the
GPUBuffer.
5.5. Buffer Mapping
An
application
can
request
to
map
a
GPUBuffer
so
that
they
can
access
its
content
via
ArrayBuffer
s
that
represent
part
of
the
GPUBuffer
's
allocations.
Mapping
a
GPUBuffer
is
requested
asynchronously
with
mapAsync()
so
that
the
user
agent
can
ensure
the
GPU
finished
using
the
GPUBuffer
before
the
application
can
access
its
content.
Once
the
GPUBuffer
is
mapped
the
application
can
synchronously
ask
for
access
to
ranges
of
its
content
with
getMappedRange
.
A
mapped
GPUBuffer
cannot
be
used
by
the
GPU
and
must
be
unmapped
using
unmap
before
work
using
it
can
be
submitted
to
the
Queue
timeline
.
Add
client-side
validation
that
a
mapped
buffer
can
only
be
unmapped
and
destroyed
on
the
worker
on
which
it
was
mapped.
Likewise
getMappedRange
can
only
be
called
on
that
worker.
<https://github.com/gpuweb/gpuweb/issues/605>
typedef [EnforceRange ]unsigned long ;GPUMapModeFlags interface {GPUMapMode const GPUFlagsConstant = 0x0001;READ const GPUFlagsConstant = 0x0002; };WRITE
-
mapAsync(mode, offset, size) -
Maps the given range of the
GPUBufferand resolves the returnedPromisewhen theGPUBuffer's content is ready to be accessed withgetMappedRange().Called on:GPUBufferthis .Arguments:
Arguments for the GPUBuffer.mapAsync(mode, offset, size) method. Parameter Type Nullable Optional Description modeGPUMapModeFlags ✘ ✘ Whether the buffer should be mapped for reading or writing. offsetGPUSize64 ✘ ✔ Offset in bytes into the buffer to the start of the range to map. sizeGPUSize64 ✘ ✔ Size in bytes of the range to map. Returns:
Promise<undefined>Handle error buffers once we have a description of the error monad. <https://github.com/gpuweb/gpuweb/issues/605>
-
If size is unspecified:
-
Let rangeSize be max(0, this .
[[size]]- offset ).
Otherwise, let rangeSize be size .
-
-
If any of the following conditions are unsatisfied:
Then:
-
Record a validation error on the current scope.
-
Return a promise rejected with an
OperationErroron the Device timeline .
-
-
Let p be a new
Promise. -
Set this .
[[mapping]]to p . -
Set this .
[[state]]to mapping pending . -
Set this .
[[map_mode]]to mode . -
Enqueue an operation on the default queue’s Queue timeline that will execute the following:
-
If this .
[[state]]is mapping pending :-
Let m be a new
ArrayBufferof size rangeSize . -
Set the content of m to the content of this ’s allocation starting at offset offset and for rangeSize bytes.
-
Set this .
[[mapping]]to m . -
Set this .
[[mapping_range]]to[ offset , offset + rangeSize ]. -
Set this .
[[mapped_ranges]]to[].
-
-
Resolve p .
-
-
Return p .
-
-
getMappedRange(offset, size) -
Returns a
ArrayBufferwith the contents of theGPUBufferin the given mapped range.Called on:GPUBufferthis .Arguments:
Arguments for the GPUBuffer.getMappedRange(offset, size) method. Parameter Type Nullable Optional Description offsetGPUSize64 ✘ ✔ Offset in bytes into the buffer to return buffer contents from. sizeGPUSize64 ✘ ✔ Size in bytes of the ArrayBufferto return.Returns:
ArrayBuffer-
If size is unspecified:
-
Let rangeSize be max(0, this .
[[size]]- offset ).
Otherwise, let rangeSize be size .
-
-
If any of the following conditions are unsatisfied, throw an
OperationErrorand stop.-
this .
[[state]]is mapped or mapped at creation . -
offset is a multiple of 8.
-
rangeSize is a multiple of 4.
-
offset is greater than or equal to this .
[[mapping_range]][0]. -
offset + rangeSize is less than or equal to this .
[[mapping_range]][1]. -
[ offset , offset + rangeSize ) does not overlap another range in this .
[[mapped_ranges]].
Note: It is always valid to get mapped ranges of a
GPUBufferthat is mapped at creation , even if it is invalid , because the Content timeline might not know it is invalid. -
-
Let m be a new
ArrayBufferof size rangeSize pointing at the content of this .[[mapping]]at offset offset - this .[[mapping_range]][0]. -
Append m to this .
[[mapped_ranges]]. -
Return m .
-
-
unmap() -
Unmaps the mapped range of the
GPUBufferand makes it’s contents available for use by the GPU again.Called on:GPUBufferthis .Returns:
undefined-
If any of the following conditions are unsatisfied, generate a validation error and stop.
Note: It is valid to unmap an error
GPUBufferthat is mapped at creation because the Content timeline might not know it is an errorGPUBuffer. -
If this .
[[state]]is mapping pending :-
Reject
[[mapping]]with anAbortError. -
Set this .
[[mapping]]tonull.
-
-
If this .
[[state]]is mapped or mapped at creation :-
If one of the two following conditions holds:
-
this .
[[state]]is mapped at creation -
this .
[[state]]is mapped and this .[[map_mode]]containsWRITE
Then:
-
Enqueue an operation on the default queue’s Queue timeline that updates the this .
[[mapping_range]]of this ’s allocation to the content of this .[[mapping]].
-
-
Detach each
ArrayBufferin this .[[mapped_ranges]]from its content. -
Set this .
[[mapping]]tonull. -
Set this .
[[mapping_range]]tonull. -
Set this .
[[mapped_ranges]]tonull.
-
Note: When a
MAP_READbuffer (not currently mapped at creation) is unmapped, any local modifications done by the application to the mapped rangesArrayBufferare discarded and will not affect the content of follow-up mappings. -
6. Textures and Texture Views
define texture (internal object)
define mipmap level , array layer , aspect , slice (concepts)
6.1.
GPUTexture
[Serializable ]{interface GPUTexture {GPUTextureView createView (optional GPUTextureViewDescriptor descriptor = {});undefined destroy (); };;GPUTexture includes GPUObjectBase ;
GPUTexture
has
the
following
internal
slots:
-
[[textureSize]]of typeGPUExtent3D. -
The size of the
GPUTexturein texels in mipmap level 0. -
[[mipLevelCount]]of typeGPUIntegerCoordinate. -
The total number of the mipmap levels of the
GPUTexture. -
[[sampleCount]]of typeGPUSize32. -
The number of samples in each texel of the
GPUTexture. -
[[dimension]]of typeGPUTextureDimension. -
The dimension of the
GPUTexture. -
[[format]]of typeGPUTextureFormat. -
The format of the
GPUTexture. -
[[textureUsage]]of typeGPUTextureUsageFlags. -
The allowed usages for this
GPUTexture.
6.1.1. Texture Creation
dictionary :GPUTextureDescriptor GPUObjectDescriptorBase {required GPUExtent3D ;size GPUIntegerCoordinate = 1;mipLevelCount GPUSize32 = 1;sampleCount GPUTextureDimension = "2d";dimension required GPUTextureFormat ;format required GPUTextureUsageFlags ; };usage
enum {GPUTextureDimension ,"1d" ,"2d" };"3d"
typedef [EnforceRange ]unsigned long ;GPUTextureUsageFlags interface {GPUTextureUsage const GPUFlagsConstant = 0x01;COPY_SRC const GPUFlagsConstant = 0x02;COPY_DST const GPUFlagsConstant = 0x04;SAMPLED const GPUFlagsConstant = 0x08;STORAGE const GPUFlagsConstant = 0x10; };RENDER_ATTACHMENT
-
createTexture(descriptor) -
Creates a
GPUTexture.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createTexture(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUTextureDescriptor ✘ ✘ Description of the GPUTextureto create.Returns:
GPUTextureDescribe
createTexture()algorithm steps.
6.1.2. Texture Destruction
An
application
that
no
longer
requires
a
GPUTexture
can
choose
to
lose
access
to
it
before
garbage
collection
by
calling
destroy()
.
Note:
This
allows
the
user
agent
to
reclaim
the
GPU
memory
associated
with
the
GPUTexture
once
all
previously
submitted
operations
using
it
are
complete.
-
destroy() -
Destroys the
GPUTexture.
6.2.
GPUTextureView
interface GPUTextureView { };GPUTextureView includes GPUObjectBase ;
GPUTextureView
has
the
following
internal
slots:
-
[[texture]] -
The
GPUTextureinto which this is a view. -
[[descriptor]] -
The
GPUTextureViewDescriptordescribing this texture view.All optional fields of
GPUTextureViewDescriptorare defined.
6.2.1. Texture View Creation
dictionary :GPUTextureViewDescriptor GPUObjectDescriptorBase {GPUTextureFormat ;format GPUTextureViewDimension ;dimension GPUTextureAspect = "all";aspect GPUIntegerCoordinate = 0;baseMipLevel GPUIntegerCoordinate ;mipLevelCount GPUIntegerCoordinate = 0;baseArrayLayer GPUIntegerCoordinate ; };arrayLayerCount
Make this a standalone algorithm used in the createView algorithm.
The references to GPUTextureDescriptor here should actually refer to internal slots of a texture internal object once we have one.
-
dimension: If unspecified: -
mipLevelCount: If undefined, defaults to texture .mipLevelCount−baseMipLevel. -
arrayLayerCount: If undefined, defaults to texture .size. depth −baseArrayLayer.
enum {GPUTextureViewDimension ,"1d" ,"2d" ,"2d-array" ,"cube" ,"cube-array" };"3d"
enum {GPUTextureAspect ,"all" ,"stencil-only" };"depth-only"
-
createView(descriptor) -
Creates a
GPUTextureView.
GPUTexture
this
.
Arguments:
| Parameter | Type | Nullable | Optional | Description |
|---|---|---|---|---|
descriptor
| GPUTextureViewDescriptor | ✘ | ✔ |
Description
of
the
GPUTextureView
to
create.
|
Returns:
view
,
of
type
GPUTextureView
.
6.3. Texture Formats
The name of the format specifies the order of components, bits per component, and data type for the component.
-
r,g,b,a= red, green, blue, alpha -
unorm= unsigned normalized -
snorm= signed normalized -
uint= unsigned int -
sint= signed int -
float= floating point
If
the
format
has
the
-srgb
suffix,
then
sRGB
conversions
from
gamma
to
linear
and
vice
versa
are
applied
during
the
reading
and
writing
of
color
values
in
the
shader.
Compressed
texture
formats
are
provided
by
features
.
Their
naming
should
follow
the
convention
here,
with
the
texture
name
as
a
prefix.
e.g.
etc2-rgba8unorm
.
The
texel
block
is
a
single
addressable
element
of
the
textures
in
pixel-based
GPUTextureFormat
s,
and
a
single
compressed
block
of
the
textures
in
block-based
compressed
GPUTextureFormat
s.
The texel block width and texel block height specifies the dimension of one texel block .
-
For pixel-based
GPUTextureFormats, the texel block width and texel block height are always 1. -
For block-based compressed
GPUTextureFormats, the texel block width is the number of texels in each row of one texel block , and the texel block height is the number of texel rows in one texel block .
The
texel
block
size
of
a
GPUTextureFormat
is
the
number
of
bytes
to
store
one
texel
block
.
The
texel
block
size
of
each
GPUTextureFormat
is
constant
except
for
"stencil8"
,
"depth24plus"
,
and
"depth24plus-stencil8"
.
enum { // 8-bit formatsGPUTextureFormat ,"r8unorm" ,"r8snorm" ,"r8uint" , // 16-bit formats"r8sint" ,"r16uint" ,"r16sint" ,"r16float" ,"rg8unorm" ,"rg8snorm" ,"rg8uint" , // 32-bit formats"rg8sint" ,"r32uint" ,"r32sint" ,"r32float" ,"rg16uint" ,"rg16sint" ,"rg16float" ,"rgba8unorm" ,"rgba8unorm-srgb" ,"rgba8snorm" ,"rgba8uint" ,"rgba8sint" ,"bgra8unorm" , // Packed 32-bit formats"bgra8unorm-srgb" ,"rgb9e5ufloat" ,"rgb10a2unorm" , // 64-bit formats"rg11b10ufloat" ,"rg32uint" ,"rg32sint" ,"rg32float" ,"rgba16uint" ,"rgba16sint" , // 128-bit formats"rgba16float" ,"rgba32uint" ,"rgba32sint" , // Depth and stencil formats"rgba32float" ,"stencil8" ,"depth16unorm" ,"depth24plus" ,"depth24plus-stencil8" , // BC compressed formats usable if "texture-compression-bc" is both // supported by the device/user agent and enabled in requestDevice."depth32float" ,"bc1-rgba-unorm" ,"bc1-rgba-unorm-srgb" ,"bc2-rgba-unorm" ,"bc2-rgba-unorm-srgb" ,"bc3-rgba-unorm" ,"bc3-rgba-unorm-srgb" ,"bc4-r-unorm" ,"bc4-r-snorm" ,"bc5-rg-unorm" ,"bc5-rg-snorm" ,"bc6h-rgb-ufloat" ,"bc6h-rgb-float" ,"bc7-rgba-unorm" , // "depth24unorm-stencil8" feature"bc7-rgba-unorm-srgb" , // "depth32float-stencil8" feature"depth24unorm-stencil8" , };"depth32float-stencil8"
The
depth
aspect
of
the
"depth24plus"
)
and
"depth24plus-stencil8"
)
formats
may
be
implemented
as
either
a
24-bit
unsigned
normalized
value
("depth24unorm")
or
a
32-bit
IEEE
754
floating
point
value
("depth32float").
add something on GPULimits that gives an estimate of the bytes per texel of "stencil8"
The
stencil8
)
format
may
be
implemented
as
either
a
real
"stencil8",
or
"depth24stencil8",
where
the
depth
aspect
is
hidden
and
inaccessible.
Note: While the precision of depth32float is strictly higher than the precision of depth24unorm for all values in the representable range (0.0 to 1.0), note that the set of representable values is not exactly the same: for depth24unorm, 1 ULP has a constant value of 1 / (2 24 − 1); for depth32float, 1 ULP has a variable value no greater than 1 / (2 24 ).
"rgb9e5ufloat"
cannot
be
used
as
a
color
attachment.
enum {GPUTextureComponentType ,"float" ,"sint" , // Texture is used with comparison sampling only."uint" };"depth-comparison"
7. Samplers
7.1.
GPUSampler
A
GPUSampler
encodes
transformations
and
filtering
information
that
can
be
used
in
a
shader
to
interpret
texture
resource
data.
GPUSamplers
are
created
via
GPUDevice.createSampler(optional
descriptor)
that
returns
a
new
sampler
object.
interface GPUSampler { };GPUSampler includes GPUObjectBase ;
GPUSampler
has
the
following
internal
slots:
-
[[descriptor]], of typeGPUSamplerDescriptor, readonly -
The
GPUSamplerDescriptorwith which theGPUSamplerwas created. -
[[compareEnable]]of typeboolean. -
Whether the
GPUSampleris used as a comparison sampler.
7.2. Sampler Creation
7.2.1.
GPUSamplerDescriptor
A
GPUSamplerDescriptor
specifies
the
options
to
use
to
create
a
GPUSampler
.
dictionary :GPUSamplerDescriptor GPUObjectDescriptorBase {GPUAddressMode = "clamp-to-edge";addressModeU GPUAddressMode = "clamp-to-edge";addressModeV GPUAddressMode = "clamp-to-edge";addressModeW GPUFilterMode = "nearest";magFilter GPUFilterMode = "nearest";minFilter GPUFilterMode = "nearest";mipmapFilter float = 0;lodMinClamp float = 0xffffffff; // TODO: What should this be? Was Number.MAX_VALUE.lodMaxClamp GPUCompareFunction ;compare unsigned short = 1; };maxAnisotropy
-
addressModeU,addressModeV, andaddressModeWspecify the address modes for the texture width, height, and depth coordinates, respectively. -
magFilterspecifies the sampling behavior when the sample footprint is smaller than or equal to one texel. -
minFilterspecifies the sampling behavior when the sample footprint is larger than one texel. -
mipmapFilterspecifies behavior for sampling between two mipmap levels. -
lodMinClampandlodMaxClampspecify the minimum and maximum levels of detail, respectively, used internally when sampling a texture. -
If
compareis provided, the sampler will be a comparison sampler with the specifiedGPUCompareFunction. -
maxAnisotropyspecifies the maximum anisotropy value clamp used by the sampler.Note: most implementations support
maxAnisotropyvalues in range between 1 and 16, inclusive.
explain how LOD is calculated and if there are differences here between platforms. Issue: explain what anisotropic sampling is
GPUAddressMode
describes
the
behavior
of
the
sampler
if
the
sample
footprint
extends
beyond
the
bounds
of
the
sampled
texture.
Describe a "sample footprint" in greater detail.
enum {GPUAddressMode "clamp-to-edge" ,"repeat" ,"mirror-repeat" };
-
"clamp-to-edge" -
Texture coordinates are clamped between 0.0 and 1.0, inclusive.
-
"repeat" -
Texture coordinates wrap to the other side of the texture.
-
"mirror-repeat" -
Texture coordinates wrap to the other side of the texture, but the texture is flipped when the integer part of the coordinate is odd.
GPUFilterMode
describes
the
behavior
of
the
sampler
if
the
sample
footprint
does
not
exactly
match
one
texel.
enum {GPUFilterMode "nearest" ,"linear" };
-
"nearest" -
Return the value of the texel nearest to the texture coordinates.
-
"linear" -
Select two texels in each dimension and return a linear interpolation between their values.
GPUCompareFunction
specifies
the
behavior
of
a
comparison
sampler.
If
a
comparison
sampler
is
used
in
a
shader,
an
input
value
is
compared
to
the
sampled
texture
value,
and
the
result
of
this
comparison
test
(0.0f
for
pass,
or
1.0f
for
fail)
is
used
in
the
filtering
operation.
describe how filtering interacts with comparison sampling.
enum {GPUCompareFunction "never" ,"less" ,"equal" ,"less-equal" ,"greater" ,"not-equal" ,"greater-equal" ,"always" };
-
"never" -
Comparison tests never pass.
-
"less" -
A provided value passes the comparison test if it is less than the sampled value.
-
"equal" -
A provided value passes the comparison test if it is equal to the sampled value.
-
"less-equal" -
A provided value passes the comparison test if it is less than or equal to the sampled value.
-
"greater" -
A provided value passes the comparison test if it is greater than the sampled value.
-
"not-equal" -
A provided value passes the comparison test if it is not equal to the sampled value.
-
"greater-equal" -
A provided value passes the comparison test if it is greater than or equal to the sampled value.
-
"always" -
Comparison tests always pass.
-
GPUDevicedevice -
GPUSamplerDescriptordescriptor
Returns:
boolean
Return
true
if
and
only
if
all
of
the
following
conditions
are
satisfied:
-
device is valid.
-
descriptor .
lodMinClampis greater than or equal to 0. -
descriptor .
lodMaxClampis greater than or equal to descriptor .lodMinClamp.
-
createSampler(descriptor) -
Creates a
GPUBindGroupLayout. -
Let s be a new
GPUSamplerobject. -
Set s .
[[descriptor]]to descriptor . -
Set s .
[[compareEnable]]tofalseif thecompareattribute of s .[[descriptor]]isnullor undefined. Otherwise, set it totrue. -
Return s .
-
If descriptor is not
nullor undefined:-
If validating GPUSamplerDescriptor (this, descriptor ) returns
false:-
Generate a
GPUValidationErrorin the current scope with appropriate error message. -
Create a new invalid
GPUSamplerand return the result.
-
-
GPUDevice
this.
Arguments:
| Parameter | Type | Nullable | Optional | Description |
|---|---|---|---|---|
descriptor
| GPUSamplerDescriptor | ✘ | ✔ |
Description
of
the
GPUSampler
to
create.
|
Returns:
GPUSampler
8. Resource Binding
8.1.
GPUBindGroupLayout
A
GPUBindGroupLayout
defines
the
interface
between
a
set
of
resources
bound
in
a
GPUBindGroup
and
their
accessibility
in
shader
stages.
[Serializable ]interface GPUBindGroupLayout { };GPUBindGroupLayout includes GPUObjectBase ;
8.1.1. Creation
A
GPUBindGroupLayout
is
created
via
GPUDevice.createBindGroupLayout()
.
dictionary :GPUBindGroupLayoutDescriptor GPUObjectDescriptorBase {required sequence <GPUBindGroupLayoutEntry >; };entries
A
GPUBindGroupLayoutEntry
describes
a
single
shader
resource
binding
to
be
included
in
a
GPUBindGroupLayout
.
dictionary {GPUBindGroupLayoutEntry required GPUIndex32 binding ;required GPUShaderStageFlags visibility ;required GPUBindingType type ; // Used for uniform buffer and storage buffer bindings. Must be undefined for other binding types.boolean hasDynamicOffset ; // Used for uniform buffer and storage buffer bindings. Must be undefined for other binding types.GPUSize64 minBufferBindingSize ; // Used for sampled texture and storage texture bindings. Must be undefined for other binding types.GPUTextureViewDimension viewDimension ; // Used for sampled texture bindings. Must be undefined for other binding types.GPUTextureComponentType textureComponentType ; // Used for storage texture bindings. Must be undefined for other binding types.GPUTextureFormat storageTextureFormat ; };
consider
making
textureComponentType
and
storageTextureFormat
truly
optional.
-
binding, of type GPUIndex32 -
A unique identifier for a resource binding within a
GPUBindGroupLayoutEntry, a correspondingGPUBindGroupEntry, and theGPUShaderModules. -
visibility, of type GPUShaderStageFlags -
A bitset of the members of
GPUShaderStage. Each set bit indicates that aGPUBindGroupLayoutEntry's resource will be accessible from the associated shader stage. -
type, of type GPUBindingType -
The type of the binding. The value of this member influences the interpretation of other members.
Note: This member is used to determine compatibility between a
GPUPipelineLayoutand aGPUShaderModule. -
hasDynamicOffset, of type boolean -
If the binding resource type for
typeisGPUBufferBinding:-
This indicates whether a binding requires a dynamic offset.
-
If
undefined, it defaults tofalse.
Otherwise, it must be
undefined. -
-
minBufferBindingSize, of type GPUSize64 -
If the binding resource type for
typeisGPUBufferBinding:-
This may be used to indicate the minimum buffer binding size.
-
If
undefined, it defaults to 0.
Otherwise, it must be
undefined. -
-
viewDimension, of type GPUTextureViewDimension -
If the binding resource type for
typeisGPUTextureView:-
This is the required
dimensionof a texture view bound to this binding. -
If
undefined, it defaults to"2d".
Otherwise, it must be
undefined. -
-
textureComponentType, of type GPUTextureComponentType -
If the
typeis"sampled-texture":-
This is the required component type of the
formatof a texture view bound to this binding. -
If
undefined, it defaults to"float".
Otherwise, it must be
undefined. -
-
storageTextureFormat, of type GPUTextureFormat -
If the
typeis"readonly-storage-texture"or"writeonly-storage-texture":-
This is the required
formatof a texture view bound to this binding.
Otherwise, it must be
undefined. -
Note:
viewDimension
enables
Metal-based
WebGPU
implementations
to
back
the
respective
bind
groups
with
MTLArgumentBuffer
objects
that
are
more
efficient
to
bind
at
run-time.
typedef [EnforceRange ]unsigned long ;GPUShaderStageFlags interface {GPUShaderStage const GPUFlagsConstant = 0x1;VERTEX const GPUFlagsConstant = 0x2;FRAGMENT const GPUFlagsConstant = 0x4; };COMPUTE
-
type: A member ofGPUBindingTypethat indicates the intended usage of a resource binding in its visibleGPUShaderStages.
enum {GPUBindingType ,"uniform-buffer" ,"storage-buffer" ,"readonly-storage-buffer" ,"sampler" ,"comparison-sampler" ,"sampled-texture" ,"multisampled-texture" ,"readonly-storage-texture" };"writeonly-storage-texture"
Each
GPUBindingType
has
an
associated
GPUBindingResource
type
and
internal
usage
,
given
by
this
table:
A
GPUBindGroupLayout
object
has
the
following
internal
slots:
-
[[entryMap]]of type ordered map <GPUSize32,GPUBindGroupLayoutEntry>. -
The map of binding indices pointing to the
GPUBindGroupLayoutEntrys, which thisGPUBindGroupLayoutdescribes. -
[[dynamicOffsetCount]]of typeGPUSize32. -
The number of buffer bindings with dynamic offsets in this
GPUBindGroupLayout.
-
createBindGroupLayout(descriptor) -
Creates a
GPUBindGroupLayout.Called on:GPUDevicethis .Arguments:
Arguments for the GPUDevice.createBindGroupLayout(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUBindGroupLayoutDescriptor ✘ ✘ Description of the GPUBindGroupLayoutto create.Returns:
GPUBindGroupLayout-
Let layout be a new valid
GPUBindGroupLayoutobject. -
Issue the following steps on the Device timeline of this :
-
If any of the following conditions are unsatisfied:
-
The
bindingof each entry in descriptor is unique. -
For each shader stage, the number of entries in descriptor with
type"uniform-buffer"≤GPULimits.maxUniformBuffersPerShaderStage. -
For each shader stage, the number of entries in descriptor with
type"storage-buffer"≤GPULimits.maxStorageBuffersPerShaderStage. -
For each shader stage, the number of entries in descriptor with
type"sampled-texture"≤GPULimits.maxSampledTexturesPerShaderStage. -
For each shader stage, the number of entries in descriptor with
type"readonly-storage-texture"or"writeonly-storage-texture"≤GPULimits.maxStorageTexturesPerShaderStage. -
For each shader stage, the number of entries in descriptor with
type"sampler"≤GPULimits.maxSamplersPerShaderStage. -
The number of entries in descriptor with
type"uniform-buffer"andhasDynamicOffsettrue≤GPULimits.maxDynamicUniformBuffersPerPipelineLayout. -
The number of entries in descriptor with
type"storage-buffer"andhasDynamicOffsettrue≤GPULimits.maxDynamicStorageBuffersPerPipelineLayout. -
For each
GPUBindGroupLayoutEntrybindingDescriptor in descriptor .entries:-
If bindingDescriptor .
visibilityincludesVERTEX:-
bindingDescriptor .
typeis not"storage-buffer"or"writeonly-storage-texture".
-
-
If bindingDescriptor .
typeis not"uniform-buffer","storage-buffer", or"readonly-storage-buffer":-
bindingDescriptor .
hasDynamicOffsetisundefined. -
bindingDescriptor .
minBufferBindingSizeisundefined.
-
-
If bindingDescriptor .
typeis not"sampled-texture","readonly-storage-texture", or"writeonly-storage-texture":-
bindingDescriptor .
viewDimensionisundefined.
-
-
If bindingDescriptor .
typeis not"sampled-texture"or"multisampled-texture":-
bindingDescriptor .
textureComponentTypeisundefined.
-
-
If bindingDescriptor .
typeis not"readonly-storage-texture"or"writeonly-storage-texture":-
bindingDescriptor .
storageTextureFormatisundefined.
-
-
If bindingDescriptor .
typeis"multisampled-texture":-
bindingDescriptor .
viewDimensionis2d. -
bindingDescriptor .
textureComponentTypeis notdepth-comparison.
-
-
If bindingDescriptor .
typeis"readonly-storage-texture"or"writeonly-storage-texture":-
bindingDescriptor .
viewDimensionis notcubeorcube-array. -
bindingDescriptor .
storageTextureFormatmust be a format which can support storage usage.
-
-
Then:
-
Generate a
GPUValidationErrorin the current scope with appropriate error message. -
Make layout invalid and return layout .
-
Set layout .
[[dynamicOffsetCount]]to the number of entries in descriptor wherehasDynamicOffsetistrue. -
For each
GPUBindGroupLayoutEntrybindingDescriptor in descriptor .entries:-
Insert bindingDescriptor into layout .
[[entryMap]]with the key of bindingDescriptor .binding.
Add a step to bake the default values (e.g.
viewDimensionto "2d") into the bindingDescriptor . -
-
-
Return layout .
-
8.1.2. Compatibility
GPUBindGroupLayout
objects
a
and
b
are
considered
group-equivalent
if
and
only
if,
for
any
binding
number
binding
,
one
of
the
following
conditions
is
satisfied:
-
it’s missing from both a .
[[entryMap]]and b .[[entryMap]]. -
a .
[[entryMap]][ binding ] == b .[[entryMap]][ binding ]
If bind groups layouts are group-equivalent they can be interchangeably used in all contents.
8.2.
GPUBindGroup
A
GPUBindGroup
defines
a
set
of
resources
to
be
bound
together
in
a
group
and
how
the
resources
are
used
in
shader
stages.
interface GPUBindGroup { };GPUBindGroup includes GPUObjectBase ;
8.2.1. Bind Group Creation
A
GPUBindGroup
is
created
via
GPUDevice.createBindGroup()
.
dictionary :GPUBindGroupDescriptor GPUObjectDescriptorBase {required GPUBindGroupLayout ;layout required sequence <GPUBindGroupEntry >; };entries
A
GPUBindGroupEntry
describes
a
single
resource
to
be
bound
in
a
GPUBindGroup
.
typedef (GPUSampler or GPUTextureView or GPUBufferBinding );GPUBindingResource dictionary {GPUBindGroupEntry required GPUIndex32 ;binding required GPUBindingResource ; };resource
dictionary {GPUBufferBinding required GPUBuffer ;buffer GPUSize64 = 0;offset GPUSize64 ; };size
A
GPUBindGroup
object
has
the
following
internal
slots:
-
[[layout]]of typeGPUBindGroupLayout. -
The
GPUBindGroupLayoutassociated with thisGPUBindGroup. -
[[entries]]of type sequence<GPUBindGroupEntry>. -
The set of
GPUBindGroupEntrys thisGPUBindGroupdescribes. -
[[usedResources]]of type ordered map < subresource , list < internal usage >>. -
The set of buffer and texture subresource s used by this bind group, associated with lists of the internal usage flags.
-
createBindGroup(descriptor) -
Creates a
GPUBindGroup.Called on:GPUDevicethis .Arguments:
Arguments for the GPUDevice.createBindGroup(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUBindGroupDescriptor ✘ ✘ Description of the GPUBindGroupto create.Returns:
GPUBindGroup-
Let bindGroup be a new valid
GPUBindGroupobject. -
Issue the following steps on the Device timeline of this :
-
If any of the following conditions are unsatisfied:
-
descriptor .
layoutis valid to use with this . -
The number of
entriesof descriptor .layoutis exactly equal to the number of descriptor .entries.
For each
GPUBindGroupEntrybindingDescriptor in descriptor .entries:-
Let resource be bindingDescriptor .
resource. -
Let bindingType be layoutBinding .
type. -
There is exactly one
GPUBindGroupLayoutEntrylayoutBinding in descriptor .layout.entriessuch that layoutBinding .bindingequals to bindingDescriptor .binding. -
If the binding resource type for bindingType is
-
GPUSampler -
-
resource is a
GPUSampler. -
resource is valid to use with this .
-
If bindingType is
-
"sampler" -
resource .
[[compareEnable]]isfalse. -
"comparison-sampler" -
resource .
[[compareEnable]]istrue.
-
-
-
GPUTextureView -
-
resource is a
GPUTextureView. -
resource is valid to use with this .
-
Let texture be resource .
[[texture]]. -
layoutBinding .
viewDimensionis equal to resource ’sdimension. -
If bindingType is
"multisampled-texture"texture ’ssampleCount>1, Otherwise texture ’ssampleCountis1. -
If bindingType is
-
"sampled-texture"or"multisampled-texture" -
layoutBinding .
textureComponentTypeis compatible with resource ’sformat. -
"readonly-storage-texture"or"writeonly-storage-texture" -
resource .
[[descriptor]].formatis equal to layoutBinding .storageTextureFormat.
-
-
-
GPUBufferBinding -
-
resource is a
GPUBufferBinding. -
resource .
bufferis valid to use with this . -
The bound part designated by resource .
offsetand resource .sizeresides inside the buffer. -
If layoutBinding .
minBufferBindingSizeis notundefined:-
The effective binding size, that is either explict in resource .
sizeor derived from resource .offsetand the full size of the buffer, is greater than or equal to layoutBinding .minBufferBindingSize.
-
-
If bindingType is
-
"uniform-buffer" -
resource .
buffer.usageincludesUNIFORM.resource .
size≤maxUniformBufferBindingSize.This validation should take into account the default when
sizeis not set. Also shouldsizedefault to thebuffer.byteLength - offsetormin(buffer.byteLength - offset, limits.maxUniformBufferBindingSize)? -
"storage-buffer"or"readonly-storage-buffer" -
resource .
buffer.usageincludesSTORAGE.resource .
size≤maxStorageBufferBindingSize.
-
-
-
define the association between texture formats and component types
Then:
-
Generate a
GPUValidationErrorin the current scope with appropriate error message. -
Make bindGroup invalid and return bindGroup .
-
Let bindGroup .
[[layout]]= descriptor .layout. -
Let bindGroup .
[[entries]]= descriptor .entries. -
Let bindGroup .
[[usedResources]]= {}. -
For each
GPUBindGroupEntrybindingDescriptor in descriptor .entries:-
Let internalUsage be the binding usage for layoutBinding .
type. -
Each subresource seen by resource is added to
[[usedResources]]as internalUsage .
-
-
-
Return bindGroup .
-
8.3.
GPUPipelineLayout
A
GPUPipelineLayout
defines
the
mapping
between
resources
of
all
GPUBindGroup
objects
set
up
during
command
encoding
in
setBindGroup
,
and
the
shaders
of
the
pipeline
set
by
GPURenderEncoderBase.setPipeline
or
GPUComputePassEncoder.setPipeline
.
The full binding address of a resource can be defined as a trio of:
-
shader stage mask, to which the resource is visible
-
bind group index
-
binding number
The
components
of
this
address
can
also
be
seen
as
the
binding
space
of
a
pipeline.
A
GPUBindGroup
(with
the
corresponding
GPUBindGroupLayout
)
covers
that
space
for
a
fixed
bind
group
index.
The
contained
bindings
need
to
be
a
superset
of
the
resources
used
by
the
shader
at
this
bind
group
index.
[Serializable ]interface GPUPipelineLayout { };GPUPipelineLayout includes GPUObjectBase ;
GPUPipelineLayout
has
the
following
internal
slots:
-
[[bindGroupLayouts]]of type list <GPUBindGroupLayout>. -
The
GPUBindGroupLayoutobjects provided at creation inGPUPipelineLayoutDescriptor.bindGroupLayouts.
Note:
using
the
same
GPUPipelineLayout
for
many
GPURenderPipeline
or
GPUComputePipeline
pipelines
guarantees
that
the
user
agent
doesn’t
need
to
rebind
any
resources
internally
when
there
is
a
switch
between
these
pipelines.
GPUComputePipeline
object
X
was
created
with
GPUPipelineLayout.bindGroupLayouts
A,
B,
C.
GPUComputePipeline
object
Y
was
created
with
GPUPipelineLayout.bindGroupLayouts
A,
D,
C.
Supposing
the
command
encoding
sequence
has
two
dispatches:
In
this
scenario,
the
user
agent
would
have
to
re-bind
the
group
slot
2
for
the
second
dispatch,
even
though
neither
the
GPUBindGroupLayout
at
index
2
of
GPUPipelineLayout.bindGrouplayouts
,
or
the
GPUBindGroup
at
slot
2,
change.
should this example and the note be moved to some "best practices" document?
Note:
the
expected
usage
of
the
GPUPipelineLayout
is
placing
the
most
common
and
the
least
frequently
changing
bind
groups
at
the
"bottom"
of
the
layout,
meaning
lower
bind
group
slot
numbers,
like
0
or
1.
The
more
frequently
a
bind
group
needs
to
change
between
draw
calls,
the
higher
its
index
should
be.
This
general
guideline
allows
the
user
agent
to
minimize
state
changes
between
draw
calls,
and
consequently
lower
the
CPU
overhead.
8.3.1. Creation
A
GPUPipelineLayout
is
created
via
GPUDevice.createPipelineLayout()
.
dictionary :GPUPipelineLayoutDescriptor GPUObjectDescriptorBase {required sequence <GPUBindGroupLayout >; };bindGroupLayouts
-
createPipelineLayout(descriptor) -
Creates a
GPUPipelineLayout.Called on:GPUDevicethis .Arguments:
Arguments for the GPUDevice.createPipelineLayout(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUPipelineLayoutDescriptor ✘ ✘ Description of the GPUPipelineLayoutto create.Returns:
GPUPipelineLayout-
If any of the following conditions are unsatisfied:
-
There is
GPULimits.maxBindGroupsor fewer elements in descriptor .bindGroupLayouts. -
Every
GPUBindGroupLayoutin descriptor .bindGroupLayoutsis valid to use with this .
Then:
-
Generate a
GPUValidationErrorin the current scope with appropriate error message. -
Create a new invalid
GPUPipelineLayoutand return the result.
-
Let pl be a new
GPUPipelineLayoutobject. -
Set the pl .
[[bindGroupLayouts]]to descriptor .bindGroupLayouts. -
Return pl .
there will be more limits applicable to the whole pipeline layout.
-
Note:
two
GPUPipelineLayout
objects
are
considered
equivalent
for
any
usage
if
their
internal
[[bindGroupLayouts]]
sequences
contain
GPUBindGroupLayout
objects
that
are
group-equivalent
.
9. Shader Modules
9.1.
GPUShaderModule
enum {GPUCompilationMessageType ,"error" ,"warning" }; ["info" Serializable ]interface {GPUCompilationMessage readonly attribute DOMString ;message readonly attribute GPUCompilationMessageType ;type readonly attribute unsigned long long ;lineNum readonly attribute unsigned long long ; }; [linePos Serializable ]interface {GPUCompilationInfo readonly attribute FrozenArray <GPUCompilationMessage >; }; [messages Serializable ]interface GPUShaderModule {Promise <GPUCompilationInfo >compilationInfo (); };GPUShaderModule includes GPUObjectBase ;
GPUShaderModule
is
Serializable
.
It
is
a
reference
to
an
internal
shader
module
object,
and
Serializable
means
that
the
reference
can
be
copied
between
realms
(threads/workers),
allowing
multiple
realms
to
access
it
concurrently.
Since
GPUShaderModule
is
immutable,
there
are
no
race
conditions.
9.1.1. Shader Module Creation
dictionary :GPUShaderModuleDescriptor GPUObjectDescriptorBase {required USVString ;code object ; };sourceMap
sourceMap
,
if
defined,
MAY
be
interpreted
as
a
source-map-v3
format.
(https://sourcemaps.info/spec.html)
Source
maps
are
optional,
but
serve
as
a
standardized
way
to
support
dev-tool
integration
such
as
source-language
debugging.
-
createShaderModule(descriptor) -
Creates a
GPUShaderModule.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createShaderModule(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUShaderModuleDescriptor ✘ ✘ Description of the GPUShaderModuleto create.Returns:
GPUShaderModuleDescribe
createShaderModule()algorithm steps.
9.1.2. Shader Module Compilation Information
-
compilationInfo() -
Returns any messages generated during the
GPUShaderModule's compilation.Called on:GPUShaderModulethis.Returns:
Promise<GPUCompilationInfo>Describe
compilationInfo()algorithm steps.
10. Pipelines
A
pipeline
,
be
it
GPUComputePipeline
or
GPURenderPipeline
,
represents
the
complete
function
done
by
a
combination
of
the
GPU
hardware,
the
driver,
and
the
user
agent,
that
process
the
input
data
in
the
shape
of
bindings
and
vertex
buffers,
and
produces
some
output,
like
the
colors
in
the
output
render
targets.
Structurally, the pipeline consists of a sequence of programmable stages (shaders) and fixed-function states, such as the blending modes.
Note: Internally, depending on the target platform, the driver may convert some of the fixed-function states into shader code, and link it together with the shaders provided by the user. This linking is one of the reason the object is created as a whole.
This
combination
state
is
created
as
a
single
object
(by
GPUDevice.createComputePipeline()
or
GPUDevice.createRenderPipeline()
),
and
switched
as
one
(by
GPUComputePassEncoder.setPipeline
or
GPURenderEncoderBase.setPipeline
correspondingly).
10.1. Base pipelines
dictionary :GPUPipelineDescriptorBase GPUObjectDescriptorBase {GPUPipelineLayout ; };layout interface mixin {GPUPipelineBase GPUBindGroupLayout getBindGroupLayout (unsigned long index ); };
GPUPipelineBase
has
the
following
internal
slots:
-
[[layout]]of typeGPUPipelineLayout. -
The definition of the layout of resources which can be used with
this.
GPUPipelineBase
has
the
following
methods:
-
getBindGroupLayout(index) -
Gets a
GPUBindGroupLayoutthat is compatible with theGPUPipelineBase'sGPUBindGroupLayoutatindex.Called on:GPUPipelineBasethis .Arguments:
Arguments for the GPUPipelineBase.getBindGroupLayout(index) method. Parameter Type Nullable Optional Description indexunsigned long ✘ ✘ Index into the pipeline layout’s [[bindGroupLayouts]]sequence.Returns:
GPUBindGroupLayout-
If index is greater or equal to
maxBindGroups:-
Throw a
RangeError.
-
-
If this is not valid :
-
Return a new error
GPUBindGroupLayout.
-
-
Return a new
GPUBindGroupLayoutobject that references the same internal object as this .[[layout]].[[bindGroupLayouts]][ index ].
Specify this more properly once we have internal objects for
GPUBindGroupLayout. Alternatively only spec is as a new internal objects that’s group-equivalentNote: Only returning new
GPUBindGroupLayoutobjects ensures no synchronization is necessary between the Content timeline and the Device timeline . -
10.1.1. Default pipeline layout
A
GPUPipelineBase
object
that
was
created
without
a
layout
has
a
default
layout
created
and
used
instead.
-
Let groupDescs be a sequence of device .
[[limits]].maxBindGroupsnewGPUBindGroupLayoutDescriptorobjects. -
For each groupDesc in groupDescs :
-
Set groupDesc .
entriesto an empty sequence.
-
-
For each
GPUProgrammableStageDescriptorstageDesc in the descriptor used to create the pipeline:-
Let stageInfo be the "reflection information" for stageDesc .
Define the reflection information concept so that this spec can interface with the WGSL spec and get information what the interface is for a
GPUShaderModulefor a specific entrypoint. -
Let shaderStage be the
GPUShaderStageFlagsfor stageDesc .entryPointin stageDesc .module. -
For each resource resource in stageInfo ’s resource interface:
-
Let group be resource ’s "group" decoration.
-
Let binding be resource ’s "binding" decoration.
-
Let entry be a new
GPUBindGroupLayoutEntry. -
Set entry .
bindingto binding . -
Set entry .
visibilityto shaderStage . -
If resource is for a sampler binding:
-
If resource is for a comparison sampler binding:
-
Set entry .
typeto"comparison-sampler".
-
-
If resource is for a buffer binding:
-
Set entry .
hasDynamicOffsettofalse. -
Set entry .
minBufferBindingSizeto resource ’s minimum buffer binding size.link to a definition for "minimum buffer binding size" in the "reflection information".
-
If resource is for a uniform buffer:
-
Set entry .
typeto"uniform-buffer".
-
-
If resource is for a read-only storage buffer:
-
Set entry .
typeto"readonly-storage-buffer".
-
-
If resource is for a storage buffer:
-
Set entry .
typeto"storage-buffer".
-
-
-
If resource is for a texture binding:
-
Set entry .
textureComponentTypeto resource ’s component type. -
Set entry .
viewDimensionto resource ’s dimension. -
If resource is for a multisampled texture:
-
Set entry .
typeto"multisampled-texture".
-
-
If resource is for a single-sampled texture:
-
Set entry .
typeto"sampled-texture".
-
-
If resource is for a read-only storage texture:
-
Set entry .
typeto"readonly-storage-texture". -
Set entry .
storageTextureFormatto resource ’s format.
-
-
If resource is for a write-only storage texture:
-
Set entry .
typeto"writeonly-storage-texture". -
Set entry .
storageTextureFormatto resource ’s format.
-
-
-
If groupDescs [ group ] has an entry previousEntry with
bindingequal to binding :-
If entry has different
visibilitythan previousEntry :-
Add the bits set in entry .
visibilityinto previousEntry .visibility
-
-
If entry has greater
minBufferBindingSizethan previousEntry :-
Set previousEntry .
minBufferBindingSizeto entry .minBufferBindingSize.
-
-
If any other property is unequal between entry and previousEntry :
-
Return
null(which will cause the creation of the pipeline to fail).
-
-
-
Else
-
Append entry to groupDescs [ group ].
-
-
-
-
Let groupLayouts be a new sequence.
-
For each groupDesc in groupDescs :
-
Append device .
createBindGroupLayout()( groupDesc ) to groupLayouts .
-
-
Let desc be a new
GPUPipelineLayoutDescriptor. -
Set desc .
bindGroupLayoutsto groupLayouts . -
Return device .
createPipelineLayout()( desc ).
This fills the pipeline layout with empty bindgroups. Revisit once the behavior of empty bindgroups is specified.
10.1.2.
GPUProgrammableStageDescriptor
dictionary GPUProgrammableStageDescriptor {required GPUShaderModule ;module required USVString ; };entryPoint
A
GPUProgrammableStageDescriptor
describes
the
entry
point
in
the
user-provided
GPUShaderModule
that
controls
one
of
the
programmable
stages
of
a
pipeline
.
-
GPUShaderStagestage -
GPUProgrammableStageDescriptordescriptor -
GPUPipelineLayoutlayout
-
If the descriptor .
moduleis not a validGPUShaderModulereturnfalse. -
If the descriptor .
moduledoesn’t contain an entry point at stage named descriptor .entryPointreturnfalse. -
For each binding that is statically used by the shader entry point, if the result of validating shader binding ( binding , layout ) is
false, returnfalse. -
Return
true.
-
shader binding , reflected from the shader module
-
GPUPipelineLayoutlayout
Consider the shader binding annotation of bindIndex for the binding index and bindGroup for the bind group index.
Return
true
if
all
of
the
following
conditions
are
satisfied:
-
layout .
[[bindGroupLayouts]][ bindGroup ] contains aGPUBindGroupLayoutEntryentry whose entry .binding== bindIndex . -
If entry .
typeis:-
"sampler" -
the binding is a non-comparison sampler
-
"comparison-sampler" -
the binding is a comparison sampler
-
"sampled-texture" -
the binding is a sampled texture with the component type of entry .
textureComponentTypeand it has to have a sample count of 1. -
"multisampled-texture" -
the binding is a multisampled texture with the component type of entry .
textureComponentType. -
"readonly-storage-texture" -
the binding is a read-only storage texture with format of entry .
storageTextureFormat -
"writeonly-storage-texture" -
the binding is a writable storage texture with format of entry .
storageTextureFormat -
"uniform-buffer" -
the binding is a uniform buffer
-
"storage-buffer" -
the binding is a storage buffer
-
"readonly-storage-buffer" -
the binding is a read-only storage buffer
-
-
If entry .
typeis"sampled-texture","readonly-storage-texture", or"writeonly-storage-texture", the shader view dimension of the texture has to match entry .viewDimension. -
If entry .
minBufferBindingSizeis not undefined:-
If the last field of the corresponding structure defined in the shader has an unbounded array type, then the value of entry .
minBufferBindingSizemust be greater than or equal to the byte offset of that field plus the stride of the unbounded array. -
If the corresponding shader structure doesn’t end with an unbounded array type, then the value of entry .
minBufferBindingSizemust be greater than or equal to the size of the structure.
-
is there a match/switch statement in bikeshed?
A resource binding is considered to be statically used by a shader entry point if and only if it’s reachable by the control flow graph of the shader module, starting at the entry point.
10.2.
GPUComputePipeline
A
GPUComputePipeline
is
a
kind
of
pipeline
that
controls
the
compute
shader
stage,
and
can
be
used
in
GPUComputePassEncoder
.
Compute
inputs
and
outputs
are
all
contained
in
the
bindings,
according
to
the
given
GPUPipelineLayout
.
The
outputs
correspond
to
"storage-buffer"
and
"writeonly-storage-texture"
binding
types.
Stages of a compute pipeline :
-
Compute shader
[Serializable ]interface GPUComputePipeline { };GPUComputePipeline includes GPUObjectBase ;GPUComputePipeline includes GPUPipelineBase ;
10.2.1. Creation
dictionary :GPUComputePipelineDescriptor GPUPipelineDescriptorBase {required GPUProgrammableStageDescriptor ; };computeStage
-
createComputePipeline(descriptor) -
Creates a
GPUComputePipeline.Called on:GPUDevicethis .Arguments:
Arguments for the GPUDevice.createComputePipeline(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUComputePipelineDescriptor ✘ ✘ Description of the GPUComputePipelineto create.Returns:
GPUComputePipelineIf any of the following conditions are unsatisfied:
-
descriptor .
layoutis valid to use with this . -
validating GPUProgrammableStageDescriptor (
COMPUTE, descriptor .computeStage, descriptor .layout) succeeds.
Then:
-
Generate a
GPUValidationErrorin the current scope with appropriate error message. -
Create a new invalid
GPUComputePipelineand return the result.
-
createReadyComputePipeline(descriptor) -
Creates a
GPUComputePipeline. The returnedPromiseresolves when the created pipeline is ready to be used without additional delay.If pipeline creation fails, the returned
Promiseresolves to an invalidGPUComputePipelineobject.Note: Use of this method is preferred whenever possible, as it prevents blocking the queue timeline work on pipeline compilation.
Called on:GPUDevicethis .Arguments:
Arguments for the GPUDevice.createReadyComputePipeline(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUComputePipelineDescriptor ✘ ✘ Description of the GPUComputePipelineto create.Returns:
Promise<GPUComputePipeline>-
Let promise be a new promise .
-
Issue the following steps on the Device timeline of this :
-
Let pipeline be a new
GPUComputePipelinecreated as if this .createComputePipeline()was called with descriptor ; -
When pipeline is ready to be used, resolve promise with pipeline .
-
-
Return promise .
-
10.3.
GPURenderPipeline
A
GPURenderPipeline
is
a
kind
of
pipeline
that
controls
the
vertex
and
fragment
shader
stages,
and
can
be
used
in
GPURenderPassEncoder
as
well
as
GPURenderBundleEncoder
.
Render pipeline inputs are:
-
bindings, according to the given
GPUPipelineLayout -
vertex and index buffers, described by
GPUVertexStateDescriptor -
the color attachments, described by
GPUColorStateDescriptor -
optionally, the depth-stencil attachment, described by
GPUDepthStencilStateDescriptor
Render pipeline outputs are:
-
bindings of types
"storage-buffer"and"writeonly-storage-texture" -
the color attachments, described by
GPUColorStateDescriptor -
optionally, depth-stencil attachment, described by
GPUDepthStencilStateDescriptor
Stages of a render pipeline :
-
Vertex fetch, controlled by
GPUVertexStateDescriptor -
Vertex shader
-
Primitive assembly, controlled by
GPUPrimitiveTopology -
Rasterization, controlled by
GPURasterizationStateDescriptor -
Fragment shader
-
Stencil test and operation, controlled by
GPUDepthStencilStateDescriptor -
Depth test and write, controlled by
GPUDepthStencilStateDescriptor -
Output merging, controlled by
GPUColorStateDescriptor
we need a deeper description of these stages
[Serializable ]interface GPURenderPipeline { };GPURenderPipeline includes GPUObjectBase ;GPURenderPipeline includes GPUPipelineBase ;
GPURenderPipeline
has
the
following
internal
slots:
-
[[descriptor]], of typeGPURenderPipelineDescriptor -
The
GPURenderPipelineDescriptordescribing this pipeline.All optional fields of
GPURenderPipelineDescriptorare defined. -
[[strip_index_format]], of typeGPUIndexFormat? -
The format index data this pipeline requires, initially
undefined.
10.3.1. Creation
dictionary :GPURenderPipelineDescriptor GPUPipelineDescriptorBase {required GPUProgrammableStageDescriptor ;vertexStage GPUProgrammableStageDescriptor ;fragmentStage required GPUPrimitiveTopology ;primitiveTopology GPURasterizationStateDescriptor = {};rasterizationState required sequence <GPUColorStateDescriptor >;colorStates GPUDepthStencilStateDescriptor ;depthStencilState GPUVertexStateDescriptor = {};vertexState GPUSize32 = 1;sampleCount GPUSampleMask = 0xFFFFFFFF;sampleMask boolean =alphaToCoverageEnabled false ; };
-
vertexStagedescribes the vertex shader entry point of the pipeline -
fragmentStagedescribes the fragment shader entry point of the pipeline . If it’snull, the § 10.3.2 No Color Output mode is enabled. -
primitiveTopologyconfigures the primitive assembly stage of the pipeline . -
rasterizationStateconfigures the rasterization stage of the pipeline . -
colorStatesdescribes the color attachments that are written by the pipeline . -
depthStencilStatedescribes the optional depth-stencil attachment that is written by the pipeline . -
vertexStateconfigures the vertex fetch stage of the pipeline . -
sampleCountis the number of MSAA samples that each attachment has to have. -
sampleMaskis a binary mask of MSAA samples, according to § 10.3.4 Sample Masking . -
alphaToCoverageEnabledenables the § 10.3.3 Alpha to Coverage mode.
Refactor the shape of the render pipeline descriptor to clearly enumerate the (ordered) list of pipeline stages. And start formalizing the spec text.
10.3.2. No Color Output
In
no-color-output
mode,
pipeline
does
not
produce
any
color
attachment
outputs,
and
the
colorStates
is
expected
to
be
empty.
The pipeline still performs rasterization and produces depth values based on the vertex position output. The depth testing and stencil operations can still be used.
10.3.3. Alpha to Coverage
In
alpha-to-coverage
mode,
an
additional
alpha-to-coverage
mask
of
MSAA
samples
is
generated
based
on
the
alpha
component
of
the
fragment
shader
output
value
of
the
colorStates
[0].
The algorithm of producing the extra mask is platform-dependent and can vary for different pixels. It guarantees that:
-
if alpha is 0.0 or less, the result is 0x0
-
if alpha is 1.0 or greater, the result is 0xFFFFFFFF
-
if alpha is greater than some other alpha1 , then the produced sample mask has at least as many bits set to 1 as the mask for alpha1
10.3.4. Sample Masking
The
final
sample
mask
for
a
pixel
is
computed
as:
rasterization
mask
&
sampleMask
&
shader-output
mask
.
Only
the
lower
sampleCount
bits
of
the
mask
are
considered.
If the least-significant bit at position N of the final sample mask has value of "0", the sample color outputs (corresponding to sample N ) to all attachments of the fragment shader are discarded. Also, no depth test or stencil operations are executed on the relevant samples of the depth-stencil attachment.
Note: the color output for sample N is produced by the fragment shader execution with SV_SampleIndex == N for the current pixel. If the fragment shader doesn’t use this semantics, it’s only executed once per pixel.
The rasterization mask is produced by the rasterization stage, based on the shape of the rasterized polygon. The samples incuded in the shape get the relevant bits 1 in the mask.
The
shader-output
mask
takes
the
output
value
of
SV_Coverage
semantics
in
the
fragment
shader.
If
the
semantics
is
not
statically
used
by
the
shader,
and
alphaToCoverageEnabled
is
enabled,
the
shader-output
mask
becomes
the
alpha-to-coverage
mask
.
Otherwise,
it
defaults
to
0xFFFFFFFF.
link to the semantics of SV_SampleIndex and SV_Coverage in WGSL spec.
-
createRenderPipeline(descriptor) -
Creates a
GPURenderPipeline.Called on:GPUDevicethis .Arguments:
Arguments for the GPUDevice.createRenderPipeline(descriptor) method. Parameter Type Nullable Optional Description descriptorGPURenderPipelineDescriptor ✘ ✘ Description of the GPURenderPipelineto create.Returns:
GPURenderPipeline-
Let pipeline be a new valid
GPURenderPipelineobject. -
Issue the following steps on the Device timeline of this :
-
If any of the following conditions are unsatisfied:
-
descriptor .
layoutis valid to use with this . -
validating GPUProgrammableStageDescriptor (
VERTEX, descriptor .vertexStage, descriptor .layout) succeeds. -
If descriptor .
fragmentStageis notnull:-
validating GPUProgrammableStageDescriptor (
FRAGMENT, descriptor .fragmentStage, descriptor .layout) succeeds.
-
-
descriptor .
colorStates.length is less than or equal to 4. -
Each colorState layout descriptor in the list descriptor .
colorStatespasses validating GPUColorStateDescriptor ( colorState ). -
validating GPUVertexStateDescriptor ( descriptor .
vertexState, descriptor .vertexStage) passes. -
If descriptor .
alphaToCoverageEnabledistrue:-
descriptor .
sampleCountis greater than 1.
-
-
If the output SV_Coverage semantics is statically used by descriptor .
fragmentStage:-
descriptor .
alphaToCoverageEnabledisfalse.
-
-
If descriptor .
primitiveTopologyis:-
"line-strip"or"triangle-strip" -
descriptor .
vertexState.indexFormatis notundefined - Otherwise
-
descriptor .
vertexState.indexFormatisundefined
-
Then:
-
Generate a
GPUValidationErrorin the current scope with appropriate error message. -
Make pipeline invalid .
-
Set pipeline .
[[descriptor]]to descriptor . -
If descriptor .
primitiveTopologyis"line-strip"or"triangle-strip":-
Set pipeline .
[[strip_index_format]]to descriptor .vertexState.indexFormat.
-
-
-
Return pipeline .
need a proper limit for the maximum number of color targets.
-
-
createReadyRenderPipeline(descriptor) -
Creates a
GPURenderPipeline. The returnedPromiseresolves when the created pipeline is ready to be used without additional delay.If pipeline creation fails, the returned
Promiseresolves to an invalidGPURenderPipelineobject.Note: Use of this method is preferred whenever possible, as it prevents blocking the queue timeline work on pipeline compilation.
Called on:GPUDevicethis .Arguments:
Arguments for the GPUDevice.createReadyRenderPipeline(descriptor) method. Parameter Type Nullable Optional Description descriptorGPURenderPipelineDescriptor ✘ ✘ Description of the GPURenderPipelineto create.Returns:
Promise<GPURenderPipeline>-
Let promise be a new promise .
-
Issue the following steps on the Device timeline of this :
-
Let pipeline be a new
GPURenderPipelinecreated as if this .createRenderPipeline()was called with descriptor ; -
When pipeline is ready to be used, resolve promise with pipeline .
-
-
Return promise .
-
10.3.5. Primitive Topology
enum {GPUPrimitiveTopology ,"point-list" ,"line-list" ,"line-strip" ,"triangle-list" };"triangle-strip"
10.3.6. Rasterization State
dictionary {GPURasterizationStateDescriptor GPUFrontFace = "ccw";frontFace GPUCullMode = "none"; // Enable depth clamping (requires "depth-clamping" feature)cullMode boolean =clampDepth false ;GPUDepthBias = 0;depthBias float = 0;depthBiasSlopeScale float = 0; };depthBiasClamp
-
If device is lost return
false. -
If descriptor .
clampDepthistrueand device .[[features]]doesn’t contain"depth-clamping", returnfalse. -
Return
true.
enum {GPUFrontFace ,"ccw" };"cw"
enum {GPUCullMode ,"none" ,"front" };"back"
10.3.7. Color State
dictionary {GPUColorStateDescriptor required GPUTextureFormat ;format GPUBlendDescriptor = {};alphaBlend GPUBlendDescriptor = {};colorBlend GPUColorWriteFlags = 0xF; // GPUColorWrite.ALL };writeMask
typedef [EnforceRange ]unsigned long ;GPUColorWriteFlags interface {GPUColorWrite const GPUFlagsConstant = 0x1;RED const GPUFlagsConstant = 0x2;GREEN const GPUFlagsConstant = 0x4;BLUE const GPUFlagsConstant = 0x8;ALPHA const GPUFlagsConstant = 0xF; };ALL
10.3.7.1. Blend State
dictionary {GPUBlendDescriptor GPUBlendFactor = "one";srcFactor GPUBlendFactor = "zero";dstFactor GPUBlendOperation = "add"; };operation
enum {GPUBlendFactor ,"zero" ,"one" ,"src-color" ,"one-minus-src-color" ,"src-alpha" ,"one-minus-src-alpha" ,"dst-color" ,"one-minus-dst-color" ,"dst-alpha" ,"one-minus-dst-alpha" ,"src-alpha-saturated" ,"blend-color" };"one-minus-blend-color"
enum {GPUBlendOperation ,"add" ,"subtract" ,"reverse-subtract" ,"min" };"max"
-
GPUColorStateDescriptordescriptor
Return
true
,
if
and
only
if,
all
of
the
following
conditions
are
satisfied:
-
descriptor .
formatis listed in {#plain-color-formats} withRENDER_ATTACHMENTcapability. -
descriptor .
alphaBlendand descriptor .colorBlendare either both defaults, or descriptor .formathas"float"component type. -
descriptor .
writeMaskis less than 16.
10.3.8. Depth/Stencil State
dictionary {GPUDepthStencilStateDescriptor required GPUTextureFormat ;format boolean =depthWriteEnabled false ;GPUCompareFunction = "always";depthCompare GPUStencilStateFaceDescriptor = {};stencilFront GPUStencilStateFaceDescriptor = {};stencilBack GPUStencilValue = 0xFFFFFFFF;stencilReadMask GPUStencilValue = 0xFFFFFFFF; };stencilWriteMask
dictionary {GPUStencilStateFaceDescriptor GPUCompareFunction = "always";compare GPUStencilOperation = "keep";failOp GPUStencilOperation = "keep";depthFailOp GPUStencilOperation = "keep"; };passOp
enum {GPUStencilOperation ,"keep" ,"zero" ,"replace" ,"invert" ,"increment-clamp" ,"decrement-clamp" ,"increment-wrap" };"decrement-wrap"
10.3.9. Vertex State
enum {GPUIndexFormat ,"uint16" };"uint32"
The
index
format
determines
both
the
data
type
of
index
values
in
a
buffer
and,
when
used
with
strip
primitive
topologies
(
"line-strip"
or
"triangle-strip"
)
also
specifies
the
primitive
restart
value.
The
primitive
restart
value
indicates
which
index
value
indicates
that
a
new
primitive
should
be
started
rather
than
continuing
to
construct
the
triangle
strip
with
the
prior
indexed
vertices.
GPURenderPipelineDescriptor
s
that
specify
a
strip
primitive
topology
must
not
have
the
indexFormat
set
to
undefined
so
that
the
primitive
restart
value
that
will
be
used
is
known
at
pipline
creation
time.
| Index format | Primitive restart value |
|---|---|
"uint16"
| 0xFFFF |
"uint32"
| 0xFFFFFFFF |
10.3.9.1. Vertex Formats
The name of the format specifies the data type of the component, the number of values, and whether the data is normalized.
-
uchar= unsigned 8-bit value -
char= signed 8-bit value -
ushort= unsigned 16-bit value -
short= signed 16-bit value -
half= half-precision 16-bit floating point value -
float= 32-bit floating point value -
uint= unsigned 32-bit integer value -
int= signed 32-bit integer value
If
no
number
of
values
is
given
in
the
name,
a
single
value
is
provided.
If
the
format
has
the
-bgra
suffix,
it
means
the
values
are
arranged
as
blue,
green,
red
and
alpha
values.
enum {GPUVertexFormat ,"uchar2" ,"uchar4" ,"char2" ,"char4" ,"uchar2norm" ,"uchar4norm" ,"char2norm" ,"char4norm" ,"ushort2" ,"ushort4" ,"short2" ,"short4" ,"ushort2norm" ,"ushort4norm" ,"short2norm" ,"short4norm" ,"half2" ,"half4" ,"float" ,"float2" ,"float3" ,"float4" ,"uint" ,"uint2" ,"uint3" ,"uint4" ,"int" ,"int2" ,"int3" };"int4"
enum {GPUInputStepMode ,"vertex" };"instance"
dictionary {GPUVertexStateDescriptor GPUIndexFormat ;indexFormat sequence <GPUVertexBufferLayoutDescriptor ?>= []; };vertexBuffers
A
vertex
buffer
is,
conceptually,
a
view
into
buffer
memory
as
an
array
of
structures
.
arrayStride
is
the
stride,
in
bytes,
between
elements
of
that
array.
Each
element
of
a
vertex
buffer
is
like
a
structure
with
a
memory
layout
defined
by
its
attributes
,
which
describe
the
members
of
the
structure.
Each
GPUVertexAttributeDescriptor
describes
its
format
and
its
offset
,
in
bytes,
within
the
structure.
Each
attribute
appears
as
a
separate
input
in
a
vertex
shader,
each
bound
by
a
numeric
location
,
which
is
specified
by
shaderLocation
.
Every
location
must
be
unique
within
the
GPUVertexStateDescriptor
.
dictionary {GPUVertexBufferLayoutDescriptor required GPUSize64 ;arrayStride GPUInputStepMode = "vertex";stepMode required sequence <GPUVertexAttributeDescriptor >; };attributes
dictionary {GPUVertexAttributeDescriptor required GPUVertexFormat ;format required GPUSize64 ;offset required GPUIndex32 ; };shaderLocation
-
GPUVertexBufferLayoutDescriptordescriptor -
GPUProgrammableStageDescriptorvertexStage
Return
true
,
if
and
only
if,
all
of
the
following
conditions
are
satisfied:
-
descriptor .
attributes.length is less than or equal to 16. -
descriptor .
arrayStrideis less then or equal to 2048. -
Any attribute at in the list descriptor .
attributeshas at .{{GPUVertexAttributeDescriptor/offset} + sizeOf( at .formatless or equal to descriptor .arrayStride. -
For every vertex attribute in the shader reflection of vertexStage .
modulethat is know to be statically used by vertexStage .entryPoint, there is a corresponding at element of descriptor .attributesthat:-
The shader format is at .
format. -
The shader location is at .
shaderLocation.
-
add a limit to the number of vertex attributes
-
GPUVertexStateDescriptordescriptor -
GPUProgrammableStageDescriptorvertexStage
Return
true
,
if
and
only
if,
all
of
the
following
conditions
are
satisfied:
-
descriptor .
vertexBuffers.length is less than or equal to 8 -
Each vertexBuffer layout descriptor in the list descriptor .
vertexBufferspasses validating GPUVertexBufferLayoutDescriptor ( vertexBuffer , vertexStage ) -
Each at in the union of all
GPUVertexAttributeDescriptoracross descriptor .vertexBuffershas a distinct at .shaderLocationvalue.
add a limit to the number of vertex buffers
11. Command Buffers
Command
buffers
are
pre-recorded
lists
of
GPU
commands
that
can
be
submitted
to
a
GPUQueue
for
execution.
Each
GPU
command
represents
a
task
to
be
performed
on
the
GPU,
such
as
setting
state,
drawing,
copying
resources,
etc.
11.1.
GPUCommandBuffer
interface GPUCommandBuffer {readonly attribute Promise <double >executionTime ; };GPUCommandBuffer includes GPUObjectBase ;
GPUCommandBuffer
has
the
following
attributes:
-
executionTimeof type Promise<, of type Promise< double >, readonlydouble>, readonly -
The total time, in seconds, that the GPU took to execute this command buffer.
Note: If
measureExecutionTimeistrue, this resolves after the command buffer executes. Otherwise, this rejects with anOperationError.Specify the creation and resolution of the promise.In
finish(), it should be specified that a new promise is created and stored in this attribute. The promise starts rejected ifmeasureExecutionTimeisfalse. If the finish() fails, then the promise resolves to 0.In
submit(), it should be specified that (ifmeasureExecutionTimeis set), work is issued to read back the execution time, and, when that completes, the promise is resolved with that value. If the submit() fails, then the promise resolves to 0.
GPUCommandBuffer
has
the
following
internal
slots:
-
[[command_list]]of type list < GPU command >. -
A list of GPU commands to be executed on the Queue timeline when this command buffer is submitted.
11.1.1. Creation
dictionary :GPUCommandBufferDescriptor GPUObjectDescriptorBase { };
12. Command Encoding
12.1.
GPUCommandEncoder
interface GPUCommandEncoder {GPURenderPassEncoder beginRenderPass (GPURenderPassDescriptor descriptor );GPUComputePassEncoder beginComputePass (optional GPUComputePassDescriptor descriptor = {});undefined copyBufferToBuffer (GPUBuffer source ,GPUSize64 sourceOffset ,GPUBuffer destination ,GPUSize64 destinationOffset ,GPUSize64 size );undefined copyBufferToTexture (GPUBufferCopyView source ,GPUTextureCopyView destination ,GPUExtent3D copySize );undefined copyTextureToBuffer (GPUTextureCopyView source ,GPUBufferCopyView destination ,GPUExtent3D copySize );undefined copyTextureToTexture (GPUTextureCopyView source ,GPUTextureCopyView destination ,GPUExtent3D copySize );undefined pushDebugGroup (USVString groupLabel );undefined popDebugGroup ();undefined insertDebugMarker (USVString markerLabel );undefined writeTimestamp (GPUQuerySet querySet ,GPUSize32 queryIndex );undefined resolveQuerySet (GPUQuerySet querySet ,GPUSize32 firstQuery ,GPUSize32 queryCount ,GPUBuffer destination ,GPUSize64 destinationOffset );GPUCommandBuffer finish (optional GPUCommandBufferDescriptor descriptor = {}); };GPUCommandEncoder includes GPUObjectBase ;
GPUCommandEncoder
has
the
following
internal
slots:
-
[[command_list]]of type list < GPU command >. -
A list of GPU command to be executed on the Queue timeline when the
GPUCommandBufferthis encoder produces is submitted. -
[[state]]of typeencoder state. -
The current state of the
GPUCommandEncoder, initially set toopen. -
[[debug_group_stack]]of type stack <USVString>. -
A stack of active debug group labels.
Each
GPUCommandEncoder
has
a
current
encoder
state
on
the
Content
timeline
which
may
be
one
of
the
following:
-
"
open" -
Indicates the
GPUCommandEncoderis available to begin new operations. The[[state]]isopenany time theGPUCommandEncoderis valid and has no activeGPURenderPassEncoderorGPUComputePassEncoder. -
"
encoding a render pass" -
Indicates the
GPUCommandEncoderhas an activeGPURenderPassEncoder. The[[state]]becomesencoding a render passoncebeginRenderPass()is called sucessfully untilendPass()is called on the returnedGPURenderPassEncoder, at which point the[[state]](if the encoder is still valid) reverts toopen. -
"
encoding a compute pass" -
Indicates the
GPUCommandEncoderhas an activeGPUComputePassEncoder. The[[state]]becomesencoding a compute passoncebeginComputePass()is called sucessfully untilendPass()is called on the returnedGPUComputePassEncoder, at which point the[[state]](if the encoder is still valid) reverts toopen. -
"
closed" -
Indicates the
GPUCommandEncoderis no longer available for any operations. The[[state]]becomesclosedoncefinish()is called or theGPUCommandEncoderotherwise becomes invalid .
12.1.1. Creation
dictionary :GPUCommandEncoderDescriptor GPUObjectDescriptorBase {boolean measureExecutionTime =false ; // TODO: reusability flag? };
-
measureExecutionTime, of type boolean , defaulting tofalse -
Enable measurement of the GPU execution time of the entire command buffer.
-
createCommandEncoder(descriptor) -
Creates a
GPUCommandEncoder.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createCommandEncoder(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUCommandEncoderDescriptor ✘ ✔ Description of the GPUCommandEncoderto create.Returns:
GPUCommandEncoderDescribe
createCommandEncoder()algorithm steps.
12.2. Pass Encoding
-
beginRenderPass(descriptor) -
Begins encoding a render pass described by descriptor .
Called on:GPUCommandEncoderthis .Arguments:
Arguments for the GPUCommandEncoder.beginRenderPass(descriptor) method. Parameter Type Nullable Optional Description descriptorGPURenderPassDescriptor ✘ ✘ Description of the GPURenderPassEncoderto create.Returns:
GPURenderPassEncoderIssue the following steps on the Device timeline of this :
-
If any of the following conditions are unsatisfied, generate a validation error and stop.
-
descriptor meets the GPURenderPassDescriptor Valid Usage rules.
-
Set this .
[[state]]toencoding a render pass. -
For each colorAttachment in descriptor .
colorAttachments:-
The texture subresource seen by colorAttachment .
attachmentis considered to be used as attachment for the duration of the render pass.
-
-
Let depthStencilAttachment be descriptor .
depthStencilAttachment. -
If depthStencilAttachment is not
null:-
if depthStencilAttachment .
depthReadOnlyandstencilReadOnlyare set-
The texture subresources seen by depthStencilAttachment .
attachmentare considered to be used as attachment-read for the duration of the render pass.
-
-
Else, the texture subresource seen by depthStencilAttachment .
attachmentis considered to be used as attachment for the duration of the render pass.
-
specify the behavior of read-only depth/stencil Issue: Enqueue attachment loads (with loadOp clear).
-
-
beginComputePass(descriptor) -
Begins encoding a compute pass described by descriptor .
Called on:GPUCommandEncoderthis .Arguments:
Arguments for the GPUCommandEncoder.beginComputePass(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUComputePassDescriptor ✘ ✔ Returns:
GPUComputePassEncoderIssue the following steps on the Device timeline of this :
-
If any of the following conditions are unsatisfied, generate a validation error and stop.
-
Set this .
[[state]]toencoding a compute pass.
-
12.3. Copy Commands
12.3.1.
GPUTextureDataLayout
dictionary GPUTextureDataLayout {GPUSize64 = 0;offset GPUSize32 bytesPerRow ;GPUSize32 rowsPerImage ; };
A
GPUTextureDataLayout
is
a
layout
of
images
within
some
linear
memory.
It’s
used
when
copying
data
between
a
texture
and
a
buffer
,
or
when
scheduling
a
write
into
a
texture
from
the
GPUQueue
.
-
For
2dtextures, data is copied between one or multiple contiguous images and array layers . -
For
3dtextures, data is copied between one or multiple contiguous images and depth slices .
Operations that copy between byte arrays and textures always work with rows of texel blocks , which we’ll call block row s. It’s not possible to update only a part of a texel block .
Define images more precisely. In particular, define them as being comprised of texel blocks .
Define the exact copy semantics, by reference to common algorithms shared by the copy methods.
-
bytesPerRow, of type GPUSize32 -
The stride, in bytes, between the beginning of each block row and the subsequent block row .
Required if there are multiple block rows (i.e. the height or depth is more than one block).
-
rowsPerImage, of type GPUSize32 -
Number of block rows per single image of the texture .
rowsPerImage×bytesPerRowis the stride, in bytes, between the beginning of each image of data and the subsequent image .Required if there are multiple images (i.e. the depth is more than one).
12.3.2.
GPUBufferCopyView
dictionary GPUBufferCopyView :GPUTextureDataLayout {required GPUBuffer ; };buffer
A
GPUBufferCopyView
contains
the
actual
texture
data
placed
in
a
buffer
according
to
GPUTextureDataLayout
.
Arguments:
-
GPUBufferCopyViewbufferCopyView
Returns:
boolean
Return
true
if
and
only
if
all
of
the
following
conditions
are
satisfied:
-
bufferCopyView .
bytesPerRowmust be a multiple of 256.
12.3.3.
GPUTextureCopyView
dictionary GPUTextureCopyView {;required GPUTexture ;texture GPUIntegerCoordinate = 0;mipLevel GPUOrigin3D = {};origin GPUTextureAspect = "all"; };aspect
A
GPUTextureCopyView
is
a
view
of
a
sub-region
of
one
or
multiple
contiguous
texture
subresources
with
the
initial
offset
GPUOrigin3D
in
texels,
used
when
copying
data
from
or
to
a
GPUTexture
.
-
origin: If unspecified, defaults to[0, 0, 0].
Arguments:
-
GPUTextureCopyViewtextureCopyView -
GPUExtent3DcopySize
Returns:
boolean
Let:
-
blockWidth be the texel block width of textureCopyView .
texture.[[format]]. -
blockHeight be the texel block height of textureCopyView .
texture.[[format]].
Return
true
if
and
only
if
all
of
the
following
conditions
apply:
-
textureCopyView .
texturemust be a validGPUTexture. -
textureCopyView .
mipLevelmust be less than the[[mipLevelCount]]of textureCopyView .texture. -
textureCopyView .
origin. x must be a multiple of blockWidth . -
textureCopyView .
origin. y must be a multiple of blockHeight . -
The textureCopyView subresource size of textureCopyView is equal to copySize if either of the following conditions is true:
-
textureCopyView .
texture.[[format]]is a depth-stencil format. -
textureCopyView .
texture.[[sampleCount]]is greater than 1.
-
Define
the
copies
with
1d
and
3d
textures.
<https://github.com/gpuweb/gpuweb/issues/69>
12.3.4.
GPUImageBitmapCopyView
dictionary GPUImageBitmapCopyView {required ImageBitmap ;imageBitmap GPUOrigin2D = {}; };origin
-
origin: If unspecified, defaults to[0, 0].
-
copyBufferToBuffer(source, sourceOffset, destination, destinationOffset, size) -
Encode a command into the
GPUCommandEncoderthat copies data from a sub-region of aGPUBufferto a sub-region of anotherGPUBuffer.Called on:GPUCommandEncoderthis .Arguments:
Arguments for the GPUCommandEncoder.copyBufferToBuffer(source, sourceOffset, destination, destinationOffset, size) method. Parameter Type Nullable Optional Description sourceGPUBuffer ✘ ✘ The GPUBufferto copy from.sourceOffsetGPUSize64 ✘ ✘ Offset in bytes into source to begin copying from. destinationGPUBuffer ✘ ✘ The GPUBufferto copy to.destinationOffsetGPUSize64 ✘ ✘ Offset in bytes into destination to place the copied data. sizeGPUSize64 ✘ ✘ Bytes to copy. Returns:
undefinedIf any of the following conditions are unsatisfied, generate a validation error and stop.
-
source is valid to use with this .
-
destination is valid to use with this .
-
size is a multiple of 4.
-
sourceOffset is a multiple of 4.
-
destinationOffset is a multiple of 4.
-
( sourceOffset + size ) does not overflow a
GPUSize64. -
( destinationOffset + size ) does not overflow a
GPUSize64. -
source .
[[size]]is greater than or equal to ( sourceOffset + size ). -
destination .
[[size]]is greater than or equal to ( destinationOffset + size ). -
source and destination are not the same
GPUBuffer.
Define the state machine for GPUCommandEncoder. <https://github.com/gpuweb/gpuweb/issues/21>
figure out how to handle overflows in the spec. <https://github.com/gpuweb/gpuweb/issues/69>
12.3.5. Copy Between Buffer and Texture
WebGPU
provides
copyBufferToTexture()
for
buffer-to-texture
copies
and
copyTextureToBuffer()
for
texture-to-buffer
copies.
The
following
definitions
and
validation
rules
apply
to
both
copyBufferToTexture()
and
copyTextureToBuffer()
.
textureCopyView
subresource
size
and
Valid
Texture
Copy
Range
also
applies
to
copyTextureToTexture()
.
textureCopyView subresource size
Arguments:
-
GPUTextureCopyViewtextureCopyView
Returns:
GPUExtent3D
The textureCopyView subresource size of textureCopyView is calculated as follows:
Its
width
,
height
and
depth
are
the
width,
height,
and
depth,
respectively,
of
the
physical
size
of
textureCopyView
.
texture
subresource
at
mipmap
level
textureCopyView
.
mipLevel
.
define this as an algorithm with (texture, mipmapLevel) parameters and use the call syntax instead of referring to the definition by label.
Arguments:
-
GPUTextureDataLayoutlayout -
Layout of the linear texture data.
-
GPUSize64byteSize -
Total size of the linear data, in bytes.
-
GPUTextureFormatformat -
Format of the texture.
-
GPUExtent3DcopyExtent -
Extent of the texture to copy.
-
Let blockWidth , blockHeight , and blockSize be the texel block width , height , and size of format .
-
It is assumed that copyExtent . width is a multiple of blockWidth and copyExtent . height is a multiple of blockHeight . Let:
-
widthInBlocks be copyExtent . width ÷ blockWidth .
-
heightInBlocks be copyExtent . height ÷ blockHeight .
-
bytesInLastRow be blockSize × widthInBlocks .
-
bytesPerImage be layout .
bytesPerRow× layout .rowsPerImage.
-
-
Fail if the following conditions are not satisfied:
-
If heightInBlocks > 1, layout .
bytesPerRowmust be specified. -
If copyExtent . depth > 1, layout .
bytesPerRowand layout .rowsPerImagemust be specified. -
If specified, layout .
bytesPerRowmust be greater than or equal to bytesInLastRow . -
If specified, layout .
rowsPerImagemust be greater than or equal to heightInBlocks .
-
-
Let requiredBytesInCopy be 0.
-
If copyExtent . depth > 0:
-
Let bytesBeforeLastImage be bytesPerImage × ( copyExtent . depth − 1)
-
Add bytesBeforeLastImage to requiredBytesInCopy .
-
If heightInBlocks > 0:
-
Let bytesInLastImage be layout .
bytesPerRow× ( heightInBlocks − 1) + bytesInLastRow . -
Add bytesInLastImage to requiredBytesInCopy .
-
-
-
Fail if the following conditions are not satisfied:
-
layout .
offset+ requiredBytesInCopy ≤ byteSize .
-
Valid Texture Copy Range
Given
a
GPUTextureCopyView
textureCopyView
and
a
GPUExtent3D
copySize
,
let
-
blockWidth be the texel block width of textureCopyView .
texture.[[format]]. -
blockHeight be the texel block height of textureCopyView .
texture.[[format]].
The following validation rules apply:
-
If the
[[dimension]]of textureCopyView .textureis1d: -
If the
[[dimension]]of textureCopyView .textureis2d:-
( textureCopyView .
origin. x + copySize . width ), ( textureCopyView .origin. y + copySize . height ), and ( textureCopyView .origin. z + copySize . depth ) must be less than or equal to the width , height , and depth , respectively, of the textureCopyView subresource size of textureCopyView .
-
-
copySize . width must be a multiple of blockWidth .
-
copySize . height must be a multiple of blockHeight .
Define
the
copies
with
1d
and
3d
textures.
<https://github.com/gpuweb/gpuweb/issues/69>
Additional restrictions on rowsPerImage if needed. <https://github.com/gpuweb/gpuweb/issues/537>
Define
the
copies
with
"depth24plus"
,
"depth24plus-stencil8"
,
and
"stencil8"
.
<https://github.com/gpuweb/gpuweb/issues/652>
convert "Valid Texture Copy Range" into an algorithm with parameters, similar to "validating linear texture data"
-
copyBufferToTexture(source, destination, copySize) -
Encode a command into the
GPUCommandEncoderthat copies data from a sub-region of aGPUBufferto a sub-region of one or multiple continuous texture subresources .Called on:GPUCommandEncoderthis .Arguments:
Arguments for the GPUCommandEncoder.copyBufferToTexture(source, destination, copySize) method. Parameter Type Nullable Optional Description sourceGPUBufferCopyView ✘ ✘ Combined with copySize , defines the region of the source buffer. destinationGPUTextureCopyView ✘ ✘ Combined with copySize , defines the region of the destination texture subresource . copySizeGPUExtent3D ✘ ✘ Returns:
undefinedIf any of the following conditions are unsatisfied, generate a validation error and stop.
-
validating GPUBufferCopyView ( source ) returns
true. -
validating GPUTextureCopyView ( destination , copySize ) returns
true. -
destination .
texture.[[textureUsage]]containsCOPY_DST. -
destination .
texture.[[sampleCount]]is 1. -
If destination .
texture.[[format]]is a depth-stencil format:-
destination .
aspectmust refer to a single copyable aspect of destination .texture.[[format]]. See depth-formats .
-
-
Valid Texture Copy Range applies to destination and copySize .
-
source .
offsetis a multiple of the texel block size of destination .texture.[[format]]. -
validating linear texture data ( source , source .
buffer.[[size]], destination .texture.[[format]], copySize ) succeeds.
-
copyTextureToBuffer(source, destination, copySize) -
Encode a command into the
GPUCommandEncoderthat copies data from a sub-region of one or multiple continuous texture subresources to a sub-region of aGPUBuffer.Called on:GPUCommandEncoderthis .Arguments:
Arguments for the GPUCommandEncoder.copyTextureToBuffer(source, destination, copySize) method. Parameter Type Nullable Optional Description sourceGPUTextureCopyView ✘ ✘ Combined with copySize , defines the region of the source texture subresources . destinationGPUBufferCopyView ✘ ✘ Combined with copySize , defines the region of the destination buffer. copySizeGPUExtent3D ✘ ✘ Returns:
undefinedIf any of the following conditions are unsatisfied, generate a validation error and stop.
-
validating GPUTextureCopyView ( source , copySize ) returns
true. -
source .
texture.[[textureUsage]]containsCOPY_SRC. -
source .
texture.[[sampleCount]]is 1. -
If source .
texture.[[format]]is a depth-stencil format:-
source .
aspectmust refer to a single copyable aspect of source .texture.[[format]]. See depth-formats .
-
-
validating GPUBufferCopyView ( destination ) returns
true. -
Valid Texture Copy Range applies to source and copySize .
-
destination .
offsetis a multiple of the texel block size of destination .texture.[[format]]. -
validating linear texture data ( destination , destination .
buffer.[[size]], source .texture.[[format]], copySize ) succeeds.
-
copyTextureToTexture(source, destination, copySize) -
Encode a command into the
GPUCommandEncoderthat copies data from a sub-region of one or multiple contiguous texture subresources to another sub-region of one or multiple continuous texture subresources .Called on:GPUCommandEncoderthis .Arguments:
Arguments for the GPUCommandEncoder.copyTextureToTexture(source, destination, copySize) method. Parameter Type Nullable Optional Description sourceGPUTextureCopyView ✘ ✘ Combined with copySize , defines the region of the source texture subresources . destinationGPUTextureCopyView ✘ ✘ Combined with copySize , defines the region of the destination texture subresources . copySizeGPUExtent3D ✘ ✘ Returns:
undefined-
If any of the following conditions are unsatisfied, generate a validation error and stop.
-
validating GPUTextureCopyView ( source , copySize ) returns
true. -
source .
texture.[[textureUsage]]containsCOPY_SRC. -
validating GPUTextureCopyView ( destination , copySize ) returns
true. -
destination .
texture.[[textureUsage]]containsCOPY_DST. -
source .
texture.[[sampleCount]]is equal to destination .texture.[[sampleCount]]. -
source .
texture.[[format]]is equal to destination .texture.[[format]]. -
If source .
texture.[[format]]is a depth-stencil format:-
source .
aspectand destination .aspectmust both refer to all aspects of source .texture.[[format]]and destination .texture.[[format]], respectively.
-
-
Valid Texture Copy Range applies to source and copySize .
-
Valid Texture Copy Range applies to destination and copySize .
-
The set of subresources for texture copy ( source , copySize ) and the set of subresources for texture copy ( destination , copySize ) is disjoint.
-
-
If textureCopyView .
texture.[[dimension]]is"2d":-
For each arrayLayer of the copySize . depth array layers starting at textureCopyView .
origin. z :-
The subresource of textureCopyView .
textureat mipmap level textureCopyView .mipLeveland array layer arrayLayer .
-
-
-
Otherwise:
-
The subresource of textureCopyView .
textureat mipmap level textureCopyView .mipLevel.
-
12.4. Debug Markers
Both command encoders and programmable pass encoders provide methods to apply debug labels to groups of commands or insert a single label into the command sequence. Debug groups can be nested to create a hierarchy of labeled commands. These labels may be passed to the native API backends for tooling, may be used by the user agent’s internal tooling, or may be a no-op when such tooling is not available or applicable.
Debug
groups
in
a
GPUCommandEncoder
or
GPUProgrammablePassEncoder
must
be
well
nested.
-
pushDebugGroup(groupLabel) -
Marks the beginning of a labeled group of commands for the
GPUCommandEncoder.Called on:GPUCommandEncoderthis .Arguments:
Arguments for the GPUCommandEncoder.pushDebugGroup(groupLabel) method. Parameter Type Nullable Optional Description groupLabelUSVString ✘ ✘ The label for the command group. Returns:
undefinedIssue the following steps on the Device timeline of this :
-
If any of the following conditions are unsatisfied, make this invalid and stop.
-
Push groupLabel onto this .
[[debug_group_stack]].
-
-
popDebugGroup() -
Marks the end of a labeled group of commands for the
GPUCommandEncoder.Called on:GPUCommandEncoderthis .Returns:
undefinedIssue the following steps on the Device timeline of this :
-
If any of the following conditions are unsatisfied, make this invalid and stop.
-
this .
[[debug_group_stack]]'s size is greater than 0.
-
Pop an entry off this .
[[debug_group_stack]].
-
-
insertDebugMarker(markerLabel) -
Marks the end of a labeled group of commands for the
GPUCommandEncoder.Called on:GPUCommandEncoderthis .Arguments:
Arguments for the GPUCommandEncoder.insertDebugMarker(markerLabel) method. Parameter Type Nullable Optional Description markerLabelUSVString ✘ ✘ The label to insert. Returns:
undefinedIssue the following steps on the Device timeline of this :
12.5. Queries
-
writeTimestamp(querySet, queryIndex) -
Called on:
GPUCommandEncoderthis.Arguments:
Arguments for the GPUCommandEncoder.writeTimestamp(querySet, queryIndex) method. Parameter Type Nullable Optional Description querySetGPUQuerySet ✘ ✘ queryIndexGPUSize32 ✘ ✘ Returns:
undefinedDescribe
writeTimestamp()algorithm steps. -
resolveQuerySet(querySet, firstQuery, queryCount, destination, destinationOffset) -
Called on:
GPUCommandEncoderthis.Arguments:
Arguments for the GPUCommandEncoder.resolveQuerySet(querySet, firstQuery, queryCount, destination, destinationOffset) method. Parameter Type Nullable Optional Description querySetGPUQuerySet ✘ ✘ firstQueryGPUSize32 ✘ ✘ queryCountGPUSize32 ✘ ✘ destinationGPUBuffer ✘ ✘ destinationOffsetGPUSize64 ✘ ✘ Returns:
undefinedIf any of the following conditions are unsatisfied, generate a
GPUValidationErrorand stop.-
querySet is valid to use with this .
-
destination is valid to use with this .
-
destination .
[[usage]]containsQUERY_RESOLVE. -
firstQuery is less than the number of queries in querySet .
-
( firstQuery + queryCount ) is less than or equal to the number of queries in querySet .
-
destinationOffset is a multiple of 8.
-
destinationOffset + 8 × queryCount ≤ destination .
[[size]].
Describe
resolveQuerySet()algorithm steps.
12.6. Finalization
A
GPUCommandBuffer
containing
the
commands
recorded
by
the
GPUCommandEncoder
can
be
created
by
calling
finish()
.
Once
finish()
has
been
called
the
command
encoder
can
no
longer
be
used.
-
finish(descriptor) -
Completes recording of the commands sequence and returns a corresponding
GPUCommandBuffer.Called on:GPUCommandEncoderthis .Arguments:
Arguments for the GPUCommandEncoder.finish(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUCommandBufferDescriptor ✘ ✔ Returns:
GPUCommandBuffer-
Let commandBuffer be a new
GPUCommandBuffer. -
Issue the following steps on the Device timeline of this :
-
If any of the following conditions are unsatisfied, generate a validation error and stop.
-
this is valid .
-
this .
[[debug_group_stack]]'s size is 0. -
Every usage scope contained in this satisfies the usage scope validation .
-
-
Let commandBuffer .
[[command_list]]be a clone of this .[[command_list]].
-
-
Return commandBuffer .
-
13. Programmable Passes
interface mixin {GPUProgrammablePassEncoder undefined setBindGroup (GPUIndex32 index ,GPUBindGroup bindGroup ,optional sequence <GPUBufferDynamicOffset >= []);dynamicOffsets undefined setBindGroup (GPUIndex32 index ,GPUBindGroup bindGroup ,Uint32Array dynamicOffsetsData ,GPUSize64 dynamicOffsetsDataStart ,GPUSize32 dynamicOffsetsDataLength );undefined pushDebugGroup (USVString groupLabel );undefined popDebugGroup ();undefined insertDebugMarker (USVString markerLabel ); };
GPUProgrammablePassEncoder
has
the
following
internal
slots:
-
[[command_encoder]]of typeGPUCommandEncoder. -
The
GPUCommandEncoderthat created this programmable pass. -
[[debug_group_stack]]of type stack <USVString>. -
A stack of active debug group labels.
-
[[bind_groups]], of type ordered map <GPUIndex32,GPUBindGroup> -
The current
GPUBindGroupfor each index, initially empty.
13.1. Bind Groups
-
setBindGroup(index, bindGroup, dynamicOffsets) -
Sets the current
GPUBindGroupfor the given index.Called on:GPUProgrammablePassEncoderthis.Arguments:
Arguments for the GPUProgrammablePassEncoder.setBindGroup(index, bindGroup, dynamicOffsets) method. Parameter Type Nullable Optional Description indexGPUIndex32 ✘ ✘ The index to set the bind group at. bindGroupGPUBindGroup ✘ ✘ Bind group to use for subsequent render or compute commands. Resolve bikeshed conflict when using
argumentdefwith overloaded functions that prevents us from defining dynamicOffsets .Returns:
undefinedIssue the following steps on the Device timeline of this .
[[device]]:-
If any of the following conditions are unsatisfied, make this invalid and stop.
-
bindGroup is valid to use with this .
-
index <
GPULimits.maxBindGroups. -
dynamicOffsets .length is bindGroup .
[[layout]].[[dynamicOffsetCount]]. -
Iterate over each dynamic binding offset in bindGroup and run the following steps for each bufferBinding , minBufferBindingSize , and dynamicOffsetIndex :
-
-
Set this .
[[bind_groups]][ index ] to be bindGroup .
-
-
setBindGroup(index, bindGroup, dynamicOffsetsData, dynamicOffsetsDataStart, dynamicOffsetsDataLength) -
Sets the current
GPUBindGroupfor the given index, specifying dynamic offsets as a subset of aUint32Array.Called on:GPUProgrammablePassEncoderthis.Arguments:
Arguments for the GPUProgrammablePassEncoder.setBindGroup(index, bindGroup, dynamicOffsetsData, dynamicOffsetsDataStart, dynamicOffsetsDataLength) method. Parameter Type Nullable Optional Description indexGPUIndex32 ✘ ✘ The index to set the bind group at. bindGroupGPUBindGroup ✘ ✘ Bind group to use for subsequent render or compute commands. dynamicOffsetsDataUint32Array ✘ ✘ Array containing buffer offsets in bytes for each entry in bindGroup with marked as hasDynamicOffset.dynamicOffsetsDataStartGPUSize64 ✘ ✘ Offset in elements into dynamicOffsetsData where the buffer offset data begins. dynamicOffsetsDataLengthGPUSize32 ✘ ✘ Number of buffer offsets to read from dynamicOffsetsData . Returns:
undefinedIssue the following steps on the Device timeline of this .
[[device]]:-
If any of the following conditions are unsatisfied, make this invalid and stop.
-
bindGroup is valid to use with this .
-
index <
GPULimits.maxBindGroups. -
dynamicOffsetsDataLength is bindGroup .
[[layout]].[[dynamicOffsetCount]]. -
dynamicOffsetsDataStart + dynamicOffsetsDataLength ≤ dynamicOffsetsData .length.
-
Iterate over each dynamic binding offset in bindGroup and run the following steps for each bufferBinding , minBufferBindingSize , and dynamicOffsetIndex :
-
-
Set this .
[[bind_groups]][ index ] to be bindGroup .
-
GPUBindGroup
bindGroup
with
a
given
list
of
steps
to
be
executed
for
each
dynamic
offset:
-
Let dynamicOffsetIndex be
0. -
Let layout be bindGroup .
[[layout]]. -
For each
GPUBindGroupEntryentry in bindGroup .[[entries]]:-
Let bindingDescriptor be the
GPUBindGroupLayoutEntryat layout .[[entryMap]][ entry .binding]: -
If bindingDescriptor .
hasDynamicOffsetistrue:-
Let bufferBinding be entry .
resource. -
Let minBufferBindingSize be bindingDescriptor .
minBufferBindingSize. -
Call steps with bufferBinding , minBufferBindingSize , and dynamicOffsetIndex .
-
Let dynamicOffsetIndex be dynamicOffsetIndex +
1
-
-
Arguments:
-
GPUProgrammablePassEncoderencoder -
Encoder who’s bind groups are being validated.
-
GPUPipelineBasepipeline -
Pipline to validate encoder s bind groups are compatible with.
If
any
of
the
following
conditions
are
unsatisfied,
return
false
:
-
pipeline must not be
null. -
For each pair of (
GPUIndex32index ,GPUBindGroupLayoutbindGroupLayout ) in pipeline .[[layout]].[[bindGroupLayouts]].-
Let bindGroup be encoder .
[[bind_groups]][ index ]. -
bindGroup must not be
null. -
bindGroup .
[[layout]]must be group-equivalent with bindGroupLayout .
-
Check
buffer
bindings
against
minBufferBindingSize
if
present.
Otherwise
return
true
.
13.2. Debug Markers
Debug marker methods for programmable pass encoders provide the same functionality as command encoder debug markers while recording a programmable pass.
-
pushDebugGroup(groupLabel) -
Marks the beginning of a labeled group of commands for the
GPUProgrammablePassEncoder.Called on:GPUProgrammablePassEncoderthis .Arguments:
Arguments for the GPUProgrammablePassEncoder.pushDebugGroup(groupLabel) method. Parameter Type Nullable Optional Description groupLabelUSVString ✘ ✘ The label for the command group. Returns:
undefinedIssue the following steps on the Device timeline of this :
-
Push groupLabel onto this .
[[debug_group_stack]].
-
-
popDebugGroup() -
Marks the end of a labeled group of commands for the
GPUProgrammablePassEncoder.Called on:GPUProgrammablePassEncoderthis .Returns:
undefinedIssue the following steps on the Device timeline of this :
-
If any of the following conditions are unsatisfied, generate a validation error and stop.
-
this .
[[debug_group_stack]]'s size is greater than 0.
-
-
Pop an entry off of this .
[[debug_group_stack]].
-
-
insertDebugMarker(markerLabel) -
Inserts a single debug marker label into the
GPUProgrammablePassEncoder's commands sequence.Called on:GPUProgrammablePassEncoderthis.Arguments:
Arguments for the GPUProgrammablePassEncoder.insertDebugMarker(markerLabel) method. Parameter Type Nullable Optional Description markerLabelUSVString ✘ ✘ The label to insert. Returns:
undefined
14. Compute Passes
14.1.
GPUComputePassEncoder
interface GPUComputePassEncoder {undefined setPipeline (GPUComputePipeline pipeline );undefined dispatch (GPUSize32 x ,optional GPUSize32 y = 1,optional GPUSize32 z = 1);undefined dispatchIndirect (GPUBuffer indirectBuffer ,GPUSize64 indirectOffset );undefined beginPipelineStatisticsQuery (GPUQuerySet querySet ,GPUSize32 queryIndex );undefined endPipelineStatisticsQuery ();undefined writeTimestamp (GPUQuerySet querySet ,GPUSize32 queryIndex );undefined endPass (); };GPUComputePassEncoder includes GPUObjectBase ;GPUComputePassEncoder includes GPUProgrammablePassEncoder ;
GPUComputePassEncoder
has
the
following
internal
slots:
-
[[pipeline]], of typeGPUComputePipeline -
The current
GPUComputePipeline, initiallynull.
14.1.1. Creation
dictionary :GPUComputePassDescriptor GPUObjectDescriptorBase { };
14.1.2. Dispatch
-
setPipeline(pipeline) -
Sets the current
GPUComputePipeline.Called on:GPUComputePassEncoderthis.Arguments:
Arguments for the GPUComputePassEncoder.setPipeline(pipeline) method. Parameter Type Nullable Optional Description pipelineGPUComputePipeline ✘ ✘ The compute pipeline to use for subsequent dispatch commands. Returns:
undefinedIssue the following steps on the Device timeline of this .
[[device]]:-
If any of the following conditions are unsatisfied, make this invalid and stop.
-
pipeline is valid to use with this .
-
-
Set this .
[[pipeline]]to be pipeline .
-
-
dispatch(x, y, z) -
Dispatch work to be performed with the current
GPUComputePipeline.Called on:GPUComputePassEncoderthis.Arguments:
Arguments for the GPUComputePassEncoder.dispatch(x, y, z) method. Parameter Type Nullable Optional Description xGPUSize32 ✘ ✘ X dimension of the grid of workgroups to dispatch. yGPUSize32 ✘ ✔ Y dimension of the grid of workgroups to dispatch. zGPUSize32 ✘ ✔ Z dimension of the grid of workgroups to dispatch. Returns:
undefinedIssue the following steps on the Device timeline of this .
[[device]]:-
If any of the following conditions are unsatisfied, make this invalid and stop.
-
Validate encoder bind groups ( this , this .
[[pipeline]]) istrue.
-
-
Append a GPU command to this .
[[command_encoder]].[[command_list]]that captures theGPUComputePassEncoderstate of this as passState and, when executed, issues the following steps on the appropriate Queue timeline :-
Dispatch a grid of workgroups with dimensions [ x , y , z ] with passState .
[[pipeline]]using passState .[[bind_groups]].
-
-
-
dispatchIndirect(indirectBuffer, indirectOffset) -
Dispatch work to be performed with the current
GPUComputePipelineusing parameters read from aGPUBuffer.The indirect dispatch parameters encoded in the buffer must be a tightly packed block of three 32-bit unsigned integer values (12 bytes total) , given in the same order as the arguments for
dispatch(). For example:let dispatchIndirectParameters= new Uint32Array( 3 ); dispatchIndirectParameters[ 0 ] = x; dispatchIndirectParameters[ 1 ] = y; dispatchIndirectParameters[ 2 ] = z; Called on:GPUComputePassEncoderthis.Arguments:
Arguments for the GPUComputePassEncoder.dispatchIndirect(indirectBuffer, indirectOffset) method. Parameter Type Nullable Optional Description indirectBufferGPUBuffer ✘ ✘ Buffer containing the indirect dispatch parameters . indirectOffsetGPUSize64 ✘ ✘ Offset in bytes into indirectBuffer where the dispatch data begins. Returns:
undefinedIssue the following steps on the Device timeline of this .
[[device]]:-
If any of the following conditions are unsatisfied, make this invalid and stop.
-
Validate encoder bind groups ( this , this .
[[pipeline]]) istrue. -
indirectBuffer is valid to use with this .
-
indirectOffset + sizeof( indirect dispatch parameters ) ≤ indirectBuffer .
[[size]]. -
indirectOffset is a multiple of 4.
-
-
Add indirectBuffer to the usage scope as
INDIRECT.
-
14.1.3. Queries
-
beginPipelineStatisticsQuery(querySet, queryIndex) -
Called on:
GPUComputePassEncoderthis.Arguments:
Arguments for the GPUComputePassEncoder.beginPipelineStatisticsQuery(querySet, queryIndex) method. Parameter Type Nullable Optional Description querySetGPUQuerySet ✘ ✘ queryIndexGPUSize32 ✘ ✘ Returns:
undefinedDescribe
beginPipelineStatisticsQuery()algorithm steps. -
endPipelineStatisticsQuery() -
Called on:
GPUComputePassEncoderthis.Returns:
undefinedDescribe
endPipelineStatisticsQuery()algorithm steps. -
writeTimestamp(querySet, queryIndex) -
Called on:
GPUComputePassEncoderthis.Arguments:
Arguments for the GPUComputePassEncoder.writeTimestamp(querySet, queryIndex) method. Parameter Type Nullable Optional Description querySetGPUQuerySet ✘ ✘ queryIndexGPUSize32 ✘ ✘ Returns:
undefinedDescribe
writeTimestamp()algorithm steps.
14.1.4. Finalization
The
compute
pass
encoder
can
be
ended
by
calling
endPass()
once
the
user
has
finished
recording
commands
for
the
pass.
Once
endPass()
has
been
called
the
compute
pass
encoder
can
no
longer
be
used.
-
endPass() -
Completes recording of the compute pass commands sequence.
Called on:GPUComputePassEncoderthis .Returns:
undefinedIssue the following steps on the Device timeline of this :
-
If any of the following conditions are unsatisfied, generate a validation error and stop.
-
this .
[[debug_group_stack]]'s size is 0.
-
-
15. Render Passes
15.1.
GPURenderPassEncoder
interface mixin {GPURenderEncoderBase undefined setPipeline (GPURenderPipeline pipeline );undefined setIndexBuffer (GPUBuffer buffer ,GPUIndexFormat indexFormat ,optional GPUSize64 offset = 0,optional GPUSize64 size = 0);undefined setVertexBuffer (GPUIndex32 slot ,GPUBuffer buffer ,optional GPUSize64 offset = 0,optional GPUSize64 size = 0);undefined draw (GPUSize32 vertexCount ,optional GPUSize32 instanceCount = 1,optional GPUSize32 firstVertex = 0,optional GPUSize32 firstInstance = 0);undefined drawIndexed (GPUSize32 indexCount ,optional GPUSize32 instanceCount = 1,optional GPUSize32 firstIndex = 0,optional GPUSignedOffset32 baseVertex = 0,optional GPUSize32 firstInstance = 0);undefined drawIndirect (GPUBuffer indirectBuffer ,GPUSize64 indirectOffset );undefined drawIndexedIndirect (GPUBuffer indirectBuffer ,GPUSize64 indirectOffset ); };interface GPURenderPassEncoder {undefined setViewport (float x ,float y ,float width ,float height ,float minDepth ,float maxDepth );undefined setScissorRect (GPUIntegerCoordinate x ,GPUIntegerCoordinate y ,GPUIntegerCoordinate width ,GPUIntegerCoordinate height );undefined setBlendColor (GPUColor color );undefined setStencilReference (GPUStencilValue reference );undefined beginOcclusionQuery (GPUSize32 queryIndex );undefined endOcclusionQuery ();undefined beginPipelineStatisticsQuery (GPUQuerySet querySet ,GPUSize32 queryIndex );undefined endPipelineStatisticsQuery ();undefined writeTimestamp (GPUQuerySet querySet ,GPUSize32 queryIndex );undefined executeBundles (sequence <GPURenderBundle >bundles );undefined endPass (); };GPURenderPassEncoder includes GPUObjectBase ;GPURenderPassEncoder includes GPUProgrammablePassEncoder ;GPURenderPassEncoder includes GPURenderEncoderBase ;
-
In indirect draw calls, the base instance field (inside the indirect buffer data) must be set to zero.
GPURenderEncoderBase
has
the
following
internal
slots:
-
[[pipeline]], of typeGPURenderPipeline -
The current
GPURenderPipeline, initiallynull. -
[[index_buffer]], of typeGPUBuffer -
The current buffer to read index data from, initially
null. -
[[index_format]], of typeGPUIndexFormat -
The format of the index data in
[[index_buffer]]. -
[[vertex_buffers]], of type ordered map <slot,GPUBuffer> -
The current
GPUBuffers to read vertex data from for each slot, initially empty.
GPURenderPassEncoder
has
the
following
internal
slots:
-
[[attachment_size]] -
Set to the following extents:
-
width, height= the dimensions of the pass’s render attachments
-
When
a
GPURenderPassEncoder
is
created,
it
has
the
following
default
state:
-
Viewport:
-
x, y=0.0, 0.0 -
width, height= the dimensions of the pass’s render targets -
minDepth, maxDepth=0.0, 1.0
-
-
Scissor rectangle:
-
x, y=0, 0 -
width, height= the dimensions of the pass’s render targets
-
15.1.1. Creation
dictionary :GPURenderPassDescriptor GPUObjectDescriptorBase {required sequence <GPURenderPassColorAttachmentDescriptor >colorAttachments ;GPURenderPassDepthStencilAttachmentDescriptor depthStencilAttachment ;GPUQuerySet occlusionQuerySet ; };
-
colorAttachments, of type sequence< GPURenderPassColorAttachmentDescriptor > -
The set of
GPURenderPassColorAttachmentDescriptorvalues in this sequence defines which color attachments will be output to when executing this render pass. -
depthStencilAttachment, of type GPURenderPassDepthStencilAttachmentDescriptor -
The
GPURenderPassDepthStencilAttachmentDescriptorvalue that defines the depth/stencil attachment that will be output to and tested against when executing this render pass. -
occlusionQuerySet, of type GPUQuerySet
Given
a
GPURenderPassDescriptor
this
the
following
validation
rules
apply:
-
this .
colorAttachments.length must be less than or equal to the maximum color attachments . -
this .
colorAttachments.length must greater than0or this .depthStencilAttachmentmust not benull. -
For each colorAttachment in this .
colorAttachments:-
colorAttachment must meet the GPURenderPassColorAttachmentDescriptor Valid Usage rules.
-
-
If this .
depthStencilAttachmentis notnull:-
this .
depthStencilAttachmentmust meet the GPURenderPassDepthStencilAttachmentDescriptor Valid Usage rules.
-
-
Each
attachmentin this .colorAttachmentsand this .depthStencilAttachment.attachment, if present, must have all have the same[[sampleCount]]. -
The dimensions of the subresource s seen by each
attachmentin this .colorAttachmentsand this .depthStencilAttachment.attachment, if present, must match.
Define maximum color attachments
support for no attachments <https://github.com/gpuweb/gpuweb/issues/503>
15.1.1.1. Color Attachments
dictionary {GPURenderPassColorAttachmentDescriptor required GPUTextureView attachment ;GPUTextureView resolveTarget ;required (GPULoadOp or GPUColor )loadValue ;GPUStoreOp storeOp = "store"; };
-
attachment, of type GPUTextureView -
A
GPUTextureViewdescribing the texture subresource that will be output to for this color attachment. -
resolveTarget, of type GPUTextureView -
A
GPUTextureViewdescribing the texture subresource that will receive the resolved output for this color attachment ifattachmentis multisampled. -
loadValue, of type(GPULoadOp or GPUColor) -
If a
GPULoadOp, indicates the load operation to perform onattachmentprior to executing the render pass. If aGPUColor, indicates the value to clearattachmentto prior to executing the render pass. -
storeOp, of type GPUStoreOp , defaulting to"store" -
The store operation to perform on
attachmentafter executing the render pass.
Given
a
GPURenderPassColorAttachmentDescriptor
this
the
following
validation
rules
apply:
-
this .
attachmentmust have a renderable color format. -
this .
attachment.[[texture]].[[textureUsage]]must containRENDER_ATTACHMENT. -
this .
attachmentmust be a view of a single subresource . -
If this .
resolveTargetis notnull:-
this .
attachmentmust be multisampled. -
this .
resolveTargetmust not be multisampled. -
this .
resolveTarget.[[texture]].[[textureUsage]]must containRENDER_ATTACHMENT. -
this .
resolveTargetmust be a view of a single subresource . -
The dimensions of the subresource s seen by this .
resolveTargetand this .attachmentmust match. -
this .
resolveTarget.[[texture]].[[format]]must match this .attachment.[[texture]].[[format]].
-
15.1.1.2. Depth/Stencil Attachments
dictionary {GPURenderPassDepthStencilAttachmentDescriptor required GPUTextureView attachment ;required (GPULoadOp or float )depthLoadValue ;required GPUStoreOp depthStoreOp ;boolean depthReadOnly =false ;required (GPULoadOp or GPUStencilValue )stencilLoadValue ;required GPUStoreOp stencilStoreOp ;boolean stencilReadOnly =false ; };
-
attachment, of type GPUTextureView -
A
GPUTextureViewdescribing the texture subresource that will be output to and read from for this depth/stencil attachment. -
depthLoadValue, of type(GPULoadOp or float) -
If a
GPULoadOp, indicates the load operation to perform onattachment's depth component prior to executing the render pass. If afloat, indicates the value to clearattachment's depth component to prior to executing the render pass. -
depthStoreOp, of type GPUStoreOp -
The store operation to perform on
attachment's depth component after executing the render pass. -
depthReadOnly, of type boolean , defaulting tofalse -
Indicates that the depth component of
attachmentis read only. -
stencilLoadValue, of type(GPULoadOp or GPUStencilValue) -
If a
GPULoadOp, indicates the load operation to perform onattachment's stencil component prior to executing the render pass. If aGPUStencilValue, indicates the value to clearattachment's stencil component to prior to executing the render pass. -
stencilStoreOp, of type GPUStoreOp -
The store operation to perform on
attachment's stencil component after executing the render pass. -
stencilReadOnly, of type boolean , defaulting tofalse -
Indicates that the stencil component of
attachmentis read only.
Given
a
GPURenderPassDepthStencilAttachmentDescriptor
this
the
following
validation
rules
apply:
-
this .
attachmentmust have a renderable depth-and/or-stencil format. -
this .
attachmentmust be a view of a single texture subresource . -
this .
attachment.[[textureUsage]]must containRENDER_ATTACHMENT. -
this .
depthReadOnlyistrue, this .depthLoadValuemust be"load"and this .depthStoreOpmust be"store". -
this .
stencilReadOnlyistrue, this .stencilLoadValuemust be"load"and this .stencilStoreOpmust be"store".
15.1.1.3. Load & Store Operations
enum {GPULoadOp };"load"
enum {GPUStoreOp ,"store" };"clear"
15.1.2. Drawing
-
setPipeline(pipeline) -
Sets the current
GPURenderPipeline.Called on:GPURenderEncoderBasethis.Arguments:
Arguments for the GPURenderEncoderBase.setPipeline(pipeline) method. Parameter Type Nullable Optional Description pipelineGPURenderPipeline ✘ ✘ The render pipeline to use for subsequent drawing commands. Returns:
undefinedIssue the following steps on the Device timeline of this .
[[device]]:-
If any of the following conditions are unsatisfied, make this invalid and stop.
-
pipeline is valid to use with this .
Validate that pipeline is compatible with the render pass descriptor.
-
-
Set this .
[[pipeline]]to be pipeline .
-
-
setIndexBuffer(buffer, indexFormat, offset, size) -
Sets the current index buffer.
Called on:GPURenderEncoderBasethis.Arguments:
Arguments for the GPURenderEncoderBase.setIndexBuffer(buffer, indexFormat, offset, size) method. Parameter Type Nullable Optional Description bufferGPUBuffer ✘ ✘ Buffer containing index data to use for subsequent drawing commands. indexFormatGPUIndexFormat ✘ ✘ Format of the index data contained in buffer . offsetGPUSize64 ✘ ✔ Offset in bytes into buffer where the index data begins. sizeGPUSize64 ✘ ✔ Size in bytes of the index data in buffer . If 0, buffer .[[size]]- offset is used.Returns:
undefinedIssue the following steps on the Device timeline of this .
[[device]]:-
If any of the following conditions are unsatisfied, make this invalid and stop.
-
buffer is valid to use with this .
-
offset + size ≤ buffer .
[[size]].
-
-
Add buffer to the usage scope as input .
-
Set this .
[[index_buffer]]to be buffer . -
Set this .
[[index_format]]to be indexFormat .
-
-
setVertexBuffer(slot, buffer, offset, size) -
Sets the current vertex buffer for the given slot.
Called on:GPURenderEncoderBasethis.Arguments:
Arguments for the GPURenderEncoderBase.setVertexBuffer(slot, buffer, offset, size) method. Parameter Type Nullable Optional Description slotGPUIndex32 ✘ ✘ The vertex buffer slot to set the vertex buffer for. bufferGPUBuffer ✘ ✘ Buffer containing vertex data to use for subsequent drawing commands. offsetGPUSize64 ✘ ✔ Offset in bytes into buffer where the vertex data begins. sizeGPUSize64 ✘ ✔ Size in bytes of the vertex data in buffer . If 0, buffer .[[size]]- offset is used.Returns:
undefinedIssue the following steps on the Device timeline of this .
[[device]]:-
If any of the following conditions are unsatisfied, make this invalid and stop.
-
buffer is valid to use with this .
-
slot < maximum number of vertex buffers .
-
offset + size ≤ buffer .
[[size]].
-
-
Add buffer to the usage scope as input .
-
Set this .
[[vertex_buffers]][ slot ] to be buffer .
-
-
draw(vertexCount, instanceCount, firstVertex, firstInstance) -
Draws primitives.
Called on:GPURenderEncoderBasethis.Arguments:
Arguments for the GPURenderEncoderBase.draw(vertexCount, instanceCount, firstVertex, firstInstance) method. Parameter Type Nullable Optional Description vertexCountGPUSize32 ✘ ✘ The number of vertices to draw. instanceCountGPUSize32 ✘ ✔ The number of instances to draw. firstVertexGPUSize32 ✘ ✔ Offset into the vertex buffers, in vertices, to begin drawing from. firstInstanceGPUSize32 ✘ ✔ First instance to draw. Returns:
undefinedIssue the following steps on the Device timeline of this .
[[device]]:If any of the following conditions are unsatisfied, make this invalid and stop.-
It is valid to draw with this .
-
-
drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance) -
Draws indexed primitives.
Called on:GPURenderEncoderBasethis.Arguments:
Arguments for the GPURenderEncoderBase.drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance) method. Parameter Type Nullable Optional Description indexCountGPUSize32 ✘ ✘ The number of indices to draw. instanceCountGPUSize32 ✘ ✔ The number of instances to draw. firstIndexGPUSize32 ✘ ✔ Offset into the index buffer, in indices, begin drawing from. baseVertexGPUSignedOffset32 ✘ ✔ Added to each index value before indexing into the vertex buffers. firstInstanceGPUSize32 ✘ ✔ First instance to draw. Returns:
undefinedIssue the following steps on the Device timeline of this .
[[device]]:If any of the following conditions are unsatisfied, make this invalid and stop.-
It is valid to draw indexed with this .
-
-
drawIndirect(indirectBuffer, indirectOffset) -
Draws primitives using parameters read from a
GPUBuffer.The indirect draw parameters encoded in the buffer must be a tightly packed block of four 32-bit unsigned integer values (16 bytes total) , given in the same order as the arguments for
draw(). For example:let drawIndirectParameters= new Uint32Array( 4 ); drawIndirectParameters[ 0 ] = vertexCount; drawIndirectParameters[ 1 ] = instanceCount; drawIndirectParameters[ 2 ] = firstVertex; drawIndirectParameters[ 3 ] = firstInstance; Called on:GPURenderEncoderBasethis.Arguments:
Arguments for the GPURenderEncoderBase.drawIndirect(indirectBuffer, indirectOffset) method. Parameter Type Nullable Optional Description indirectBufferGPUBuffer ✘ ✘ Buffer containing the indirect draw parameters . indirectOffsetGPUSize64 ✘ ✘ Offset in bytes into indirectBuffer where the drawing data begins. Returns:
undefinedIssue the following steps on the Device timeline of this .
[[device]]:-
If any of the following conditions are unsatisfied, make this invalid and stop.
-
It is valid to draw with this .
-
indirectBuffer is valid to use with this .
-
indirectOffset + sizeof( indirect draw parameters ) ≤ indirectBuffer .
[[size]]. -
indirectOffset is a multiple of 4.
-
-
Add indirectBuffer to the usage scope as input .
-
-
drawIndexedIndirect(indirectBuffer, indirectOffset) -
Draws indexed primitives using parameters read from a
GPUBuffer.The indirect drawIndexed parameters encoded in the buffer must be a tightly packed block of five 32-bit unsigned integer values (20 bytes total) , given in the same order as the arguments for
drawIndexed(). For example:let drawIndexedIndirectParameters= new Uint32Array( 5 ); drawIndexedIndirectParameters[ 0 ] = indexCount; drawIndexedIndirectParameters[ 1 ] = instanceCount; drawIndexedIndirectParameters[ 2 ] = firstIndex; drawIndexedIndirectParameters[ 3 ] = baseVertex; drawIndexedIndirectParameters[ 4 ] = firstInstance; Called on:GPURenderEncoderBasethis.Arguments:
Arguments for the GPURenderEncoderBase.drawIndexedIndirect(indirectBuffer, indirectOffset) method. Parameter Type Nullable Optional Description indirectBufferGPUBuffer ✘ ✘ Buffer containing the indirect drawIndexed parameters . indirectOffsetGPUSize64 ✘ ✘ Offset in bytes into indirectBuffer where the drawing data begins. Returns:
undefinedIssue the following steps on the Device timeline of this .
[[device]]:-
If any of the following conditions are unsatisfied, make this invalid and stop.
-
It is valid to draw indexed with this .
-
indirectBuffer is valid to use with this .
-
indirectOffset + sizeof( indirect drawIndexed parameters ) ≤ indirectBuffer .
[[size]]. -
indirectOffset is a multiple of 4.
-
-
Add indirectBuffer to the usage scope as input .
-
GPURenderEncoderBase
encoder
run
the
following
steps:
If
any
of
the
following
conditions
are
unsatisfied,
return
false
:
-
Validate encoder bind groups ( encoder , encoder .
[[pipeline]]) must betrue. -
Let pipelineDescriptor be encoder .
[[pipeline]].[[descriptor]]. -
For each
GPUIndex32slot0to pipelineDescriptor .vertexState.vertexBuffers.length:-
encoder .
[[vertex_buffers]][ slot ] must not benull.
-
Otherwise
return
true
.
GPURenderEncoderBase
encoder
run
the
following
steps:
If
any
of
the
following
conditions
are
unsatisfied,
return
false
:
-
It must be valid to draw with encoder .
-
encoder .
[[index_buffer]]must not benull. -
Let stripIndexFormat be encoder .
[[pipeline]].[[strip_index_format]]. -
If stripIndexFormat is not
undefined:-
encoder .
[[index_format]]must be stripIndexFormat .
-
Otherwise
return
true
.
15.1.3. Rasterization state
The
GPURenderPassEncoder
has
several
methods
which
affect
how
draw
commands
are
rasterized
to
attachments
used
by
this
encoder.
-
setViewport(x, y, width, height, minDepth, maxDepth) -
Sets the viewport used during the rasterization stage to linearly map from normalized device coordinates to viewport coordinates.
Called on:GPURenderPassEncoderthis .Arguments:
Arguments for the GPURenderPassEncoder.setViewport(x, y, width, height, minDepth, maxDepth) method. Parameter Type Nullable Optional Description xfloat ✘ ✘ Minimum X value of the viewport in pixels. yfloat ✘ ✘ Minimum Y value of the viewport in pixels. widthfloat ✘ ✘ Width of the viewport in pixels. heightfloat ✘ ✘ Height of the viewport in pixels. minDepthfloat ✘ ✘ Minimum depth value of the viewport. maxDepthfloat ✘ ✘ Maximum depth value of the viewport. Returns:
undefinedIssue the following steps on the Device timeline of this :
-
If any of the following conditions are unsatisfied, generate a validation error and stop.
-
x is greater than or equal to
0. -
y is greater than or equal to
0. -
width is greater than or equal to
0. -
height is greater than or equal to
0. -
x + width is less than or equal to this .
[[attachment_size]].width. -
y + height is less than or equal to this .
[[attachment_size]].height. -
minDepth is greater than or equal to
0.0and less than or equal to1.0. -
maxDepth is greater than or equal to
0.0and less than or equal to1.0. -
maxDepth is greater than minDepth .
-
-
Set the viewport to the extents x , y , width , height , minDepth , and maxDepth .
Allowed for GPUs to use fixed point or rounded viewport coordinates
-
-
setScissorRect(x, y, width, height) -
Sets the scissor rectangle used during the rasterization stage. After transformation into viewport coordinates any fragments which fall outside the scissor rectangle will be discarded.
Called on:GPURenderPassEncoderthis .Arguments:
Arguments for the GPURenderPassEncoder.setScissorRect(x, y, width, height) method. Parameter Type Nullable Optional Description xGPUIntegerCoordinate ✘ ✘ Minimum X value of the scissor rectangle in pixels. yGPUIntegerCoordinate ✘ ✘ Minimum Y value of the scissor rectangle in pixels. widthGPUIntegerCoordinate ✘ ✘ Width of the scissor rectangle in pixels. heightGPUIntegerCoordinate ✘ ✘ Height of the scissor rectangle in pixels. Returns:
undefinedIssue the following steps on the Device timeline of this :
-
If any of the following conditions are unsatisfied, generate a validation error and stop.
-
x + width is less than or equal to this .
[[attachment_size]].width. -
y + height is less than or equal to this .
[[attachment_size]].height.
-
-
Set the scissor rectangle to the extents x , y , width , and height .
-
-
setBlendColor(color) -
Sets the constant blend color and alpha values used with
"blend-color"and"one-minus-blend-color"GPUBlendFactors.Called on:GPURenderPassEncoderthis.Arguments:
Arguments for the GPURenderPassEncoder.setBlendColor(color) method. Parameter Type Nullable Optional Description colorGPUColor ✘ ✘ The color to use when blending. -
setStencilReference(reference) -
Sets the stencil reference value used during stencil tests with the the
"replace"GPUStencilOperation.Called on:GPURenderPassEncoderthis.Arguments:
Arguments for the GPURenderPassEncoder.setStencilReference(reference) method. Parameter Type Nullable Optional Description referenceGPUStencilValue ✘ ✘ The stencil reference value.
15.1.4. Queries
-
beginOcclusionQuery(queryIndex) -
Called on:
GPURenderPassEncoderthis.Arguments:
Arguments for the GPURenderPassEncoder.beginOcclusionQuery(queryIndex) method. Parameter Type Nullable Optional Description queryIndexGPUSize32 ✘ ✘ Returns:
undefinedDescribe
beginOcclusionQuery()algorithm steps. -
endOcclusionQuery() -
Called on:
GPURenderPassEncoderthis.Returns:
undefinedDescribe
endOcclusionQuery()algorithm steps. -
beginPipelineStatisticsQuery(querySet, queryIndex) -
Called on:
GPURenderPassEncoderthis.Arguments:
Arguments for the GPURenderPassEncoder.beginPipelineStatisticsQuery(querySet, queryIndex) method. Parameter Type Nullable Optional Description querySetGPUQuerySet ✘ ✘ queryIndexGPUSize32 ✘ ✘ Returns:
undefinedDescribe
beginPipelineStatisticsQuery()algorithm steps. -
endPipelineStatisticsQuery() -
Called on:
GPURenderPassEncoderthis.Returns:
undefinedDescribe
endPipelineStatisticsQuery()algorithm steps. -
writeTimestamp(querySet, queryIndex) -
Called on:
GPURenderPassEncoderthis.Arguments:
Arguments for the GPURenderPassEncoder.writeTimestamp(querySet, queryIndex) method. Parameter Type Nullable Optional Description querySetGPUQuerySet ✘ ✘ queryIndexGPUSize32 ✘ ✘ Returns:
undefinedDescribe
writeTimestamp()algorithm steps.
15.1.5. Bundles
-
executeBundles(bundles) -
Executes the commands previously recorded into the given
GPURenderBundles as part of this render pass.When a
GPURenderBundleis executed, it does not inherit the render pass’s pipeline, bind groups, or vertex and index buffers. After aGPURenderBundlehas executed, the render pass’s pipeline, bind groups, and vertex and index buffers are cleared. If zeroGPURenderBundles are executed, the command buffer state is unchanged.Called on:GPURenderPassEncoderthis.Arguments:
Arguments for the GPURenderPassEncoder.executeBundles(bundles) method. Parameter Type Nullable Optional Description bundlessequence<GPURenderBundle> ✘ ✘ List of render bundles to execute. Returns:
undefinedDescribe
executeBundles()algorithm steps.
15.1.6. Finalization
The
render
pass
encoder
can
be
ended
by
calling
endPass()
once
the
user
has
finished
recording
commands
for
the
pass.
Once
endPass()
has
been
called
the
render
pass
encoder
can
no
longer
be
used.
-
endPass() -
Completes recording of the render pass commands sequence.
Called on:GPURenderPassEncoderthis .Returns:
undefinedIssue the following steps on the Device timeline of this :
-
If any of the following conditions are unsatisfied, generate a validation error and stop.
-
this .
[[debug_group_stack]]'s size is 0.
-
-
16. Bundles
16.1.
GPURenderBundle
interface GPURenderBundle { };GPURenderBundle includes GPUObjectBase ;
16.1.1. Creation
dictionary :GPURenderBundleDescriptor GPUObjectDescriptorBase { };
interface {GPURenderBundleEncoder GPURenderBundle finish (optional GPURenderBundleDescriptor descriptor = {}); };GPURenderBundleEncoder includes GPUObjectBase ;GPURenderBundleEncoder includes GPUProgrammablePassEncoder ;GPURenderBundleEncoder includes GPURenderEncoderBase ;
-
createRenderBundleEncoder(descriptor) -
Creates a
GPURenderBundleEncoder.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createRenderBundleEncoder(descriptor) method. Parameter Type Nullable Optional Description descriptorGPURenderBundleEncoderDescriptor ✘ ✘ Description of the GPURenderBundleEncoderto create.Returns:
GPURenderBundleEncoderDescribe
createRenderBundleEncoder()algorithm steps.
16.1.2. Encoding
dictionary :GPURenderBundleEncoderDescriptor GPUObjectDescriptorBase {required sequence <GPUTextureFormat >;colorFormats GPUTextureFormat ;depthStencilFormat GPUSize32 = 1; };sampleCount
16.1.3. Finalization
-
finish(descriptor) -
Completes recording of the render bundle commands sequence.
Called on:GPURenderBundleEncoderthis.Arguments:
Arguments for the GPURenderBundleEncoder.finish(descriptor) method. Parameter Type Nullable Optional Description descriptorGPURenderBundleDescriptor ✘ ✔ Returns:
GPURenderBundleDescribe
finish()algorithm steps.
17. Queues
interface {GPUQueue undefined submit (sequence <GPUCommandBuffer >commandBuffers );GPUFence createFence (optional GPUFenceDescriptor descriptor = {});undefined signal (GPUFence fence ,GPUFenceValue signalValue );undefined writeBuffer (GPUBuffer buffer ,GPUSize64 bufferOffset , [AllowShared ]BufferSource data ,optional GPUSize64 dataOffset = 0,optional GPUSize64 size );undefined writeTexture (GPUTextureCopyView destination , [AllowShared ]BufferSource data ,GPUTextureDataLayout dataLayout ,GPUExtent3D size );undefined copyImageBitmapToTexture (GPUImageBitmapCopyView source ,GPUTextureCopyView destination ,GPUExtent3D copySize ); };GPUQueue includes GPUObjectBase ;
GPUQueue
has
the
following
methods:
-
writeBuffer(buffer, bufferOffset, data, dataOffset, size) -
Issues a write operation of the provided data into a
GPUBuffer.Called on:GPUQueuethis .Arguments:
Arguments for the GPUQueue.writeBuffer(buffer, bufferOffset, data, dataOffset, size) method. Parameter Type Nullable Optional Description bufferGPUBuffer ✘ ✘ The buffer to write to. bufferOffsetGPUSize64 ✘ ✘ Offset in bytes into buffer to begin writing at. dataBufferSource ✘ ✘ Data to write into buffer . dataOffsetGPUSize64 ✘ ✔ Offset in into data to begin writing from. Given in elements if data is a TypedArrayand bytes otherwise.sizeGPUSize64 ✘ ✔ Size of content to write from data to buffer . Given in elements if data is a TypedArrayand bytes otherwise.Returns:
undefined-
If data is an
ArrayBufferorDataView, let the element type be "byte". Otherwise, data is a TypedArray; let the element type be the type of the TypedArray. -
Let dataSize be the size of data , in elements.
-
If size is unspecified, let contentsSize be dataSize − dataOffset . Otherwise, let contentsSize be size .
-
If any of the following conditions are unsatisfied, throw
OperationErrorand stop.-
contentsSize ≥ 0.
-
dataOffset + contentsSize ≤ dataSize .
-
contentsSize , converted to bytes, is a multiple of 4 bytes.
-
-
Let dataContents be a copy of the bytes held by the buffer source .
-
Let contents be the contentsSize elements of dataContents starting at an offset of dataOffset elements.
-
Issue the following steps on the Queue timeline of this :
-
If any of the following conditions are unsatisfied, generate a validation error and stop.
-
Write contents into buffer starting at bufferOffset .
-
-
-
writeTexture(destination, data, dataLayout, size) -
Issues a write operation of the provided data into a
GPUTexture.Called on:GPUQueuethis .Arguments:
Arguments for the GPUQueue.writeTexture(destination, data, dataLayout, size) method. Parameter Type Nullable Optional Description destinationGPUTextureCopyView ✘ ✘ The texture subresource and origin to write to. dataBufferSource ✘ ✘ Data to write into destination . dataLayoutGPUTextureDataLayout ✘ ✘ Layout of the content in data . sizeGPUExtent3D ✘ ✘ Extents of the content to write from data to destination . Returns:
undefined-
Let dataBytes be a copy of the bytes held by the buffer source data .
-
Let dataByteSize be the number of bytes in dataBytes .
-
If any of the following conditions are unsatisfied, throw
OperationErrorand stop.-
validating linear texture data ( dataLayout , dataByteSize , destination .
texture.[[format]], size ) succeeds.
-
-
Let contents be the contents of the images seen by viewing dataBytes with dataLayout and size .
-
Issue the following steps on the Queue timeline of this :
-
If any of the following conditions are unsatisfied, generate a validation error and stop.
-
validating GPUTextureCopyView ( destination , size ) returns
true. -
destination .
texture.[[textureUsage]]includesCOPY_DST. -
destination .
texture.[[sampleCount]]is 1. -
Valid Texture Copy Range ( destination , size ) is satisfied.
-
destination .
aspectrefers to a single copyable aspect of destination .texture.[[format]]. See depth-formats .
Note: unlike
GPUCommandEncoder.copyBufferToTexture(), there is no alignment requirement on dataLayout .bytesPerRow. -
-
Write contents into destination .
-
-
-
copyImageBitmapToTexture(source, destination, copySize) -
Schedules a copy operation of the contents of an image bitmap into the destination texture.
Called on:GPUQueuethis.Arguments:
Arguments for the GPUQueue.copyImageBitmapToTexture(source, destination, copySize) method. Parameter Type Nullable Optional Description sourceGPUImageBitmapCopyView ✘ ✘ ImageBitmapand origin to copy to destination .destinationGPUTextureCopyView ✘ ✘ The texture subresource and origin to write to. copySizeGPUExtent3D ✘ ✘ Extents of the content to write from source to destination . Returns:
undefinedIf any of the following conditions are unsatisfied, throw an
OperationErrorand stop.-
copySize . depth is
1. -
destination .
texture.[[format]]is one of the following:
-
-
submit(commandBuffers) -
Schedules the execution of the command buffers by the GPU on this queue.
Called on:GPUQueuethis.Arguments:
Arguments for the GPUQueue.submit(commandBuffers) method. Parameter Type Nullable Optional Description commandBufferssequence<GPUCommandBuffer> ✘ ✘ Returns:
undefinedIssue the following steps on the Device timeline of this :
-
If any of the following conditions are unsatisfied, generate a validation error and stop.
-
Every
GPUBufferreferenced in any element of commandBuffers is in the"unmapped"buffer state .
-
-
Issue the following steps on the Queue timeline of this :
-
For each commandBuffer in commandBuffers :
-
Execute each command in commandBuffer .
[[command_list]].
-
-
-
17.1.
GPUFence
interface GPUFence {GPUFenceValue getCompletedValue ();Promise <undefined >onCompletion (GPUFenceValue completionValue ); };GPUFence includes GPUObjectBase ;
17.1.1. Creation
dictionary :GPUFenceDescriptor GPUObjectDescriptorBase {GPUFenceValue = 0; };initialValue
-
createFence(descriptor) -
Creates a
GPUFence.Called on:GPUQueuethis.Arguments:
Arguments for the GPUQueue.createFence(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUFenceDescriptor ✘ ✔ Description of the GPUFenceto create.Returns:
GPUFenceDescribe
createFence()algorithm steps.
17.1.2. Completion
Completion
of
a
fence
is
signaled
from
the
GPUQueue
that
created
it.
-
signal(fence, signalValue) -
Signals the given fence, increasing it’s completed value to
signalValue.Called on:GPUQueuethis.Arguments:
Arguments for the GPUQueue.signal(fence, signalValue) method. Parameter Type Nullable Optional Description fenceGPUFence ✘ ✘ The fence to signal. signalValueGPUFenceValue ✘ ✘ The value to increase fence ’s completion value to. Returns:
undefinedDescribe
signal()algorithm steps.
The
completion
of
the
fence
and
the
value
it
completes
with
can
be
observed
from
the
GPUFence
.
-
getCompletedValue() -
Returns the largest signalled value completion value for the fence that has propagated to the content timeline .
-
onCompletion(completionValue) -
Returns a
Promisethat resolves once the fence’s completion value ≥completionValue.Called on:GPUFencethis.Arguments:
Arguments for the GPUFence.onCompletion(completionValue) method. Parameter Type Nullable Optional Description completionValueGPUFenceValue ✘ ✘ The completion value that the fence must meet or exceed before resolving the returned PromiseReturns:
Promise<undefined>Describe
onCompletion()algorithm steps.
18. Queries
18.1.
GPUQuerySet
interface GPUQuerySet {undefined destroy (); };GPUQuerySet includes GPUObjectBase ;
18.1.1. Creation
dictionary :GPUQuerySetDescriptor GPUObjectDescriptorBase {required GPUQueryType ;type required GPUSize32 ;count sequence <GPUPipelineStatisticName >pipelineStatistics = []; };
-
pipelineStatistics, of type sequence< GPUPipelineStatisticName >, defaulting to[] -
The set of
GPUPipelineStatisticNamevalues in this sequence defines which pipeline statistics will be returned in the new query set.Valid Usage-
pipelineStatistics is ignored if type is not
pipeline-statistics. -
If
pipeline-statistics-queryis not available, type must not bepipeline-statistics. -
If type is
pipeline-statistics, pipelineStatistics must be a sequence ofGPUPipelineStatisticNamevalues which cannot be duplicated.
-
-
createQuerySet(descriptor) -
Creates a
GPUQuerySet.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createQuerySet(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUQuerySetDescriptor ✘ ✘ Description of the GPUQuerySetto create.Returns:
GPUQuerySetDescribe
createQuerySet()algorithm steps.
18.1.2. Finalization
-
destroy() -
Destroys the
GPUQuerySet.
18.2. QueryType
enum {GPUQueryType ,"occlusion" ,"pipeline-statistics" };"timestamp"
18.3. Pipeline Statistics Query
enum {GPUPipelineStatisticName ,"vertex-shader-invocations" ,"clipper-invocations" ,"clipper-primitives-out" ,"fragment-shader-invocations" };"compute-shader-invocations"
When
resolving
pipeline
statistics
query,
each
result
is
written
into
GPUSize64
,
and
the
number
and
order
of
the
results
written
to
GPU
buffer
matches
the
number
and
order
of
GPUPipelineStatisticName
specified
in
pipelineStatistics
.
The
beginPipelineStatisticsQuery()
and
endPipelineStatisticsQuery()
(on
both
GPUComputePassEncoder
and
GPURenderPassEncoder
)
cannot
be
nested.
A
pipeline
statistics
query
must
be
ended
before
beginning
another
one.
Pipeline
statistics
query
requires
pipeline-statistics-query
is
available
on
the
device.
18.4. Timestamp Query
Timestamp
query
allows
application
to
write
timestamp
values
to
a
GPUQuerySet
by
calling
writeTimestamp()
on
GPUComputePassEncoder
or
GPURenderPassEncoder
or
GPUCommandEncoder
,
and
then
resolve
timestamp
values
in
nanoseconds
(type
of
GPUSize64
)
to
a
GPUBuffer
(using
resolveQuerySet()
).
Timestamp
query
requires
timestamp-query
is
available
on
the
device.
Note: The timestamp values may be zero if the physical device reset timestamp counter, please ignore it and the following values.
Write normative text about timestamp value resets.
Because timestamp query provides high-resolution GPU timestamp, we need to decide what constraints, if any, are on its availability.
19. Canvas Rendering & Swap Chains
interface {GPUCanvasContext GPUSwapChain configureSwapChain (GPUSwapChainDescriptor descriptor );Promise <GPUTextureFormat >getSwapChainPreferredFormat (GPUDevice device ); };
-
configureSwapChain(descriptor) -
Configures the swap chain for this canvas, and returns a new
GPUSwapChainobject representing it. Destroys any swapchain previously returned byconfigureSwapChain, including all of the textures it has produced.Called on:GPUCanvasContextthis.Arguments:
Arguments for the GPUCanvasContext.configureSwapChain(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUSwapChainDescriptor ✘ ✘ Description of the GPUSwapChainto configure.Returns:
GPUSwapChainDescribe
configureSwapChain()algorithm steps. -
getSwapChainPreferredFormat(device) -
Returns an optimal
GPUTextureFormatto use for swap chains with this context and the given device.Called on:GPUCanvasContextthis.Arguments:
Arguments for the GPUCanvasContext.getSwapChainPreferredFormat(device) method. Parameter Type Nullable Optional Description deviceGPUDevice ✘ ✘ Device the swap chain format should be queried for. Returns:
Promise<GPUTextureFormat>Describe
getSwapChainPreferredFormat()algorithm steps.
dictionary :GPUSwapChainDescriptor GPUObjectDescriptorBase {required GPUDevice ;device required GPUTextureFormat ;format GPUTextureUsageFlags = 0x10; // GPUTextureUsage.RENDER_ATTACHMENT };usage
interface {GPUSwapChain ();GPUTexture getCurrentTexture (); };GPUSwapChain includes GPUObjectBase ;
In
the
"update
the
rendering
[of
the]
Document
"
step
of
the
"Update
the
rendering"
HTML
processing
model,
the
contents
of
the
GPUTexture
most
recently
returned
by
getCurrentTexture()
are
used
to
update
the
rendering
for
the
canvas
,
and
it
is
as
if
destroy()
were
called
on
it
(making
it
unusable
elsewhere
in
WebGPU).
Before this drawing buffer is presented for compositing, the implementation shall ensure that all rendering operations have been flushed to the drawing buffer.
-
getCurrentTexture() -
Get the
GPUTexturethat will be composited to the document by theGPUCanvasContextthat created this swap chain next.
20. Errors & Debugging
20.1. Fatal Errors
interface {GPUDeviceLostInfo readonly attribute DOMString ; };message partial interface GPUDevice {readonly attribute Promise <GPUDeviceLostInfo >; };lost
20.2. Error Scopes
enum {GPUErrorFilter ,"out-of-memory" };"validation"
interface {GPUOutOfMemoryError (); };constructor interface {GPUValidationError (constructor DOMString );message readonly attribute DOMString ; };message typedef (GPUOutOfMemoryError or GPUValidationError );GPUError
partial interface GPUDevice {undefined pushErrorScope (GPUErrorFilter );filter Promise <GPUError ?>popErrorScope (); };
-
pushErrorScope(filter) -
popErrorScope() -
Rejects with
OperationErrorif:-
The device is lost.
-
There are no error scopes on the stack.
-
20.3. Telemetry
[
Exposed =(Window , DedicatedWorker )
]
interface GPUUncapturedErrorEvent : Event {
constructor (
DOMString type ,
GPUUncapturedErrorEventInit gpuUncapturedErrorEventInitDict
);
[SameObject ] readonly attribute GPUError error ;
};
dictionary GPUUncapturedErrorEventInit : EventInit {
required GPUError error ;
};
partial interface GPUDevice { [Exposed =(Window ,DedicatedWorker )]attribute EventHandler ; };onuncapturederror
21. Type Definitions
typedef [EnforceRange ]unsigned long ;GPUBufferDynamicOffset typedef [EnforceRange ]unsigned long long ;GPUFenceValue typedef [EnforceRange ]unsigned long ;GPUStencilValue typedef [EnforceRange ]unsigned long ;GPUSampleMask typedef [EnforceRange ]long ;GPUDepthBias typedef [EnforceRange ]unsigned long long ;GPUSize64 typedef [EnforceRange ]unsigned long ;GPUIntegerCoordinate typedef [EnforceRange ]unsigned long ;GPUIndex32 typedef [EnforceRange ]unsigned long ;GPUSize32 typedef [EnforceRange ]long ;GPUSignedOffset32 typedef unsigned long ;GPUFlagsConstant
21.1. Colors & Vectors
dictionary {GPUColorDict required double ;r required double ;g required double ;b required double ; };a typedef (sequence <double >or GPUColorDict );GPUColor
Note:
double
is
large
enough
to
precisely
hold
32-bit
signed/unsigned
integers
and
single-precision
floats.
dictionary {GPUOrigin2DDict GPUIntegerCoordinate = 0;x GPUIntegerCoordinate = 0; };y typedef (sequence <GPUIntegerCoordinate >or GPUOrigin2DDict );GPUOrigin2D
An
Origin2D
is
a
GPUOrigin2D
.
Origin2D
is
a
spec
namespace
for
the
following
definitions:
GPUOrigin2D
value
origin
,
depending
on
its
type,
the
syntax:
-
origin . x refers to either
GPUOrigin2DDict.xor the first item of the sequence or 0 if it isn’t present. -
origin . y refers to either
GPUOrigin2DDict.yor the second item of the sequence or 0 if it isn’t present.
dictionary {GPUOrigin3DDict GPUIntegerCoordinate = 0;x GPUIntegerCoordinate = 0;y GPUIntegerCoordinate = 0; };z typedef (sequence <GPUIntegerCoordinate >or GPUOrigin3DDict );GPUOrigin3D
An
Origin3D
is
a
GPUOrigin3D
.
Origin3D
is
a
spec
namespace
for
the
following
definitions:
GPUOrigin3D
value
origin
,
depending
on
its
type,
the
syntax:
-
origin . x refers to either
GPUOrigin3DDict.xor the first item of the sequence or 0 if it isn’t present. -
origin . y refers to either
GPUOrigin3DDict.yor the second item of the sequence or 0 if it isn’t present. -
origin . z refers to either
GPUOrigin3DDict.zor the third item of the sequence or 0 if it isn’t presnet.
dictionary {GPUExtent3DDict GPUIntegerCoordinate = 1;width GPUIntegerCoordinate = 1;height GPUIntegerCoordinate = 1; };depth typedef (sequence <GPUIntegerCoordinate >or GPUExtent3DDict );GPUExtent3D
An
Extent3D
is
a
GPUExtent3D
.
Extent3D
is
a
spec
namespace
for
the
following
definitions:
GPUExtent3D
value
extent
,
depending
on
its
type,
the
syntax:
-
extent . width refers to either
GPUExtent3DDict.widthor the first item of the sequence or 1 if it isn’t present. -
extent . height refers to either
GPUExtent3DDict.heightor the second item of the sequence or 1 if it isn’t present. -
extent . depth refers to either
GPUExtent3DDict.depthor the third item of the sequence or 1 if it isn’t present.
22. Feature Index
22.1.
depth-clamping
Define
functionality
when
the
"depth-clamping"
feature
is
enabled.
Feature Dictionary Values
The
following
dictionary
values
are
supported
if
and
only
if
the
"depth-clamping"
feature
is
enabled,
otherwise
they
must
be
set
to
their
default
values:
-
GPURasterizationStateDescriptor
22.2.
depth24unorm-stencil8
Allows
for
explicit
creation
of
textures
of
format
"depth24unorm-stencil8"
.
Feature Enums
The
following
enums
are
supported
if
and
only
if
the
"depth24unorm-stencil8"
feature
is
enabled:
-
GPUTextureFormat
22.3.
depth32float-stencil8
Allows
for
explicit
creation
of
textures
of
format
"depth32float-stencil8"
.
Feature Enums
The
following
enums
are
supported
if
and
only
if
the
"depth32float-stencil8"
feature
is
enabled:
-
GPUTextureFormat
22.4.
pipeline-statistics-query
Define
functionality
when
the
"pipeline-statistics-query"
feature
is
enabled.
Feature Enums
The
following
enums
are
supported
if
and
only
if
the
"pipeline-statistics-query"
feature
is
enabled:
-
GPUQueryType
22.5.
texture-compression-bc
Allows for explicit creation of textures of BC compressed formats.
Feature Enums
The
following
enums
are
supported
if
and
only
if
the
"texture-compression-bc"
feature
is
enabled:
-
GPUTextureFormat
22.6.
timestamp-query
Define
functionality
when
the
"timestamp-query"
feature
is
enabled.
Feature Enums
The
following
enums
are
supported
if
and
only
if
the
"timestamp-query"
feature
is
enabled:
-
GPUQueryType
23. Appendices
23.1. Texture Format Capabilities
Add multisampling to the tables below.
23.1.1. Plain color formats
All
plain
color
formats
support
COPY_SRC
,
COPY_DST
,
and
SAMPLED
usage.
Only
formats
with
GPUTextureComponentType
"float"
can
be
blended.
The
GPUTextureUsage.STORAGE
column
specifies
the
support
for
STORAGE
usage
in
the
core
API,
including
both
"readonly-storage-texture"
and
"writeonly-storage-texture"
.
The
"Filter"
column
specifies
whether
textures
of
this
format
can
be
sampled
in
shaders
with
a
sampler
having
linear
filtering.
| Format |
Component
Type
|
RENDER_ATTACHMENT
|
STORAGE
| Filter |
|---|---|---|---|---|
| 8-bit per component | ||||
r8unorm
|
"float"
| ✓ | ✓ | |
r8snorm
|
"float"
| ✓ | ||
r8uint
|
"uint"
| ✓ | ||
r8sint
|
"sint"
| ✓ | ||
rg8unorm
|
"float"
| ✓ | ✓ | |
rg8snorm
|
"float"
| ✓ | ||
rg8uint
|
"uint"
| ✓ | ||
rg8sint
|
"sint"
| ✓ | ||
rgba8unorm
|
"float"
| ✓ | ✓ | ✓ |
rgba8unorm-srgb
|
"float"
| ✓ | ✓ | |
rgba8snorm
|
"float"
| ✓ | ✓ | |
rgba8uint
|
"uint"
| ✓ | ✓ | |
rgba8sint
|
"sint"
| ✓ | ✓ | |
bgra8unorm
|
"float"
| ✓ | ✓ | |
bgra8unorm-srgb
|
"float"
| ✓ | ✓ | |
| 16-bit per component | ||||
r16uint
|
"uint"
| ✓ | ||
r16sint
|
"sint"
| ✓ | ||
r16float
|
"float"
| ✓ | ✓ | |
rg16uint
|
"uint"
| ✓ | ||
rg16sint
|
"sint"
| ✓ | ||
rg16float
|
"float"
| ✓ | ✓ | |
rgba16uint
|
"uint"
| ✓ | ✓ | |
rgba16sint
|
"sint"
| ✓ | ✓ | |
rgba16float
|
"float"
| ✓ | ✓ | ✓ |
| 32-bit per component | ||||
r32uint
|
"uint"
| ✓ | ✓ | |
r32sint
|
"sint"
| ✓ | ✓ | |
r32float
|
"float"
| ✓ | ✓ | |
rg32uint
|
"uint"
| ✓ | ✓ | |
rg32sint
|
"sint"
| ✓ | ✓ | |
rg32float
|
"float"
| ✓ | ✓ | |
rgba32uint
|
"uint"
| ✓ | ✓ | |
rgba32sint
|
"sint"
| ✓ | ✓ | |
rgba32float
|
"float"
| ✓ | ✓ | |
| mixed component width | ||||
rgb10a2unorm
|
"float"
| ✓ | ✓ | |
rg11b10ufloat
|
"float"
| ✓ |
23.1.2. Depth/stencil formats
All
depth
formats
support
COPY_SRC
,
COPY_DST
,
SAMPLED
,
and
RENDER_ATTACHMENT
usage.
However,
the
source/destination
is
restricted
based
on
the
format.
None of the depth formats can be filtered.
| Format | Bytes per texel | Aspect |
Component
Types
| Copy aspect from Buffer | Copy aspect into Buffer |
|---|---|---|---|---|---|
stencil8
| 1 − 5 | stencil |
"uint"
| ✓ | |
depth16unorm
| 2 | depth |
"float"
,
"depth-comparison"
| ✓ | |
depth24plus
| 4 | depth |
"float"
,
"depth-comparison"
| ✗ | |
depth24plus-stencil8
| 4 − 8 | depth |
"float"
,
"depth-comparison"
| ✗ | |
| stencil |
"uint"
| ✓ | |||
depth32float
| 4 | depth |
"float"
,
"depth-comparison"
| ✗ | ✓ |
Copies between depth textures can only happen within the following sets of formats:
-
stencil8,depth24plus-stencil8(stencil component),r8uint -
depth24plus,depth24plus-stencil8(depth aspect)
The
depth32float
format
can
only
the
destination
if
copied
from
another
texture
of
the
same
format.
It
can
also
be
a
source
of
copies
into
r32float
.
clarify
if
depth24plus-stencil8
is
copyable
into
depth24plus
in
Metal.
23.1.3. Packed formats
All
packed
texture
formats
support
COPY_SRC
,
COPY_DST
,
and
SAMPLED
usages.
All
of
these
formats
have
float
type
and
can
be
filtered
on
sampling.
| Format | Bytes per block |
Component
Types
| Block Size | Feature |
|---|---|---|---|---|
rgb9e5ufloat
| 4 |
"float"
| 1 × 1 | |
bc1-rgba-unorm
| 8 |
"float"
| 4 × 4 |
texture-compression-bc
|
bc1-rgba-unorm-srgb
| ||||
bc2-rgba-unorm
| 16 | |||
bc2-rgba-unorm-srgb
| ||||
bc3-rgba-unorm
| 16 | |||
bc3-rgba-unorm-srgb
| ||||
bc4-r-unorm
| 8 | |||
bc4-r-snorm
| ||||
bc5-rg-unorm
| 16 | |||
bc5-rg-snorm
| ||||
bc6h-rgb-ufloat
| 16 | |||
bc6h-rgb-float
| ||||
bc7-rgba-unorm
| 16 | |||
bc7-rgba-unorm-srgb
|
23.2. Temporary usages of non-exported dfns
Eventually all of these should disappear but they are useful to avoid warning while building the specification.