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 (post-2014) 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
setBlendConstant()
.
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"
GPUBufferBinding
),
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
minBindingSize
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 completion of work on the queue, 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 control of how much the machine specifics are exposed. One strategy to reduce fingerprinting 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 default limits are also deliberately high enough to allow most applications 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.
2.8.4. User Agent State
This
specification
doesn’t
define
any
additional
user-agent
state
for
an
origin.
However
it
is
expected
that
user
agents
will
have
compilation
caches
for
the
result
of
expensive
compilation
like
GPUShaderModule
,
GPURenderPipeline
and
GPUComputePipeline
.
These
caches
are
important
to
improve
the
loading
time
of
WebGPU
applications
after
the
first
visit.
For
the
specification,
these
caches
are
indifferentiable
from
incredibly
fast
compilation,
but
for
applications
it
would
be
easy
to
measure
how
long
createComputePipelineAsync()
takes
to
resolve.
This
can
leak
information
across
origins
(like
"did
the
user
access
a
site
with
this
specific
shader")
so
user
agents
should
follow
the
best
practices
in
storage
partitioning
.
The system’s GPU driver may also have its own cache of compiled shaders and pipelines. User agents may want to disable these when at all possible, or add per-partition data to shaders in ways that will make the GPU driver consider them different.
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
."
The
?.
("optional
chaining")
syntax,
adopted
from
JavaScript,
is
also
used.
The
phrasing
"
Foo?.Bar
"
means
"if
Foo
is
null
or
undefined
,
undefined
;
otherwise,
Foo.Bar
".
For
example,
where
buffer
is
a
GPUBuffer
,
buffer?.[[device]].[[adapter]]
means
"if
buffer
is
null
or
undefined
,
then
undefined
;
otherwise,
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.
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
Object creation operations in WebGPU are internally asynchronous, so they don’t fail with exceptions. Instead, returned objects may refer to internal objects which are either valid or invalid . An invalid object may never become valid at a later time. Some objects may become invalid during their lifetime, while most may only be invalid from creation.
Objects are invalid from creation if it wasn’t possible to create them. 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.
Internal
objects
of
most
types
cannot
become
invalid
after
they
are
created,
but
still
may
become
unusable,
e.g.
if
the
owning
device
is
lost
or
destroyed
,
or
the
object
has
a
special
internal
state,
like
buffer
state
destroyed
.
Internal objects of some types can become invalid after they are created; specifically, devices , adapters , and command/pass/bundle encoders.
GPUObjectBase
object
is
valid
to
use
with
a
targetObject
if
and
only
if
the
following
requirements
are
met:
-
object must be valid .
-
object .
[[device]]must be valid . -
object .
[[device]]must equal targetObject .[[device]].
3.3. Coordinate Systems
-
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.
Note: WebGPU’s coordinate systems match DirectX’s coordinate systems in a graphics pipeline.
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 with an internal usage :
- input
-
Buffer with input data for draw or dispatch calls. Preserves the contents. Allowed by buffer
INDEX, bufferVERTEX, or bufferINDIRECT. - constant
-
Resource bindings that are constant from the shader point of view. Preserves the contents. Allowed by buffer
UNIFORMor textureTEXTURE_BINDING. - storage
-
Writable storage resource binding. Allowed by buffer
STORAGEor textureSTORAGE_BINDING. - storage-read
-
Read-only storage resource bindings. Preserves the contents. Allowed by buffer
STORAGE. - attachment
-
Texture used as an output attachment in a render pass. Allowed by texture
RENDER_ATTACHMENT. - attachment-read
-
Texture used as a read-only attachment in a render pass. Preserves the contents. Allowed by texture
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 .
-
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
GPURenderPassColorAttachment.view
and
GPURenderPassColorAttachment.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
GPUTextureFormats, the physical size is always equal to the size of the texture subresource used in the sampling hardwares. -
Textures in block-based compressed
GPUTextureFormatsalways have a mipmap level 0 whose[[descriptor]].sizeis a multiple of the texel block size , but the lower mipmap levels might not be multiples of the texel block size and can have paddings.
GPUTexture
in
BC
format
whose
[[descriptor]]
.
size
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 . 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 :
-
Outside of a pass (in
GPUCommandEncoder), each (non-state-setting) command is one usage scope (e.g.copyBufferToTexture()). -
In a compute pass, each dispatch command (
dispatch()ordispatchIndirect()) is one usage scope. A subresource is "used" in the usage scope if it is potentially accessible by the command. Within a dispatch, for each bind group slot that is used by the currentGPUComputePipeline's[[layout]], every subresource referenced by that bind group is "used" in the usage scope. State-setting compute pass commands, likesetBindGroup(index, bindGroup, dynamicOffsets), do not contribute directly to a usage scope; they instead change the state that is checked in dispatch commands. -
One render pass is one usage scope. A subresource is "used" in the usage scope if it’s referenced by any (state-setting or non-state-setting) command. For example, in
setBindGroup(index, bindGroup, dynamicOffsets), every subresource inbindGroupis "used" in the render pass’s usage scope.
The above should probably talk about GPU commands . But we don’t have a way to reference specific GPU commands (like dispatch) yet.
-
In a render pass, subresources used in any
setBindGroup()call, regardless of whether the currently bound pipeline’s shader or layout actually depends on these bindings, or the bind group is shadowed by another 'set' call. -
A buffer used in any
setVertexBuffer()call, regardless of whether any draw call depends on this buffer, or this buffer is shadowed by another 'set' call. -
A buffer used in any
setIndexBuffer()call, regardless of whether any draw call depends on this buffer, or this buffer is shadowed by another 'set' call. -
A texture subresource used as a color attachment, resolve attachment, or depth/stencil attachment in
GPURenderPassDescriptorbybeginRenderPass(), regardless of whether the shader actually depends on these attachments. -
Resources used in bind group entries with visibility 0, or visible only to the compute stage but used in a render pass (or vice versa).
During
command
encoding,
every
usage
of
a
subresource
is
recorded
in
one
of
the
usage
scopes
in
the
command
buffer.
For
each
usage
scope
,
the
implementation
performs
usage
scope
validation
by
composing
the
list
of
all
internal
usage
flags
of
each
subresource
used
in
the
usage
scope
.
If
any
of
those
lists
is
not
a
compatible
usage
list
,
GPUCommandEncoder.finish()
generates
a
GPUValidationError
in
the
current
error
scope.
3.5. Core Internal Objects
3.5.1. Adapters
An adapter identifies an implementation of WebGPU on the system: both an instance of compute/rendering functionality on the platform underlying a browser, and an instance of a browser’s implementation of WebGPU on top of that functionality.
Adapters
do
not
uniquely
represent
underlying
implementations:
calling
requestAdapter()
multiple
times
returns
a
different
adapter
object
each
time.
An adapter object may become invalid at any time. This happens inside " lose the device " and " mark adapters stale ". An invalid adapter is unable to vend new devices .
Note:
This
mechanism
ensures
that
various
adapter-creation
scenarios
look
similar
to
applications,
so
they
can
easily
be
robust
to
more
scenarios
with
less
testing:
first
initialization,
reinitialization
due
to
an
unplugged
adapter,
reinitialization
due
to
a
test
GPUDevice.destroy()
call,
etc.
It
also
ensures
applications
use
the
latest
system
state
to
make
decisions
about
which
adapter
to
use.
An adapter may be considered a fallback adapter if it has significant performance caveats in exchange for some combination of wider compatibility, more predictable behavior, or improved privacy. It is not required that a fallback adapter is available on every system.
An adapter has the following internal slots:
-
[[features]], of type ordered set <GPUFeatureName>, readonly -
The features which can be used to create devices on this adapter.
-
[[limits]], of type supported limits , 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 supported limits .
-
[[fallback]], of type boolean -
If set to
trueindicates that the adapter is a fallback adapter .
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
or
destroyed
,
it
and
all
objects
created
on
it
(directly,
e.g.
createTexture()
,
or
indirectly,
e.g.
createView()
)
become
implicitly
unusable
.
A device has the following internal slots:
-
[[adapter]], of type adapter , readonly -
The adapter from which this device was created.
-
[[features]], of type ordered set <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 type supported limits , 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 the set of values in descriptor .requiredFeatures. -
Let device .
[[limits]]be a supported limits object with the default values. For each ( key , value ) pair in descriptor .requiredLimits, set the member corresponding to key in device .[[limits]]to the better value of value or the default value in supported limits .
Any
time
the
user
agent
needs
to
revoke
access
to
a
device,
it
calls
lose
the
device
(device,
undefined
).
-
Make device .
[[adapter]]invalid . -
Make device invalid .
-
explain how to get from device to its "primary"
GPUDevice. -
Resolve
GPUDevice.lostwith a newGPUDeviceLostInfowithreasonset to reason andmessageset to an implementation-defined value.Note:
messageshould not disclose unnecessary user/system information and should never be parsed by applications.
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.
A
supported
limits
object
has
a
value
for
every
defined
limit.
Each
adapter
has
a
set
of
supported
limits
,
and
devices
are
created
with
specific
supported
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
default
value.
Every
adapter
is
guaranteed
to
support
the
default
value
or
better
.
The
default
is
used
if
a
value
is
not
explicitly
specified
in
requiredLimits
.
| Limit name | Type | Better | Default |
|---|---|---|---|
maxTextureDimension1D
|
GPUSize32
| Higher | 8192 |
The
maximum
allowed
value
for
the
size
.
width
of
a
texture
created
with
dimension
"1d"
.
| |||
maxTextureDimension2D
|
GPUSize32
| Higher | 8192 |
The
maximum
allowed
value
for
the
size
.
width
and
size
.
height
of
a
texture
created
with
dimension
"2d"
.
| |||
maxTextureDimension3D
|
GPUSize32
| Higher | 2048 |
The
maximum
allowed
value
for
the
size
.
width
,
size
.
height
and
size
.
depthOrArrayLayers
of
a
texture
created
with
dimension
"3d"
.
| |||
maxTextureArrayLayers
|
GPUSize32
| Higher | 256 |
The
maximum
allowed
value
for
the
size
.
depthOrArrayLayers
of
a
texture
created
with
dimension
"1d"
or
"2d"
.
| |||
maxBindGroups
|
GPUSize32
| Higher | 4 |
The
maximum
number
of
GPUBindGroupLayouts
allowed
in
bindGroupLayouts
when
creating
a
GPUPipelineLayout
.
| |||
maxDynamicUniformBuffersPerPipelineLayout
|
GPUSize32
| Higher | 8 |
The
maximum
number
of
GPUBindGroupLayoutEntry
entries
across
a
GPUPipelineLayout
which
are
uniform
buffers
with
dynamic
offsets.
See
Exceeds
the
binding
slot
limits
.
| |||
maxDynamicStorageBuffersPerPipelineLayout
|
GPUSize32
| Higher | 4 |
The
maximum
number
of
GPUBindGroupLayoutEntry
entries
across
a
GPUPipelineLayout
which
are
storage
buffers
with
dynamic
offsets.
See
Exceeds
the
binding
slot
limits
.
| |||
maxSampledTexturesPerShaderStage
|
GPUSize32
| Higher | 16 |
For
each
possible
GPUShaderStage
stage
,
the
maximum
number
of
GPUBindGroupLayoutEntry
entries
across
a
GPUPipelineLayout
which
are
sampled
textures.
See
Exceeds
the
binding
slot
limits
.
| |||
maxSamplersPerShaderStage
|
GPUSize32
| Higher | 16 |
For
each
possible
GPUShaderStage
stage
,
the
maximum
number
of
GPUBindGroupLayoutEntry
entries
across
a
GPUPipelineLayout
which
are
samplers.
See
Exceeds
the
binding
slot
limits
.
| |||
maxStorageBuffersPerShaderStage
|
GPUSize32
| Higher | 8 |
For
each
possible
GPUShaderStage
stage
,
the
maximum
number
of
GPUBindGroupLayoutEntry
entries
across
a
GPUPipelineLayout
which
are
storage
buffers.
See
Exceeds
the
binding
slot
limits
.
| |||
maxStorageTexturesPerShaderStage
|
GPUSize32
| Higher | 4 |
For
each
possible
GPUShaderStage
stage
,
the
maximum
number
of
GPUBindGroupLayoutEntry
entries
across
a
GPUPipelineLayout
which
are
storage
textures.
See
Exceeds
the
binding
slot
limits
.
| |||
maxUniformBuffersPerShaderStage
|
GPUSize32
| Higher | 12 |
For
each
possible
GPUShaderStage
stage
,
the
maximum
number
of
GPUBindGroupLayoutEntry
entries
across
a
GPUPipelineLayout
which
are
uniform
buffers.
See
Exceeds
the
binding
slot
limits
.
| |||
maxUniformBufferBindingSize
|
GPUSize64
| Higher | 65536 |
The
maximum
GPUBufferBinding
.
size
for
bindings
with
a
GPUBindGroupLayoutEntry
entry
for
which
entry
.
buffer
?.
type
is
"uniform"
.
| |||
maxStorageBufferBindingSize
|
GPUSize64
| Higher | 134217728 (128 MiB) |
The
maximum
GPUBufferBinding
.
size
for
bindings
with
a
GPUBindGroupLayoutEntry
entry
for
which
entry
.
buffer
?.
type
is
"storage"
or
"read-only-storage"
.
| |||
minUniformBufferOffsetAlignment
|
GPUSize32
| Lower | 256 |
The
required
alignment
for
GPUBufferBinding
.
offset
and
setBindGroup
dynamicOffsets
arguments
for
binding
with
a
GPUBindGroupLayoutEntry
entry
for
which
entry
.
buffer
?.
type
is
"uniform"
.
| |||
minStorageBufferOffsetAlignment
|
GPUSize32
| Lower | 256 |
The
required
alignment
for
GPUBufferBinding
.
offset
and
setBindGroup
dynamicOffsets
arguments
for
binding
with
a
GPUBindGroupLayoutEntry
entry
for
which
entry
.
buffer
?.
type
is
"storage"
or
"read-only-storage"
.
| |||
maxVertexBuffers
|
GPUSize32
| Higher | 8 |
The
maximum
number
of
buffers
when
creating
a
GPURenderPipeline
.
| |||
maxVertexAttributes
|
GPUSize32
| Higher | 16 |
The
maximum
number
of
attributes
in
total
across
buffers
when
creating
a
GPURenderPipeline
.
| |||
maxVertexBufferArrayStride
|
GPUSize32
| Higher | 2048 |
The
maximum
allowed
arrayStride
when
creating
a
GPURenderPipeline
.
| |||
maxInterStageShaderComponents
|
GPUSize32
| Higher | 60 |
| The maximum allowed number of components of input or output variables for inter-stage communication (like vertex outputs or fragment inputs). | |||
maxComputeWorkgroupStorageSize
|
GPUSize32
| Higher | 16352 |
The
maximum
number
of
bytes
used
for
a
compute
stage
GPUShaderModule
entry-point.
| |||
maxComputeInvocationsPerWorkgroup
|
GPUSize32
| Higher | 256 |
The
maximum
value
of
the
product
of
the
workgroup_size
dimensions
for
a
compute
stage
GPUShaderModule
entry-point.
| |||
maxComputeWorkgroupSizeX
|
GPUSize32
| Higher | 256 |
The
maximum
value
of
the
workgroup_size
X
dimension
for
a
compute
stage
GPUShaderModule
entry-point.
| |||
maxComputeWorkgroupSizeY
|
GPUSize32
| Higher | 256 |
The
maximum
value
of
the
workgroup_size
Y
dimensions
for
a
compute
stage
GPUShaderModule
entry-point.
| |||
maxComputeWorkgroupSizeZ
|
GPUSize32
| Higher | 64 |
The
maximum
value
of
the
workgroup_size
Z
dimensions
for
a
compute
stage
GPUShaderModule
entry-point.
| |||
maxComputeWorkgroupsPerDimension
|
GPUSize32
| Higher | 65535 |
The
maximum
value
for
the
arguments
of
dispatch(x,
y,
z)
.
| |||
Do we need to have a max per-pixel render target size?
3.6.2.1.
GPUSupportedLimits
GPUSupportedLimits
exposes
the
limits
supported
by
an
adapter
or
device.
See
GPUAdapter.limits
and
GPUDevice.limits
.
[Exposed =(Window ,DedicatedWorker ),SecureContext ]interface GPUSupportedLimits {readonly attribute unsigned long ;maxTextureDimension1D readonly attribute unsigned long ;maxTextureDimension2D readonly attribute unsigned long ;maxTextureDimension3D readonly attribute unsigned long ;maxTextureArrayLayers readonly attribute unsigned long ;maxBindGroups readonly attribute unsigned long ;maxDynamicUniformBuffersPerPipelineLayout readonly attribute unsigned long ;maxDynamicStorageBuffersPerPipelineLayout readonly attribute unsigned long ;maxSampledTexturesPerShaderStage readonly attribute unsigned long ;maxSamplersPerShaderStage readonly attribute unsigned long ;maxStorageBuffersPerShaderStage readonly attribute unsigned long ;maxStorageTexturesPerShaderStage readonly attribute unsigned long ;maxUniformBuffersPerShaderStage readonly attribute unsigned long long ;maxUniformBufferBindingSize readonly attribute unsigned long long ;maxStorageBufferBindingSize readonly attribute unsigned long ;minUniformBufferOffsetAlignment readonly attribute unsigned long ;minStorageBufferOffsetAlignment readonly attribute unsigned long ;maxVertexBuffers readonly attribute unsigned long ;maxVertexAttributes readonly attribute unsigned long ;maxVertexBufferArrayStride readonly attribute unsigned long ;maxInterStageShaderComponents readonly attribute unsigned long ;maxComputeWorkgroupStorageSize readonly attribute unsigned long ;maxComputeInvocationsPerWorkgroup readonly attribute unsigned long ;maxComputeWorkgroupSizeX readonly attribute unsigned long ;maxComputeWorkgroupSizeY readonly attribute unsigned long ;maxComputeWorkgroupSizeZ readonly attribute unsigned long ; };maxComputeWorkgroupsPerDimension
3.6.2.2.
GPUSupportedFeatures
GPUSupportedFeatures
is
a
setlike
interface.
Its
set
entries
are
the
GPUFeatureName
values
of
the
features
supported
by
an
adapter
or
device.
It
must
only
contain
strings
from
the
GPUFeatureName
enum.
[Exposed =(Window ,DedicatedWorker ),SecureContext ]interface GPUSupportedFeatures {readonly setlike <DOMString >; };
GPUSupportedFeatures
set
entries
is
DOMString
to
allow
user
agents
to
gracefully
handle
valid
GPUFeatureName
s
which
are
added
in
later
revisions
of
the
spec
but
which
the
user
agent
has
not
been
updated
to
recognize
yet.
If
the
set
entries
type
was
GPUFeatureName
the
following
code
would
throw
an
TypeError
rather
than
reporting
false
:
3.7. Origin Restrictions
WebGPU allows accessing image data stored in images, videos, and canvases. Restrictions are imposed on the use of cross-domain media, because shaders can be used to indirectly deduce the contents of textures which have been uploaded to the GPU.
WebGPU disallows uploading an image source if it is not origin-clean .
This
also
implies
that
the
origin-clean
flag
for
a
canvas
rendered
using
WebGPU
will
never
be
set
to
false
.
For more information on issuing CORS requests for image and video elements, consult:
3.8. Color Spaces and Encoding
WebGPU does not provide color management. All values within WebGPU (such as texture elements) are raw numeric values, not color-managed color values.
WebGPU
does
interface
with
color-managed
outputs
(via
GPUCanvasConfiguration
)
and
inputs
(via
copyExternalImageToTexture()
and
importExternalTexture()
).
Thus,
color
conversion
must
be
performed
between
the
WebGPU
numeric
values
and
the
external
color
values.
Each
such
interface
point
locally
defines
an
encoding
(color
space,
transfer
function,
and
alpha
premultiplication)
in
which
the
WebGPU
numeric
values
are
to
be
interpreted.
Each color space is defined over an extended range, if defined by the referenced CSS definitions, to represent color values outside of its space (in both chrominance and luminance).
enum {GPUPredefinedColorSpace "srgb" , };
Possibly
replace
this
with
PredefinedColorSpace
,
but
note
that
doing
so
would
mean
new
WebGPU
functionality
gets
added
automatically
when
items
are
added
to
that
enum
in
the
upstream
spec.
Consider a path for uploading srgb-encoded images into linearly-encoded textures. [Issue #gpuweb/gpuweb#1715]
-
"srgb" -
The CSS predefined color space srgb .
3.8.1. Color Space Conversions
A color is converted between spaces by translating its representation in one space to a representation in another according to the definitions above.
If
the
source
value
has
fewer
than
4
channels,
the
remaining
green/blue/alpha
channels
are
set
to
0,
0,
1
respectively,
as
needed,
before
converting
for
color
space/encoding
and
alpha
premultiplication.
After
conversion,
if
the
destination
needs
fewer
than
4
channels,
the
additional
channels
are
ignored.
Colors are not lossily clamped during conversion: converting from one color space to another will result in values outside the range [0, 1] if the source color values were outside the range of the destination color space’s gamut (e.g. if a Display P3 image is converted to sRGB).
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
in
the
Window
and
DedicatedWorkerGlobalScope
contexts
through
the
Navigator
and
WorkerNavigator
interfaces
respectively
and
is
exposed
via
navigator.gpu
:
interface mixin { [NavigatorGPU SameObject ,SecureContext ]readonly attribute GPU ; };gpu Navigator includes NavigatorGPU ;WorkerNavigator includes NavigatorGPU ;
4.3. GPU
GPU
is
the
entry
point
to
WebGPU.
[Exposed =(Window ,DedicatedWorker ),SecureContext ]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, it should:
-
Create a valid adapter adapter , chosen according to the rules in § 4.3.1 Adapter Selection and the criteria in options .
-
If adapter meets the criteria of a fallback adapter set adapter .
[[fallback]]totrue. -
Resolve promise with a new
GPUAdapterencapsulating adapter .
-
-
Otherwise, promise resolves with
null.
-
-
Return promise .
-
GPU
has
the
following
internal
slots:
-
[[previously_returned_adapters]], of type ordered set < adapter > -
The set of adapters that have been returned via
requestAdapter(). It is used, then cleared, in mark adapters stale .
Upon
any
change
in
the
system’s
state
that
could
affect
the
result
of
any
requestAdapter()
call,
the
user
agent
should
mark
adapters
stale
.
For
example:
-
A physical adapter is added/removed (via plug, driver update, TDR, etc.)
-
The system’s power configuration has changed (laptop unplugged, power settings changed, etc.)
Additionally,
mark
adapters
stale
may
by
scheduled
at
any
time.
User
agents
may
choose
to
do
this
often
even
when
there
has
been
no
system
state
change
(e.g.
several
seconds
after
the
last
call
to
requestDevice()
.
This
has
no
effect
on
well-formed
applications,
obfuscates
real
system
state
changes,
and
makes
developers
more
aware
that
calling
requestAdapter()
again
is
always
necessary
before
calling
requestDevice()
.
-
For each adapter in
navigator.gpu.[[previously_returned_adapters]]:-
Make adapter .
[[adapter]]invalid .
-
-
Empty
navigator.gpu.[[previously_returned_adapters]].
Update
here
if
an
adaptersadded
/
adapterschanged
event
is
introduced.
GPUAdapter
:
const adapter= await navigator. gpu. requestAdapter( /* ... */ ); const features= adapter. features; // ...
4.3.1. Adapter Selection
GPURequestAdapterOptions
provides
hints
to
the
user
agent
indicating
what
configuration
is
suitable
for
the
application.
dictionary GPURequestAdapterOptions {GPUPowerPreference powerPreference ;boolean forceFallbackAdapter =false ; };
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.
-
-
forceFallbackAdapter, of type boolean , defaulting tofalse -
When set to
trueindicates that only a fallback adapter may be returned. If the user agent does not support a fallback adapter , will causerequestAdapter()to resolve tonull.Note:
requestAdapter()may still return a fallback adapter ifforceFallbackAdapteris set tofalseand either no other appropriate adapter is available or the user agent chooses to return a fallback adapter . Developers that wish to prevent their applications from running on fallback adapters should check theGPUAdapter.isFallbackAdapterattribute prior to requesting aGPUDevice.
4.4.
GPUAdapter
A
GPUAdapter
encapsulates
an
adapter
,
and
describes
its
capabilities
(
features
and
limits
).
To
get
a
GPUAdapter
,
use
requestAdapter()
.
[Exposed =(Window ,DedicatedWorker ),SecureContext ]interface GPUAdapter {readonly attribute DOMString name ; [SameObject ]readonly attribute GPUSupportedFeatures features ; [SameObject ]readonly attribute GPUSupportedLimits limits ;readonly attribute boolean isFallbackAdapter ;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 GPUSupportedFeatures , readonly -
The set of values in
this.[[adapter]].[[features]]. -
limits, of type GPUSupportedLimits , readonly -
The limits in
this.[[adapter]].[[limits]]. -
isFallbackAdapter, of type boolean , readonly -
Returns the value of
[[adapter]].[[fallback]].
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 .
-
Let adapter be this .
[[adapter]]. -
Issue the following steps to the Device timeline :
-
If any of the following requirements are unmet, reject promise with a
TypeErrorand stop.-
The set of values in descriptor .
requiredFeaturesmust be a subset of those in adapter .[[features]].
Note: This is the same error that is produced if a feature name isn’t known by the browser at all (in its
GPUFeatureNamedefinition). This converges the behavior when the browser doesn’t support a feature with the behavior when a particular adapter doesn’t support a feature. -
-
If any of the following requirements are unmet, reject promise with an
OperationErrorand stop.-
Each key in descriptor .
requiredLimitsmust be the name of a member of supported limits . -
For each type of limit in supported limits , the value of that limit in descriptor .
requiredLimitsmust be no better than the value of that limit in adapter .[[limits]].
-
-
If adapter is invalid , or the user agent otherwise cannot fulfill the request:
-
Let device be a new device .
-
Lose the device ( device ,
undefined).Note: This makes adapter invalid , if it wasn’t already.
Note: User agents should consider issuing developer-visible warnings in most or all cases when this occurs. Applications should perform reinitialization logic starting with
requestAdapter(). -
Resolve promise with a new
GPUDeviceencapsulating device , and stop.
-
-
Resolve promise with 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 >requiredFeatures = [];record <DOMString ,GPUSize64 >requiredLimits = {}; };
GPUDeviceDescriptor
has
the
following
members:
-
requiredFeatures, of type sequence< GPUFeatureName >, defaulting to[] -
Specifies the features that are required by the device request. The request will fail if the adapter cannot provide these features.
Exactly the specified set of features, and no more or less, will be allowed in validation of API calls on the resulting device.
-
requiredLimits, of type record< DOMString , GPUSize64 >, defaulting to{} -
Specifies the limits that are required by the device request. The request will fail if the adapter cannot provide these limits.
Each key must be the name of a member of supported limits . Exactly the specified limits, and no better or worse, will be allowed in validation of API calls on the resulting 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-clip-control" ,"depth24unorm-stencil8" ,"depth32float-stencil8" ,"texture-compression-bc" ,"texture-compression-etc2" ,"texture-compression-astc" ,"timestamp-query" ,"indirect-first-instance" , };
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 ),SecureContext ]interface GPUDevice :EventTarget { [SameObject ]readonly attribute GPUSupportedFeatures features ; [SameObject ]readonly attribute GPUSupportedLimits limits ; [SameObject ]readonly attribute GPUQueue queue ;undefined destroy ();GPUBuffer createBuffer (GPUBufferDescriptor descriptor );GPUTexture createTexture (GPUTextureDescriptor descriptor );GPUSampler createSampler (optional GPUSamplerDescriptor descriptor = {});GPUExternalTexture importExternalTexture (GPUExternalTextureDescriptor 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 >createComputePipelineAsync (GPUComputePipelineDescriptor descriptor );Promise <GPURenderPipeline >createRenderPipelineAsync (GPURenderPipelineDescriptor descriptor );GPUCommandEncoder createCommandEncoder (optional GPUCommandEncoderDescriptor descriptor = {});GPURenderBundleEncoder createRenderBundleEncoder (GPURenderBundleEncoderDescriptor descriptor );GPUQuerySet createQuerySet (GPUQuerySetDescriptor descriptor ); };GPUDevice includes GPUObjectBase ;
GPUDevice
has
the
following
attributes:
-
features, of type GPUSupportedFeatures , readonly -
A set containing the
GPUFeatureNamevalues of the features supported by the device (i.e. the ones with which it was created). -
limits, of type GPUSupportedLimits , readonly -
Exposes the limits supported by the device (which are exactly the ones with which it was created).
-
queue, of type GPUQueue , readonly -
The primary
GPUQueuefor this device.
The
[[device]]
for
a
GPUDevice
is
the
device
that
the
GPUDevice
refers
to.
GPUDevice
has
the
methods
listed
in
its
WebIDL
definition
above.
Those
not
defined
here
are
defined
elsewhere
in
this
document.
-
destroy() -
Destroys the device , preventing further operations on it. Outstanding asynchronous operations will fail.
Called on:GPUDevicethis .-
Lose the device ( this .
[[device]],"destroyed").
Note: Since no further operations can occur on this device, implementations can free resource allocations and abort outstanding asynchronous operations immediately.
-
GPUDevice
objects
are
serializable
objects
.
Finish
defining
multithreading
API
and
add
[Serializable]
back
to
the
interface.
[Issue
#gpuweb/gpuweb#354]
-
Set serialized .agentCluster to be the surrounding agent 's agent cluster .
-
If serialized .agentCluster’s cross-origin isolated capability 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.
[Exposed =(Window ,DedicatedWorker ),SecureContext ]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? [Issue #gpuweb/gpuweb#605] -
[[mapping_range]]of type list <unsigned long long> 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
[[descriptor]]
.
usage
.
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
a
reference
to
an
internal
buffer
object.
Finish
defining
multithreading
API
and
add
[Serializable]
back
to
the
interface.
[Issue
#gpuweb/gpuweb#354]
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 ; };
-
mappedAtCreationguarantees that even if the buffer eventually fails creation, it will still appear as if the mapped range can be written/read to until it is unmapped.
5.2.2. Buffer Usage
typedef [EnforceRange ]unsigned long ; [GPUBufferUsageFlags Exposed =(Window ,DedicatedWorker )]namespace {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 what are a
GPUDevice's[[allowed buffer usages]]. [Issue #gpuweb/gpuweb#605]
Note: If buffer creation fails, and descriptor .
mappedAtCreationisfalse, any calls tomapAsync()will reject, so any resources allocated to enable mapping can and may be discarded or recycled.-
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.3. Buffer Destruction
An
application
that
no
longer
requires
a
GPUBuffer
can
choose
to
lose
access
to
it
before
garbage
collection
by
calling
destroy()
.
Destroying
a
buffer
also
unmaps
it,
freeing
any
memory
allocated
for
the
mapping.
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.4. 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.
[Issue
#gpuweb/gpuweb#605]
typedef [EnforceRange ]unsigned long ; [GPUMapModeFlags Exposed =(Window ,DedicatedWorker )]namespace {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. [Issue #gpuweb/gpuweb#605]
-
If size is missing:
-
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 missing:
-
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 requirements are unmet, generate a validation error and stop.
-
this .
[[state]]must be mapped at creation , mapping pending , or mapped .
Note: It is valid to unmap an invalid
GPUBufferthat is mapped at creation because the Content timeline might not know it is an errorGPUBuffer. This allows the temporary[[mapping]]memory to be freed. -
-
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
GPUTextures
are
created
via
GPUDevice.createTexture(descriptor)
that
returns
a
new
texture.
[Exposed =(Window ,DedicatedWorker ),SecureContext ]interface GPUTexture {GPUTextureView createView (optional GPUTextureViewDescriptor descriptor = {});undefined destroy (); };GPUTexture includes GPUObjectBase ;
GPUTexture
has
the
following
internal
slots:
-
[[descriptor]], of typeGPUTextureDescriptor -
The
GPUTextureDescriptordescribing this texture.All optional fields of
GPUTextureDescriptorare defined. -
[[destroyed]], of typeboolean, initially false -
If the texture is destroyed, it can no longer be used in any operation, and its underlying memory can be freed.
Arguments:
-
GPUExtent3DbaseSize -
GPUSize32mipLevel
Returns:
GPUExtent3DDict
-
Let extent be a new
GPUExtent3DDictobject. -
Set extent .
heightto max(1, baseSize . height ≫ mipLevel ). -
Set extent .
depthOrArrayLayersto 1. -
Return extent .
share this definition with the part of the specification that describes sampling.
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 Exposed =(Window ,DedicatedWorker )]namespace {GPUTextureUsage const GPUFlagsConstant = 0x01;COPY_SRC const GPUFlagsConstant = 0x02;COPY_DST const GPUFlagsConstant = 0x04;TEXTURE_BINDING const GPUFlagsConstant = 0x08;STORAGE_BINDING 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:
GPUTexture-
Issue the following steps on the Device timeline of this :
-
If descriptor .
formatis aGPUTextureFormatthat requires a feature (see § 24.1 Texture Format Capabilities ), but this .[[device]].[[features]]does not contain the feature, throw aTypeError. -
If any of the following requirements are unmet:
-
descriptor .
size. width , descriptor .size. height , and descriptor .size. depthOrArrayLayers must be greater than zero. -
descriptor .
mipLevelCountmust be greater than zero. -
descriptor .
sampleCountmust be either 1 or 4. -
If descriptor .
dimensionis:-
"1d" -
-
descriptor .
size. width must be less than or equal to this .limits.maxTextureDimension1D. -
descriptor .
size. depthOrArrayLayers must be 1. -
descriptor .
sampleCountmust be 1. -
descriptor .
formatmust not be a compressed format or depth-or-stencil format .
-
-
"2d" -
-
descriptor .
size. width must be less than or equal to this .limits.maxTextureDimension2D. -
descriptor .
size. height must be less than or equal to this .limits.maxTextureDimension2D. -
descriptor .
size. depthOrArrayLayers must be less than or equal to this .limits.maxTextureArrayLayers.
-
-
"3d" -
-
descriptor .
size. width must be less than or equal to this .limits.maxTextureDimension3D. -
descriptor .
size. height must be less than or equal to this .limits.maxTextureDimension3D. -
descriptor .
size. depthOrArrayLayers must be less than or equal to this .limits.maxTextureDimension3D. -
descriptor .
sampleCountmust be 1. -
descriptor .
formatmust not be a compressed format or depth-or-stencil format .
-
-
-
descriptor .
size. width must be multiple of texel block width . -
descriptor .
size. height must be multiple of texel block height . -
If descriptor .
sampleCount> 1:-
descriptor .
mipLevelCountmust be 1. -
descriptor .
size. depthOrArrayLayers must be 1. -
descriptor .
usagemust not include theSTORAGE_BINDINGbit. -
descriptor .
formatmust be a renderable format .
-
-
descriptor .
mipLevelCountmust be less than or equal to maximum mipLevel count ( descriptor .dimension, descriptor .size). -
descriptor .
usagemust be a combination ofGPUTextureUsagevalues. -
If descriptor .
usageincludes theRENDER_ATTACHMENTbit, descriptor .formatmust be a renderable format . -
If descriptor .
usageincludes theSTORAGE_BINDINGbit, descriptor .formatmust be listed in § 24.1.1 Plain color formats table withSTORAGE_BINDINGcapability.
Then:
-
Generate a
GPUValidationErrorin the current scope with appropriate error message. -
Return a new invalid
GPUTexture.
-
Let t be a new
GPUTextureobject. -
Set t .
[[descriptor]]to descriptor . -
Return t .
-
-
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
[Exposed =(Window ,DedicatedWorker ),SecureContext ]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. -
[[renderExtent]] -
For renderable views, this is the effective
GPUExtent3DDictfor rendering.Note: this extent depends on the
baseMipLevel.
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
enum {GPUTextureViewDimension ,"1d" ,"2d" ,"2d-array" ,"cube" ,"cube-array" , };"3d"
enum {GPUTextureAspect ,"all" ,"stencil-only" , };"depth-only"
-
createView(descriptor) -
Creates a
GPUTextureView.Called on:GPUTexturethis .Arguments:
Arguments for the GPUTexture.createView(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUTextureViewDescriptor ✘ ✔ Description of the GPUTextureViewto create.Returns: view , of type
GPUTextureView.-
Set descriptor to the result of resolving GPUTextureViewDescriptor defaults with descriptor .
-
Issue the following steps on the Device timeline of this :
-
If any of the following requirements are unmet:
-
this is valid
-
If the descriptor .
aspectis-
"stencil-only" -
this .
[[descriptor]].formatmust be a depth-or-stencil format which has a stencil aspect. -
"depth-only" -
this .
[[descriptor]].formatmust be a depth-or-stencil format which has a depth aspect.
-
-
descriptor .
mipLevelCountmust be > 0. -
descriptor .
baseMipLevel+ descriptor .mipLevelCountmust be ≤ this .[[descriptor]].mipLevelCount. -
descriptor .
arrayLayerCountmust be > 0. -
descriptor .
baseArrayLayer+ descriptor .arrayLayerCountmust be ≤ the array layer count of this . -
descriptor .
formatmust be this .[[descriptor]].format. -
If descriptor .
dimensionis:-
"1d" -
this .
[[descriptor]].dimensionmust be"1d".descriptor .
arrayLayerCountmust be1. -
"2d" -
this .
[[descriptor]].dimensionmust be"2d".descriptor .
arrayLayerCountmust be1. -
"2d-array" -
this .
[[descriptor]].dimensionmust be"2d". -
"cube" -
this .
[[descriptor]].dimensionmust be"2d".descriptor .
arrayLayerCountmust be6.this .
[[descriptor]].size. width must be this .[[descriptor]].size. height . -
"cube-array" -
this .
[[descriptor]].dimensionmust be"2d".descriptor .
arrayLayerCountmust be a multiple of6.this .
[[descriptor]].size. width must be this .[[descriptor]].size. height . -
"3d" -
this .
[[descriptor]].dimensionmust be"3d".descriptor .
arrayLayerCountmust be1.
-
Then:
-
Generate a
GPUValidationErrorin the current scope with appropriate error message. -
Return a new invalid
GPUTextureView.
-
-
Let view be a new
GPUTextureViewobject. -
Set view .
[[texture]]to this . -
Set view .
[[descriptor]]to descriptor . -
If this .
[[descriptor]].usagecontainsRENDER_ATTACHMENT:-
Let renderExtent be compute render extent ( this .
[[descriptor]].size, descriptor .baseMipLevel). -
Set view .
[[renderExtent]]to renderExtent .
-
-
Return view .
-
-
GPUTextureViewDescriptor
descriptor
run
the
following
steps:
-
Let resolved be a copy of descriptor .
-
If resolved .
formatisundefined, set resolved .formatto texture .[[descriptor]].format. -
If resolved .
mipLevelCountisundefined, set resolved .mipLevelCountto texture .[[descriptor]].mipLevelCount−baseMipLevel. -
If resolved .
dimensionisundefinedand texture .[[descriptor]].dimensionis: -
If resolved .
arrayLayerCountisundefinedand resolved .dimensionis:-
"1d","2d", or"3d" -
Set resolved .
arrayLayerCountto1. -
"cube" -
Set resolved .
arrayLayerCountto6. -
"2d-array"or"cube-array" -
Set resolved .
arrayLayerCountto texture .[[descriptor]].size. depthOrArrayLayers −baseArrayLayer.
-
-
Return resolved .
GPUTexture
texture
,
run
the
following
steps:
-
If texture .
[[descriptor]].dimensionis:-
"1d"or"3d" -
Return
1. -
"2d" -
Return texture .
[[descriptor]].size. depthOrArrayLayers .
-
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/stencil formats"rgba32float" ,"stencil8" ,"depth16unorm" ,"depth24plus" ,"depth24plus-stencil8" , // "depth24unorm-stencil8" feature"depth32float" , // "depth32float-stencil8" feature"depth24unorm-stencil8" , // BC compressed formats usable if "texture-compression-bc" is both // supported by the device/user agent and enabled in requestDevice."depth32float-stencil8" ,"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" , // ETC2 compressed formats usable if "texture-compression-etc2" is both // supported by the device/user agent and enabled in requestDevice."bc7-rgba-unorm-srgb" ,"etc2-rgb8unorm" ,"etc2-rgb8unorm-srgb" ,"etc2-rgb8a1unorm" ,"etc2-rgb8a1unorm-srgb" ,"etc2-rgba8unorm" ,"etc2-rgba8unorm-srgb" ,"eac-r11unorm" ,"eac-r11snorm" ,"eac-rg11unorm" , // ASTC compressed formats usable if "texture-compression-astc" is both // supported by the device/user agent and enabled in requestDevice."eac-rg11snorm" ,"astc-4x4-unorm" ,"astc-4x4-unorm-srgb" ,"astc-5x4-unorm" ,"astc-5x4-unorm-srgb" ,"astc-5x5-unorm" ,"astc-5x5-unorm-srgb" ,"astc-6x5-unorm" ,"astc-6x5-unorm-srgb" ,"astc-6x6-unorm" ,"astc-6x6-unorm-srgb" ,"astc-8x5-unorm" ,"astc-8x5-unorm-srgb" ,"astc-8x6-unorm" ,"astc-8x6-unorm-srgb" ,"astc-8x8-unorm" ,"astc-8x8-unorm-srgb" ,"astc-10x5-unorm" ,"astc-10x5-unorm-srgb" ,"astc-10x6-unorm" ,"astc-10x6-unorm-srgb" ,"astc-10x8-unorm" ,"astc-10x8-unorm-srgb" ,"astc-10x10-unorm" ,"astc-10x10-unorm-srgb" ,"astc-12x10-unorm" ,"astc-12x10-unorm-srgb" ,"astc-12x12-unorm" , };"astc-12x12-unorm-srgb"
The
depth
component
of
the
"depth24plus"
)
and
"depth24plus-stencil8"
)
formats
may
be
implemented
as
either
a
24-bit
unsigned
normalized
value
(like
"depth24unorm"
in
"depth24unorm-stencil8"
)
or
a
32-bit
IEEE
754
floating
point
value
(like
"depth32float"
).
add
something
on
GPUAdapter(?)
that
gives
an
estimate
of
the
bytes
per
texel
of
"stencil8"
,
"depth24plus-stencil8"
,
and
"depth32float-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 channels is strictly higher than the precision of depth24unorm channels for all values in the representable range (0.0 to 1.0), note that the set of representable values is not an exact superset: 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 ).
A
renderable
format
is
either
a
color
renderable
format
,
or
a
depth-or-stencil
format
.
If
a
format
is
listed
in
§ 24.1.1
Plain
color
formats
with
RENDER_ATTACHMENT
capability,
it
is
a
color
renderable
format.
Any
other
format
is
not
a
color
renderable
format.
All
depth-or-stencil
formats
are
renderable.
6.4.
GPUExternalTexture
A
GPUExternalTexture
is
a
sampleable
texture
wrapping
an
external
video
object.
The
contents
of
a
GPUExternalTexture
object
may
not
change,
either
from
inside
WebGPU
(it
is
only
sampleable)
or
from
outside
WebGPU
(e.g.
due
to
video
frame
advancement).
Update this description with canvas.
They
are
bound
into
bind
group
layouts
using
the
externalTexture
bind
group
layout
entry
member.
External
textures
use
several
binding
slots:
see
Exceeds
the
binding
slot
limits
.
The underlying representation of an external texture is unobservable (except for sampling behavior) but typically may include
-
Up to three 2D planes of data (e.g. RGBA, Y+UV, Y+U+V).
-
Metadata for converting coordinates before reading from those planes (crop and rotation).
-
Metadata for converting values into the specified output color space (matrices, gammas, 3D LUT).
The configuration used may not be stable across time, systems, user agents, media sources, or frames within a single video source. In order to account for many possible representations, the binding conservatively uses the following, for each external texture:
-
three sampled texture bindings (for up to 3 planes),
-
one sampled texture binding for a 3D LUT,
-
one sampler binding to sample the 3D LUT, and
-
one uniform buffer binding for metadata.
[Exposed =(Window ,DedicatedWorker ),SecureContext ]interface GPUExternalTexture { };GPUExternalTexture includes GPUObjectBase ;
GPUExternalTexture
has
the
following
internal
slots:
-
[[destroyed]], of typeboolean -
Indicates whether the object has been destroyed (can no longer be used). Initially set to
false.
6.4.1. Importing External Textures
An
external
texture
is
created
from
an
external
video
object
using
importExternalTexture()
.
Update this description with canvas.
External textures are destroyed automatically, as a microtask, instead of manually or upon garbage collection like other resources.
dictionary :GPUExternalTextureDescriptor GPUObjectDescriptorBase {required HTMLVideoElement ;source GPUPredefinedColorSpace = "srgb"; };colorSpace
-
importExternalTexture(descriptor) -
Creates a
GPUExternalTexturewrapping the provided image source.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.importExternalTexture(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUExternalTextureDescriptor ✘ ✘ Provides the external image source object (and any creation options). Returns:
GPUExternalTexture-
Let source be descriptor .
source. -
Let usability be the result of checking the usability of source (which may throw an exception).
-
If usability is
bad, throw anInvalidStateErrorand stop. -
If source is not origin-clean , throw a
SecurityErrorand stop. -
Let data be the result of converting the current image contents of source into the color space descriptor .
colorSpacewith unpremultiplied alpha.This may result in values outside of the range [0, 1]. If clamping is desired, it may be performed after sampling.
Note: This is described like a copy, but may be implemented as a reference to read-only underlying data plus appropriate metadata to perform conversion later.
-
Let result be a new
GPUExternalTextureobject wrapping data . -
Queue a microtask to set result .
[[destroyed]]totrue, releasing the underlying resource. -
Return result .
-
6.4.2. Sampling External Textures
External
textures
are
represented
in
WGSL
with
texture_external
and
may
be
read
using
textureLoad
and
textureSampleLevel
.
The
sampler
provided
to
textureSampleLevel
is
used
to
sample
the
underlying
textures.
The
result
is
in
the
color
space
set
by
colorSpace
.
It
is
implementation-dependent
whether,
for
any
given
external
texture,
the
sampler
(and
filtering)
is
applied
before
or
after
conversion
from
underlying
values
into
the
specified
color
space.
Note: If the internal representation is an RGBA plane, sampling behaves as on a regular 2D texture. If there are several underlying planes (e.g. Y+UV), the sampler is used to sample each underlying texture separately, prior to conversion from YUV to the specified color space.
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.
[Exposed =(Window ,DedicatedWorker ),SecureContext ]interface GPUSampler { };GPUSampler includes GPUObjectBase ;
GPUSampler
has
the
following
internal
slots:
-
[[descriptor]], of typeGPUSamplerDescriptor, readonly -
The
GPUSamplerDescriptorwith which theGPUSamplerwas created. -
[[isComparison]]of typeboolean. -
Whether the
GPUSampleris used as a comparison sampler. -
[[isFiltering]]of typeboolean. -
Whether the
GPUSamplerweights multiple samples of a texture.
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 = 32;lodMaxClamp GPUCompareFunction ; [compare Clamp ]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.
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. -
descriptor .
maxAnisotropyis greater than or equal to 1. -
When descriptor .
maxAnisotropyis greater than 1, descriptor .magFilter, descriptor .minFilter, and descriptor .mipmapFiltermust be equal to"linear".
-
createSampler(descriptor) -
Creates a
GPUBindGroupLayout.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createSampler(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUSamplerDescriptor ✘ ✔ Description of the GPUSamplerto create.Returns:
GPUSampler-
Let s be a new
GPUSamplerobject. -
Set s .
[[descriptor]]to descriptor . -
Set s .
[[isComparison]]tofalseif thecompareattribute of s .[[descriptor]]isnullor undefined. Otherwise, set it totrue. -
Set s .
[[isFiltering]]tofalseif none ofminFilter,magFilter, ormipmapFilterhas the value of"linear". Otherwise, set it totrue. -
Return s .
Valid Usage-
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.
-
-
-
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.
[Exposed =(Window ,DedicatedWorker ),SecureContext ]interface GPUBindGroupLayout { };GPUBindGroupLayout includes GPUObjectBase ;
GPUBindGroupLayout
has
the
following
internal
slots:
-
[[descriptor]]
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
.
typedef [EnforceRange ]unsigned long ; [GPUShaderStageFlags Exposed =(Window ,DedicatedWorker )]namespace {GPUShaderStage const GPUFlagsConstant = 0x1;VERTEX const GPUFlagsConstant = 0x2;FRAGMENT const GPUFlagsConstant = 0x4; };COMPUTE dictionary {GPUBindGroupLayoutEntry required GPUIndex32 binding ;required GPUShaderStageFlags visibility ;GPUBufferBindingLayout buffer ;GPUSamplerBindingLayout sampler ;GPUTextureBindingLayout texture ;GPUStorageTextureBindingLayout storageTexture ;GPUExternalTextureBindingLayout externalTexture ; };
GPUBindGroupLayoutEntry
dictionaries
have
the
following
members:
-
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. -
buffer, of type GPUBufferBindingLayout -
When not
undefined, indicates the binding resource type for thisGPUBindGroupLayoutEntryisGPUBufferBinding. -
sampler, of type GPUSamplerBindingLayout -
When not
undefined, indicates the binding resource type for thisGPUBindGroupLayoutEntryisGPUSampler. -
texture, of type GPUTextureBindingLayout -
When not
undefined, indicates the binding resource type for thisGPUBindGroupLayoutEntryisGPUTextureView. -
storageTexture, of type GPUStorageTextureBindingLayout -
When not
undefined, indicates the binding resource type for thisGPUBindGroupLayoutEntryisGPUTextureView. -
externalTexture, of type GPUExternalTextureBindingLayout -
When not
undefined, indicates the binding resource type for thisGPUBindGroupLayoutEntryisGPUExternalTexture.
The
binding
member
of
a
GPUBindGroupLayoutEntry
is
determined
by
which
member
of
the
GPUBindGroupLayoutEntry
is
defined:
buffer
,
sampler
,
texture
,
storageTexture
,
or
externalTexture
.
Only
one
may
be
defined
for
any
given
GPUBindGroupLayoutEntry
.
Each
member
has
an
associated
GPUBindingResource
type
and
each
binding
type
has
an
associated
internal
usage
,
given
by
this
table:
| Binding member | Resource type |
Binding
type
| Binding usage |
|---|---|---|---|
buffer
|
GPUBufferBinding
|
"uniform"
| constant |
"storage"
| storage | ||
"read-only-storage"
| storage-read | ||
sampler
|
GPUSampler
|
"filtering"
| constant |
"non-filtering"
| |||
"comparison"
| |||
texture
|
GPUTextureView
|
"float"
| constant |
"unfilterable-float"
| |||
"depth"
| |||
"sint"
| |||
"uint"
| |||
storageTexture
|
GPUTextureView
|
"write-only"
| storage |
externalTexture
|
GPUExternalTexture
| constant |
GPUBindGroupLayoutEntry
values
entries
exceeds
the
binding
slot
limits
of
supported
limits
limits
if
the
number
of
slots
used
toward
a
limit
exceeds
the
supported
value
in
limits
.
Each
entry
may
use
multiple
slots
toward
multiple
limits.
-
For each entry in entries , if:
-
entry
.
buffer?.typeis"uniform"and entry .buffer?.hasDynamicOffsetistrue -
Consider 1
maxDynamicUniformBuffersPerPipelineLayoutslot to be used. -
entry
.
buffer?.typeis"storage"and entry .buffer?.hasDynamicOffsetistrue -
Consider 1
maxDynamicStorageBuffersPerPipelineLayoutslot to be used.
-
entry
.
-
For each shader stage stage in «
VERTEX,FRAGMENT,COMPUTE»:-
For each entry in entries for which entry .
visibilitycontains stage , if:-
entry
.
buffer?.typeis"uniform" -
Consider 1
maxUniformBuffersPerShaderStageslot to be used. -
entry
.
buffer?.typeis"storage"or"read-only-storage" -
Consider 1
maxStorageBuffersPerShaderStageslot to be used. -
entry
.
sampleris notundefined -
Consider 1
maxSamplersPerShaderStageslot to be used. -
entry
.
textureis notundefined -
Consider 1
maxSampledTexturesPerShaderStageslot to be used. -
entry
.
storageTextureis notundefined -
Consider 1
maxStorageTexturesPerShaderStageslot to be used. -
entry
.
externalTextureis notundefined -
Consider 4
maxSampledTexturesPerShaderStageslot, 1maxSamplersPerShaderStageslot, and 1maxUniformBuffersPerShaderStageslot to be used.
-
entry
.
-
enum {GPUBufferBindingType ,"uniform" ,"storage" , };"read-only-storage" dictionary {GPUBufferBindingLayout GPUBufferBindingType type = "uniform";boolean hasDynamicOffset =false ;GPUSize64 minBindingSize = 0; };
GPUBufferBindingLayout
dictionaries
have
the
following
members:
-
type, of type GPUBufferBindingType , defaulting to"uniform" -
Indicates the type required for buffers bound to this bindings.
-
hasDynamicOffset, of type boolean , defaulting tofalse -
Indicates whether this binding requires a dynamic offset.
-
minBindingSize, of type GPUSize64 , defaulting to0 -
Indicates the minimum buffer binding size.
Bindings are always validated against this size in
createBindGroup().If this is not
0, pipeline creation additionally validates that this value is large enough for the bindings declared in the shader.If this is
0, draw/dispatch commands additionally validate that each binding in theGPUBindGroupis large enough for the bindings declared in the shader.Note: Similar execution-time validation is theoretically possible for other binding-related fields specified for early validation, like
sampleTypeandformat, which currently can only be validated in pipeline creation. However, such execution-time validation could be costly or unnecessarily complex, so it is available only forminBindingSizewhich is expected to have the most ergonomic impact.
enum {GPUSamplerBindingType ,"filtering" ,"non-filtering" , };"comparison" dictionary {GPUSamplerBindingLayout GPUSamplerBindingType type = "filtering"; };
GPUSamplerBindingLayout
dictionaries
have
the
following
members:
-
type, of type GPUSamplerBindingType , defaulting to"filtering" -
Indicates the required type of a sampler bound to this bindings.
enum {GPUTextureSampleType ,"float" ,"unfilterable-float" ,"depth" ,"sint" , };"uint" dictionary {GPUTextureBindingLayout GPUTextureSampleType sampleType = "float";GPUTextureViewDimension viewDimension = "2d";boolean multisampled =false ; };
consider
making
sampleType
truly
optional.
GPUTextureBindingLayout
dictionaries
have
the
following
members:
-
sampleType, of type GPUTextureSampleType , defaulting to"float" -
Indicates the type required for texture views bound to this binding.
-
viewDimension, of type GPUTextureViewDimension , defaulting to"2d" -
Indicates the required
dimensionfor texture views bound to this binding. -
multisampled, of type boolean , defaulting tofalse -
Indicates whether or not texture views bound to this binding must be multisampled.
enum {GPUStorageTextureAccess , };"write-only" dictionary {GPUStorageTextureBindingLayout GPUStorageTextureAccess access = "write-only";required GPUTextureFormat format ;GPUTextureViewDimension viewDimension = "2d"; };
consider
making
format
truly
optional.
GPUStorageTextureBindingLayout
dictionaries
have
the
following
members:
-
access, of type GPUStorageTextureAccess , defaulting to"write-only" -
Indicates whether texture views bound to this binding will be bound for read-only or write-only access.
-
format, of type GPUTextureFormat -
The required
formatof texture views bound to this binding. -
viewDimension, of type GPUTextureViewDimension , defaulting to"2d" -
Indicates the required
dimensionfor texture views bound to this binding.
dictionary { };GPUExternalTextureBindingLayout
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. -
[[exclusivePipeline]]of typeGPUPipelineBase?, initiallynull. -
The pipeline that created this
GPUBindGroupLayout, if it was created as part of a default pipeline layout . If notnull,GPUBindGroups created with thisGPUBindGroupLayoutcan only be used with the specifiedGPUPipelineBase.
-
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. -
Set layout .
[[descriptor]]to descriptor . -
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. -
The
bindingof each entry in descriptor must be < 65536. -
descriptor .
entriesmust not exceed the binding slot limits of this .[[device]].[[limits]]. -
For each
GPUBindGroupLayoutEntryentry in descriptor .entries:-
Let bufferLayout be entry .
buffer -
Let samplerLayout be entry .
sampler -
Let textureLayout be entry .
texture -
Let storageTextureLayout be entry .
storageTexture -
Exactly one of bufferLayout , samplerLayout , textureLayout , or storageTextureLayout are not
undefined. -
If entry .
visibilityincludesVERTEX:-
entry .
storageTexture?.accessmust not be"write-only".
-
If the textureLayout is not
undefinedand textureLayout .multisampledistrue:-
textureLayout .
viewDimensionis"2d". -
textureLayout .
sampleTypeis not"float"or"depth".
-
-
If storageTextureLayout is not
undefined:-
storageTextureLayout .
viewDimensionis not"cube"or"cube-array". -
storageTextureLayout .
formatmust 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 wherebufferis notundefinedandbuffer.hasDynamicOffsetistrue. -
For each
GPUBindGroupLayoutEntryentry in descriptor .entries:-
Insert entry into layout .
[[entryMap]]with the key of entry .binding.
-
-
-
Return layout .
-
8.1.2. Compatibility
GPUBindGroupLayout
objects
a
and
b
are
considered
group-equivalent
if
and
only
if
all
of
the
following
conditions
are
satisfied:
-
a .
[[exclusivePipeline]]== b .[[exclusivePipeline]]. -
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.
[Exposed =(Window ,DedicatedWorker ),SecureContext ]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 or GPUExternalTexture );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. -
Let limits be this .
[[device]].[[limits]]. -
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. -
There is exactly one
GPUBindGroupLayoutEntrylayoutBinding in descriptor .layout.entriessuch that layoutBinding .bindingequals to bindingDescriptor .binding. -
If the defined binding member for layoutBinding is
-
sampler -
-
resource is a
GPUSampler. -
resource is valid to use with this .
-
If layoutBinding .
sampler.typeis:-
"filtering" -
resource .
[[isComparison]]isfalse. -
"non-filtering" -
resource .
[[isFiltering]]isfalse. resource .[[isComparison]]isfalse. -
"comparison" -
resource .
[[isComparison]]istrue.
-
-
-
texture -
-
resource is a
GPUTextureView. -
resource is valid to use with this .
-
Let texture be resource .
[[texture]]. -
layoutBinding .
texture.viewDimensionis equal to resource ’sdimension. -
layoutBinding .
texture.sampleTypeis compatible with resource ’sformat. -
texture ’s
usageincludesTEXTURE_BINDING. -
If layoutBinding .
texture.multisampledistrue, texture ’ssampleCount>1, Otherwise texture ’ssampleCountis1.
-
-
storageTexture -
-
resource is a
GPUTextureView. -
resource is valid to use with this .
-
Let texture be resource .
[[texture]]. -
layoutBinding .
storageTexture.viewDimensionis equal to resource ’sdimension. -
layoutBinding .
storageTexture.formatis equal to resource .[[descriptor]].format. -
texture ’s
usageincludesSTORAGE_BINDING. -
resource .
[[descriptor]].mipLevelCountmust be 1.
-
-
buffer -
-
resource is a
GPUBufferBinding. -
resource .
bufferis valid to use with this . -
The bound part designated by resource .
offsetand resource .sizeresides inside the buffer. -
effective buffer binding size ( resource ), is greater than or equal to layoutBinding .
buffer.minBindingSize. -
If layoutBinding .
buffer.typeis-
"uniform" -
resource .
buffer.usageincludesUNIFORM.effective buffer binding size ( resource ) ≤ limits .
maxUniformBufferBindingSize.resource .
offsetis a multiple of limits .minUniformBufferOffsetAlignment. -
"storage"or"read-only-storage" -
resource .
buffer.usageincludesSTORAGE.effective buffer binding size ( resource ) ≤ limits .
maxStorageBufferBindingSize.resource .
offsetis a multiple of limits .minStorageBufferOffsetAlignment.
-
-
-
externalTexture -
-
resource is a
GPUExternalTexture. -
resource is valid to use with this .
-
-
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 .
-
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.
[Exposed =(Window ,DedicatedWorker ),SecureContext ]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 requirements are unmet:
Let limits be this .[[device]].[[limits]].Let allEntries be the result of concatenating bgl .
[[descriptor]].entriesfor all bgl in descriptor .bindGroupLayouts.-
Every
GPUBindGroupLayoutin descriptor .bindGroupLayoutsmust be valid to use with this and have a[[exclusivePipeline]]ofnull. -
The size of descriptor .
bindGroupLayoutsmust be ≤ limits .maxBindGroups. -
allEntries must not exceed the binding slot limits of limits .
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 .
-
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
[Exposed =(Window ,DedicatedWorker ),SecureContext ]interface GPUShaderModule {Promise <GPUCompilationInfo >compilationInfo (); };GPUShaderModule includes GPUObjectBase ;
GPUShaderModule
is
a
reference
to
an
internal
shader
module
object.
Finish
defining
multithreading
API
and
add
[Serializable]
back
to
the
interface.
[Issue
#gpuweb/gpuweb#354]
9.1.1. Shader Module Creation
dictionary {GPUShaderModuleCompilationHint required GPUPipelineLayout ; };layout dictionary :GPUShaderModuleDescriptor GPUObjectDescriptorBase {required USVString ;code object ;sourceMap record <USVString ,GPUShaderModuleCompilationHint >; };hints
sourceMap
,
if
defined,
MAY
be
interpreted
as
a
source-map-v3
format.
Source
maps
are
optional,
but
serve
as
a
standardized
way
to
support
dev-tool
integration
such
as
source-language
debugging.
[SourceMap]
hints
,
if
defined,
maps
an
entry
point
name
from
the
shader
to
a
GPUShaderModuleCompilationHint
.
No
validation
is
performed
with
any
of
these
GPUShaderModuleCompilationHint
.
Implementations
should
use
any
information
present
in
the
GPUShaderModuleCompilationHint
to
perform
as
much
compilation
as
is
possible
within
createShaderModule()
.
Note:
Supplying
information
in
hints
does
not
have
any
observable
effect,
other
than
performance.
Because
a
single
shader
module
can
hold
multiple
entry
points,
and
multiple
pipelines
can
be
created
from
a
single
shader
module,
it
can
be
more
performant
for
an
implementation
to
do
as
much
compilation
as
possible
once
in
createShaderModule()
rather
than
multiple
times
in
the
multiple
calls
to
createComputePipeline()
/
createRenderPipeline()
.
Note:
If
possible,
authors
should
be
supplying
the
same
information
to
createShaderModule()
and
createComputePipeline()
/
createRenderPipeline()
.
Note:
If
an
author
is
unable
to
provide
this
hints
information
at
the
time
of
calling
createShaderModule()
,
they
should
usually
not
delay
calling
createShaderModule()
;
but
should
instead
just
omit
the
unknown
information
from
hints
or
GPUShaderModuleCompilationHint
.
Omitting
this
information
may
cause
compilation
to
be
deferred
to
createComputePipeline()
/
createRenderPipeline()
.
Note:
If
an
author
is
not
confident
that
the
information
passed
to
createShaderModule()
will
match
the
information
later
passed
to
createComputePipeline()
/
createRenderPipeline()
with
that
same
module,
they
should
avoid
passing
that
information
to
createShaderModule()
,
as
passing
mismatched
information
to
createShaderModule()
may
cause
unnecessary
compilations
to
occur.
-
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
enum {GPUCompilationMessageType ,"error" ,"warning" , }; ["info" Exposed =(Window ,DedicatedWorker ),Serializable ,SecureContext ]interface {GPUCompilationMessage readonly attribute DOMString message ;readonly attribute GPUCompilationMessageType type ;readonly attribute unsigned long long lineNum ;readonly attribute unsigned long long linePos ;readonly attribute unsigned long long offset ;readonly attribute unsigned long long length ; }; [Exposed =(Window ,DedicatedWorker ),Serializable ,SecureContext ]interface {GPUCompilationInfo readonly attribute FrozenArray <GPUCompilationMessage >; };messages
A
GPUCompilationMessage
is
an
informational,
warning,
or
error
message
generated
by
the
GPUShaderModule
compiler.
The
messages
are
intended
to
be
human
readable
to
help
developers
diagnose
issues
with
their
shader
code
.
Each
message
may
correspond
to
either
a
single
point
in
the
shader
code,
a
substring
of
the
shader
code,
or
may
not
correspond
to
any
specific
point
in
the
code
at
all.
GPUCompilationMessage
has
the
following
attributes:
-
message, of type DOMString , readonly -
A human-readable string containing the message generated during the shader compilation.
-
type, of type GPUCompilationMessageType , readonly -
The severity level of the message.
If the
typeis "error", it corresponds to a shader-creation error . -
lineNum, of type unsigned long long , readonly -
The line number in the shader
codethemessagecorresponds to. Value is one-based, such that a lineNum of1indicates the first line of the shadercode.If the
messagecorresponds to a substring this points to the line on which the substring begins. Must be0if themessagedoes not correspond to any specific point in the shadercode.Reference WGSL spec when it defines what a line is .
-
linePos, of type unsigned long long , readonly -
The offset, in UTF-16 code units, from the beginning of line
lineNumof the shadercodeto the point or beginning of the substring that themessagecorresponds to. Value is one-based, such that alinePosof1indicates the first character of the line.If
messagecorresponds to a substring this points to the first UTF-16 code unit of the substring. Must be0if themessagedoes not correspond to any specific point in the shadercode. -
offset, of type unsigned long long , readonly -
The offset from the beginning of the shader
codein UTF-16 code units to the point or beginning of the substring thatmessagecorresponds to. Must reference the same position aslineNumandlinePos. Must be0if themessagedoes not correspond to any specific point in the shadercode. -
length, of type unsigned long long , readonly -
The number of UTF-16 code units in the substring that
messagecorresponds to. If the message does not correspond with a substring thenlengthmust be 0.
Note:
GPUCompilationMessage
.
lineNum
and
GPUCompilationMessage
.
linePos
are
one-based
since
the
most
common
use
for
them
is
expected
to
be
printing
human
readable
messages
that
can
be
correlated
with
the
line
and
column
numbers
shown
in
many
text
editors.
Note:
GPUCompilationMessage
.
offset
and
GPUCompilationMessage
.
length
are
appropriate
to
pass
to
substr()
in
order
to
retrieve
the
substring
of
the
shader
code
the
message
corresponds
to.
-
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 ≥ this .
[[device]].[[limits]].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.
To
create
a
default
pipeline
layout
for
GPUPipelineBase
pipeline
,
run
the
following
steps:
-
Let groupDescs be a sequence of device .
[[limits]].maxBindGroupsnewGPUBindGroupLayoutDescriptorobjects. -
For each groupDesc in groupDescs :
-
Set groupDesc .
entriesto an empty sequence.
-
-
For each
GPUProgrammableStagestageDesc in the descriptor used to create 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:
-
Let samplerLayout be a new
GPUSamplerBindingLayout. -
Set entry .
samplerto samplerLayout .
-
-
If resource is for a comparison sampler binding:
-
Let samplerLayout be a new
GPUSamplerBindingLayout. -
Set samplerLayout .
typeto"comparison". -
Set entry .
samplerto samplerLayout .
-
-
If resource is for a buffer binding:
-
Let bufferLayout be a new
GPUBufferBindingLayout. -
Set bufferLayout .
minBindingSizeto resource ’s minimum buffer binding size.link to a definition for "minimum buffer binding size" in the "reflection information".
-
If resource is for a read-only storage buffer:
-
Set bufferLayout .
typeto"read-only-storage".
-
-
If resource is for a storage buffer:
-
Set entry .
bufferto bufferLayout .
-
-
If resource is for a sampled texture binding:
-
Let textureLayout be a new
GPUTextureBindingLayout. -
If resource is a depth texture binding:
-
Set textureLayout .
sampleTypeto"depth"
Else if the sampled type of resource is:
-
-
f32and resource is statically used with a textureSample* builtin in the shader -
Set textureLayout .
sampleTypeto"float" -
f32otherwise -
Set textureLayout .
sampleTypeto"unfilterable-float" -
i32 -
Set textureLayout .
sampleTypeto"sint" -
u32 -
Set textureLayout .
sampleTypeto"uint"
-
-
-
Set textureLayout .
viewDimensionto resource ’s dimension. -
If resource is for a multisampled texture:
-
Set textureLayout .
multisampledtotrue.
-
-
Set entry .
textureto textureLayout .
-
-
If resource is for a storage texture binding:
-
Let storageTextureLayout be a new
GPUStorageTextureBindingLayout. -
Set storageTextureLayout .
formatto resource ’s format. -
Set storageTextureLayout .
viewDimensionto resource ’s dimension. -
If resource is for a write-only storage texture:
-
Set storageTextureLayout .
accessto"write-only".
-
-
Set entry .
storageTextureto storageTextureLayout .
-
-
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 resource is for a buffer binding and entry has greater
buffer.minBindingSizethan previousEntry :-
Set previousEntry .
buffer.minBindingSizeto entry .buffer.minBindingSize.
-
-
If resource is a sampled texture binding and entry has different
texture.sampleTypethan previousEntry and both entry and previousEntry havetexture.sampleTypeof either"float"or"unfilterable-float":-
Set previousEntry .
texture.sampleTypeto"float".
-
-
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 :
-
Let bindGroupLayout be the result of calling device .
createBindGroupLayout()( groupDesc ). -
Set bindGroupLayout .
[[exclusivePipeline]]to pipeline . -
Append bindGroupLayout 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.
GPUProgrammableStage
A
GPUProgrammableStage
describes
the
entry
point
in
the
user-provided
GPUShaderModule
that
controls
one
of
the
programmable
stages
of
a
pipeline
.
dictionary GPUProgrammableStage {required GPUShaderModule ;module required USVString ;entryPoint record <USVString ,GPUPipelineConstantValue >constants ; };typedef double GPUPipelineConstantValue ; // May represent WGSL’s bool, f32, i32, u32.
-
constants, of type record< USVString , GPUPipelineConstantValue > -
Specifies the values of pipeline-overridable constants in the shader module
module.Each such pipeline-overridable constant is uniquely identified by a single pipeline-overridable constant identifier string (representing the numeric ID of the constant, if one is specified, and otherwise the constant’s identifier name).
The key of each key-value pair must equal the identifier string of one such constant. When the pipeline is executed, that constant will have the specified value.
Values are specified as
GPUPipelineConstantValue, which is adoublewhich is converted to the WGSL data type of the corresponding pipeline-overridable constant (bool,i32,u32, orf32) via an IDL value (boolean,long,unsigned long, orfloat).Pipeline-overridable constants defined in WGSL:[[ override ( 0 )]] let has_point_light :bool = true ; // Algorithmic control. [[ override ( 1200 )]] let specular_param :f32 = 2.3 ; // Numeric control. [[ override ( 1300 )]] let gain :f32 ; // Must be overridden. [[ override ]] let width :f32 = 0.0 ; // Specifed at the API level // using the name "width". [[ override ]] let depth :f32 ; // Specifed at the API level // using the name "depth". // Must be overridden. Corresponding JavaScript code, providing only the overrides which are required (have no defaults):
{ // ... constants: { 1300 : 2.0 , // "gain" depth: - 1 , // "depth" } } Corresponding JavaScript code, overriding all constants:
{ // ... constants: { 0 : false , // "has_point_light" 1200 : 3.0 , // "specular_param" 1300 : 2.0 , // "gain" width: 20 , // "width" depth: - 1 , // "depth" } }
Arguments:
-
GPUShaderStagestage -
GPUProgrammableStagedescriptor -
GPUPipelineLayoutlayout
Return
true
if
all
of
the
following
conditions
are
met:
-
descriptor .
modulemust be a validGPUShaderModule. -
descriptor .
modulemust contain an entry point, for shader stage stage , named descriptor .entryPoint. -
For each binding that is statically used by the shader entry point:
-
validating shader binding ( binding , layout ) must return
true.
-
-
For each texture sampling shader call that is statically used by the entry point:
-
Let texture be the
GPUBindGroupLayoutEntrycorresponding to the sampled texture in the call. -
Let sampler be the
GPUBindGroupLayoutEntrycorresponding to the used sampler in the call. -
If sampler .
typeis"filtering", then texture .sampleTypemust not be"unfilterable-float".
-
-
For each key in the keys of descriptor .
constants:-
key must equal the pipeline-overridable constant identifier string of some pipeline-overridable constant defined in the shader module descriptor .
module.
-
-
For each pipeline-overridable constant identifier string key which is statically accessed by the shader entry point:
-
If the pipeline-overridable constant identified by key does not have a default value , descriptor .
constantsmust contain key .
-
A
return
value
of
false
corresponds
to
a
pipeline-creation
error
.
Arguments:
-
shader binding declaration variable , a module-scope variable declaration reflected from a shader module
-
GPUPipelineLayoutlayout
Let bindGroup be the bind group index, and bindIndex be the binding index, of the shader binding declaration variable .
Return
true
if
all
of
the
following
conditions
are
satisfied:
-
layout .
[[bindGroupLayouts]][ bindGroup ] contains aGPUBindGroupLayoutEntryentry whose entry .binding== bindIndex . -
If the defined binding member for entry is:
-
buffer -
-
"uniform" -
variable is declared with the storage class
uniform. -
"storage" -
variable is declared with the storage class
storageand access moderead_write. -
"read-only-storage" -
variable is declared with the storage class
storageand access moderead.
If entry .
buffer.minBindingSizeis not0:-
If the last field of the corresponding structure defined in the shader has an unbounded array type, then the value of entry .
buffer.minBindingSizemust 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 .
buffer.minBindingSizemust be greater than or equal to the size of the structure.
-
-
sampler -
-
"filtering"or"non-filtering" -
variable has type
sampler. -
"comparison" -
variable has type
comparison_sampler.
-
-
texture -
If, and only if, entry .
texture.multisampledistrue, variable has typetexture_multisampled_2d<T>ortexture_depth_multisampled_2d<T>.If entry .
texture.sampleTypeis:-
"float","unfilterable-float","sint"or"uint" -
variable has type
texture_1d<T>,texture_2d<T>,texture_2d_array<T>,texture_cube<T>,texture_cube_array<T>,texture_3d<T>, ortexture_multisampled_2d<T>.If entry .
texture.sampleTypeis:-
"float"or"unfilterable-float" -
The sampled type
Tisf32. -
"sint" -
The sampled type
Tisi32. -
"uint" -
The sampled type
Tisu32.
-
"depth" -
variable has type
texture_depth_2d,texture_depth_2d_array,texture_depth_cube,texture_depth_cube_array, ortexture_depth_multisampled_2d.
If entry .
texture.viewDimensionis:-
"1d" -
variable has type
texture_1d<T>. -
"2d" -
variable has type
texture_2d<T>ortexture_multisampled_2d<T>. -
"2d-array" -
variable has type
texture_2d_array<T>. -
"cube" -
variable has type
texture_cube<T>. -
"cube-array" -
variable has type
texture_cube_array<T>. -
"3d" -
variable has type
texture_3d<T>.
-
storageTexture -
If entry .
storageTexture.viewDimensionis:-
"1d" -
variable has type
texture_storage_1d<T, A>. -
"2d" -
variable has type
texture_storage_2d<T, A>. -
"2d-array" -
variable has type
texture_storage_2d_array<T, A>. -
"3d" -
variable has type
texture_storage_3d<T, A>.
If entry .
storageTexture.accessis:-
"write-only" -
The access mode
Aiswrite.
The texel format
Tequals entry .storageTexture.format. -
-
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
buffer
bindings
with
a
type
of
"storage"
and
storageTexture
bindings
with
a
type
of
"write-only"
.
Stages of a compute pipeline :
-
Compute shader
[Exposed =(Window ,DedicatedWorker ),SecureContext ]interface GPUComputePipeline { };GPUComputePipeline includes GPUObjectBase ;GPUComputePipeline includes GPUPipelineBase ;
10.2.1. Creation
dictionary :GPUComputePipelineDescriptor GPUPipelineDescriptorBase {required GPUProgrammableStage ; };compute
-
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:
GPUComputePipeline-
Let pipeline be a new valid
GPUComputePipelineobject. -
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 GPUProgrammableStage (
COMPUTE, descriptor .compute, descriptor .layout) succeeds. -
descriptor .
computeuses ≤ device .limits.maxComputeWorkgroupStorageSizebytes of workgroup storage. -
descriptor .
computeuses ≤ device .limits.maxComputeInvocationsPerWorkgroupper workgroup. -
descriptor .
compute'sworkgroup_sizeattribute has each component ≤ the corresponding component in [ device .limits.maxComputeWorkgroupSizeX, device .limits.maxComputeWorkgroupSizeY, device .limits.maxComputeWorkgroupSizeZ].
Then:
-
Generate a
GPUValidationErrorin the current scope with appropriate error message. -
Make pipeline invalid .
-
-
If descriptor .
layoutisundefined:-
Set pipeline .
[[layout]]to a new default pipeline layout for pipeline .
Otherwise set pipeline .
[[layout]]to descriptor .layout. -
-
-
Return pipeline .
-
-
createComputePipelineAsync(descriptor) -
Creates a
GPUComputePipeline. The returnedPromiseresolves when the created pipeline is ready to be used without additional delay.If pipeline creation fails, the returned
Promiserejects with anOperationError.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.createComputePipelineAsync(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
GPUVertexState -
the color attachments, described by
GPUColorTargetState -
optionally, the depth-stencil attachment, described by
GPUDepthStencilState
Render pipeline outputs are:
-
storageTexturebindings with aaccessof"write-only" -
the color attachments, described by
GPUColorTargetState -
optionally, depth-stencil attachment, described by
GPUDepthStencilState
A render pipeline is comprised of the following render stages :
-
Vertex fetch, controlled by
GPUVertexState.buffers -
Vertex shader, controlled by
GPUVertexState -
Primitive assembly, controlled by
GPUPrimitiveState -
Rasterization, controlled by
GPUPrimitiveState,GPUDepthStencilState, andGPUMultisampleState -
Fragment shader, controlled by
GPUFragmentState -
Stencil test and operation, controlled by
GPUDepthStencilState -
Depth test and write, controlled by
GPUDepthStencilState -
Output merging, controlled by
GPUFragmentState.targets
[Exposed =(Window ,DedicatedWorker ),SecureContext ]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. -
[[writesDepth]], of type boolean -
True if the pipeline writes to the depth component of the depth/stencil attachment
-
[[writesStencil]], of type boolean -
True if the pipeline writes to the stencil component of the depth/stencil attachment
10.3.1. Creation
dictionary :GPURenderPipelineDescriptor GPUPipelineDescriptorBase {required GPUVertexState ;vertex GPUPrimitiveState = {};primitive GPUDepthStencilState ;depthStencil GPUMultisampleState = {};multisample GPUFragmentState ; };fragment
A
GPURenderPipelineDescriptor
describes
the
state
of
a
render
pipeline
by
configuring
each
of
the
render
stages
.
See
§ 21.3
Rendering
for
the
details.
-
vertexdescribes the vertex shader entry point of the pipeline and its input buffer layouts. -
primitivedescribes the the primitive-related properties of the pipeline . -
depthStencildescribes the optional depth-stencil properties, including the testing, operations, and bias. -
multisampledescribes the multi-sampling properties of the pipeline . -
fragmentdescribes the fragment shader entry point of the pipeline and its output colors. If it’snull, the § 21.3.8 No Color Output mode is enabled.
-
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 GPURenderPipelineDescriptor ( descriptor , this ) succeeds.
Then:
-
Generate a
GPUValidationErrorin the current scope with appropriate error message. -
Make pipeline invalid .
-
-
Set pipeline .
[[descriptor]]to descriptor . -
Set pipeline .
[[writesDepth]]to false. -
Set pipeline .
[[writesStencil]]to false. -
Let depthStencil be descriptor .
depthStencil. -
If depthStencil is not null:
-
Set pipeline .
[[writesDepth]]to depthStencil .depthWriteEnabled. -
If depthStencil .
stencilWriteMaskis not 0:-
Let stencilFront be depthStencil .
stencilFront. -
Let stencilBack be depthStencil .
stencilBack. -
If cullMode is not
"front", and any of stencilFront .passOp, stencilFront .depthFailOp, or stencilFront .failOpis not"keep":-
Set pipeline .
[[writesStencil]]to true.
-
-
If cullMode is not
"back", and any of stencilBack .passOp, stencilBack .depthFailOp, or stencilBack .failOpis not"keep":-
Set pipeline .
[[writesStencil]]to true.
-
-
-
-
If descriptor .
layoutisundefined:-
Set pipeline .
[[layout]]to a new default pipeline layout for pipeline .
Otherwise set pipeline .
[[layout]]to descriptor .layout. -
-
-
Return pipeline .
-
-
createRenderPipelineAsync(descriptor) -
Creates a
GPURenderPipeline. The returnedPromiseresolves when the created pipeline is ready to be used without additional delay.If pipeline creation fails, the returned
Promiserejects with anOperationError.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.createRenderPipelineAsync(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 .
-
-
GPURenderPipelineDescriptordescriptor -
GPUDevicedevice
Return
true
if
all
of
the
following
conditions
are
satisfied:
-
validating GPUProgrammableStage (
VERTEX, descriptor .vertex, descriptor .layout) succeeds. -
validating GPUVertexState ( device , descriptor .
vertex, descriptor .vertex) succeeds. -
If descriptor .
fragmentis notnull:-
validating GPUProgrammableStage (
FRAGMENT, descriptor .fragment, descriptor .layout) succeeds. -
validating GPUFragmentState ( descriptor .
fragment) succeeds. -
If the "sample_mask" builtin is a pipeline output of descriptor .
fragment:-
descriptor .
multisample.alphaToCoverageEnabledisfalse.
-
-
-
validating GPUPrimitiveState ( descriptor .
primitive, device .[[features]]) succeeds. -
if descriptor .
depthStencilis notnull:-
validating GPUDepthStencilState ( descriptor .
depthStencil) succeeds.
-
-
validating GPUMultisampleState ( descriptor .
multisample) succeeds. -
For each user-defined output of descriptor .
vertexthere must be a user-defined input of descriptor .fragmentthat matches the location , type, and interpolation of the output. -
For each user-defined input of descriptor .
fragmentthere must be a user-defined output of descriptor .vertexthat location , type, and interpolation of the input. -
There is less than device .limits.
maxInterStageShaderComponentscomponents of user-defined outputs for descriptor .vertex. -
There is less than device .limits.
maxInterStageShaderComponentscomponents of user-defined inputs for descriptor .fragment.
should
we
validate
that
cullMode
is
none
for
points
and
lines?
define what "compatible" means for render target formats.
need a proper limit for the maximum number of color targets.
10.3.2. Primitive State
enum {GPUPrimitiveTopology ,"point-list" ,"line-list" ,"line-strip" ,"triangle-list" , };"triangle-strip"
dictionary {GPUPrimitiveState GPUPrimitiveTopology = "triangle-list";topology GPUIndexFormat ;stripIndexFormat GPUFrontFace = "ccw";frontFace GPUCullMode = "none"; // Requires "depth-clip-control" feature.cullMode boolean =unclippedDepth false ; };
-
GPUPrimitiveStatedescriptor -
list <
GPUFeatureName> features
Return
true
if
all
of
the
following
conditions
are
satisfied:
-
If descriptor .
topologyis not"line-strip"or"triangle-strip":-
descriptor .
stripIndexFormatisundefined
-
-
If descriptor .
unclippedDepthistrue:-
features must contain
"depth-clip-control".
-
enum {GPUFrontFace ,"ccw" , };"cw"
enum {GPUCullMode ,"none" ,"front" , };"back"
10.3.3. Multisample State
dictionary {GPUMultisampleState GPUSize32 = 1;count GPUSampleMask = 0xFFFFFFFF;mask boolean =alphaToCoverageEnabled false ; };
-
GPUMultisampleStatedescriptor
Return
true
if
all
of
the
following
conditions
are
satisfied:
-
If descriptor .
alphaToCoverageEnabledistrue:-
descriptor .
countis greater than 1.
-
10.3.4. Fragment State
dictionary :GPUFragmentState GPUProgrammableStage {required sequence <GPUColorTargetState >; };targets
true
if
all
of
the
following
requirements
are
met:
-
descriptor .
targets.length must be ≤ 8. -
For each colorState layout descriptor in the list descriptor .
targets:-
colorState .
formatmust be listed in § 24.1.1 Plain color formats withRENDER_ATTACHMENTcapability. -
If colorState .
blendis notundefined:-
The colorState .
formatmust be filterable according to the § 24.1.1 Plain color formats table. -
colorState .
blend.colormust be a valid GPUBlendComponent . -
colorState .
blend.alphamust be a valid GPUBlendComponent .
-
-
colorState .
writeMaskmust be < 16. -
If descriptor .
entryPointhas a pipeline output value with location attribute equal to the index of the colorState in the descriptor .targetslist:-
The pipeline output type must be compatible with colorState .
format.
Otherwise:
-
colorState .
writeMaskmust be 0.
-
-
define
the
area
of
reach
for
"statically
used"
things
of
GPUProgrammableStage
10.3.5. Color Target State
dictionary {GPUColorTargetState required GPUTextureFormat ;format GPUBlendState ;blend GPUColorWriteFlags = 0xF; // GPUColorWrite.ALL };writeMask
dictionary {GPUBlendState required GPUBlendComponent ;color required GPUBlendComponent ; };alpha
typedef [EnforceRange ]unsigned long ; [GPUColorWriteFlags Exposed =(Window ,DedicatedWorker )]namespace {GPUColorWrite const GPUFlagsConstant = 0x1;RED const GPUFlagsConstant = 0x2;GREEN const GPUFlagsConstant = 0x4;BLUE const GPUFlagsConstant = 0x8;ALPHA const GPUFlagsConstant = 0xF; };ALL
10.3.5.1. Blend State
dictionary {GPUBlendComponent GPUBlendOperation = "add";operation GPUBlendFactor = "one";srcFactor GPUBlendFactor = "zero"; };dstFactor
enum {GPUBlendFactor ,"zero" ,"one" ,"src" ,"one-minus-src" ,"src-alpha" ,"one-minus-src-alpha" ,"dst" ,"one-minus-dst" ,"dst-alpha" ,"one-minus-dst-alpha" ,"src-alpha-saturated" ,"constant" , };"one-minus-constant"
enum {GPUBlendOperation ,"add" ,"subtract" ,"reverse-subtract" ,"min" , };"max"
10.3.6. Depth/Stencil State
dictionary {GPUDepthStencilState required GPUTextureFormat ;format boolean =depthWriteEnabled false ;GPUCompareFunction = "always";depthCompare GPUStencilFaceState = {};stencilFront GPUStencilFaceState = {};stencilBack GPUStencilValue = 0xFFFFFFFF;stencilReadMask GPUStencilValue = 0xFFFFFFFF;stencilWriteMask GPUDepthBias = 0;depthBias float = 0;depthBiasSlopeScale float = 0; };depthBiasClamp
dictionary {GPUStencilFaceState 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"
-
GPUDepthStencilStatedescriptor
Return
true
,
if
and
only
if,
all
of
the
following
conditions
are
satisfied:
-
descriptor .
formatis a depth-or-stencil format . -
if descriptor .
depthWriteEnabledistrueor descriptor .depthCompareis not"always":-
descriptor .
formatmust have a depth component.
-
-
if descriptor .
stencilFrontor descriptor .stencilBackare not default values:-
descriptor .
formatmust have a stencil component.
-
how can this algorithm support depth/stencil formats that are added in extensions?
10.3.7. 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.
GPUPrimitiveState
s
that
specify
a
strip
primitive
topology
must
specify
a
stripIndexFormat
if
they
are
used
for
indexed
draws
so
that
the
primitive
restart
value
that
will
be
used
is
known
at
pipeline
creation
time.
GPUPrimitiveState
s
that
specify
a
list
primitive
topology
will
use
the
index
format
passed
to
setIndexBuffer()
when
doing
indexed
rendering.
| Index format | Byte size | Primitive restart value |
|---|---|---|
"uint16"
| 2 | 0xFFFF |
"uint32"
| 4 | 0xFFFFFFFF |
10.3.7.1. Vertex Formats
The name of the format specifies the order of components, bits per component, and vertex data type for the component.
-
unorm= unsigned normalized -
snorm= signed normalized -
uint= unsigned int -
sint= signed int -
float= floating point
enum {GPUVertexFormat ,"uint8x2" ,"uint8x4" ,"sint8x2" ,"sint8x4" ,"unorm8x2" ,"unorm8x4" ,"snorm8x2" ,"snorm8x4" ,"uint16x2" ,"uint16x4" ,"sint16x2" ,"sint16x4" ,"unorm16x2" ,"unorm16x4" ,"snorm16x2" ,"snorm16x4" ,"float16x2" ,"float16x4" ,"float32" ,"float32x2" ,"float32x3" ,"float32x4" ,"uint32" ,"uint32x2" ,"uint32x3" ,"uint32x4" ,"sint32" ,"sint32x2" ,"sint32x3" , };"sint32x4"
The
multi-component
formats
specify
the
number
of
components
after
"x".
As
such,
"sint32x3"
denotes
a
3-component
vector
of
i32
values
in
the
shader.
enum {GPUVertexStepMode ,"vertex" , };"instance"
The step mode configures how an address for vertex buffer data is computed, based on the current vertex or instance index:
-
"vertex" -
The address is advanced by
arrayStridefor each vertex, and reset between instances. -
"instance" -
The address is advanced by
arrayStridefor each instance.
dictionary :GPUVertexState GPUProgrammableStage {sequence <GPUVertexBufferLayout ?>= []; };buffers
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
GPUVertexAttribute
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
GPUVertexState
.
dictionary {GPUVertexBufferLayout required GPUSize64 ;arrayStride GPUVertexStepMode = "vertex";stepMode required sequence <GPUVertexAttribute >; };attributes
dictionary {GPUVertexAttribute required GPUVertexFormat ;format required GPUSize64 ;offset required GPUIndex32 ; };shaderLocation
-
GPUDevicedevice -
GPUVertexBufferLayoutdescriptor -
GPUProgrammableStagevertexStage
Return
true
,
if
and
only
if,
all
of
the
following
conditions
are
satisfied:
-
descriptor .
arrayStride≤ device .[[device]].[[limits]].maxVertexBufferArrayStride. -
descriptor .
arrayStrideis a multiple of 4. -
For each attribute attrib in the list descriptor .
attributes:-
If descriptor .
arrayStrideis zero:-
attrib .
offset+ sizeof( attrib .format) ≤ device .[[device]].[[limits]].maxVertexBufferArrayStride.
Otherwise:
-
attrib .
offset+ sizeof( attrib .format) ≤ descriptor .arrayStride.
-
-
attrib .
offsetis a multiple of the minimum of 4 and sizeof( attrib .format). -
attrib .
shaderLocationis less than device .[[device]].[[limits]].maxVertexAttributes.
-
-
For every vertex attribute in the shader reflection of vertexStage .
modulethat is a pipeline input of vertexStage .entryPoint, there is a corresponding attrib element of descriptor .attributesfor which all of the following are true:-
The shader format is compatible with attrib .
format's vertex data type :- "unorm", "snorm", or "float"
-
shader format must be
f32orvecN<f32>. - "uint"
-
shader format must be
u32orvecN<u32>. - "sint"
-
shader format must be
i32orvecN<i32>.
-
The shader location is attrib .
shaderLocation.
-
-
GPUDevicedevice -
GPUVertexStatedescriptor
Return
true
,
if
and
only
if,
all
of
the
following
conditions
are
satisfied:
-
descriptor .
buffers.length is less than or equal to device .[[device]].[[limits]].maxVertexBuffers. -
Each vertexBuffer layout descriptor in the list descriptor .
bufferspasses validating GPUVertexBufferLayout ( device , vertexBuffer , descriptor ) -
The sum of vertexBuffer .
attributes.length, over every vertexBuffer in descriptor .buffers, is less than or equal to device .[[device]].[[limits]].maxVertexAttributes. -
Each attrib in the union of all
GPUVertexAttributeacross descriptor .buffershas a distinct attrib .shaderLocationvalue.
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
[Exposed =(Window ,DedicatedWorker ),SecureContext ]interface GPUCommandBuffer { };GPUCommandBuffer includes GPUObjectBase ;
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
[Exposed =(Window ,DedicatedWorker ),SecureContext ]interface GPUCommandEncoder {GPURenderPassEncoder beginRenderPass (GPURenderPassDescriptor descriptor );GPUComputePassEncoder beginComputePass (optional GPUComputePassDescriptor descriptor = {});undefined copyBufferToBuffer (GPUBuffer source ,GPUSize64 sourceOffset ,GPUBuffer destination ,GPUSize64 destinationOffset ,GPUSize64 size );undefined copyBufferToTexture (GPUImageCopyBuffer source ,GPUImageCopyTexture destination ,GPUExtent3D copySize );undefined copyTextureToBuffer (GPUImageCopyTexture source ,GPUImageCopyBuffer destination ,GPUExtent3D copySize );undefined copyTextureToTexture (GPUImageCopyTexture source ,GPUImageCopyTexture destination ,GPUExtent3D copySize );undefined clearBuffer (GPUBuffer buffer ,optional GPUSize64 offset = 0,optional GPUSize64 size );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 commands to be executed on the Queue timeline when the
GPUCommandBufferthis encoder produces is submitted. -
[[state]]of type encoder state . -
The current state of the
GPUCommandEncoder, initially set to open . -
[[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]]is open any time theGPUCommandEncoderis valid and has no activeGPURenderPassEncoderorGPUComputePassEncoder. - encoding a render pass
-
Indicates the
GPUCommandEncoderhas an activeGPURenderPassEncoder. The[[state]]becomes encoding a render pass oncebeginRenderPass()is called successfully untilendPass()is called on the returnedGPURenderPassEncoder, at which point the[[state]](if the encoder is still valid) reverts to open . - encoding a compute pass
-
Indicates the
GPUCommandEncoderhas an activeGPUComputePassEncoder. The[[state]]becomes encoding a compute pass oncebeginComputePass()is called successfully untilendPass()is called on the returnedGPUComputePassEncoder, at which point the[[state]](if the encoder is still valid) reverts to open . - closed
-
Indicates the
GPUCommandEncoderis no longer available for any operations. The[[state]]becomes closed oncefinish()is called.
12.1.1. Creation
dictionary :GPUCommandEncoderDescriptor GPUObjectDescriptorBase { };
-
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 :
-
Let pass be a new
GPURenderPassEncoderobject. -
If any of the following conditions are unsatisfied, generate a validation error and stop.
-
descriptor meets the Valid Usage rules.
-
descriptor .
timestampWritesis empty, or this .[[device]].[[features]]contain s"timestamp-query". -
For each timestampWrite in descriptor .
timestampWrites,-
timestampWrite .
querySetis valid to use with this .
-
-
Set this .
[[state]]to encoding a render pass . -
For each colorAttachment in descriptor .
colorAttachments:-
The texture subresource seen by colorAttachment .
viewis considered to be used as attachment for the duration of the render pass.
-
-
Let depthStencilAttachment be descriptor .
depthStencilAttachment. -
If depthStencilAttachment is not
null:-
Let depthStencilView be depthStencilAttachment .
view. -
If depthStencilAttachment .
depthReadOnlyandstencilReadOnlyare set:-
The texture subresources seen by depthStencilView are considered to be used as attachment-read for the duration of the render pass.
-
-
Else, the texture subresource seen by depthStencilView is considered to be used as attachment for the duration of the render pass.
-
Set pass .
[[depthReadOnly]]to depthStencilAttachment .depthReadOnly. -
Set pass .
[[stencilReadOnly]]to depthStencilAttachment .stencilReadOnly.
-
-
Set pass .
[[layout]]to derive render targets layout from pass ( descriptor ). -
For each timestampWrite in descriptor .
timestampWrites,-
If timestampWrite .
locationis"beginning", Append a GPU command to pass .[[command_encoder]].[[command_list]]that writes the GPU’s timestamp value into the timestampWrite .queryIndexth index in timestampWrite .querySet. -
Otherwise, if timestampWrite .
locationis"end", Append timestampWrite to pass .[[endTimestampWrites]].
-
-
Return 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.
-
this .
[[state]]is [=encoder state/open}}. -
descriptor .
timestampWritesis empty, or this .[[device]].[[features]]contain s"timestamp-query". -
For each timestampWrite in descriptor .
timestampWrites,-
timestampWrite .
querySetis valid to use with this .
-
-
-
Set this .
[[state]]to [=encoder state/encoding a compute pass}}. -
Let pass be a new
GPUComputePassEncoderobject. -
For each timestampWrite in descriptor .
timestampWrites,-
If timestampWrite .
locationis"beginning", Append a GPU command to pass .[[command_encoder]].[[command_list]]that writes the GPU’s timestamp value into the timestampWrite .queryIndexth index in timestampWrite .querySet. -
Otherwise, if timestampWrite .
locationis"end", Append timestampWrite to pass .[[endTimestampWrites]].
-
-
Return pass .
-
12.3. Copy Commands
these dictionary definitions should be inside the image copies section.
12.3.1.
GPUImageDataLayout
dictionary GPUImageDataLayout {GPUSize64 = 0;offset GPUSize32 bytesPerRow ;GPUSize32 rowsPerImage ; };
A
GPUImageDataLayout
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 .
Define images more precisely. In particular, define them as being comprised of texel blocks .
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 .
Texel blocks are tightly packed within each block row in the linear memory layout of an image copy, with each subsequent texel block immediately following the previous texel block, with no padding. This includes copies to/from specific aspects of depth-or-stencil format textures: stencil values are tightly packed in an array of bytes; depth values are tightly packed in an array of the appropriate type ("depth16unorm" or "depth32float").
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 copy 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 copy depth is more than one).
12.3.2.
GPUImageCopyBuffer
In
an
image
copy
operation,
GPUImageCopyBuffer
defines
a
GPUBuffer
and,
together
with
the
copySize
,
how
image
data
is
laid
out
in
the
buffer’s
memory
(see
GPUImageDataLayout
).
dictionary GPUImageCopyBuffer :GPUImageDataLayout {required GPUBuffer ; };buffer
Arguments:
-
GPUImageCopyBufferimageCopyBuffer
Returns:
boolean
Return
true
if
and
only
if
all
of
the
following
conditions
are
satisfied:
-
imageCopyBuffer .
bytesPerRowmust be a multiple of 256.
12.3.3.
GPUImageCopyTexture
In
an
image
copy
operation,
a
GPUImageCopyTexture
defines
a
GPUTexture
and,
together
with
the
copySize
,
the
sub-region
of
the
texture
(spanning
one
or
more
contiguous
texture
subresources
at
the
same
mip-map
level).
dictionary GPUImageCopyTexture {required GPUTexture texture ;GPUIntegerCoordinate mipLevel = 0;GPUOrigin3D origin = {};GPUTextureAspect aspect = "all"; };
-
texture, of type GPUTexture -
Texture to copy to/from.
-
mipLevel, of type GPUIntegerCoordinate , defaulting to0 -
Mip-map level of the
textureto copy to/from. -
origin, of type GPUOrigin3D , defaulting to{} -
Defines the origin of the copy - the minimum corner of the texture sub-region to copy to/from. Together with
copySize, defines the full copy sub-region. -
aspect, of type GPUTextureAspect , defaulting to"all" -
Defines which aspects of the
textureto copy to/from.
Arguments:
-
GPUImageCopyTextureimageCopyTexture -
GPUExtent3DcopySize
Returns:
boolean
Let:
-
blockWidth be the texel block width of imageCopyTexture .
texture.[[descriptor]].format. -
blockHeight be the texel block height of imageCopyTexture .
texture.[[descriptor]].format.
Return
true
if
and
only
if
all
of
the
following
conditions
apply:
-
imageCopyTexture .
texturemust be a validGPUTexture. -
imageCopyTexture .
mipLevelmust be less than the[[descriptor]].mipLevelCountof imageCopyTexture .texture. -
imageCopyTexture .
origin. x must be a multiple of blockWidth . -
imageCopyTexture .
origin. y must be a multiple of blockHeight . -
The imageCopyTexture subresource size of imageCopyTexture is equal to copySize if either of the following conditions is true:
-
imageCopyTexture .
texture.[[descriptor]].formatis a depth-stencil format. -
imageCopyTexture .
texture.[[descriptor]].sampleCountis greater than 1.
-
Define
the
copies
with
1d
and
3d
textures.
[Issue
#gpuweb/gpuweb#69]
12.3.4.
GPUImageCopyTextureTagged
WebGPU
textures
hold
raw
numeric
data,
and
are
not
tagged
with
semantic
metadata
describing
colors.
However,
copyExternalImageToTexture()
copies
from
sources
that
describe
colors.
A
GPUImageCopyTextureTagged
is
a
GPUImageCopyTexture
which
is
additionally
tagged
with
color
space/encoding
and
alpha-premultiplication
metadata,
so
that
semantic
color
data
may
be
preserved
during
copies.
This
metadata
affects
only
the
semantics
of
the
copyExternalImageToTexture()
operation,
not
the
semantics
of
the
destination
texture.
dictionary GPUImageCopyTextureTagged :GPUImageCopyTexture {GPUPredefinedColorSpace colorSpace = "srgb";boolean premultipliedAlpha =false ; };
-
colorSpace, of type GPUPredefinedColorSpace , defaulting to"srgb" -
Describes the color space and encoding used to encode data into the destination texture.
This may result in values outside of the range [0, 1] being written to the target texture, if its format can represent them. Otherwise, the results are clamped to the target texture format’s range.
Note: If
colorSpacematches the source image, no conversion occurs.ImageBitmapcolor space tagging and conversion can be controlled viaImageBitmapOptions. -
premultipliedAlpha, of type boolean , defaulting tofalse -
Describes whether the data written into the texture should be have its RGB channels premultiplied by the alpha channel, or not.
If this option is set to
trueand thesourceis also premultiplied, the source RGB values must be preserved even if they exceed their corresponding alpha values.Note: If
premultipliedAlphamatches the source image, no conversion occurs. 2d canvases are always premultiplied , while WebGL canvases can be controlled via WebGLContextAttributes .ImageBitmappremultiplication can be controlled viaImageBitmapOptions.
Define
(and
test)
the
encoding
of
color
values
into
the
various
encodings
allowed
by
copyExternalImageToTexture()
.
12.3.5.
GPUImageCopyExternalImage
dictionary GPUImageCopyExternalImage {required (ImageBitmap or HTMLCanvasElement or OffscreenCanvas )source ;GPUOrigin2D origin = {}; };
GPUImageCopyExternalImage
has
the
following
members:
-
source, of type(ImageBitmap or HTMLCanvasElement or OffscreenCanvas) -
The source of the image copy . The copy source data is captured at the moment that
copyExternalImageToTexture()is issued. -
origin, of type GPUOrigin2D , defaulting to{} -
Defines the origin of the copy - the minimum corner of the source sub-region to copy from. Together with
copySize, defines the full copy sub-region.
12.3.6. Buffer Copies
-
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. [Issue #gpuweb/gpuweb#21]
figure out how to handle overflows in the spec. [Issue #gpuweb/gpuweb#69]
12.3.7. Buffer Fills
-
clearBuffer(buffer, offset, size) -
Encode a command into the
GPUCommandEncoderthat fills a sub-region of aGPUBufferwith zeros.Called on:GPUCommandEncoderthis .Arguments:
Arguments for the GPUCommandEncoder.clearBuffer(buffer, offset, size) method. Parameter Type Nullable Optional Description bufferGPUBuffer ✘ ✘ The GPUBufferto clear.offsetGPUSize64 ✘ ✔ Offset in bytes into buffer where the sub-region to clear begins. sizeGPUSize64 ✘ ✔ Size in bytes of the sub-region to clear. Defaults to the size of the buffer minus offset . Returns:
undefinedIssue the following steps on the Device timeline of this .
[[device]]:-
If size is missing, set size to
max(0, |buffer|.{{GPUBuffer/[[size]]}} - |offset|). -
If any of the following conditions are unsatisfied, generate a validation error and stop.
-
12.3.8. Image Copies
WebGPU
provides
copyBufferToTexture()
for
buffer-to-texture
copies
and
copyTextureToBuffer()
for
texture-to-buffer
copies,
as
well
as
writeTexture()
for
ArrayBuffer-to-texture
writes.
The
following
definitions
and
validation
rules
are
used
by
these
methods,
as
well
as
copyTextureToTexture()
.
Does the term "image copy" include copyTextureToTexture?
imageCopyTexture
subresource
size
and
Valid
Texture
Copy
Range
also
applies
to
copyTextureToTexture()
.
imageCopyTexture subresource size
Arguments:
-
GPUImageCopyTextureimageCopyTexture
Returns:
GPUExtent3D
The imageCopyTexture subresource size of imageCopyTexture is calculated as follows:
Its
width
,
height
and
depthOrArrayLayers
are
the
width,
height,
and
depth,
respectively,
of
the
physical
size
of
imageCopyTexture
.
texture
subresource
at
mipmap
level
imageCopyTexture
.
mipLevel
.
define this as an algorithm with (texture, mipmapLevel) parameters and use the call syntax instead of referring to the definition by label.
Arguments:
-
GPUImageDataLayoutlayout -
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:
-
Fail if the following conditions are not satisfied:
-
If heightInBlocks > 1, layout .
bytesPerRowmust be specified. -
If copyExtent . depthOrArrayLayers > 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 . depthOrArrayLayers > 1:
-
Let bytesPerImage be layout .
bytesPerRow× layout .rowsPerImage. -
Let bytesBeforeLastImage be bytesPerImage × ( copyExtent . depthOrArrayLayers − 1).
-
Add bytesBeforeLastImage to requiredBytesInCopy .
-
-
If copyExtent . depthOrArrayLayers > 0:
-
If heightInBlocks > 1, add layout .
bytesPerRow× ( heightInBlocks − 1) to requiredBytesInCopy . -
If heightInBlocks > 0, add bytesInLastRow to requiredBytesInCopy .
-
-
Fail if the following conditions are not satisfied:
-
layout .
offset+ requiredBytesInCopy ≤ byteSize .
-
Valid Texture Copy Range
Given
a
GPUImageCopyTexture
imageCopyTexture
and
a
GPUExtent3D
copySize
,
let
-
blockWidth be the texel block width of imageCopyTexture .
texture.[[descriptor]].format. -
blockHeight be the texel block height of imageCopyTexture .
texture.[[descriptor]].format.
The following validation rules apply:
-
If the
[[descriptor]].dimensionof imageCopyTexture .textureis1d:-
Both copySize . height and depthOrArrayLayers must be 1.
-
-
If the
[[descriptor]].dimensionof imageCopyTexture .textureis2d:-
( imageCopyTexture .
origin. x + copySize . width ), ( imageCopyTexture .origin. y + copySize . height ), and ( imageCopyTexture .origin. z + copySize . depthOrArrayLayers ) must be less than or equal to the width , height , and depthOrArrayLayers , respectively, of the imageCopyTexture subresource size of imageCopyTexture .
-
-
copySize . width must be a multiple of blockWidth .
-
copySize . height must be a multiple of blockHeight .
Define
the
copies
with
1d
and
3d
textures.
[Issue
#gpuweb/gpuweb#69]
Additional restrictions on rowsPerImage if needed. [Issue #gpuweb/gpuweb#537]
Define
the
copies
with
"depth24plus"
,
"depth24plus-stencil8"
,
and
"stencil8"
.
[Issue
#gpuweb/gpuweb#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 sourceGPUImageCopyBuffer ✘ ✘ Combined with copySize , defines the region of the source buffer. destinationGPUImageCopyTexture ✘ ✘ 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.
-
Let dstTextureDesc be destination .
texture.[[descriptor]]. -
validating GPUImageCopyBuffer ( source ) returns
true. -
validating GPUImageCopyTexture ( destination , copySize ) returns
true. -
dstTextureDesc .
sampleCountis 1. -
If dstTextureDesc .
formatis a depth-or-stencil format :-
destination .
aspectmust refer to a single aspect of dstTextureDesc .format, and that aspect must be a valid image copy destination according to § 24.1.2 Depth-stencil formats .
-
-
Valid Texture Copy Range applies to destination and copySize .
-
If dstTextureDesc .
formatis not a depth-or-stencil format :-
source .
offsetis a multiple of the texel block size of dstTextureDesc .format.
-
-
If dstTextureDesc .
formatis a depth-or-stencil format :-
source .
offsetis a multiple of 4.
-
-
validating linear texture data ( source , source .
buffer.[[size]], dstTextureDesc .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 sourceGPUImageCopyTexture ✘ ✘ Combined with copySize , defines the region of the source texture subresources . destinationGPUImageCopyBuffer ✘ ✘ 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.
-
Let srcTextureDesc be source .
texture.[[descriptor]]. -
validating GPUImageCopyTexture ( source , copySize ) returns
true. -
srcTextureDesc .
sampleCountis 1. -
If srcTextureDesc .
formatis a depth-stencil format:-
destination .
aspectmust refer to a single aspect of srcTextureDesc .format, and that aspect must be a valid image copy source according to § 24.1.2 Depth-stencil formats .
-
-
validating GPUImageCopyBuffer ( destination ) returns
true. -
Valid Texture Copy Range applies to source and copySize .
-
If srcTextureDesc .
formatis not a depth-or-stencil format :-
destination .
offsetis a multiple of the texel block size of srcTextureDesc .format.
-
-
If srcTextureDesc .
formatis a depth-or-stencil format :-
destination .
offsetis a multiple of 4.
-
-
validating linear texture data ( destination , destination .
buffer.[[size]], srcTextureDesc .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 sourceGPUImageCopyTexture ✘ ✘ Combined with copySize , defines the region of the source texture subresources . destinationGPUImageCopyTexture ✘ ✘ 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.
-
Let srcTextureDesc be source .
texture.[[descriptor]]. -
Let dstTextureDesc be destination .
texture.[[descriptor]]. -
validating GPUImageCopyTexture ( source , copySize ) returns
true. -
validating GPUImageCopyTexture ( destination , copySize ) returns
true. -
srcTextureDesc .
sampleCountis equal to dstTextureDesc .sampleCount. -
srcTextureDesc .
formatand dstTextureDesc .formatmust be copy-compatible . -
If srcTextureDesc .
formatis a depth-stencil format: -
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.
-
-
GPUTextureFormat
s
format1
and
format2
are
copy-compatible
if:
-
format1 equals format2 , or
-
format1 and format2 differ only in whether they are
srgbformats (have the-srgbsuffix).
-
If imageCopyTexture .
texture.[[descriptor]].dimensionis"2d":-
For each arrayLayer of the copySize . depthOrArrayLayers array layers starting at imageCopyTexture .
origin. z :-
The subresource of imageCopyTexture .
textureat mipmap level imageCopyTexture .mipLeveland array layer arrayLayer .
-
-
-
Otherwise:
-
The subresource of imageCopyTexture .
textureat mipmap level imageCopyTexture .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:
undefined-
If this .
[[state]]is not open :-
Figure out what to do in this case. [Issue #gpuweb/gpuweb#2264]
-
-
Issue 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
GPUCommandEncoder.Called on:GPUCommandEncoderthis .Returns:
undefined-
If this .
[[state]]is not open :-
Figure out what to do in this case. [Issue #gpuweb/gpuweb#2264]
-
-
Issue the following steps on the Device timeline of this :
-
If any of the following requirements are unmet, make this invalid and stop.
-
this .
[[debug_group_stack]]'s size must be > 0.
-
-
Pop an entry off this .
[[debug_group_stack]].
-
-
-
insertDebugMarker(markerLabel) -
Marks a point in a stream of commands with a label string.
Called on:GPUCommandEncoderthis .Arguments:
Arguments for the GPUCommandEncoder.insertDebugMarker(markerLabel) method. Parameter Type Nullable Optional Description markerLabelUSVString ✘ ✘ The label to insert. Returns:
undefined-
If this .
[[state]]is not open :-
Figure out what to do in this case. [Issue #gpuweb/gpuweb#2264]
-
-
12.5. Queries
-
writeTimestamp(querySet, queryIndex) -
Writes a timestamp value into a querySet when all previous commands have completed executing.
Called on:GPUCommandEncoderthis .Arguments:
Arguments for the GPUCommandEncoder.writeTimestamp(querySet, queryIndex) method. Parameter Type Nullable Optional Description querySetGPUQuerySet ✘ ✘ The query set that will store the timestamp values. queryIndexGPUSize32 ✘ ✘ The index of the query in the query set. Returns:
undefined-
If this .
[[device]].[[features]]does not contain"timestamp-query", throw aTypeError. -
If any of the following conditions are unsatisfied, generate a validation error and stop.
-
querySet is valid to use with this .
-
querySet .
[[descriptor]].typeis"timestamp". -
queryIndex < querySet .
[[descriptor]].count.
Describe
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 256.
-
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 requirements are unmet:
-
this must be valid .
-
this .
[[debug_group_stack]]'s size must be 0. -
Every usage scope contained in this must satisfy the usage scope validation .
Then:
-
Generate a
GPUValidationErrorin the current scope with appropriate error message. -
Return a new invalid
GPUCommandBuffer.
-
-
Set commandBuffer .
[[command_list]]to 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 < this .
[[device]].[[limits]].maxBindGroups. -
dynamicOffsets .length is bindGroup .
[[layout]].[[dynamicOffsetCount]]. -
Iterate over each dynamic binding offset in bindGroup and run the following steps for each bufferBinding , bufferLayout , and dynamicOffsetIndex :
-
Let bufferDynamicOffset be dynamicOffsets [ dynamicOffsetIndex ].
-
bufferBinding .
offset+ bufferDynamicOffset + bufferLayout .minBindingSize≤ bufferBinding .buffer.[[size]]. -
if bufferLayout .
typeis"uniform":-
dynamicOffset is a multiple of
minUniformBufferOffsetAlignment.
-
-
if bufferLayout .
typeis"storage"or"read-only-storage":-
dynamicOffset is a multiple of
minStorageBufferOffsetAlignment.
-
-
-
-
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 marked as buffer.hasDynamicOffset.dynamicOffsetsDataStartGPUSize64 ✘ ✘ Offset in elements into dynamicOffsetsData where the buffer offset data begins. dynamicOffsetsDataLengthGPUSize32 ✘ ✘ Number of buffer offsets to read from dynamicOffsetsData . Returns:
undefined-
If any of the following requirements are unmet, throw a
RangeErrorand stop.-
dynamicOffsetsDataStart must be ≥ 0.
-
dynamicOffsetsDataStart + dynamicOffsetsDataLength must be ≤ dynamicOffsetsData .
length.
-
-
Let dynamicOffsets be a list containing the range, starting at index dynamicOffsetsDataStart , of dynamicOffsetsDataLength elements of a copy of dynamicOffsetsData .
-
Call this .
setBindGroup( index , bindGroup , dynamicOffsets ).
-
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 .
bufferis notundefinedand bindingDescriptor .buffer.hasDynamicOffsetistrue:
-
Arguments:
-
GPUProgrammablePassEncoderencoder -
Encoder who’s bind groups are being validated.
-
GPUPipelineBasepipeline -
Pipeline 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 .
-
Add
validation
that,
for
buffer
bindings
that
weren’t
prevalidated
with
minBindingSize
,
the
binding
ranges
are
large
enough
for
the
shader’s
minimum
binding
size
requirements.
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
[Exposed =(Window ,DedicatedWorker ),SecureContext ]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 endPass (); };GPUComputePassEncoder includes GPUObjectBase ;GPUComputePassEncoder includes GPUProgrammablePassEncoder ;
GPUComputePassEncoder
has
the
following
internal
slots:
-
[[pipeline]], of typeGPUComputePipeline -
The current
GPUComputePipeline, initiallynull. -
[[endTimestampWrites]], of typeGPUComputePassTimestampWrites -
The timestamp attachments which need to be executed when the pass ends.
14.1.1. Creation
enum {GPUComputePassTimestampLocation ,"beginning" , };"end" dictionary {GPUComputePassTimestampWrite required GPUQuerySet ;querySet required GPUSize32 ;queryIndex required GPUComputePassTimestampLocation ; };location typedef sequence <GPUComputePassTimestampWrite >;GPUComputePassTimestampWrites dictionary :GPUComputePassDescriptor GPUObjectDescriptorBase {GPUComputePassTimestampWrites timestampWrites = []; };
-
timestampWrites, of type GPUComputePassTimestampWrites , defaulting to[] -
A sequence of
GPUComputePassTimestampWritevalues define where and when timestamp values will be written for this pass.
Given
a
GPUComputePassDescriptor
this
the
following
validation
rules
apply:
-
For each timestampWrite in this .
timestampWrites:-
timestampWrite .
querySet.[[descriptor]].typeis"timestamp". -
timestampWrite .
queryIndex< timestampWrite .querySet.[[descriptor]].count.
-
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. See § 21.2 Computing for the detailed specification.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. -
all of x , y and z are less than this .device.limits.
maxComputeWorkgroupsPerDimension.
-
-
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. See § 21.2 Computing for the detailed specification.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.
add some validation related to
maxComputeWorkgroupsPerDimension. -
14.1.3. 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, make this .
[[command_encoder]]invalid and stop.-
this must be valid .
-
this .
[[debug_group_stack]]'s size is 0.
-
-
For each timestampWrite in this .
[[endTimestampWrites]],-
Append a GPU command to this .
[[command_encoder]].[[command_list]]that writes the GPU’s timestamp value into the timestampWrite .queryIndexth index in timestampWrite .querySet.
-
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 );undefined setVertexBuffer (GPUIndex32 slot ,GPUBuffer buffer ,optional GPUSize64 offset = 0,optional GPUSize64 size );undefined draw (GPUSize32 vertexCount ,optional GPUSize32 instanceCount = 1,optional GPUSize32 firstVertex = 0,optional GPUSize32 firstInstance = 0);undefined drawIndexed (GPUSize32 indexCount ,optional GPUSize32 instanceCount = 1,optional GPUSize32 firstIndex = 0,optional GPUSignedOffset32 baseVertex = 0,optional GPUSize32 firstInstance = 0);undefined drawIndirect (GPUBuffer indirectBuffer ,GPUSize64 indirectOffset );undefined drawIndexedIndirect (GPUBuffer indirectBuffer ,GPUSize64 indirectOffset ); }; [Exposed =(Window ,DedicatedWorker ),SecureContext ]interface GPURenderPassEncoder {undefined setViewport (float x ,float y ,float width ,float height ,float minDepth ,float maxDepth );undefined setScissorRect (GPUIntegerCoordinate x ,GPUIntegerCoordinate y ,GPUIntegerCoordinate width ,GPUIntegerCoordinate height );undefined setBlendConstant (GPUColor color );undefined setStencilReference (GPUStencilValue reference );undefined beginOcclusionQuery (GPUSize32 queryIndex );undefined endOcclusionQuery ();undefined executeBundles (sequence <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:
-
[[layout]], of typeGPURenderPassLayout -
The layout of the render pass.
-
[[depthReadOnly]], of type boolean? -
If present, indicates that the depth component is not modified.
-
[[stencilReadOnly]], of type boolean? -
If present, indicates that the stencil component is not modified.
-
[[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]]. -
[[index_buffer_size]], of typeGPUSize64 -
The size in bytes of the section of
[[index_buffer]]currently set, initially0. -
[[vertex_buffers]], of type ordered map <slot,GPUBuffer> -
The current
GPUBuffers to read vertex data from for each slot, initially empty. -
[[vertex_buffer_sizes]], of type ordered map <slot,GPUSize64> -
The size in bytes of the section of
GPUBuffercurrently set 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
-
-
[[occlusion_query_set]], of typeGPUQuerySet. -
The
GPUQuerySetto store occlusion query results for the pass, which is initialized withGPURenderPassDescriptor.occlusionQuerySetat pass creation time. -
[[occlusion_query_active]], of typeboolean. -
Whether the pass’s
[[occlusion_query_set]]is being written. -
[[viewport]] -
Current viewport rectangle and depth range.
-
[[endTimestampWrites]], of typeGPURenderPassTimestampWrites -
The timestamp attachments which need to be executed when the pass ends.
When
a
GPURenderPassEncoder
is
created,
it
has
the
following
default
state:
-
-
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
enum {GPURenderPassTimestampLocation ,"beginning" , };"end" dictionary {GPURenderPassTimestampWrite required GPUQuerySet ;querySet required GPUSize32 ;queryIndex required GPURenderPassTimestampLocation ; };location typedef sequence <GPURenderPassTimestampWrite >;GPURenderPassTimestampWrites dictionary :GPURenderPassDescriptor GPUObjectDescriptorBase {required sequence <GPURenderPassColorAttachment >colorAttachments ;GPURenderPassDepthStencilAttachment depthStencilAttachment ;GPUQuerySet occlusionQuerySet ;GPURenderPassTimestampWrites timestampWrites = []; };
-
colorAttachments, of type sequence< GPURenderPassColorAttachment > -
The set of
GPURenderPassColorAttachmentvalues in this sequence defines which color attachments will be output to when executing this render pass. -
depthStencilAttachment, of type GPURenderPassDepthStencilAttachment -
The
GPURenderPassDepthStencilAttachmentvalue that defines the depth/stencil attachment that will be output to and tested against when executing this render pass. -
occlusionQuerySet, of type GPUQuerySet -
The
GPUQuerySetvalue defines where the occlusion query results will be stored for this pass. -
timestampWrites, of type GPURenderPassTimestampWrites , defaulting to[] -
A sequence of
GPURenderPassTimestampWritevalues defines where and when timestamp values will be written for this pass.
Given
a
GPURenderPassDescriptor
this
the
following
validation
rules
apply:
-
this .
colorAttachments.length must be less than or equal to 8. -
this .
colorAttachments.length must be greater than0or this .depthStencilAttachmentmust not benull. -
For each colorAttachment in this .
colorAttachments:-
colorAttachment must meet the GPURenderPassColorAttachment Valid Usage rules.
-
-
If this .
depthStencilAttachmentis notnull:-
this .
depthStencilAttachmentmust meet the GPURenderPassDepthStencilAttachment Valid Usage rules.
-
-
All
views in this .colorAttachments, and this .depthStencilAttachment.viewif present, must have equal[[descriptor]].sampleCounts. -
For each
viewin this .colorAttachmentsand this .depthStencilAttachment.view, if present, the[[renderExtent]]must match. -
If this .
occlusionQuerySetis notnull:-
this .
occlusionQuerySet.[[descriptor]].typemust beocclusion.
-
-
For each timestampWrite in this .
timestampWrites:-
timestampWrite .
querySet.[[descriptor]].typeis"timestamp". -
timestampWrite .
queryIndex< timestampWrite .querySet.[[descriptor]].count.
-
support for no attachments [Issue #gpuweb/gpuweb#503]
GPURenderPassDescriptor
value
descriptor
,
the
syntax:
-
descriptor . renderExtent refers to
[[renderExtent]]of any[[descriptor]]in either descriptor .depthStencilAttachment.view, or any of theviewin descriptor .colorAttachments.
make it a define once we reference to this from other places
Note: the Valid Usage guarantees that all of the render extents of the attachments are the same, so we can take any of them, assuming the descriptor is valid.
15.1.1.1. Color Attachments
dictionary {GPURenderPassColorAttachment required GPUTextureView view ;GPUTextureView resolveTarget ;required (GPULoadOp or GPUColor )loadValue ;required GPUStoreOp storeOp ; };
-
view, 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 ifviewis multisampled. -
loadValue, of type(GPULoadOp or GPUColor) -
If a
GPULoadOp, indicates the load operation to perform onviewprior to executing the render pass. If aGPUColor, indicates the value to clearviewto prior to executing the render pass.Note: It is recommended to prefer a clear-value; see
"load". -
storeOp, of type GPUStoreOp -
The store operation to perform on
viewafter executing the render pass.
Given
a
GPURenderPassColorAttachment
this
the
following
validation
rules
apply:
-
Let renderTextureDesc be this .
view.[[texture]].[[descriptor]]. -
Let resolveTextureDesc be this .
resolveTarget.[[texture]].[[descriptor]]. -
this .
viewmust have a color renderable format . -
renderTextureDesc .
usagemust containRENDER_ATTACHMENT. -
this .
viewmust be a view of a single subresource . -
If this .
resolveTargetis notnull:-
this .
viewmust be multisampled. -
this .
resolveTargetmust not be multisampled. -
resolveTextureDesc .
usagemust containRENDER_ATTACHMENT. -
this .
resolveTargetmust be a view of a single subresource . -
The dimensions of the subresource s seen by this .
resolveTargetand this .viewmust match. -
resolveTextureDesc .
formatmust match renderTextureDesc .format.
-
15.1.1.2. Depth/Stencil Attachments
dictionary {GPURenderPassDepthStencilAttachment required GPUTextureView view ;required (GPULoadOp or float )depthLoadValue ;required GPUStoreOp depthStoreOp ;boolean depthReadOnly =false ;required (GPULoadOp or GPUStencilValue )stencilLoadValue ;required GPUStoreOp stencilStoreOp ;boolean stencilReadOnly =false ; };
-
view, 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 onview's depth component prior to executing the render pass. If afloat, indicates the value to clearview's depth component to prior to executing the render pass.Note: It is recommended to prefer a clear-value; see
"load". -
depthStoreOp, of type GPUStoreOp -
The store operation to perform on
view's depth component after executing the render pass.Note: It is recommended to prefer a clear-value; see
"load". -
depthReadOnly, of type boolean , defaulting tofalse -
Indicates that the depth component of
viewis read only. -
stencilLoadValue, of type(GPULoadOp or GPUStencilValue) -
If a
GPULoadOp, indicates the load operation to perform onview's stencil component prior to executing the render pass. If aGPUStencilValue, indicates the value to clearview's stencil component to prior to executing the render pass. -
stencilStoreOp, of type GPUStoreOp -
The store operation to perform on
view's stencil component after executing the render pass. -
stencilReadOnly, of type boolean , defaulting tofalse -
Indicates that the stencil component of
viewis read only.
Given
a
GPURenderPassDepthStencilAttachment
this
the
following
validation
rules
apply:
-
this .
viewmust have a depth-or-stencil format . -
this .
viewmust be a view of a single mipmap level , single array layer , and all the aspects in the texture. -
this .
view.[[descriptor]].usagemust containRENDER_ATTACHMENT. -
If this .
view.[[descriptor]].formatis a combined depth-stencil format :-
this .
depthReadOnlymust be equal to this .stencilReadOnly
-
-
If this .
depthReadOnlyistrue:-
this .
depthLoadValuemust be"load". -
this .
depthStoreOpmust be"store".
-
-
If this .
stencilReadOnlyistrue:-
this .
stencilLoadValuemust be"load". -
this .
stencilStoreOpmust be"store".
-
15.1.1.3. Load & Store Operations
enum {GPULoadOp "load" , };
-
"load" -
Loads the existing value for this attachment into the render pass.
Note: On some GPU hardware (primarily mobile), providing a clear-value is significantly cheaper because it avoids loading data from main memory into tile-local memory. On other GPU hardware, there isn’t a significant difference. As a result, it is recommended to use a clear-value, rather than
"load", in cases where the initial value doesn’t matter (e.g. the render target will be cleared using a skybox).
enum {GPUStoreOp ,"store" , };"discard"
15.1.1.4. Render Pass Layout
GPURenderPassLayout
contains
the
layout
of
the
render
targets
for
the
current
pass,
which
determines
the
compatibility
of
the
pass
with
render
pipelines.
dictionary :GPURenderPassLayout GPUObjectDescriptorBase {required sequence <GPUTextureFormat >;colorFormats GPUTextureFormat ;depthStencilFormat GPUSize32 = 1; };sampleCount
Arguments:
-
GPURenderPassDescriptordescriptor
Returns:
GPURenderPassLayout
-
Let layout be a new
GPURenderPassLayoutobject. -
For each colorAttachment in descriptor .
colorAttachments:-
Set layout .
sampleCountto colorAttachment .view.[[texture]].[[descriptor]].sampleCount. -
Append colorAttachment .
view.[[descriptor]].formatto layout .colorFormats.
-
-
Let depthStencilAttachment be descriptor .
depthStencilAttachment. -
If depthStencilAttachment is not
null:-
Let view be depthStencilAttachment .
view -
Set layout .
sampleCountto view .[[texture]].[[descriptor]].sampleCount. -
Set layout .
depthStencilFormatto view .[[descriptor]].format.
-
-
Return layout .
Arguments:
-
GPURenderPipelineDescriptordescriptor
Returns:
GPURenderPassLayout
-
Let layout be a new
GPURenderPassLayoutobject. -
Set layout .
sampleCountto descriptor .multisample.count. -
If descriptor .
depthStencilis notnull:-
Set layout .
depthStencilFormatto descriptor .depthStencil/format.
-
-
If descriptor .
fragmentis notnull:-
For each colorTarget in descriptor .
fragment.targets:-
Append colorTarget .
formatto layout .colorFormats
-
-
-
Return layout .
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]]:-
Let pipelineTargetsLayout be derive render targets layout from pipeline ( pipeline .
[[descriptor]]). -
If any of the following conditions are unsatisfied, make this invalid and stop.
-
pipeline is valid to use with this .
-
this .
[[layout]]equals pipelineTargetsLayout . -
If pipeline .
[[writesDepth]]: this .[[depthReadOnly]]must befalse. -
If pipeline .
[[writesStencil]]: this .[[stencilReadOnly]]must befalse.
-
-
Set this .
[[pipeline]]to be pipeline .
define what "equals" means for
GPURenderPassLayouthere. -
-
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. Defaults to 0.sizeGPUSize64 ✘ ✔ Size in bytes of the index data in buffer . Defaults to the size of the buffer minus the offset. Returns:
undefinedIssue the following steps on the Device timeline of this .
[[device]]:-
If size is missing, set size to max(0, buffer .
[[size]]- offset ). -
If any of the following conditions are unsatisfied, make this invalid and stop.
-
buffer is valid to use with this .
-
offset is a multiple of indexFormat ’s byte size.
-
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 . -
Set this .
[[index_buffer_size]]to be size .
-
-
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. Defaults to 0.sizeGPUSize64 ✘ ✔ Size in bytes of the vertex data in buffer . Defaults to the size of the buffer minus the offset. Returns:
undefinedIssue the following steps on the Device timeline of this .
[[device]]:-
If size is missing, set size to max(0, buffer .
[[size]]- offset ). -
If any of the following conditions are unsatisfied, make this invalid and stop.
-
buffer is valid to use with this .
-
slot < this .
[[device]].[[limits]].maxVertexBuffers. -
offset is a multiple of 4.
-
offset + size ≤ buffer .
[[size]].
-
-
Add buffer to the usage scope as input .
-
Set this .
[[vertex_buffers]][ slot ] to be buffer . -
Set this .
[[vertex_buffer_sizes]][ slot ] to be size .
-
-
draw(vertexCount, instanceCount, firstVertex, firstInstance) -
Draws primitives. See § 21.3 Rendering for the detailed specification.
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 .
-
Let buffers be this .
[[pipeline]].[[descriptor]].vertex.buffers. -
For each
GPUIndex32slot0to buffers .length:-
Let bufferSize be this .
[[vertex_buffer_sizes]][ slot ]. -
Let stride be buffers [ slot ].
arrayStride. -
If stride is zero:
-
For each attribute attrib in the list this .
[[pipeline]].[[descriptor]].vertex.buffers.attributes:
Otherwise:
-
If buffers [ slot ].
stepModeis:-
"vertex" -
( firstVertex + vertexCount ) * stride ≤ bufferSize .
-
"instance" -
( firstInstance + instanceCount ) * stride ≤ bufferSize .
-
-
-
-
-
drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance) -
Draws indexed primitives. See § 21.3 Rendering for the detailed specification.
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 .
-
firstIndex + indexCount ≤ this .
[[index_buffer_size]]÷ this .[[index_format]]'s byte size; -
Let buffers be this .
[[pipeline]].[[descriptor]].vertex.buffers. -
For each
GPUIndex32slot0to buffers .length:-
Let bufferSize be this .
[[vertex_buffer_sizes]][ slot ]. -
Let stride be buffers [ slot ].
arrayStride. -
If stride is zero:
-
For each attribute attrib in the list this .
[[pipeline]].[[descriptor]].vertex.buffers.attributes:
Otherwise:
-
If buffers [ slot ].
stepModeis"instance":-
( firstInstance + instanceCount ) * stride ≤ bufferSize .
-
-
-
-
-
drawIndirect(indirectBuffer, indirectOffset) -
Draws primitives using parameters read from a
GPUBuffer. See § 21.3 Rendering for the detailed specification.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; The value corresponding to
firstInstancemust be 0, unless the"indirect-first-instance"feature is enabled. If the"indirect-first-instance"feature is not enabled andfirstInstanceis not zero thedrawIndirect()call will be treated as a no-op.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. See § 21.3 Rendering for the detailed specification.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; The value corresponding to
firstInstancemust be 0, unless the"indirect-first-instance"feature is enabled. If the"indirect-first-instance"feature is not enabled andfirstInstanceis not zero thedrawIndexedIndirect()call will be treated as a no-op.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 .vertex.buffers.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 topology be encoder .
[[pipeline]].[[descriptor]].primitive.topology. -
If topology is
"line-strip"or"triangle-strip":-
encoder .
[[index_format]]must equal encoder .[[pipeline]].[[descriptor]].primitive.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 this .
[[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 .
-
-
setBlendConstant(color) -
Sets the constant blend color and alpha values used with
"constant"and"one-minus-constant"GPUBlendFactors.Called on:GPURenderPassEncoderthis.Arguments:
Arguments for the GPURenderPassEncoder.setBlendConstant(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 ✘ ✘ The index of the query in the query set. Returns:
undefinedIssue the following steps on the Device timeline of this .
[[device]]:-
If any of the following conditions are unsatisfied, generate a validation error and stop.
-
this .
[[occlusion_query_set]]is notnull. -
queryIndex < this .
[[occlusion_query_set]].[[descriptor]].count. -
The query at same queryIndex must not have been previously written to in this pass.
-
this .
[[occlusion_query_active]]isfalse.
-
-
Set this .
[[occlusion_query_active]]totrue.
-
-
endOcclusionQuery() -
Called on:
GPURenderPassEncoderthis.Returns:
undefinedIssue the following steps on the Device timeline of this .
[[device]]:-
If any of the following conditions are unsatisfied, generate a validation error and stop.
-
this .
[[occlusion_query_active]]istrue.
-
-
Set this .
[[occlusion_query_active]]tofalse.
-
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.Note: state is cleared even if zero
GPURenderBundlesare executed.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:
undefinedIssue the following steps on the Device timeline of this :
-
If any of the following conditions are unsatisfied, generate a validation error and stop.
-
For each bundle in bundles :
-
bundle must be valid to use with this .
-
this .
[[layout]]must equal bundle .[[layout]]. -
If this .
[[depthReadOnly]]is true, bundle .[[depthReadOnly]]must be true. -
If this .
[[stencilReadOnly]]is true, bundle .[[stencilReadOnly]]must be true.
-
-
-
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, make this .
[[command_encoder]]invalid and stop.-
this must be valid .
-
this .
[[debug_group_stack]]'s size is 0. -
this .
[[occlusion_query_active]]isfalse.
-
-
For each timestampWrite in this .
[[endTimestampWrites]],-
Append a GPU command to this .
[[command_encoder]].[[command_list]]that writes the GPU’s timestamp value into the timestampWrite .queryIndexth index in timestampWrite .querySet.
-
16. Bundles
16.1.
GPURenderBundle
[Exposed =(Window ,DedicatedWorker ),SecureContext ]interface GPURenderBundle { };GPURenderBundle includes GPUObjectBase ;
-
[[command_list]]of type list < GPU command >. -
A list of GPU commands to be submitted to the
GPURenderPassEncoderwhen theGPURenderBundleis executed. -
[[layout]], of typeGPURenderPassLayout -
The layout of the render bundle.
-
[[depthReadOnly]], of type boolean? -
If present, indicates that the depth component is not modified by executing this render bundle.
-
[[stencilReadOnly]], of type boolean? -
If present, indicates that the stencil component is not modified by executing this render bundle.
16.1.1. Creation
dictionary :GPURenderBundleDescriptor GPUObjectDescriptorBase { };
[Exposed =(Window ,DedicatedWorker ),SecureContext ]interface {GPURenderBundleEncoder GPURenderBundle finish (optional GPURenderBundleDescriptor descriptor = {}); };GPURenderBundleEncoder includes GPUObjectBase ;GPURenderBundleEncoder includes GPUProgrammablePassEncoder ;GPURenderBundleEncoder includes GPURenderEncoderBase ;
GPURenderBundleEncoder
has
the
following
internal
slots:
-
[[command_list]]of type list < GPU command >. -
A list of GPU commands to be submitted to the
GPURenderPassEncoderwhen theGPURenderBundlethis encoder produces is executed. -
[[state]]of type render bundle state . -
The current state of the
GPURenderBundleEncoder, initially set to open .
Each
GPURenderBundleEncoder
has
a
current
render
bundle
state
on
the
Content
timeline
which
may
be
one
of
the
following:
- open
-
Indicates the
GPURenderBundleEncoderis available to begin new operations. - closed
-
Indicates the
GPURenderBundleEncoderis no longer available for any operations. The[[state]]becomes closed oncefinish()is called.
-
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:
GPURenderBundleEncoderIssue the following steps on the Device timeline of this :
-
If any of the following conditions are unsatisfied, generate a validation error and stop.
-
descriptor .
colorFormats.length must be less than or equal to 8. -
descriptor .
colorFormats.length must be greater than0or descriptor .depthStencilFormatmust not benull. -
For each colorFormat in descriptor .
colorFormats:-
colorFormat must be a color renderable format .
-
-
Let depthStencilFormat be descriptor .
depthStencilFormat. -
If depthStencilFormat is not
null:-
depthStencilFormat must be a depth-or-stencil format .
-
If depthStencilFormat is a combined depth-stencil format :
-
descriptor .
depthReadOnlymust be equal to descriptor .stencilReadOnly
-
-
-
-
Let e be a new
GPURenderBundleEncoderobject. -
Set e .
[[layout]]to descriptor .GPURenderPassLayout. -
Set e .
[[depthReadOnly]]to descriptor .depthReadOnly. -
Set e .
[[stencilReadOnly]]to descriptor .stencilReadOnly. -
Return e .
Describe the reset of the steps for
createRenderBundleEncoder(). -
16.1.2. Encoding
dictionary :GPURenderBundleEncoderDescriptor GPURenderPassLayout {boolean =depthReadOnly false ;boolean =stencilReadOnly false ; };
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:
GPURenderBundle-
Let renderBundle be a new
GPURenderBundle. -
Issue the following steps on the Device timeline of this :
-
If any of the following requirements are unmet:
-
this must be valid .
-
this .
[[debug_group_stack]]'s size must be 0. -
Every usage scope contained in this must satisfy the usage scope validation .
Then:
-
Generate a
GPUValidationErrorin the current scope with appropriate error message. -
Return a new invalid
GPURenderBundle.
-
-
Set renderBundle .
[[command_list]]to this .[[command_list]].
-
-
Return renderBundle .
-
17. Queues
[Exposed =(Window ,DedicatedWorker ),SecureContext ]interface {GPUQueue undefined submit (sequence <GPUCommandBuffer >commandBuffers );Promise <undefined >onSubmittedWorkDone ();undefined writeBuffer (GPUBuffer buffer ,GPUSize64 bufferOffset , [AllowShared ]BufferSource data ,optional GPUSize64 dataOffset = 0,optional GPUSize64 size );undefined writeTexture (GPUImageCopyTexture destination , [AllowShared ]BufferSource data ,GPUImageDataLayout dataLayout ,GPUExtent3D size );undefined copyExternalImageToTexture (GPUImageCopyExternalImage source ,GPUImageCopyTextureTagged 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 missing, 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 destinationGPUImageCopyTexture ✘ ✘ The texture subresource and origin to write to. dataBufferSource ✘ ✘ Data to write into destination . dataLayoutGPUImageDataLayout ✘ ✘ 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 .
-
Let textureDesc be destination .
texture.[[descriptor]]. -
If any of the following conditions are unsatisfied, throw
OperationErrorand stop.-
validating linear texture data ( dataLayout , dataByteSize , textureDesc .
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 GPUImageCopyTexture ( destination , size ) returns
true. -
textureDesc .
sampleCountis 1. -
Valid Texture Copy Range ( destination , size ) is satisfied.
-
destination .
aspectmust refer to a single aspect of textureDesc .format, and that aspect must be a valid image copy destination according to § 24.1.2 Depth-stencil formats .
Note: unlike
GPUCommandEncoder.copyBufferToTexture(), there is no alignment requirement on either dataLayout .bytesPerRowor dataLayout .offset. -
-
Write contents into destination .
-
-
-
copyExternalImageToTexture(source, destination, copySize) -
Issues a copy operation of the contents of a platform image/canvas into the destination texture.
This operation performs color encoding into the destination encoding according to the parameters of
GPUImageCopyTextureTagged.Copying into a
-srgbtexture results in the same texture bytes, not the same decoded values, as copying into the corresponding non--srgbformat. Thus, after a copy operation, sampling the destination texture has different results depending on whether its format is-srgb, all else unchanged.If an srgb-linear color space is added, explain here how it interacts.
Called on:GPUQueuethis .Arguments:
Arguments for the GPUQueue.copyExternalImageToTexture(source, destination, copySize) method. Parameter Type Nullable Optional Description sourceGPUImageCopyExternalImage ✘ ✘ source image and origin to copy to destination . destinationGPUImageCopyTextureTagged ✘ ✘ The texture subresource and origin to write to, and its encoding metadata. copySizeGPUExtent3D ✘ ✘ Extents of the content to write from source to destination . Returns:
undefined-
Let sourceImage be source .
source -
Run Check the usability of the image argument ( sourceImage ). If it throws an exception, stop. If it does not return
good, throw anInvalidStateErrorand stop. -
If sourceImage is not origin-clean , throw a
SecurityErrorand stop. -
If any of the following requirements are unmet, throw an
OperationErrorand stop.-
If source .
sourceis anHTMLCanvasElement: Its canvas context mode must be"2d","webgl","webgl2", or"webgpu". -
If source .
sourceis anOffscreenCanvas: Its OffscreenCanvas context mode must be"2d","webgl","webgl2", or"webgpu". -
source . origin . x + copySize . width must be ≤ the width of sourceImage .
-
source . origin . y + copySize . height must be ≤ the height of sourceImage .
-
source . origin . z + copySize . depthOrArrayLayers must be ≤ 1.
-
-
Issue the following steps on the Device timeline of this :
-
Let textureDesc be destination .
texture.[[descriptor]]. -
If any of the following requirements are unmet, generate a validation error and stop.
-
destination .
texturemust be valid to use with this . -
validating GPUImageCopyTexture (destination, copySize) must return true.
-
Valid Texture Copy Range (destination, copySize) must be satisfied.
-
textureDesc .
usagemust include bothRENDER_ATTACHMENTandCOPY_DST. -
textureDesc .
sampleCountmust be 1. -
textureDesc .
formatmust be one of the following formats (which all supportRENDER_ATTACHMENTusage):
-
-
-
-
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 . -
Every
GPUQuerySetreferenced in a command in any element of commandBuffers is in the available state. For occlusion queries,occlusionQuerySetinbeginRenderPass()does not constitute a reference, whilebeginOcclusionQuery()does.
-
-
Issue the following steps on the Queue timeline of this :
-
For each commandBuffer in commandBuffers :
-
Execute each command in commandBuffer .
[[command_list]].
-
-
-
-
onSubmittedWorkDone() -
Returns a
Promisethat resolves once this queue finishes processing all the work submitted up to this moment.Called on:GPUQueuethis.Arguments:
Arguments for the GPUQueue.onSubmittedWorkDone() method. Parameter Type Nullable Optional Description Returns:
Promise<undefined>Describe
onSubmittedWorkDone()algorithm steps.
18. Queries
18.1.
GPUQuerySet
[Exposed =(Window ,DedicatedWorker ),SecureContext ]interface GPUQuerySet {undefined destroy (); };GPUQuerySet includes GPUObjectBase ;
GPUQuerySet
has
the
following
internal
slots:
-
[[descriptor]], of typeGPUQuerySetDescriptor -
The
GPUQuerySetDescriptordescribing this query set.All optional fields of
GPUTextureViewDescriptorare defined. -
[[state]]of type query set state . -
The current state of the
GPUQuerySet.
Each
GPUQuerySet
has
a
current
query
set
state
on
the
Device
timeline
which
is
one
of
the
following:
-
" available " where the
GPUQuerySetis available for GPU operations on its content. -
" destroyed " where the
GPUQuerySetis no longer available for any operations exceptdestroy.
18.1.1. QuerySet Creation
A
GPUQuerySetDescriptor
specifies
the
options
to
use
in
creating
a
GPUQuerySet
.
dictionary :GPUQuerySetDescriptor GPUObjectDescriptorBase {required GPUQueryType type ;required GPUSize32 count ; };
-
type, of type GPUQueryType -
The type of queries managed by
GPUQuerySet. -
count, of type GPUSize32 -
The number of queries managed by
GPUQuerySet.
-
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:
GPUQuerySet-
If descriptor .
typeis"timestamp", but this .[[device]].[[features]]does not contain"timestamp-query", throw aTypeError. -
If any of the following requirements are unmet, return an error query set and stop.
-
Let q be a new
GPUQuerySetobject. -
Set q .
[[descriptor]]to descriptor . -
Return q .
-
18.1.2. QuerySet Destruction
An
application
that
no
longer
requires
a
GPUQuerySet
can
choose
to
lose
access
to
it
before
garbage
collection
by
calling
destroy()
.
-
destroy() -
Destroys the
GPUQuerySet.
18.2. QueryType
enum {GPUQueryType ,"occlusion" , };"timestamp"
18.3. Occlusion Query
Occlusion query is only available on render passes, to query the number of fragment samples that pass all the per-fragment tests for a set of drawing commands, including scissor, sample mask, alpha to coverage, stencil, and depth tests. Any non-zero result value for the query indicates that at least one sample passed the tests and reached the output merging stage of the render pipeline, 0 indicates that no samples passed the tests.
When
beginning
a
render
pass,
GPURenderPassDescriptor
.
occlusionQuerySet
must
be
set
to
be
able
to
use
occlusion
queries
during
the
pass.
An
occlusion
query
is
begun
and
ended
by
calling
beginOcclusionQuery()
and
endOcclusionQuery()
in
pairs
that
cannot
be
nested.
18.4. Timestamp Query
Timestamp
query
allows
application
to
write
timestamp
values
to
a
GPUQuerySet
by
calling
writeTimestamp()
on
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
19.1.
HTMLCanvasElement.getContext()
A
GPUCanvasContext
object
can
be
obtained
via
the
getContext()
method
of
an
HTMLCanvasElement
instance
by
passing
the
string
literal
'webgpu'
as
its
contextType
argument.
GPUCanvasContext
from
an
offscreen
HTMLCanvasElement
:
const canvas= document. createElement( 'canvas' ); const context= canvas. getContext( 'webgpu' ); context. configure( /* ... */ ); // ...
19.2. GPUCanvasContext
[Exposed =(Window ,DedicatedWorker ),SecureContext ]interface {GPUCanvasContext readonly attribute (HTMLCanvasElement or OffscreenCanvas )canvas ;undefined configure (GPUCanvasConfiguration configuration );undefined unconfigure ();GPUTextureFormat getPreferredFormat (GPUAdapter adapter );GPUTexture getCurrentTexture (); };
GPUCanvasContext
has
the
following
attributes:
-
canvas, of type(HTMLCanvasElement or OffscreenCanvas), readonly -
The canvas this context was created from.
GPUCanvasContext
has
the
following
internal
slots:
-
[[validConfiguration]] of type boolean, initially false . Indicates if the context currently has a valid configuration.[[configuration]]of typeGPUCanvasConfiguration?, initially,null. -
The options this context is configured with.
nullif the context has not been configured orthe configurationhas beenremoved.unconfigured.Note: The optional
and[[size]]widthof typeGPUExtent3DheightThemembers of this slot are not used. Instead, the size of the canvas (which may be updated duringGPUTextureconfigure()s returned from this context. depthOrArrayLayers is alwaysor by setting the canvas’s/1 .widthheightproperties) is used. -
[[currentTexture]]of typeGPUTexture?, initiallynull -
The current texture that will be returned by the context when calling
getCurrentTexture(), and the next one to be composited to the document.Initially set toWhen non-
null, this always has theresult of allocating a new context texturesame dimensions as the canvas and matches the current[[configuration]]. Resizing the canvas or callingconfigure()invalidatesforthiscontext.texture.
GPUCanvasContext
has
the
following
methods:
-
configure(configuration) -
Configures the context for this canvas. Destroys any textures produced with a previous configuration.
Called on:GPUCanvasContextthis .Arguments:
Arguments for the GPUCanvasContext.configure(configuration) method. Parameter Type Nullable Optional Description configurationGPUCanvasConfiguration ✘ ✘ Desired configuration for the context. Returns: undefined
-
Setinvalidate the current texture of this .[[validConfiguration]] to false . -
Set this .
[[configuration]]to configuration . -
If
thisconfiguration .is[[currentTexture]]widthnot null call destroy() onspecified , set this ..[[currentTexture]]canvasSet this . [[currentTexture]]widthtonull . Let device beconfiguration ..device . Let canvas be this . canvaswidth -
If configuration .
issizeheightundefinedspecified , set this ..[[size]] to [ canvas .width,canvas.height, 1], otherwise set this . [[size]]heightto configuration ..size . Issue the following steps on the Device timeline of device : If any of the following conditions are unsatisfied: device is a valid GPUDevice . Supported context formats contains configuration . format . this . [[size]] . width > 0. this . [[size]] . width ≤ device . limits . maxTextureDimension2D . this . [[size]] . height > 0. this . [[size]] .height≤ device . limits . maxTextureDimension2Dthis . [[size]] . depthOrArrayLayers is 1; Then: Generate a GPUValidationError in the current scope with appropriate error message. Return. Set this . [[validConfiguration]] to true .
-
-
unconfigure() -
Removes the context configuration. Destroys any textures produced while configured.
Called on:GPUCanvasContextthis .Returns: undefined
-
Set this .[[validConfiguration]] to false . Set this . [[configuration]] to null . If this . [[currentTexture]] is not null call destroy()invalidate the current textureonof this .[[currentTexture]] . -
Set this .
to[[currentTexture]][[configuration]]null.
-
-
getPreferredFormat(adapter) -
Returns an optimal
GPUTextureFormatto use with this context and devices created from the given adapter.Called on:GPUCanvasContextthis.Arguments:
Arguments for the GPUCanvasContext.getPreferredFormat(adapter) method. Parameter Type Nullable Optional Description adapterGPUAdapter ✘ ✘ Adapter the format should be queried for. Returns:
GPUTextureFormat-
Return an optimal
GPUTextureFormatto use when callingconfigure()with the given adapter . Must be one of the supported context formats .
-
-
getCurrentTexture() -
Get the
GPUTexturethat will be composited to the document by theGPUCanvasContextnext.Called on:GPUCanvasContextthis .Returns:
GPUTexture-
If this .
[[configuration]]isnull, throw an: Throw.OperationErrorInvalidStateErrorand stop. -
If this .
[[currentTexture]]isnullor this .[[currentTexture]].[[destroyed]]is true:-
Set this .
[[currentTexture]]to the result of allocating a new context texture for this .
-
-
Return this .
[[currentTexture]].
Note: Developers can expect that the same
GPUTextureobject will be returned by every call togetCurrentTexture()made within the same frame (i.e. between invocations of Update the rendering ) unlessconfigure() is called.the current texture has been invalidated . -
Document
"
step
of
the
"
Update
the
rendering
"
HTML
processing
model,
each
GPUCanvasContext
context
must
present
the
context
content
to
the
canvas
by
running
the
following
steps:
-
If context .
[[currentTexture]]is notnulland context .[[currentTexture]].[[destroyed]]isfalse:-
Let imageContents be a copy of the image contents of context .
-
Update context .
canvaswith imageContents . -
Call context .
[[currentTexture]].destroy().
-
-
Set context .
[[currentTexture]]tonull.
transferToImageBitmap()
is
called
on
a
canvas
with
GPUCanvasContext
context
:
-
Let imageContents be a copy of the image contents of context .
-
If context .
[[currentTexture]]is notnull:-
Call context .
[[currentTexture]].destroy().
-
-
Set context .
[[currentTexture]]tonull. -
Return a new
ImageBitmapcontaining the imageContents .
drawImage()
,
texImage2D()
,
texSubImage2D()
,
toDataURL()
,
toBlob()
,
and
so
on,
they
get
a
copy
of
the
image
contents
of
a
context
:
Arguments:
-
context : the
GPUCanvasContext
Returns: image contents
-
Let texture be context .
[[currentTexture]]. -
If any of the following requirements is
unmet, return a transparent black image of size context . [[size]] and stop.unmet:-
texture must not be
null. -
texture .
[[destroyed]]must be false. -
If context .
canvasis anOffscreenCanvas, it must not be linked to a placeholder canvas element .
If added, canvasCanvas must also not bedesynchronized .desynchronized, if such an option is added.Then return a transparent black image with the size of the context .
canvas. -
-
Ensure that all submitted work items (e.g. queue submissions) have completed writing to texture .
-
Return the contents of texture , tagged as having alpha premultiplied, and with the color space context .
[[configuration]].colorSpace.Does compositingAlphaMode=opaque make this return opaque contents? [Issue #gpuweb/gpuweb#1847]
GPUCanvasContext
context
run
the
following
steps:
-
Let device beAssert : context .[[configuration]]is not. devicenull. -
IfLet device be context ..[[validConfiguration]][[configuration]]is false : Generate a.GPUValidationError in the current scope ofdevicewith an appropriate error message. Return a new invalid GPUTexture -
Let textureDescriptor be a new
GPUTextureDescriptor. -
Set textureDescriptor .
sizeto [ context ..width, context .[[size]]canvas.canvas.height]. -
Set textureDescriptor .
formatto context .[[configuration]].format. -
Set textureDescriptor .
usageto context .[[configuration]].usage. -
Let texture be a new
GPUTexturecreated as if device .createTexture()were called with textureDescriptor .Note: This results in an invalid
GPUTextureand generates an error if the texture can’t be created (e.g. the texture size is larger than the device’smaxTextureDimension2D.Note: If a previously presented texture from context matches the required criteria, its GPU memory may be re-used.
-
Ensure texture is cleared to
(0, 0, 0, 0). -
Return texture .
GPUCanvasContext
context
:If context .
[[currentTexture]]is notnull, call itsdestroy()method.Set context .
[[currentTexture]]tonull.
19.3. GPUCanvasConfiguration
The
supported
context
formats
are
a
set
of
GPUTextureFormat
s
that
must
be
supported
when
specified
as
a
GPUCanvasConfiguration
.
format
regardless
of
the
given
GPUCanvasConfiguration
.
device
,
initially
set
to:
«
"bgra8unorm"
,
"bgra8unorm-srgb"
,
"rgba8unorm"
,
"rgba8unorm-srgb"
».
enum {GPUCanvasCompositingAlphaMode ,"opaque" , };"premultiplied" dictionary {GPUCanvasConfiguration ;required GPUDevice ;device required GPUTextureFormat ;format GPUTextureUsageFlags = 0x10; // GPUTextureUsage.RENDER_ATTACHMENTusage GPUPredefinedColorSpace = "srgb";colorSpace GPUCanvasCompositingAlphaMode = "opaque";compositingAlphaMode ;GPUIntegerCoordinate ;width GPUIntegerCoordinate ; };height
19.3.1. Canvas Color Space
During
presentation,
the
chrominance
of
color
values
outside
of
the
[0,
1]
range
is
not
to
be
clamped
to
that
range;
extended
values
may
be
used
to
display
colors
outside
of
the
gamut
defined
by
the
canvas'
color
space’s
primaries,
when
permitted
by
the
configured
format
and
the
user’s
display
capabilities.
This
is
in
contrast
with
luminance,
which
is
to
be
clamped
to
the
maximum
standard
dynamic
range
luminance.
Unless high dynamic range is explicitly enabled for the canvas element.
19.3.2. Canvas Context sizing
A
GPUCanvasContext
's
[[size]]
WebGPU
canvas’s
size
is
set
by
the
GPUCanvasConfiguration
width
passed
to
configure()
,
and
remains
height
properties
of
the
same
until
canvas.
Calling
configure()
is
called
again
with
a
new
size.
If
a
size
is
not
specified
then
the
width
and
height
attributes
of
the
optional
and/or
GPUCanvasContext
width
.
canvas
height
at
members
also
sets
the
time
configure()
width
is
called
will
be
used.
If
GPUCanvasContext
.
[[size]]
/
height
does
not
match
the
dimensions
properties
of
the
canvas.
GPUCanvasContext
width
height
-
Default GPUCanvasConfiguration .size when calling configure() , if not overridden. If it is desired to match the dimensions of the canvas after it is resized,invalidate theGPUCanvasContext must be reconfigured by calling configure()current textureagain with the new dimensions.of context .
GPUCanvasContext
in
response
to
canvas
resize,
monitored
using
ResizeObserver
to
get
the
exact
pixel
dimensions
of
the
canvas:
const canvas= document. createElement( 'canvas' ); const context= canvas. getContext( 'webgpu' ); const resizeObserver= new ResizeObserver( entries=> { for ( const entryof entries) { if ( entry!= canvas) { continue ; } context device format size width height// This reports the size of the canvas element in pixels canvas. width= entry. devicePixelContentBoxSize[ 0 ]. inlineSize; canvas. height= entry. devicePixelContentBoxSize[ 0 ]. blockSize; // (Alternatively, call context.configure() with the new width/height.) } }); resizeObserver. observe( canvas);
19.4.
GPUCanvasCompositingAlphaMode
This enum selects how the contents of the canvas' context will paint onto the page.
| GPUCanvasCompositingAlphaMode | Description | dst.rgb | dst.a |
|---|---|---|---|
opaque
| Paint RGB as opaque and ignore alpha values. If the content is not already opaque, implementations may need to clear alpha to opaque during presentation. |
dst.rgb
=
|
dst.a
=
|
premultiplied
| Composite assuming color values are premultiplied by their alpha value. 100% red 50% opaque is [0.5, 0, 0, 0.5]. Color values must be less than or equal to their alpha value. [1.0, 0, 0, 0.5] is "super-luminant" and cannot reliably be displayed. |
dst.rgb
=
src.rgb
+
|
dst.a
=
src.a
+
|
20. Errors & Debugging
20.1. Fatal Errors
enum {GPUDeviceLostReason , }; ["destroyed" Exposed =(Window ,DedicatedWorker ),SecureContext ]interface {GPUDeviceLostInfo readonly attribute (GPUDeviceLostReason or undefined );reason readonly attribute DOMString ; };message {partial interface GPUDevice {readonly attribute Promise <GPUDeviceLostInfo >; };lost
20.2. Error Scopes
enum {GPUErrorFilter ,"out-of-memory" , };"validation"
[Exposed =(Window ,DedicatedWorker ),SecureContext ]interface {GPUOutOfMemoryError (); }; [constructor Exposed =(Window ,DedicatedWorker ),SecureContext ]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 ),SecureContext ]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. Detailed Operations
This section describes the details of various GPU operations.
21.1. Transfer
describe the transfers at the high level
21.2. Computing
Computing
operations
provide
direct
access
to
GPU’s
programmable
hardware.
Compute
shaders
do
not
have
pipeline
inputs
or
outputs,
their
results
are
side
effects
from
writing
data
into
storage
bindings
bound
as
GPUBufferBindingType."storage"
and
GPUStorageTextureBindingLayout
.
These
operations
are
encoded
within
GPUComputePassEncoder
as:
describe the computing algorithm
21.3. Rendering
Rendering
is
done
by
a
set
of
GPU
operations
that
are
executed
within
GPURenderPassEncoder
,
and
result
in
modifications
of
the
texture
data,
viewed
by
the
render
pass
attachments.
These
operations
are
encoded
with:
Note: rendering is the traditional use of GPUs, and is supported by multiple fixed-function blocks in hardware.
A
RenderState
is
an
internal
object
representing
the
state
of
the
current
GPURenderPassEncoder
during
command
encoding.
RenderState
is
a
spec
namespace
for
the
following
definitions:
GPURenderPassEncoder
pass
,
the
syntax:
-
pass . indexBuffer refers to the index buffer bound via
setIndexBuffer(), if any. -
pass . vertexBuffers refers to list <vertex buffer> bound by
setVertexBuffer(). -
pass . bindGroups refers to list <
GPUBindGroup> bound bysetBindGroup(index, bindGroup, dynamicOffsets). -
pass . viewport refers to an object containing
setViewport()arguments. At the start of a render pass, the state is equivalent to a call of setViewport(0, 0, pass .[[attachment_size]].width, pass .[[attachment_size]].height, 0.0, 1.0). -
pass . scissorRect refers to an object containing
setScissorRect()arguments. At the start of a render pass, the state is equivalent to a call of setScissorRect(0, 0, pass .[[attachment_size]].width, pass .[[attachment_size]].height).
The main rendering algorithm:
Arguments:
-
descriptor : Description of the current
GPURenderPipeline. -
drawCall : The draw call parameters.
-
state : RenderState of the
GPURenderEncoderBasewhere the draw call is issued.
-
Resolve indices . See § 21.3.1 Index Resolution .
Let vertexList be the result of resolve indices ( drawCall , state ).
-
Process vertices . See § 21.3.2 Vertex Processing .
Execute process vertices ( vertexList , drawCall , descriptor .
vertex, state ). -
Assemble primitives . See § 21.3.3 Primitive Assembly .
Execute assemble primitives ( vertexList , drawCall , descriptor .
primitive). -
Clip primitives . See § 21.3.4 Primitive Clipping .
Let primitiveList be the result of this stage.
-
Rasterize . See § 21.3.5 Rasterization .
Let rasterizationList be the result of rasterize ( primitiveList , state ).
-
Process fragments . See § 21.3.6 Fragment Processing .
Gather a list of fragments , resulting from executing process fragment ( rasterPoint , descriptor .
fragment, state ) for each rasterPoint in rasterizationList . -
Process depth/stencil .
-
Write pixels .
21.3.1. Index Resolution
At the first stage of rendering, the pipeline builds a list of vertices to process for each instance.
Arguments:
-
drawCall : The draw call parameters.
-
state : The active RenderState .
Returns: list of integer indices.
-
Let vertexIndexList be an empty list of indices.
-
If drawCall is an indexed draw call:
-
Initialize the vertexIndexList with drawCall .indexCount integers.
-
For i in range 0 .. drawCall .indexCount (non-inclusive):
-
Let relativeVertexIndex be fetch index ( i + drawCall .
firstIndex, state . indexBuffer ). -
If relativeVertexIndex has the special value
"out of bounds", stop and return the empty list.Note: Implementations may choose to display a warning when this occurs, especially when it is easy to detect (like in non-indirect indexed draw calls).
-
Append drawCall .
baseVertex+ relativeVertexIndex to the vertexIndexList .
-
-
-
Otherwise:
-
Initialize the vertexIndexList with drawCall .vertexCount integers.
-
Set each vertexIndexList item i to the value drawCall .firstVertex + i .
-
-
Return vertexIndexList .
Note:
in
case
of
indirect
draw
calls,
the
indexCount
,
vertexCount
,
and
other
properties
of
drawCall
are
read
from
the
indirect
buffer
instead
of
the
draw
command
itself.
Arguments:
-
i : Index of a vertex index to fetch.
-
indexBufferState : A value of indexBuffer (buffer, format, offset, and size).
Returns:
unsigned
integer
or
"out
of
bounds"
-
Let indexSize be defined by the indexBufferState .
format: -
If indexBufferState .
offset+ |i + 1| × indexSize > indexBufferState .size, return the special value"out of bounds". -
Interpret the data in indexBufferState .
buffer, starting at offset indexBufferState .offset+ i × indexSize , of size indexSize bytes, as an unsigned integer and return it.
21.3.2. Vertex Processing
Vertex processing stage is a programmable stage of the render pipeline that processes the vertex attribute data, and produces clip space positions for § 21.3.4 Primitive Clipping , as well as other data for the § 21.3.6 Fragment Processing .
Arguments:
-
vertexIndexList : List of vertex indices to process (mutable, passed by reference).
-
drawCall : The draw call parameters.
-
desc : The descriptor of type
GPUVertexState. -
state : The active RenderState .
Each
vertex
vertexIndex
in
the
vertexIndexList
,
in
each
instance
of
index
rawInstanceIndex
,
is
processed
independently.
The
rawInstanceIndex
is
in
range
from
0
to
drawCall
.instanceCount
-
1,
inclusive.
This
processing
happens
in
parallel,
and
any
side
effects,
such
as
writes
into
GPUBufferBindingType."storage"
bindings,
may
happen
in
any
order.
-
Let instanceIndex be rawInstanceIndex + drawCall .firstInstance.
-
For each non-
nullvertexBufferLayout in the list of desc .buffers:-
Let i be the index of the buffer layout in this list.
-
Let vertexBuffer , vertexBufferOffset , and vertexBufferBindingSize be the buffer, offset, and size at slot i of state . vertexBuffers .
-
Let vertexElementIndex be dependent on vertexBufferLayout .
stepMode:-
"vertex" -
vertexIndex
-
"instance" -
instanceIndex
-
-
For each attributeDesc in vertexBufferLayout .
attributes:-
Let attributeOffset be vertexBufferOffset + vertexElementIndex * vertexBufferLayout .
arrayStride+ attributeDesc .offset. -
Load the attribute data of format attributeDesc .
formatfrom vertexBuffer starting at offset attributeOffset . The components are loaded in the orderx,y,z,wfrom buffer memory.If this results in an out-of-bounds access, the resulting value is determined according to WGSL’s invalid memory reference behavior.
-
Optionally (implementation-defined): If attributeOffset + sizeof( attributeDesc .
format) > vertexBufferOffset + vertexBufferBindingSize , empty vertexIndexList and stop, cancelling the draw call.Note: This allows implementations to detect out-of-bounds values in the index buffer before issuing a draw call, instead of using invalid memory reference behavior.
-
Convert the data into a shader-visible format, according to channel formats rules.
An attribute of type"snorm8x2"and byte values of[0x70, 0xD0]will be converted tovec2<f32>(0.88, -0.38)in WGSL. -
Adjust the data size to the shader type:
-
if both are scalar, or both are vectors of the same dimensionality, no adjustment is needed.
-
if data is vector but the shader type is scalar, then only the first component is extracted.
-
if both are vectors, and data has a higher dimension, the extra components are dropped.
An attribute of type"float32x3"and valuevec3<f32>(1.0, 2.0, 3.0)will exposed to the shader asvec2<f32>(1.0, 2.0)if a 2-component vector is expected. -
if the shader type is a vector of higher dimensionality, or the data is a scalar, then the missing components are filled from
vec4<*>(0, 0, 0, 1)value.An attribute of type"sint32"and value5will be exposed to the shader asvec4<i32>(5, 0, 0, 1)if a 4-component vector is expected.
-
-
Bind the data to vertex shader input location attributeDesc .
shaderLocation.
-
-
-
For each
GPUBindGroupgroup at index in state . bindGroups :-
For each resource
GPUBindingResourcein the bind group:-
Let entry be the corresponding
GPUBindGroupLayoutEntryfor this resource. -
If entry .
GPUBindGroupLayoutEntry.visibility includesVERTEX:-
Bind the resource to the shader under group index and binding
GPUBindGroupLayoutEntry.binding.
-
-
-
-
Set the shader builtins :
-
Set the
vertex_indexbuiltin, if any, to vertexIndex . -
Set the
instance_indexbuiltin, if any, to instanceIndex .
-
-
Invoke the vertex shader entry point described by desc .
Note: The target platform caches the results of vertex shader invocations. There is no guarantee that any vertexIndex that repeats more than once will result in multiple invocations. Similarly, there is no guarantee that a single vertexIndex will only be processed once.
21.3.3. Primitive Assembly
Primitives are assembled by a fixed-function stage of GPUs.
Arguments:
-
vertexIndexList : List of vertex indices to process.
-
drawCall : The draw call parameters.
-
desc : The descriptor of type
GPUPrimitiveState.
For each instance, the primitives get assembled from the vertices that have been processed by the shaders, based on the vertexIndexList .
-
First, if the primitive topology is a strip, (which means that desc .
stripIndexFormatis not undefined) and the drawCall is indexed, the vertexIndexList is split into sub-lists using the maximum value of desc .stripIndexFormatas a separator.Example: a vertexIndexList with values
[1, 2, 65535, 4, 5, 6]of type"uint16"will be split in sub-lists[1, 2]and[4, 5, 6]. -
For each of the sub-lists vl , primitive generation is done according to the desc .
topology:-
"line-list" -
Line primitives are composed from ( vl .0, vl .1), then ( vl .2, vl .3), then ( vl .4 to vl .5), etc. Each subsequent primitive takes 2 vertices.
-
"line-strip" -
Line primitives are composed from ( vl .0, vl .1), then ( vl .1, vl .2), then ( vl .2, vl .3), etc. Each subsequent primitive takes 1 vertex.
-
"triangle-list" -
Triangle primitives are composed from ( vl .0, vl .1, vl .2), then ( vl .3, vl .4, vl .5), then ( vl .6, vl .7, vl .8), etc. Each subsequent primitive takes 3 vertices.
-
"triangle-strip" -
Triangle primitives are composed from ( vl .0, vl .1, vl .2), then ( vl .2, vl .1, vl .3), then ( vl .2, vl .3, vl .4), then ( vl .4, vl .3, vl .5), etc. Each subsequent primitive takes 1 vertices.
should this be defined more formally?
Any incomplete primitives are dropped.
-
21.3.4. Primitive Clipping
Vertex
shaders
have
to
produce
a
built-in
"position"
(of
type
vec4<f32>
),
which
denotes
the
clip
position
of
a
vertex.
Primitives are clipped to the clip volume , which, for any clip position p inside a primitive, is defined by the following inequalities:
-
− p .w ≤ p .x ≤ p .w
-
− p .w ≤ p .y ≤ p .w
-
0 ≤ p .z ≤ p .w ( depth clipping )
If
descriptor
.
primitive
.
unclippedDepth
is
true
,
depth
clipping
is
not
applied:
the
clip
volume
is
not
bounded
in
the
z
dimension.
A
primitive
passes
through
this
stage
unchanged
if
every
one
of
its
edges
lie
entirely
inside
the
clip
volume
.
If
the
edges
of
a
primitives
intersect
the
boundary
of
the
clip
volume
,
the
intersecting
edges
are
reconnected
by
new
edges
that
lie
along
the
boundary
of
the
clip
volume
.
For
triangular
primitives
(
descriptor
.
primitive
.
topology
is
"triangle-list"
or
"triangle-strip"
),
this
reconnection
may
result
in
introduction
of
new
vertices
into
the
polygon,
internally.
If a primitive intersects an edge of the clip volume ’s boundary, the clipped polygon must include a point on this boundary edge.
If the vertex shader outputs other floating-point values (scalars and vectors), qualified with "perspective" interpolation, they also get clipped. The output values associated with a vertex that lies within the clip volume are unaffected by clipping. If a primitive is clipped, however, the output values assigned to vertices produced by clipping are clipped.
Considering an edge between vertices a and b that got clipped, resulting in the vertex c , let’s define t to be the ratio between the edge vertices: c .p = t × a .p + (1 − t ) × b .p, where x .p is the output clip position of a vertex x .
For each vertex output value "v" with a corresponding fragment input, a .v and b .v would be the outputs for a and b vertices respectively. The clipped shader output c .v is produced based on the interpolation qualifier:
- "flat"
-
Flat interpolation is unaffected, and is based on provoking vertex , which is the first vertex in the primitive. The output value is the same for the whole primitive, and matches the vertex output of the provoking vertex : c .v = provoking vertex .v
- "linear"
-
The interpolation ratio gets adjusted against the perspective coordinates of the clip position s, so that the result of interpolation is linear in screen space.
- "perspective"
-
The value is linearly interpolated in clip space, producing perspective-correct values:
c .v = t × a .v + (1 − t ) × b .v
link to interpolation qualifiers in WGSL
The result of primitive clipping is a new set of primitives, which are contained within the clip volume .
21.3.5. Rasterization
Rasterization
is
the
hardware
processing
stage
that
maps
the
generated
primitives
to
the
2-dimensional
rendering
area
of
the
framebuffer
-
the
set
of
render
attachments
in
the
current
GPURenderPassEncoder
.
This
rendering
area
is
split
into
an
even
grid
of
pixels.
Rasterization
determines
the
set
of
pixels
affected
by
a
primitive.
In
case
of
multi-sampling,
each
pixel
is
further
split
into
descriptor
.
multisample
.
count
samples.
The
locations
of
samples
are
the
same
for
each
pixel,
but
not
defined
in
this
spec.
do we want to force-enable the "Standard sample locations" in Vulkan?
The framebuffer coordinates start from the top-left corner of the render targets. Each unit corresponds exactly to a pixel. See § 3.3 Coordinate Systems for more information.
Let’s define a FragmentDestination to contain:
- position
-
the 2D pixel position in framebuffer space
- sampleIndex
-
an integer in case § 21.3.10 Sample frequency shading is active, or
nullotherwise
We’ll also use a notion of NDC - normalized device coordinates. In this coordinate system, the viewport bounds range in X and Y from -1 to 1, and in Z from 0 to 1.
Rasterization produces a list of RasterizationPoint s, each containing the following data:
- destination
-
refers to FragmentDestination
- coverageMask
-
refers to multisample coverage mask (see § 21.3.11 Sample Masking )
- frontFacing
-
is true if it’s a point on the front face of a primitive
- perspectiveDivisor
-
refers to interpolated 1.0 ÷ W across the primitive
- depth
-
refers to the depth in NDC
- primitiveVertices
-
refers to the list of vertex outputs forming the primitive
- barycentricCoordinates
-
refers to § 21.3.5.3 Barycentric coordinates
define the depth computation algorithm
Arguments:
-
primitiveList : List of primitives to rasterize.
-
state : The active RenderState .
Returns: list of RasterizationPoint .
Each primitive in primitiveList is processed independently. However, the order of primitives affects later stages, such as depth/stencil operations and pixel writes.
-
First, the clipped vertices are transformed into NDC - normalized device coordinates. Given the output position p , the NDC coordinates are computed as:
divisor( p ) = 1.0 ÷ p .w
ndc( p ) = vector( p .x ÷ p .w, p .y ÷ p .w, p .z ÷ p .w)
-
Let vp be state . viewport . Then the NDC coordinates n are converted into framebuffer coordinates, based on the size of the render targets:
framebufferCoords(
n
)
=
vector(
vp
.
x
+
0.5
×
(
n
.x
+
1)
×
vp
.
width
,
vp
.
y
+
.5
×
(
n
.y
+
1)
×
vp
.
height
)
specify the depth translation into viewport as well
-
Let rasterizationPoints be an empty list.
specify
that
each
rasterization
point
gets
assigned
an
interpolated
divisor(p)
and
framebufferCoords(n)
,
as
well
as
the
other
attributes.
-
Proceed with a specific rasterization algorithm, depending on
primitive.topology:-
"point-list" -
The point, if not filtered by § 21.3.4 Primitive Clipping , goes into § 21.3.5.1 Point Rasterization .
-
"line-list"or"line-strip" -
The line cut by § 21.3.4 Primitive Clipping goes into § 21.3.5.2 Line Rasterization .
-
"triangle-list"or"triangle-strip" -
The polygon produced in § 21.3.4 Primitive Clipping goes into § 21.3.5.4 Polygon Rasterization .
-
-
Remove all the points rp from rasterizationPoints that have rp . destination . position outside of state . scissorRect .
-
Return rasterizationPoints .
21.3.5.1. Point Rasterization
A single FragmentDestination is selected within the pixel containing the framebuffer coordinates of the point.
The coverage mask depends on multi-sampling mode:
- sample-frequency
-
coverageMask = 1 ≪
sampleIndex - pixel-frequency multi-sampling
-
coverageMask = 1 ≪ descriptor .
multisample.count− 1 - no multi-sampling
-
coverageMask = 1
21.3.5.2. Line Rasterization
21.3.5.3. Barycentric coordinates
Barycentric coordinates is a list of n numbers b i , defined for a point p inside a convex polygon with n vertices v i in framebuffer space. Each b i is in range 0 to 1, inclusive, and represents the proximity to vertex v i . Their sum is always constant:
∑ ( b i ) = 1
These coordinates uniquely specify any point p within the polygon (or on its boundary) as:
p = ∑ ( b i × p i )
For a polygon with 3 vertices - a triangle, barycentric coordinates of any point p can be computed as follows:
A polygon = A( v 1 , v 2 , v 3 ) b 1 = A( p , b 2 , b 3 ) ÷ A polygon b 2 = A( b 1 , p , b 3 ) ÷ A polygon b 3 = A( b 1 , b 2 , p ) ÷ A polygon
Where A(list of points) is the area of the polygon with the given set of vertices.
For polygons with more than 3 vertices, the exact algorithm is implementation-dependent. One of the possible implementations is to triangulate the polygon and compute the barycentrics of a point based on the triangle it falls into.
21.3.5.4. Polygon Rasterization
A polygon is front-facing if it’s oriented towards the projection. Otherwise, the polygon is back-facing .
Arguments:
Returns: list of RasterizationPoint .
-
Let rasterizationPoints be an empty list.
-
Let v ( i ) be the framebuffer coordinates for the clipped vertex number i (starting with 1) in a rasterized polygon of n vertices.
Note: this section uses the term "polygon" instead of a "triangle", since § 21.3.4 Primitive Clipping stage may have introduced additional vertices. This is non-observable by the application.
-
Determine if the polygon is front-facing, which depends on the sign of the area occupied by the polygon in framebuffer coordinates:
area = 0.5 × (( v 1 .x × v n .y − v n .x × v 1 .y) + ∑ ( v i +1 .x × v i .y − v i .x × v i +1 .y))
The sign of area is interpreted based on the
primitive.frontFace:-
"ccw" -
area > 0 is considered front-facing , otherwise back-facing
-
"cw" -
area < 0 is considered front-facing , otherwise back-facing
-
-
Cull based on
primitive.cullMode:-
"none" -
All polygons pass this test.
-
"front" -
The front-facing polygons are discarded, and do not process in later stages of the render pipeline.
-
"back" -
The back-facing polygons are discarded.
-
-
Determine a set of fragments inside the polygon in framebuffer space - these are locations scheduled for the per-fragment operations. This operation is known as "point sampling". The logic is based on descriptor .
multisample:- disabled
-
Fragment s are associated with pixel centers. That is, all the points with coordinates C , where fract( C ) = vector2(0.5, 0.5) in the framebuffer space, enclosed into the polygon, are included. If a pixel center is on the edge of the polygon, whether or not it’s included is not defined.
Note: this becomes a subject of precision for the rasterizer.
- enabled
-
Each pixel is associated with descriptor .
multisample.countlocations, which are implementation-defined. The locations are ordered, and the list is the same for each pixel of the framebuffer . Each location corresponds to one fragment in the multisampled framebuffer .The rasterizer builds a mask of locations being hit inside each pixel and provides is as "sample-mask" built-in to the fragment shader.
-
For each produced fragment of type FragmentDestination :
-
Let rp be be a new RasterizationPoint object
-
Compute the list b as § 21.3.5.3 Barycentric coordinates of that fragment. Set rp . barycentricCoordinates to b .
-
Let d i be the depth value of v i .
-
Set rp . depth to ∑ ( b i × d i )
-
Append rp to rasterizationPoints .
-
-
Return rasterizationPoints .
21.3.6. Fragment Processing
The fragment processing stage is a programmable stage of the render pipeline that computes the fragment data (often a color) to be written into render targets.
This stage produces a Fragment for each RasterizationPoint :
-
destination refers to FragmentDestination .
-
coverageMask refers to multisample coverage mask (see § 21.3.11 Sample Masking ).
-
depth refers to the depth in NDC coordinates.
-
colors refers to the list of color values, one for each target in
colorAttachments.
Arguments:
-
rp : The RasterizationPoint , produced by § 21.3.5 Rasterization .
-
desc : The descriptor of type
GPUFragmentState. -
state : The active RenderState .
Returns:
Fragment
or
null
.
-
Let fragment be a new Fragment object.
-
Set fragment . destination to rp . destination .
-
Set fragment . coverageMask to rp . coverageMask .
-
If desc is not
null:-
Set the shader input builtins . For each non-composite argument of the entry point, annotated as a builtin , set its value based on the annotation:
-
position -
vec4<f32>( rp . destination . position , rp . depth , rp . perspectiveDivisor ) -
front_facing -
rp . frontFacing
-
sample_index -
rp . destination . sampleIndex
-
sample_mask -
rp . coverageMask
-
-
For each user-specified pipeline input of the fragment stage:
-
Let value be the interpolated fragment input, based on rp . barycentricCoordinates , rp . primitiveVertices , and the interpolation qualifier on the input.
-
Set the corresponding fragment shader location input to value .
-
-
Invoke the fragment shader entry point described by desc .
-
If the fragment issued
discard, returnnull. -
Set fragment . colors to the user-specified pipeline output values from the shader.
-
Take the shader output builtins :
-
If
sample_maskbuiltin is produced by the shader as value :-
Set fragment . coverageMask to fragment . coverageMask ∧ value .
-
Otherwise we are in § 21.3.8 No Color Output mode, and fragment . colors is empty.
-
-
Return fragment .
Processing
of
fragments
happens
in
parallel,
while
any
side
effects,
such
as
writes
into
GPUBufferBindingType."storage"
bindings,
may
happen
in
any
order.
21.3.7. Output Merging
The
depth
input
to
this
stage,
if
any,
is
clamped
to
the
current
[[viewport]]
depth
range
(regardless
of
whether
the
fragment
shader
stage
writes
the
frag_depth
builtin).
21.3.8. No Color Output
In no-color-output mode, pipeline does not produce any color attachment outputs.
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.
21.3.9. 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
fragment
.
targets
[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
21.3.10. Sample frequency shading
21.3.11. Sample Masking
The
final
sample
mask
for
a
pixel
is
computed
as:
rasterization
mask
&
mask
&
shader-output
mask
.
Only
the
lower
count
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 included in the shape get the relevant bits 1 in the mask.
The
shader-output
mask
takes
the
output
value
of
"sample_mask"
builtin
in
the
fragment
shader.
If
the
builtin
is
not
output
from
the
fragment
shader,
and
alphaToCoverageEnabled
is
enabled,
the
shader-output
mask
becomes
the
alpha-to-coverage
mask
.
Otherwise,
it
defaults
to
0xFFFFFFFF.
22. Type Definitions
typedef [EnforceRange ]unsigned long ;GPUBufferDynamicOffset typedef [EnforceRange ]unsigned long ;GPUStencilValue typedef [EnforceRange ]unsigned long ;GPUSampleMask typedef [EnforceRange ]long ;GPUDepthBias typedef [EnforceRange ]unsigned long long ;GPUSize64 typedef [EnforceRange ]unsigned long ;GPUIntegerCoordinate typedef [EnforceRange ]unsigned long ;GPUIndex32 typedef [EnforceRange ]unsigned long ;GPUSize32 typedef [EnforceRange ]long ;GPUSignedOffset32 typedef unsigned long ;GPUFlagsConstant
22.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 = 0; = 0;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 = 0; = 0; = 0;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 present.
dictionary {GPUExtent3DDict ; = 1; = 1;required GPUIntegerCoordinate ;width GPUIntegerCoordinate = 1;height GPUIntegerCoordinate = 1; };depthOrArrayLayers ;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 (1 if not present). -
extent . height refers to either
GPUExtent3DDict.heightor the second item of the sequence (1 if not present). -
extent . depthOrArrayLayers refers to either
GPUExtent3DDict.depthOrArrayLayersor the third item of the sequence (1 if not present).
23. Feature Index
23.1.
"depth-clip-control"
Define
functionality
when
the
"depth-clip-control"
feature
is
enabled.
Feature Dictionary Values
The
following
dictionary
values
are
supported
if
and
only
if
the
"depth-clip-control"
feature
is
enabled;
otherwise,
they
must
be
set
to
their
default
values:
-
GPUPrimitiveState
23.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
23.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
23.4.
"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
23.5.
"texture-compression-etc2"
Allows for explicit creation of textures of ETC2 compressed formats.
Feature Enums
The
following
enums
are
supported
if
and
only
if
the
"texture-compression-etc2"
feature
is
enabled:
-
GPUTextureFormat
23.6.
"texture-compression-astc"
Allows for explicit creation of textures of ASTC compressed formats.
Feature Enums
The
following
enums
are
supported
if
and
only
if
the
"texture-compression-astc"
feature
is
enabled:
-
GPUTextureFormat -
23.7.
"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.8.
"indirect-first-instance"
Removes
the
zero
value
restriction
on
firstInstance
in
indirect
draw
parameters
and
indirect
drawIndexed
parameters
.
firstInstance
is
allowed
to
be
non-zero
if
and
only
if
the
"indirect-first-instance"
feature
is
enabled.
24. Appendices
24.1. Texture Format Capabilities
24.1.1. Plain color formats
All
plain
color
formats
support
COPY_SRC
,
COPY_DST
,
and
TEXTURE_BINDING
usage.
Only
formats
with
GPUTextureSampleType
"float"
can
be
blended.
The
RENDER_ATTACHMENT
and
STORAGE_BINDING
columns
specify
support
for
GPUTextureUsage.RENDER_ATTACHMENT
and
GPUTextureUsage.STORAGE_BINDING
usage
respectively.
24.1.2. Depth-stencil formats
A depth-or-stencil format is any format with depth and/or stencil aspects. A combined depth-stencil format is a depth-or-stencil format that has both depth and stencil aspects.
All
depth-or-stencil
formats
support
the
COPY_SRC
,
COPY_DST
,
TEXTURE_BINDING
,
and
RENDER_ATTACHMENT
usages.
However,
certain
copy
operations
also
restrict
the
source
and
destination
formats.
None of the depth formats can be filtered.
| Format | Bytes per texel | Aspect |
GPUTextureSampleType
| Valid image copy source | Valid image copy destination |
|---|---|---|---|---|---|
stencil8
| 1 − 4 | stencil |
"uint"
| ✓ | |
depth16unorm
| 2 | depth |
"depth"
| ✓ | |
depth24plus
| 4 | depth |
"depth"
| ✗ | |
depth24plus-stencil8
| 4 − 8 | depth |
"depth"
| ✗ | |
| stencil |
"uint"
| ✓ | |||
depth32float
| 4 | depth |
"depth"
| ✓ | ✗ |
depth24unorm-stencil8
| 4 | depth |
"depth"
| ✗ | |
| stencil |
"uint"
| ✓ | |||
depth32float-stencil8
| 5 − 8 | depth |
"depth"
| ✓ | ✗ |
| stencil |
"uint"
| ✓ | |||
24.1.2.1. Reading and Sampling Depth/Stencil Textures
When
reading
or
sampling
a
depth
component
via
a
texture_depth_*
-typed
binding,
the
value
is
returned
as
an
f32
value.
Depending
on
the
resolution
of
this
issue,
allow
reading/sampling
via
texture_2d
etc.
in
the
table
above
and
specify
the
behavior.
(
vec4<f32>(D,
X,
X,
X)
?)
Update
the
note
below
which
would
become
slightly
outdated.
[Issue
#gpuweb/gpuweb#2094]
Reading
or
sampling
a
stencil
component
must
be
done
via
a
normal
texture
binding
(
texture_2d
,
texture_2d_array
,
texture_cube
,
or
texture_cube_array
).
When
doing
so,
the
value
is
returned
as
vec4<u32>(S,
X,
X,
X)
,
where
S
is
the
stencil
value
and
each
X
is
an
implementation-defined
unspecified
value.
Authors
must
not
rely
on
these
.y
,
.z
,
and
.w
components,
as
their
behavior
is
non-portable.
Note:
Short
of
adding
a
new
more
constrained
stencil
sampler
type
(like
depth),
it’s
infeasible
for
implementations
to
efficiently
paper
over
the
driver
differences
for
stencil
reads.
As
this
was
not
a
portability
pain
point
for
WebGL,
it’s
not
expected
to
be
problematic
in
WebGPU.
In
practice,
expect
either
vec4<u32>(S,
S,
S,
S)
or
vec4<u32>(S,
0,
0,
1)
,
depending
on
hardware.
24.1.2.2. Copying Depth/Stencil Textures
The
texel
values
of
depth32float
formats
(
"depth32float"
and
"depth32float-stencil8"
have
a
limited
range.
As
a
result,
copies
into
such
textures
are
only
valid
from
other
textures
of
the
same
format.
The
depth
aspects
of
depth24plus
formats
(
"depth24plus"
and
"depth24plus-stencil8"
)
have
opaque
representations
(implemented
as
either
"depth24unorm"
or
"depth32float").
The
depth
aspect
of
"depth24unorm-stencil8"
doesn’t
have
a
aligned
tightly-packed
representation
(because
its
size
is
3
bytes).
As
a
result,
depth-aspect
image
copies
are
not
allowed
with
these
formats.
-
All of these formats can be written in a render pass using a fragment shader that outputs depth values via the
frag_depthoutput. -
Textures with "depth24plus"/"depth24unorm" formats can be read as shader textures, and written to a texture (as a render pass attachment) or buffer (via a storage buffer binding in a compute shader).
24.1.3. Packed formats
All
packed
texture
formats
support
COPY_SRC
,
COPY_DST
,
and
TEXTURE_BINDING
usages.
All
of
these
formats
have
"float"
type
and
can
be
filtered
on
sampling.
A compressed format is any format with a block size greater than 1 × 1.
24.2. Temporary usages of non-exported dfns
Eventually all of these should disappear but they are useful to avoid warning while building the specification.