1. 引言
本节为非规范性内容。
图形处理单元(GPU)在个人计算领域中已成为实现丰富渲染和计算应用的关键。WebGPU 是一个为 Web 暴露 GPU 硬件能力的 API。该 API 从零开始设计,能够高效映射到(2014年之后的)原生 GPU API。WebGPU 与 WebGL 无关,也不直接针对 OpenGL ES。
WebGPU 将物理 GPU 硬件视为 GPUAdapter
。它通过
GPUDevice
提供与适配器的连接,设备负责管理资源,并通过设备的 GPUQueue
执行命令。GPUDevice
可能拥有自己的高速存储器以供处理单元访问。GPUBuffer
和
GPUTexture
是由 GPU 内存支持的物理资源。GPUCommandBuffer
和 GPURenderBundle
是用户录制命令的容器。GPUShaderModule
包含 着色器代码。其他资源如 GPUSampler
或
GPUBindGroup
用于配置 GPU 如何使用物理资源。
GPU 通过 GPUCommandBuffer
编码的命令,通过 管线
执行,该管线是固定功能与可编程阶段的混合体。可编程阶段运行着色器,即专为 GPU 硬件设计的特殊程序。管线的大部分状态由 GPURenderPipeline
或 GPUComputePipeline
对象定义。未包含在这些 管线对象中的状态,则在命令编码阶段通过如 beginRenderPass()
或 setBlendConstant()
之类命令设置。
2. 恶意使用考量
本节为非规范性内容。 介绍了在 Web 上暴露此 API 所带来的风险。
2.1. 安全考量
WebGPU 的安全要求与 Web 一贯的要求相同,也是不可协商的。总体原则是:在所有命令到达 GPU 之前进行严格校验,确保页面只能操作自身数据。
2.1.1. 基于 CPU 的未定义行为
WebGPU 实现会将用户发起的工作量转换为目标平台特定的 API 命令。原生 API 规定了命令的有效用法(例如见 vkCreateDescriptorSetLayout),并且通常不保证不遵守有效用法规则时的任何结果。这被称为“未定义行为”,攻击者可以利用它访问非授权内存,或迫使驱动执行任意代码。
为禁止不安全用法,WebGPU 针对任意输入都定义了允许的行为范围。实现必须校验所有用户输入,只允许有效工作负载到达驱动。本规范规定了所有错误条件及其处理语义。例如,在 copyBufferToBuffer() 的 "source" 和 "destination"
同时指定同一缓冲区,且区间相交时,GPUCommandEncoder
会生成错误,且不会执行其它操作。
更多错误处理信息参见 § 22 错误与调试。
2.1.2. 基于 GPU 的未定义行为
WebGPU 着色器 由 GPU 内部的计算单元执行。在原生 API
中,某些着色器指令可能在 GPU 上导致未定义行为。为应对这一点,WebGPU 严格定义了着色器指令集及其行为。当为 createShaderModule()
提供着色器时,WebGPU 实现必须在进行任何平台特定着色器转换或变换之前进行校验。
2.1.3. 未初始化数据
一般来说,分配新内存可能暴露系统上其它应用残留的数据。为避免此问题,WebGPU 在概念上会将所有资源初始化为零,尽管若实现检测到开发者已手动初始化内容时可跳过此步骤。这包括着色器内变量和共享工作组内存。
清除工作组内存的具体机制依平台而异。若原生 API 未提供清除机制,WebGPU 实现会先在所有调用中清空,再同步,然后继续执行开发者代码。
GPULoadOp
"load"
改为 "clear"
)。
因此,无论实现是否有性能损耗,所有实现应当在开发者控制台发出警告。
2.1.4. 着色器中的越界访问
着色器可以直接访问物理资源(如 "uniform"
GPUBufferBinding
),也可以通过纹理单元(为纹理坐标转换而设的固定功能硬件块)间接访问。WebGPU API 的校验只能保证所有着色器输入已提供且类型正确。如果未通过纹理单元访问,WebGPU API 无法保证数据访问不会越界。
为防止着色器访问非本应用 GPU 内存,WebGPU 实现可在驱动中启用“健壮缓冲区访问”模式,确保访问不会超出缓冲区界限。
或者,实现可在着色器代码中插入手动越界检查。此时,越界检查仅适用于数组索引,对结构体字段访问则无需手动检查,因为主机侧 minBindingSize
校验已覆盖。
若着色器尝试读取物理资源边界外的数据,实现可以:
-
返回资源边界内其他位置的值
-
返回值向量 "(0, 0, 0, X)",其中 X 可为任意值
-
部分丢弃绘制或调度调用
若着色器尝试写入物理资源边界外,实现可以:
-
写入资源边界内其他位置
-
丢弃写入操作
-
部分丢弃绘制或调度调用
2.1.5. 无效数据
从 CPU 向 GPU 上传 浮点数数据或在 GPU 上生成浮点数时,可能会出现不对应于有效数值的二进制表示(如无穷大或 NaN)。此时 GPU 行为取决于硬件对 IEEE-754 标准的实现精度。WebGPU 保证引入无效浮点数只会影响算术运算结果,不会有其他副作用。
2.1.6. 驱动漏洞
GPU 驱动程序和其他软件一样可能存在漏洞。攻击者可能利用驱动的错误行为访问非授权数据。为降低风险,WebGPU 工作组将与 GPU 厂商协作,将 WebGPU 一致性测试套件(CTS)集成到驱动测试流程中,类似 WebGL 的做法。WebGPU 实现应对已发现的部分漏洞有兼容性处理,并对无法绕过的已知漏洞驱动禁用 WebGPU。
2.1.7. 时序攻击
2.1.7.1. 内容时间线时序
WebGPU 不会向 JavaScript 暴露在 内容时间线上由 agent 在 agent cluster
中共享的新状态。内容时间线状态如 [[mapping]]
仅在显式 内容时间线任务(如普通
JavaScript)中变化。
2.1.7.2. 设备/队列时间线时序
可写存储缓冲区和其他跨调用通信机制可能用于在队列时间线上构造高精度定时器。
可选的 "timestamp-query"
特性也为 GPU 操作提供高精度计时。为缓解安全和隐私风险,定时查询的值被对齐到较低精度:参见 current queue timestamp。特别注意:
-
设备时间线通常在多个源共享的进程中运行,因此跨源隔离(如 COOP/COEP)无法隔离设备/队列时间线定时器。
-
队列时间线工作由设备时间线发起,可能在不能像 CPU 进程(如 Meltdown 缓解)那样隔离的 GPU 硬件上执行。
-
GPU 硬件通常不易受到 Spectre 类攻击,但 WebGPU 可能在软件中实现,软件实现可能运行在共享进程中,无法依赖隔离缓解。
2.1.8. Row hammer 攻击
Row hammer 是一类利用 DRAM 单元状态泄漏的攻击,可被用于 GPU。WebGPU 没有专门的防护措施,依赖于平台级解决方案,例如缩短内存刷新间隔。
2.1.9. 拒绝服务
WebGPU 应用可访问 GPU 内存和计算单元。WebGPU 实现可以限制应用可用的 GPU 内存,以保证其他应用的响应性。对于 GPU 处理时间,WebGPU 实现可以设置“看门狗”定时器,确保应用不会导致 GPU 无响应超过数秒。这些措施类似于 WebGL 所采用的策略。
2.1.10. 工作负载识别
WebGPU 提供对全局受限资源的访问,这些资源由同一台机器上不同程序(和网页)共享。应用可通过间接探测全局资源受限程度,进而推测其他网页正在进行的工作负载。这些问题与 Javascript 中的系统内存和 CPU 执行吞吐量类似。WebGPU 没有对此提供额外的缓解措施。
2.1.11. 内存资源
WebGPU 允许从机器全局内存堆(如 VRAM)进行可失败的分配。这使得应用可以通过尝试分配并观察分配失败情况,探测系统剩余可用内存(针对特定堆类型)。
GPU 内部一般有一个或多个(通常只有两个)所有运行应用共享的内存堆。当某个堆耗尽时,WebGPU 创建资源会失败。这是可观察到的,可能使恶意应用推测出其他应用使用了哪些堆,以及它们分配了多少。
2.1.12. 计算资源
如果一个站点与另一个站点同时使用 WebGPU,它可能会观察到处理某些工作的耗时增加。例如,持续向队列提交计算工作并跟踪完成时间,可能会发现其他任务也开始使用 GPU。
GPU 有多个可独立测试的部分,如算术单元、纹理采样单元、原子单元等。恶意应用可以检测某些单元的负载,并试图分析压力模式来猜测其他应用的工作负载。这与 Javascript 的 CPU 执行现实类似。
2.1.13. 能力滥用
恶意站点可能滥用 WebGPU 所暴露的能力,运行对用户或其体验无益、仅对站点有利的计算。例如隐蔽挖矿、密码破解或彩虹表计算。
无法针对这类 API 使用方式加以防范,因为浏览器无法区分有效负载和滥用负载。这是 Web 上所有通用计算能力(如 JavaScript、WebAssembly 或 WebGL)面临的普遍问题。WebGPU 只是让某些负载的实现更容易,或比 WebGL 更高效。
为缓解此类滥用,浏览器可对后台标签页的操作进行限速,可警告标签页资源占用过高,并可限制哪些上下文允许使用 WebGPU。
用户代理可基于启发式方法向用户发出高功耗警告,尤其在检测到潜在恶意使用时。如果实现此类警告,应将 WebGPU 使用纳入与 JavaScript、WebAssembly、WebGL 等相同的启发式中。
2.2. 隐私考量
WebGPU 的隐私考量与 WebGL 类似。GPU API 十分复杂,必须出于必要暴露设备能力的各个方面,以便开发者能够有效利用这些能力。一般的缓解方法是对潜在可识别信息进行归一化或分桶,并在可能的情况下强制行为一致。
用户代理不得暴露超过 32 种可区分配置或分桶。
2.2.1. 机器特有功能与限制
WebGPU 可以揭示底层 GPU 架构和设备结构的许多细节,包括可用的物理适配器、GPU 和 CPU 资源的多项限制(如最大纹理尺寸),以及可用的任何可选硬件专属能力。
用户代理没有义务暴露真实硬件限制,可以完全控制机器细节的暴露程度。减少指纹识别的一种策略是将所有目标平台归为少数几个分桶。总体来说,暴露硬件限制的隐私影响与 WebGL 相同。
默认限制值也被故意设置得足够高,以便大多数应用无需请求更高限制即可运行。所有 API 的使用都按请求限制进行校验,因此不会因意外而向用户暴露实际硬件能力。
2.2.2. 机器特有产物
和 WebGL 一样,可以观察到一些机器特有的光栅化/精度差异和性能差异。这涉及光栅化覆盖及模式、着色器阶段间 varyings 的插值精度、计算单元调度,以及更多执行相关特性。
通常,同一厂商的大多数或全部设备的光栅化和精度指纹是相同的。性能差异难以完全规避,但信号强度较低(如 JS 执行性能)。
对隐私要求高的应用和用户代理应采用软件实现以消除这类产物。
2.2.3. 机器特有性能
通过测量 GPU 上特定操作的性能也是区分用户的一个因素。即便计时精度较低,重复执行某一操作也能体现用户机器在特定负载下的快慢。这是常见的识别向量(WebGL 和 Javascript 皆有),但信号较低且难以完全规避。
WebGPU 计算管线让开发者可绕过固定功能硬件直接访问 GPU,这带来了独特设备指纹识别的额外风险。用户代理可通过将逻辑 GPU 调用与实际计算单元解耦来降低此风险。
2.2.4. 用户代理状态
本规范未为源定义任何额外用户代理状态。但预期用户代理会对 GPUShaderModule
、
GPURenderPipeline
、
GPUComputePipeline
等高开销编译结果进行缓存。这些缓存有助于提升 WebGPU 应用首次访问后的加载速度。
对规范而言,这些缓存与极快编译无异,但应用可以轻易测量 createComputePipelineAsync()
的耗时。这可能导致跨源信息泄露(如“用户是否访问过包含特定着色器的站点”),因此用户代理应遵循 存储分区最佳实践。
系统的 GPU 驱动也可能有自己的着色器和管线编译缓存。用户代理可在可能的情况下禁用该缓存,或为着色器添加分区数据,使驱动将其视为不同对象。
2.2.5. 驱动漏洞
除安全考量中提到的问题外,驱动漏洞还可能导致行为差异,成为区分用户的手段。此处可采用安全考量中提及的缓解措施,如与 GPU 厂商协作,在用户代理中实现已知问题的兼容处理。
2.2.6. 适配器标识符
WebGL 实践表明,开发者有合理需求识别其代码运行的 GPU,以便创建和维护健壮的 GPU 内容。例如识别有已知驱动漏洞的适配器,以便规避或避免在某些硬件上使用表现不佳的特性。
但暴露适配器标识符自然会增加指纹识别信息量,因此有必要限制适配器识别的精度。
可以采取多项缓解措施以平衡内容健壮性与隐私保护。首先,用户代理可通过主动识别和规避已知驱动问题,减少开发者负担,就像浏览器开始用 GPU 以来所做的一样。
默认暴露适配器标识符时应尽量宽泛,只要有用即可。例如,可仅标识适配器厂商及架构而非具体型号。有时也可报告实际适配器的合理代理的标识符。
在需要完整详细适配器信息(如提交 bug 报告)时,可请用户同意向页面披露更多硬件信息。
最后,若用户代理认为合适(如增强隐私模式下),可完全不报告适配器标识符。
3. 基础
3.1. 约定
3.1.1. 语法速记
本规范中使用了如下语法速记:
.
(点)语法,常见于编程语言。-
短语“
Foo.Bar
”表示“值(或接口)Foo
的Bar
成员”。如果Foo
是 有序映射(ordered map)且Bar
在Foo
中未存在,则返回undefined
。 ?.
(可选链)语法,借鉴自 JavaScript。-
短语“
Foo?.Bar
”表示:“如果Foo
为null
或undefined
或Bar
在Foo
中未存在,则为undefined
;否则为Foo.Bar
”。例如,若
buffer
是一个GPUBuffer
,则buffer?.\[[device]].\[[adapter]]
表示:“如果buffer
为null
或undefined
,则为undefined
;否则为buffer
的\[[device]]
内部槽的\[[adapter]]
内部槽。” ??
(空值合并)语法,借鉴自 JavaScript。-
短语“
x
??y
”表示:“如果x
不为 null 或 undefined,则为x
,否则为y
。” - 槽支持属性(slot-backed attribute)
-
由同名内部槽支持的 WebIDL 属性。其可变性视规范而定。
3.1.2. WebGPU 对象
WebGPU 接口定义了WebGPU 对象的公共接口和状态。它可在其创建的内容时间线上使用,此时它是 JavaScript 暴露的 WebIDL 接口。
任何包含 GPUObjectBase
的接口都是 WebGPU 接口。
内部对象跟踪WebGPU 对象在设备时间线上的状态。所有对内部对象可变状态的读写都发生在单一有序的设备时间线步骤中。
在WebGPU 对象上可定义以下特殊属性类型:
- 不可变属性(immutable property)
-
在对象初始化时设定的只读槽,可从任意时间线访问。
注:由于该槽不可变,实现可在多个时间线中保有副本,按需分配。不可变属性这样定义是为避免在规范中描述多个副本。
- 内容时间线属性(content timeline property)
-
仅可从对象创建的内容时间线访问的属性。
- 设备时间线属性(device timeline property)
-
跟踪内部对象状态,仅可从对象创建的设备时间线访问。设备时间线属性可为可变的。
设备时间线属性命名为
[[带括号]]
,为内部槽。 - 队列时间线属性(queue timeline property)
-
跟踪内部对象状态,仅可从对象创建的队列时间线访问。队列时间线属性可为可变的。
队列时间线属性命名为
[[带括号]]
,为内部槽。
interface mixin GPUObjectBase {attribute USVString label ; };
GPUObjectBase
parent,接口 T,GPUObjectDescriptorBase
descriptor)(其中 T 继承自 GPUObjectBase
),请在内容时间线上执行以下步骤:
-
令 device 为 parent.
[[device]]
。 -
令 object 为 T 的新实例。
-
设置 object.
[[device]]
为 device。 -
返回 object。
GPUObjectBase
具有如下不可变属性:
GPUObjectBase
具有如下内容时间线属性:
label
,类型为 USVString-
开发者提供的标签,由实现自定义使用。可由浏览器、操作系统或其他工具用于帮助开发者识别底层内部对象。示例包括在
GPUError
消息、控制台警告、浏览器开发者工具和平台调试工具中显示标签。注:实现应当利用标签提升错误消息的可读性,用于标识 WebGPU 对象。但这不必是标识对象的唯一方式:实现还应结合其他可用信息,尤其是在没有标签时。例如:
-
打印
GPUTexture
视图时,显示其父对象的标签。 -
打印
GPURenderPassEncoder
或GPUComputePassEncoder
时,显示其父GPUCommandEncoder
的标签。 -
打印
GPUCommandBuffer
时,显示其源GPUCommandEncoder
的标签。 -
打印
GPURenderBundle
时,显示其源GPURenderBundleEncoder
的标签。
注:label
是GPUObjectBase
的属性。两个GPUObjectBase
“包装器”对象即使引用同一底层对象,其 label 状态也是完全独立的(如由getBindGroupLayout()
返回时)。除非通过 JavaScript 设置,否则label
属性不会变更。这意味着一个底层对象可关联多个标签。本规范未定义标签如何传递到 设备时间线。标签的使用完全由实现自定义:错误消息可显示最近设置的标签、所有已知标签,或完全不显示标签。
属性类型为
USVString
,因为某些用户代理可能将其传递给底层原生 API 的调试工具。 -
GPUObjectBase
具有如下设备时间线属性:
[[valid]]
,类型为boolean
,初始值为true
-
若为
true
,表示该内部对象可用。
[[device]]
)被垃圾回收。然而,这无法保证,因为某些实现可能需要强引用父对象。
因此,开发者应假定 WebGPU 接口在所有子对象被回收前可能不会被垃圾回收。这可能导致部分资源比预期保留更长时间。
如果需要可预测地释放分配的资源,应优先调用 destroy
方法(如 GPUDevice
.destroy()
或 GPUBuffer
.destroy()
),而不是依赖垃圾回收。
3.1.3. 对象描述符
对象描述符用于保存创建对象所需的信息,通常通过 GPUDevice
的 create*
方法之一进行对象创建。
dictionary {
GPUObjectDescriptorBase USVString label = ""; };
GPUObjectDescriptorBase
具有如下成员:
label
,类型为 USVString,默认值为""
-
GPUObjectBase.label
的初始值。
3.2. 异步性
3.2.1. 无效的内部对象与传染性无效
WebGPU 中的对象创建操作不会返回 Promise,但其本质上是异步的。返回的对象引用的是在设备时间线上被操作的内部对象。多数在设备时间线上发生的错误不会通过异常或拒绝抛出,而是通过关联设备上生成的 GPUError
进行传递。
内部对象可以是有效或无效。无效对象不会在之后变为有效,但部分有效对象可以被使无效(invalidated)。
如果对象无法被创建,则其从创建开始即为无效。例如,对象描述符未能描述出有效对象,或者没有足够内存分配资源时会发生此情况。如果从另一个无效对象创建对象(例如对无效的 GPUTexture
调用
createView()
),也会如此。这类情况称为传染性无效。
大多数类型的内部对象在创建后不会变为无效,但仍可能变得不可用,例如其所属设备丢失或destroyed
,或对象处于特殊内部状态(如缓冲区状态“destroyed”)。
部分类型的内部对象在创建后可以变为无效;具体包括设备、适配器、GPUCommandBuffer
,以及命令/通道/捆绑编码器。
GPUObjectBase
object,若满足以下设备时间线步骤的所有要求,则其可与 targetObject 一同使用(valid to use with):
-
object.
[[valid]]
必须为true
。 -
object.
[[device]]
.[[valid]]
必须为true
。 -
object.
[[device]]
必须等于 targetObject.[[device]]
。
3.2.2. Promise 顺序
WebGPU 中有若干操作会返回 promise。
WebGPU 不保证这些 promise 的 settle(resolve 或 reject)顺序,除非有如下例外:
-
对于某个
GPUQueue
q,如果 p1 = q.onSubmittedWorkDone()
先于 p2 = q.onSubmittedWorkDone()
被调用,则 p1 必须早于 p2 settle。 -
对于某个
GPUQueue
q 和同一GPUDevice
上的GPUBuffer
b,如果 p1 = b.mapAsync()
先于 p2 = q.onSubmittedWorkDone()
被调用,则 p1 必须早于 p2 settle。
应用不得依赖于其它 promise 的 settle 顺序。
3.3. 坐标系统
渲染操作使用如下坐标系统:
-
归一化设备坐标(NDC)有三维:
-
-1.0 ≤ x ≤ 1.0
-
-1.0 ≤ y ≤ 1.0
-
0.0 ≤ z ≤ 1.0
-
左下角为 (-1.0, -1.0, z)。
归一化设备坐标。 注:
z = 0
还是z = 1
作为近平面由应用决定。上图以z = 0
为近平面,但实际行为由着色器使用的投影矩阵、depthClearValue
和depthCompare
函数共同决定。 -
-
裁剪空间坐标有四维:(x, y, z, w)
-
帧缓冲坐标用于寻址帧缓冲内的像素。
-
为二维坐标。
-
每个像素在 x、y 方向上长度为 1。
-
左上角为 (0.0, 0.0)。
-
x 向右递增。
-
y 向下递增。
-
参见 § 17 渲染通道 和 § 23.2.5 光栅化。
帧缓冲坐标。 -
-
视口坐标结合了 x、y 方向的帧缓冲坐标与 z 方向的深度。
-
通常 0.0 ≤ z ≤ 1.0,但可通过
[[viewport]]
.minDepth
和maxDepth
,以及setViewport()
修改。
-
-
片元坐标与视口坐标一致。
-
纹理坐标,在 2D 中有时称为“UV 坐标”,用于采样纹理,其分量数量与
texture dimension
匹配。-
0 ≤ u ≤ 1.0
-
0 ≤ v ≤ 1.0
-
0 ≤ w ≤ 1.0
-
(0.0, 0.0, 0.0) 位于纹理存储顺序的首个 texel。
-
(1.0, 1.0, 1.0) 位于纹理存储顺序的最后一个 texel。
二维纹理坐标。 -
-
窗口坐标,或称显示坐标,与帧缓冲坐标一致,用于与外部显示或类似接口交互时。
注:WebGPU 的坐标系统与 DirectX 图形管线中的坐标系统一致。
3.4. 编程模型
3.4.1. 时间线
WebGPU 的行为以“时间线”为单位进行描述。每个操作(以算法定义)都发生在某个时间线上。时间线明确了操作的顺序,以及哪些状态可被哪些操作访问。
注: 这种“时间线”模型反映了浏览器引擎多进程模型(如“内容进程”和“GPU 进程”)的约束,也体现了许多实现中 GPU 作为独立执行单元的现实。实现 WebGPU 并不要求时间线并行执行,因此不要求多进程,甚至不要求多线程。(但如 获取上下文图像内容副本 这类需同步阻塞其它时间线完成的情况,仍需支持并发。)
- 内容时间线
-
与 Web 脚本的执行相关。包括本规范描述的所有方法调用。
要从
GPUDevice
device
的操作向内容时间线派发步骤,可通过 为 GPUDevice 排队全局任务。 - 设备时间线
-
与用户代理发起的 GPU 设备操作相关。包括适配器、设备、GPU 资源与状态对象的创建,这些操作从用户代理控制 GPU 的部分看通常是同步的,但可在独立的操作系统进程中运行。
- 队列时间线
-
与 GPU 计算单元上操作的执行相关。包括实际在 GPU 上运行的绘制、拷贝和计算任务。
- 时间线无关
-
可以与上述任意时间线关联。
如仅操作不可变属性或调用步骤传入的参数,则可派发到任意时间线。
- 不可变值示例术语定义
-
可用于任意时间线。
- 内容时间线示例术语定义
-
仅可用于内容时间线。
- 设备时间线示例术语定义
-
仅可用于设备时间线。
- 队列时间线示例术语定义
-
仅可用于队列时间线。
本规范中,当返回值依赖于非内容时间线上发生的工作时,采用异步操作。API 以 promise 或事件的形式表现异步操作。
GPUComputePassEncoder.dispatchWorkgroups()
示例:
-
用户在 内容时间线 上通过
GPUComputePassEncoder
的方法编码dispatchWorkgroups
命令。 -
用户调用
GPUQueue.submit()
,将GPUCommandBuffer
提交给用户代理,用户代理在 设备时间线 上调用操作系统驱动进行底层提交。 -
GPU 调度器在 队列时间线 上将提交分派到实际计算单元执行。
GPUDevice.createBuffer()
示例:
-
用户填写
GPUBufferDescriptor
,并用其创建GPUBuffer
,在 内容时间线 上发生。 -
用户代理在 设备时间线 上创建底层缓冲区。
3.4.2. 内存模型
本节为非规范性内容。
一旦应用初始化过程中获取到 GPUDevice
,我们可以将
WebGPU 平台描述为包含以下各层:
-
实现本规范的用户代理。
-
为该设备提供底层原生 API 驱动的操作系统。
-
实际的 CPU 和 GPU 硬件。
WebGPU 平台的每一层可能有不同类型的内存,用户代理在实现规范时需要加以考虑:
-
脚本拥有的内存,如脚本创建的
ArrayBuffer
,通常无法被 GPU 驱动直接访问。 -
用户代理可能有不同进程分别负责内容运行和与 GPU 驱动的通信。在这种情况下,会使用进程间共享内存来传递数据。
-
独立显卡有自己的高带宽内存,而集成显卡通常与系统共享内存。
大多数物理资源分配在适合 GPU 计算或渲染的内存类型中。当用户需要向 GPU 提供新数据时,数据可能首先需要跨越进程边界,抵达与 GPU 驱动通信的用户代理部分。随后可能需要使数据对驱动可见,有时这需要拷贝到驱动分配的中转(staging)内存。最后,数据还可能需要传输到独立 GPU 内存中,并在内部转换为最适合 GPU 运算的布局。
所有这些转换都由用户代理的 WebGPU 实现负责完成。
注:上述示例描述了最坏情况,实际实现中可能无需跨越进程边界,或者能直接向用户暴露由驱动管理的内存(例如通过
ArrayBuffer
),从而避免数据拷贝。
3.4.3. 资源用法
- 输入(input)
-
为 draw 或 dispatch 调用提供输入数据的缓冲区。会保留内容。由缓冲区
INDEX
、VERTEX
或INDIRECT
允许。 - 常量(constant)
-
从着色器视角为常量的资源绑定。会保留内容。由缓冲区
UNIFORM
或纹理TEXTURE_BINDING
允许。 - 存储(storage)
-
读/写存储资源绑定。由缓冲区
STORAGE
或纹理STORAGE_BINDING
允许。 - 存储只读(storage-read)
-
只读存储资源绑定。会保留内容。由缓冲区
STORAGE
或纹理STORAGE_BINDING
允许。 - 附件(attachment)
-
在渲染通道中作为读/写输出附件或仅写解决目标的纹理。由纹理
RENDER_ATTACHMENT
允许。 - 附件只读(attachment-read)
-
在渲染通道中作为只读附件的纹理。会保留内容。由纹理
RENDER_ATTACHMENT
允许。
子资源(subresource)指整个缓冲区或纹理子资源。
-
U 中每个用法都是 存储。
即使可写,也允许有多个此类用法。这称为存储用法例外(usage scope storage exception)。
-
U 中每个用法都是 附件。
即使可写,也允许有多个此类用法。这称为附件用法例外(usage scope attachment exception)。
强制要求用法仅可组合为兼容用法列表,使得 API 能够限制内存操作中的数据竞争出现时机。该属性使基于 WebGPU 的应用更容易无修改地在不同平台上运行。
-
作为深度/模板附件,所有方面都标记为只读(根据需要使用
depthReadOnly
和/或stencilReadOnly
)。 -
作为 draw 调用的纹理绑定。
-
一个缓冲区或纹理可作为存储绑定到渲染通道的两个不同 draw 调用。
-
单个缓冲区的不相交区间可分别作为存储绑定到两个不同绑定点。
重叠区间不得在单一 dispatch/draw 调用中绑定;这由“编码器绑定组别名可写资源”检查。
但同一切片不得作为两个不同附件重复绑定;这由 beginRenderPass()
检查。
3.4.4. 同步机制
用法范围(usage scope)是一个从有序映射,其键为子资源,值为 列表<内部用法>。每个用法范围覆盖一组可能并发执行的操作,因此在该范围内对子资源的使用只能是兼容用法列表。
-
对于 A 中的每一项 [subresource, usage]:
-
添加(Add) subresource 到 B,并指定 usage usage。
-
用法范围在编码期间被构建和校验:
用法范围如下:
-
在计算通道中,每个 dispatch 命令(
dispatchWorkgroups()
或dispatchWorkgroupsIndirect()
)即为一个用法范围。若某子资源在当前 dispatch 调用中可能被访问,则视为在该用法范围内被使用,包括:
-
当前
GPUComputePipeline
的[[layout]]
所用绑定组(bind group)槽引用的全部子资源 -
dispatch 调用直接使用的缓冲区(如间接缓冲区)
注: 诸如 setBindGroup() 等状态设定命令本身不会直接将绑定资源计入用法范围,它们只改变 dispatch 命令检查的状态。
-
-
一次渲染通道(render pass)即为一个用法范围。
若某子资源在任何命令中被引用(包括状态设定命令,与计算通道不同),则视为在该用法范围内被使用,包括:
-
通过
setVertexBuffer()
设置的缓冲区 -
通过
setIndexBuffer()
设置的缓冲区 -
通过 setBindGroup() 设置的绑定组引用的所有子资源
-
draw 调用直接使用的缓冲区(如间接缓冲区)
-
注:拷贝命令为独立操作,不使用用法范围进行校验,其自身实现了防止自竞争的校验。
-
在渲染通道中,任何 setBindGroup() 调用所用的子资源,无论当前绑定的管线着色器/布局是否真的依赖这些绑定,或该绑定组是否被后续 set 覆盖。
-
任何
setVertexBuffer()
调用所用缓冲区,无论是否有 draw 调用依赖该缓冲区,或该缓冲区是否被后续 set 覆盖。 -
任何
setIndexBuffer()
调用所用缓冲区,无论是否有 draw 调用依赖该缓冲区,或该缓冲区是否被后续 set 覆盖。 -
作为颜色附件、解决附件或深度/模板附件用于
GPURenderPassDescriptor
的纹理子资源,被beginRenderPass()
使用,无论着色器是否真的依赖这些附件。 -
在绑定组条目中具有可见性 0,或仅对计算阶段可见但被用于渲染通道的资源(反之亦然)。
3.5. 核心内部对象
3.5.1. 适配器(Adapters)
适配器(adapter)标识系统上的 WebGPU 实现:既包括底层平台上的计算/渲染功能实例,也包括浏览器在该功能之上实现 WebGPU 的实例。
适配器通过 GPUAdapter
暴露。
适配器并不唯一代表底层实现:多次调用 requestAdapter()
每次都会返回不同的适配器对象。
每个 适配器对象只能用于创建一个 设备(device):一旦成功调用 requestDevice()
,该适配器的
[[state]]
变为 "consumed"
。此外,适配器对象可能在任何时刻过期(expire)。
注:
这样保证应用在创建设备时能使用最新的系统状态来选择适配器。也让多种场景(如首次初始化、因适配器移除重初始化、因 GPUDevice.destroy()
测试重初始化等)行为保持一致,提高健壮性。
若适配器以显著性能换取更广兼容性、更可预测行为或更好的隐私,则可视为回退适配器(fallback adapter)。不是每个系统都必须提供回退适配器。
[[features]]
,类型为 有序集合<GPUFeatureName
>,只读-
可用于在此适配器上创建设备的特性。
[[limits]]
,类型为支持的限制,只读[[fallback]]
,类型为boolean
,只读-
为
true
时,表示该适配器是回退适配器。 [[xrCompatible]]
,类型为 boolean-
为
true
时,表示该适配器请求了与 WebXR 会话 兼容。
[[state]]
,初始值为"valid"
-
"valid"
-
适配器可用于创建设备。
"consumed"
-
适配器已被用于创建设备,不能再次使用。
"expired"
-
适配器因其他原因已过期。
3.5.2. 设备(Devices)
设备(device)是适配器的逻辑实例,通过它可以创建内部对象。
一个设备独占其上创建的所有内部对象:当该设备变为无效(丢失或 销毁
时),它本身和所有直接(如
createTexture()
)或间接(如
createView()
)创建的对象都会隐式变为不可用。
[[adapter]]
,类型为 适配器,只读-
创建该设备的适配器。
[[features]]
,类型为 有序集合<GPUFeatureName
>,只读[[limits]]
,类型为支持的限制,只读
GPUDeviceDescriptor
descriptor 创建新设备,请执行以下设备时间线步骤:
-
令 features 为 descriptor.
requiredFeatures
中值的有序集合。 -
如果 features 包含
"texture-formats-tier2"
:-
追加
"texture-formats-tier1"
到 features。
-
-
如果 features 包含
"texture-formats-tier1"
:-
追加
"rg11b10ufloat-renderable"
到 features。
-
-
追加
"core-features-and-limits"
到 features。 -
令 limits 为所有值均为默认值的支持的限制对象。
-
对于 descriptor.
requiredLimits
中每个 (key, value):-
如果 value 不为
undefined
且 value 优于 limits[key]:-
设 limits[key] = value。
-
-
-
令 device 为新设备对象。
-
设 device.
[[adapter]]
= adapter。 -
设 device.
[[features]]
= features。 -
设 device.
[[limits]]
= limits。 -
返回 device。
每当用户代理需要撤销设备访问权限时,会在该设备的设备时间线上调用 丢失设备(device
, "unknown"
),该操作可能优先于当前队列中的其他操作。
如果某操作失败且副作用可能导致设备上的对象状态可见变化或内部实现/驱动状态损坏,应当丢失该设备以防止这些变化被观察到。
注:
非应用主动发起的设备丢失(通过 destroy()
)时,用户代理应无条件向开发者发出警告,即使
lost
promise 已被处理。此类场景应极其罕见,并且该信号对开发者至关重要,因为大多数 WebGPU API 会尽量表现为“一切正常”以避免中断运行时流程:不会抛出校验错误,大多数 promise 正常 resolve
等。
-
在 device.
[[content device]]
的内容时间线上执行: -
完成所有等待 device 变为丢失的未完成步骤。
注:丢失的设备不会再生成错误。参见 § 22 错误与调试。
则在 timeline 上执行 steps。
3.6. 可选功能
WebGPU 适配器和设备具备功能,这些功能描述了WebGPU在不同实现之间的差异, 通常是由于硬件或系统软件的限制。 一项功能可以是特性或限制。
用户代理不得透露超过32个可区分的配置或分组。
适配器的功能必须符合§ 4.2.1 适配器功能保证。
仅支持的功能可以在requestDevice()
中请求;
请求不支持的功能会导致失败。
设备的功能在"一个新的设备"中确定,
通过从适配器的默认值(无特性和默认的支持的限制)开始,
并根据在requestDevice()
中请求的功能添加功能。
这些功能无论适配器的功能如何均会被强制执行。
有关隐私方面的考虑,请参阅§ 2.2.1 机器特定的功能和限制。
3.6.1. 特性
特性是一组可选的 WebGPU 功能,并非所有实现都支持这些功能,通常是由于硬件或系统软件的限制所致。
所有特性都是可选的,但适配器会对其可用性做出一定保证 (参见§ 4.2.1 适配器功能保证)。
设备仅支持在创建时确定的那组特性(参见§ 3.6 可选功能)。 API 调用将根据这些特性(而非适配器的特性)进行校验:
-
以新方式使用已有的 API 接口通常会导致校验错误。
-
有几种类型的可选 API 接口:
-
使用新方法或枚举值时总是抛出
TypeError
异常。 -
使用带有(正确类型)非默认值的新字典成员通常会导致校验错误。
-
使用新的 WGSL
enable
指令时,总是会在createShaderModule()
的过程中产生校验错误。
-
每个特性所启用的功能描述可参见特性索引。
注意: 启用特性未必是理想选择,可能会影响性能。 因此,为了提升不同设备和实现间的可移植性,应用程序通常只应请求实际需要的特性。
3.6.2. 限制
每个限制都是对设备上 WebGPU 使用的数值限制。
注意: 设置“更好”的限制未必是理想选择,因为这样可能会对性能产生影响。 因此,为了提升不同设备和实现之间的可移植性,应用程序通常只有在确实需要时才请求比默认值更好的限制。
每个限制都有一个默认值。
适配器始终保证支持默认值或更好的 (参见§ 4.2.1 适配器功能保证)。
设备仅支持在创建时确定的那组限制(参见§ 3.6 可选功能)。 API 调用根据这些限制进行校验(而非适配器的限制), 不允许“更好”或更差。
对于任何给定的限制,一些值是更好的。 更好的限制值始终放宽校验,从而使更多程序变得有效。 对于每个限制类别,“更好”的定义如下。
不同的限制具有不同的限制类别:
支持的限制 对象具有 WebGPU 定义的每个限制的值:
限制名称 | 类型 | 限制类别 | 默认值 |
---|---|---|---|
maxTextureDimension1D
| GPUSize32
| 最大值 | 8192 |
创建dimension
"1d" 的纹理时,
size .width
的最大允许值。
| |||
maxTextureDimension2D
| GPUSize32
| 最大值 | 8192 |
创建dimension
"2d" 的纹理时,
size .width
和 size .height
的最大允许值。
| |||
maxTextureDimension3D
| GPUSize32
| 最大值 | 2048 |
创建dimension
"3d" 的纹理时,
size .width、
size .height
和 size .depthOrArrayLayers 的最大允许值。
| |||
maxTextureArrayLayers
| GPUSize32
| 最大值 | 256 |
创建dimension
"2d" 的纹理时,
size .depthOrArrayLayers
的最大允许值。
| |||
maxBindGroups
| GPUSize32
| 最大值 | 4 |
创建GPUPipelineLayout 时,
bindGroupLayouts
中允许的GPUBindGroupLayouts 的最大数量。
| |||
maxBindGroupsPlusVertexBuffers
| GPUSize32
| 最大值 | 24 |
同时使用的绑定组和顶点缓冲区槽位的最大数量,包括所有低于最大索引的空槽位。
在createRenderPipeline()
和绘制调用中验证。
| |||
maxBindingsPerBindGroup
| GPUSize32
| 最大值 | 1000 |
创建GPUBindGroupLayout 时可用的绑定索引数量。
注意: 此限制具有规范性,但属于人为设定。
按默认绑定槽位限制,一个绑定组实际上无法使用1000个绑定,
但这允许 | |||
maxDynamicUniformBuffersPerPipelineLayout
| GPUSize32
| 最大值 | 8 |
在一个GPUPipelineLayout 中,
所有为动态偏移的uniform buffer的GPUBindGroupLayoutEntry 条目的最大数量。
详见绑定槽位限制说明。
| |||
maxDynamicStorageBuffersPerPipelineLayout
| GPUSize32
| 最大值 | 4 |
在一个GPUPipelineLayout 中,
所有为动态偏移的storage buffer的GPUBindGroupLayoutEntry 条目的最大数量。
详见绑定槽位限制说明。
| |||
maxSampledTexturesPerShaderStage
| GPUSize32
| 最大值 | 16 |
对于每个GPUShaderStage
stage ,在一个GPUPipelineLayout 中,
所有采样纹理的GPUBindGroupLayoutEntry 条目的最大数量。
详见绑定槽位限制说明。
| |||
maxSamplersPerShaderStage
| GPUSize32
| 最大值 | 16 |
对于每个GPUShaderStage
stage ,在一个GPUPipelineLayout 中,
所有采样器的GPUBindGroupLayoutEntry 条目的最大数量。
详见绑定槽位限制说明。
| |||
maxStorageBuffersPerShaderStage
| GPUSize32
| 最大值 | 8 |
对于每个GPUShaderStage
stage ,在一个GPUPipelineLayout 中,
所有存储缓冲区的GPUBindGroupLayoutEntry 条目的最大数量。
详见绑定槽位限制说明。
| |||
maxStorageTexturesPerShaderStage
| GPUSize32
| 最大值 | 4 |
对于每个可能的GPUShaderStage
stage ,
在一个GPUPipelineLayout 中,
所有存储纹理类型GPUBindGroupLayoutEntry 的最大数量。
详见绑定槽位限制说明。
|
|||
maxUniformBuffersPerShaderStage
|
GPUSize32
|
最大值 | 12 |
对于每个可能的GPUShaderStage
stage ,
在一个GPUPipelineLayout 中,
所有uniform buffer类型GPUBindGroupLayoutEntry 的最大数量。
详见绑定槽位限制说明。
|
|||
maxUniformBufferBindingSize
|
GPUSize64
|
最大值 | 65536 字节 |
绑定类型为
GPUBindGroupLayoutEntry
,且entry.buffer ?.type
为 "uniform"
时,
GPUBufferBinding .size
的最大值。
|
|||
maxStorageBufferBindingSize
|
GPUSize64
|
最大值 | 134217728 字节(128 MiB) |
绑定类型为
GPUBindGroupLayoutEntry
,且entry.buffer ?.type
为 "storage"
或 "read-only-storage"
时,
GPUBufferBinding .size
的最大值。
|
|||
minUniformBufferOffsetAlignment
|
GPUSize32
|
对齐 | 256 字节 |
绑定类型为
GPUBindGroupLayoutEntry
,且entry.buffer ?.type
为 "uniform"
时,
GPUBufferBinding .offset
以及 setBindGroup() 传入的动态偏移量所需的对齐要求。
|
|||
minStorageBufferOffsetAlignment
|
GPUSize32
|
对齐 | 256 字节 |
绑定类型为
GPUBindGroupLayoutEntry
,且entry.buffer ?.type
为 "storage"
或 "read-only-storage"
时,
GPUBufferBinding .offset
以及 setBindGroup() 传入的动态偏移量所需的对齐要求。
|
|||
maxVertexBuffers
|
GPUSize32 |
最大值 | 8 |
创建GPURenderPipeline 时,允许的buffers 的最大数量。
|
|||
maxBufferSize |
GPUSize64 |
最大值 | 268435456 字节(256 MiB) |
创建GPUBuffer 时,size 的最大数值。
|
|||
maxVertexAttributes |
GPUSize32 |
最大值 | 16 |
创建GPURenderPipeline 时,所有attributes 在buffers 中的总和的最大数量。
|
|||
maxVertexBufferArrayStride
|
GPUSize32 |
最大值 | 2048 字节 |
创建GPURenderPipeline 时,arrayStride 的最大允许值。
|
|||
maxInterStageShaderVariables
|
GPUSize32 |
最大值 | 16 |
阶段间通信(如顶点输出、片元输入)可用的输入或输出变量的最大数量。 | |||
maxColorAttachments |
GPUSize32 |
最大值 | 8 |
在
GPURenderPipelineDescriptor .fragment .targets 、
GPURenderPassDescriptor .colorAttachments
和 GPURenderPassLayout .colorFormats
中允许的最大颜色附件数量。
|
|||
maxColorAttachmentBytesPerSample
|
GPUSize32
|
最大值 | 32 |
渲染管线输出数据中,跨所有颜色附件存储一个采样(像素或子像素)所需的最大字节数。 | |||
maxComputeWorkgroupStorageSize
|
GPUSize32
|
最大值 | 16384 字节 |
一个计算阶段GPUShaderModule 入口点可用的workgroup存储的最大字节数。
|
|||
maxComputeInvocationsPerWorkgroup
|
GPUSize32
|
最大值 | 256 |
一个计算阶段GPUShaderModule 入口点的workgroup_size 各维度乘积的最大值。
|
|||
maxComputeWorkgroupSizeX
|
GPUSize32
|
最大值 | 256 |
一个计算阶段GPUShaderModule 入口点的workgroup_size
X 维度的最大值。
|
|||
maxComputeWorkgroupSizeY
|
GPUSize32
|
最大值 | 256 |
一个计算阶段GPUShaderModule 入口点的workgroup_size
Y 维度的最大值。
|
|||
maxComputeWorkgroupSizeZ
|
GPUSize32
|
最大值 | 64 |
一个计算阶段GPUShaderModule 入口点的workgroup_size
Z 维度的最大值。
|
|||
maxComputeWorkgroupsPerDimension
|
GPUSize32
|
最大值 | 65535 |
dispatchWorkgroups(workgroupCountX, workgroupCountY, workgroupCountZ) 的参数的最大值。
|
3.6.2.1.
GPUSupportedLimits
GPUSupportedLimits
用于暴露适配器或设备的支持的限制。
参见 GPUAdapter.limits
和 GPUDevice.limits
。
[Exposed =(Window ,Worker ),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 ;
maxBindGroupsPlusVertexBuffers readonly attribute unsigned long ;
maxBindingsPerBindGroup 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 long ;
maxBufferSize readonly attribute unsigned long ;
maxVertexAttributes readonly attribute unsigned long ;
maxVertexBufferArrayStride readonly attribute unsigned long ;
maxInterStageShaderVariables readonly attribute unsigned long ;
maxColorAttachments readonly attribute unsigned long ;
maxColorAttachmentBytesPerSample 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
是一个 类似集合(setlike) 接口。它的
集合条目
是适配器或设备支持的 GPUFeatureName
值。
它只能包含 GPUFeatureName
枚举中的字符串。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUSupportedFeatures {readonly setlike <DOMString >; };
GPUSupportedFeatures
的 集合条目
类型为 DOMString
,
这样可以让用户代理优雅地处理后续规范修订中新增但用户代理尚未识别的有效 GPUFeatureName
。
如果 集合条目 的类型是
GPUFeatureName
,如下代码将抛出
TypeError
,
而不是返回 false
:
3.6.2.3.
WGSLLanguageFeatures
WGSLLanguageFeatures
是
navigator.gpu.
的
类似集合(setlike) 接口。
它的 集合条目
是该实现支持的 WGSL 语言扩展 的字符串名称(不论适配器或设备)。
wgslLanguageFeatures
[Exposed =(Window ,Worker ),SecureContext ]interface WGSLLanguageFeatures {readonly setlike <DOMString >; };
3.6.2.4.
GPUAdapterInfo
GPUAdapterInfo
用于暴露关于适配器的各种标识信息。
GPUAdapterInfo
的成员不保证有任何特定值;如果没有提供值,该属性将返回空字符串
""
。是否揭示这些值由用户代理自行决定,并且某些设备上可能所有值都为空。因此,应用必须能够处理任何可能的
GPUAdapterInfo
值,包括这些值缺失的情况。
适配器的 GPUAdapterInfo
可通过 GPUAdapter.info
和 GPUDevice.adapterInfo
获取。
这些信息是不可变的:对于某个适配器,每次访问同一个 GPUAdapterInfo
属性都会返回相同的值。
注意:
虽然 GPUAdapterInfo
属性一旦访问就不可变,
但实现可以在首次访问前延后决定每个属性的内容。
注意:
即便其他 GPUAdapter
实例代表同一物理适配器,
它们在 GPUAdapterInfo
中揭示的值也可能不同。
但除非有特殊事件提升了页面可访问的标识信息(本规范未定义此类事件),否则它们应当揭示相同的值。
关于隐私考虑,请参见 § 2.2.6 适配器标识符。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUAdapterInfo {readonly attribute DOMString vendor ;readonly attribute DOMString architecture ;readonly attribute DOMString device ;readonly attribute DOMString description ;readonly attribute unsigned long subgroupMinSize ;readonly attribute unsigned long subgroupMaxSize ;readonly attribute boolean isFallbackAdapter ; };
GPUAdapterInfo
拥有如下属性:
-
vendor
, 类型为 DOMString,只读 -
适配器的厂商名称(如有)。否则为空字符串。
-
architecture
, 类型为 DOMString,只读 -
适配器所属 GPU 家族或类别的名称(如有)。否则为空字符串。
-
device
, 类型为 DOMString,只读 -
适配器的厂商自定义标识符(如有)。否则为空字符串。
注意: 这是代表适配器类型的值。例如,可能是 PCI 设备ID。它不会像序列号一样唯一标识某块硬件。
-
description
, 类型为 DOMString,只读 -
驱动报告的关于适配器的人类可读字符串描述(如有)。否则为空字符串。
注意:
description
没有采用任何格式化,不建议尝试解析此值。根据GPUAdapterInfo
改变行为的应用(如为已知驱动问题应用修正),应尽量依赖其他字段。 -
subgroupMinSize
, 类型为 unsigned long,只读 -
如果支持
"subgroups"
特性,则为适配器支持的最小 子组大小。 -
subgroupMaxSize
, 类型为 unsigned long,只读 -
如果支持
"subgroups"
特性,则为适配器支持的最大 子组大小。 -
isFallbackAdapter
, 类型为 boolean,只读 -
适配器是否为回退适配器。
-
令 adapterInfo 为新的
GPUAdapterInfo
。 -
如果已知厂商,则将 adapterInfo.
vendor
设为 adapter 的厂商名,并格式化为规范化标识符字符串。为保护隐私,用户代理也可以将 adapterInfo.vendor
设为空字符串,或一个合理近似的厂商名(同样为规范化标识符字符串)。 -
如果已知架构,则将 adapterInfo.
architecture
设为代表 adapter 所属 GPU 家族或类别的规范化标识符字符串。为保护隐私,用户代理也可以设为空字符串,或合理近似的架构名(同样为规范化标识符字符串)。 -
如果已知设备,则将 adapterInfo.
device
设为 adapter 的厂商自定义标识符,并格式化为规范化标识符字符串。为保护隐私,用户代理也可以设为空字符串,或合理近似的标识符(同样为规范化标识符字符串)。 -
如果已知描述,则将 adapterInfo.
description
设为驱动报告的 adapter 描述。为保护隐私,用户代理也可以设为空字符串,或合理近似的描述。 -
如果支持
"subgroups"
特性,则将subgroupMinSize
设为支持的最小子组大小;否则设为 4。注意: 为保护隐私,用户代理可以选择不支持某些特性,或为属性提供不会区分不同设备但依然可用的值(如对所有设备使用默认值 4)。
-
如果支持
"subgroups"
特性,则将subgroupMaxSize
设为支持的最大子组大小;否则设为 128。注意: 为保护隐私,用户代理可以选择不支持某些特性,或为属性提供不会区分不同设备但依然可用的值(如对所有设备使用默认值 128)。
-
将 adapterInfo.
isFallbackAdapter
设为 adapter.[[fallback]]
。 -
返回 adapterInfo。
[a-z0-9]+(-[a-z0-9]+)*
3.7. 扩展文档
“扩展文档”是描述新功能的附加文档,这些功能是非规范性的,不属于 WebGPU/WGSL 规范的一部分。
它们描述了在这些规范基础上构建的功能,通常包含一个或多个新的 API 特性标志和/或
WGSL enable
指令,或与其他草案 Web 规范的交互。
WebGPU 实现不得暴露扩展功能;这样做属于规范违规。 新功能只有在被集成到 WebGPU 规范(本文档)和/或 WGSL 规范后,才成为 WebGPU 标准的一部分。
3.8. 源限制(Origin Restrictions)
WebGPU 允许访问存储在图片、视频和画布中的图像数据。 出于安全原因,对跨域媒体的使用施加了限制,因为着色器可以被用来间接推测已上传到 GPU 的纹理内容。
WebGPU 不允许上传 不是 origin-clean 的图片源。
这也意味着,使用 WebGPU 渲染的 canvas 的 origin-clean 标志永远不会被置为 false
。
关于为图片和视频元素发起 CORS 请求的更多信息,请参考:
3.9. 任务源(Task Sources)
3.9.1. WebGPU 任务源
WebGPU 定义了一个新的 任务源,称为 WebGPU 任务源。
它用于 uncapturederror
事件和
GPUDevice
.lost
。
GPUDevice
device 排队一个全局任务(queue a global task),并在 内容时序 上执行一系列步骤
steps:
-
在 WebGPU 任务源 上,为用于创建 device 的全局对象,按 steps 排队一个全局任务。
3.9.2. 自动过期任务源
WebGPU 定义了一个新的 任务源,称为 自动过期任务源。 它用于自动、定时地销毁某些对象:
来自 自动过期任务源 的任务应当以高优先级处理;尤其是排入队列后,应当在用户自定义(JavaScript)任务之前执行。
实现说明: 以高优先级处理过期“任务”也可以通过在事件循环处理模型的某个固定点插入额外步骤来实现,而不一定非要运行实际的任务。
3.10. 色彩空间与编码
WebGPU 不提供色彩管理。WebGPU 内的所有值(如纹理元素)都是原始数值,不是经过色彩管理的色值。
WebGPU 确实与色彩管理的输出(通过 GPUCanvasConfiguration
)和输入(通过
copyExternalImageToTexture()
及 importExternalTexture()
)对接。因此,必须在
WebGPU 数值和外部色值之间进行色彩转换。每个接口点都会本地定义一种编码(色彩空间、传递函数和 alpha 预乘),用于解释 WebGPU 的数值。
WebGPU 允许 PredefinedColorSpace
枚举中的所有色彩空间。注意,每个色彩空间都定义了扩展范围(详见 CSS 相关定义),可以表示其空间外的颜色值(包括色度和明度)。
超出色域的预乘
RGBA 值指 R/G/B 其中任意一个通道的值大于 alpha 通道的值。例如,预乘 sRGB RGBA 值 [1.0, 0, 0, 0.5] 表示原始(未预乘)颜色 [2, 0, 0] 且
alpha 为 50%,在 CSS 中可写作 rgb(srgb 2 0 0 / 50%)
。和所有 sRGB 色域外的颜色一样,这在扩展色彩空间中是有定义的点(alpha 为 0
时除外,此时没有颜色)。但若此类值输出到可见画布,结果未定义(见 GPUCanvasAlphaMode
"premultiplied"
)。
3.10.1. 色彩空间转换
颜色在空间间转换时,需根据上述定义将其在一个空间中的表示转换为另一个空间中的表示。
如果源值少于4个 RGBA 通道,则缺失的绿/蓝/alpha 通道分别设为0, 0, 1
,然后再做色彩空间/编码和 alpha 预乘转换。转换后,如果目标需要的通道数少于4,则忽略多余通道。
注意: 灰度图像通常在其色彩空间下表现为 RGB 值 (V, V, V)
或 RGBA
值 (V, V, V, A)
。
颜色在转换时不会被有损截断:若源色值本就在目标色彩空间的色域外,转换后会产生超出[0, 1]范围的值。例如,sRGB 目标下,如果源为 rgba16float,色彩空间更广(如 Display-P3),或为预乘且包含超出色域的预乘值,都可能出现上述情况。
同样,如果源值有高位深(如 16 位/分量 PNG)或扩展范围(如 float16
存储的 canvas),这些颜色会在转换过程中保留,且中间计算的精度不少于源。
3.10.2. 色彩空间转换省略
若源与目标的色彩空间/编码一致,则无需转换。通常,若某一步是恒等函数(无操作),实现应当出于性能考虑省略该步骤。
为获得最佳性能,应用应当设置色彩空间和编码选项,以最小化整个流程中所需的转换次数。
对于各种 GPUCopyExternalImageSourceInfo
图像源:
-
-
预乘由
premultiplyAlpha
控制。 -
色彩空间由
colorSpaceConversion
控制。
-
-
2d 画布:
-
色彩空间由
colorSpace
创建上下文时的属性控制。
-
WebGL 画布:
-
预乘由
WebGLContextAttributes
中的premultipliedAlpha
选项控制。 -
色彩空间由
WebGLRenderingContextBase
的drawingBufferColorSpace
状态控制。
-
注意: 在依赖这些特性前,请检查浏览器的实现支持。
3.11. JavaScript 到 WGSL 的数值转换
WebGPU API 的多个部分(可覆盖管线 constants
和渲染通道清除值)会接收来自 WebIDL(double
或 float
)的数值,并将其转换为
WGSL 值(bool
、i32
、u32
、f32
、f16
)。
double
或 float
的 IDL 值 idlValue 转换为 WGSL 类型(to WGSL type) T,可能抛出 TypeError
,请执行以下
设备时序 步骤:
注意: 该 TypeError
只会在 设备时序 内产生,并不会抛到
JavaScript。
-
断言 idlValue 是有限值,因为它不是
unrestricted double
或unrestricted float
。 -
令 v 为 将 idlValue 转换为 ECMAScript 值 后得到的 ECMAScript Number。
-
- 如果 T 是
bool
-
返回与 ! 将 v 转换为 IDL 类型
boolean
后结果对应的 WGSLbool
值。注意: 本算法是在从 ECMAScript 值到 IDL
double
或float
值的转换之后调用的。如果原始 ECMAScript 值为非数值、非布尔值(如[]
或{}
),那么 WGSLbool
结果可能与直接转换为 IDLboolean
的结果不同。 - 如果 T 是
i32
-
返回 WGSL
i32
值,该值对应于 ? 将 v 转换为类型为 [EnforceRange
]long
的 IDL 值 的结果。 - 如果 T 是
u32
-
返回 WGSL
u32
值,该值对应于 ? 将 v 转换为类型为 [EnforceRange
]unsigned long
的 IDL 值 的结果。 - 如果 T 是
f32
- 如果 T 是
f16
-
-
令 wgslF32 为 WGSL
f32
值,该值对应于 ? 将 v 转换为类型为float
的 IDL 值 的结果。 -
返回
f16(wgslF32)
,即 ! 按 WGSL 浮点数转换 所定义,将 WGSLf32
值转换为f16
的结果。
注意:只要值在
f32
的范围内,即使超出f16
的范围,也不会抛出错误。 -
- 如果 T 是
GPUColor
color 转换为纹理格式的 texel 值(to a texel value of texture
format) format,可能抛出 TypeError
,请执行以下
设备时序 步骤:
注意: 该 TypeError
只会在 设备时序 内产生,并不会抛到
JavaScript。
-
若 format 的各分量类型(断言全部相同)为:
- 浮点类型或归一化类型
-
令 T 为
f32
。 - 有符号整型
-
令 T 为
i32
。 - 无符号整型
-
令 T 为
u32
。
-
令 wgslColor 为 WGSL
vec4<T>
,其 4 个分量为 color 的 RGBA 通道,每个都 转换为 WGSL 类型 T。 -
按 § 23.2.7 输出合并 的同样规则将 wgslColor 转换为 format,并返回结果。
注意: 对于非整型类型,实际取值为实现定义。对于归一化类型,值会被限制在该类型允许的范围内。
注意: 换言之,写入的值就如同由 WGSL 着色器以
f32
、i32
或 u32
类型的 vec4
输出。
4. 初始化
4.1. navigator.gpu
在 Window
和 WorkerGlobalScope
上下文中,GPU
对象通过 Navigator
和 WorkerNavigator
接口暴露,访问方式为 navigator.gpu
:
interface mixin { [
NavigatorGPU SameObject ,SecureContext ]readonly attribute GPU gpu ; };Navigator includes NavigatorGPU ;WorkerNavigator includes NavigatorGPU ;
NavigatorGPU
具有以下属性:
gpu
,类型为 GPU,只读-
一个全局单例,提供诸如
requestAdapter()
的顶级入口点。
4.2. GPU
GPU
是
WebGPU 的入口点。
[Exposed =(Window ,Worker ),SecureContext ]interface GPU {Promise <GPUAdapter ?>requestAdapter (optional GPURequestAdapterOptions options = {});GPUTextureFormat getPreferredCanvasFormat (); [SameObject ]readonly attribute WGSLLanguageFeatures wgslLanguageFeatures ; };
GPU
具有以下方法:
requestAdapter(options)
-
从用户代理请求一个 adapter。用户代理选择是否返回适配器,并根据提供的选项进行选择。
调用对象:GPU
this.参数:
参数表:GPU.requestAdapter(options) 方法。 参数 类型 可空 可选 描述 options
GPURequestAdapterOptions
✘ ✔ 用于选择适配器的条件。 返回:
Promise
<GPUAdapter
?>内容时序步骤:
-
令 contentTimeline 为当前 内容时序。
-
令 promise 为 一个新的 promise。
-
在 this 的 设备时序上执行 初始化步骤。
-
返回 promise。
设备时序 初始化步骤:-
以下步骤的所有要求必须满足。
-
options.
featureLevel
必须为一个特性级别字符串。
如果满足要求且用户代理选择返回一个适配器:
-
设置 adapter 为根据 § 4.2.2 适配器选择 中的规则和 options 的条件选择的 adapter,并遵循 § 4.2.1 适配器能力保证。根据定义初始化适配器的属性:
-
根据适配器的支持能力设置 adapter.
[[limits]]
和 adapter.[[features]]
。adapter.[[features]]
必须包含"core-features-and-limits"
。 -
如果 adapter 满足回退适配器的条件,则将 adapter.
[[fallback]]
设置为true
。否则,设置为false
。 -
将 adapter.
[[xrCompatible]]
设置为 options.xrCompatible
。
-
否则:
-
令 adapter 为
null
。
-
-
在 contentTimeline 上执行后续步骤。
内容时序步骤:-
如果 adapter 不为
null
:-
解析(Resolve) promise,返回一个封装了 adapter 的新
GPUAdapter
。
-
-
否则,解析(Resolve) promise,返回
null
。
-
-
getPreferredCanvasFormat()
-
返回在本系统上显示 8 位深度、标准动态范围内容的最佳
GPUTextureFormat
。只能返回"rgba8unorm"
或"bgra8unorm"
。返回值可作为
format
传递给configure()
方法,以确保相关GPUCanvasContext
能高效显示其内容。注意: 未显示到屏幕上的 canvas 使用此格式可能无益,也可能有益。
调用对象:GPU
this。返回:
GPUTextureFormat
内容时序 步骤:
-
根据本系统 WebGPU canvas 显示的最佳格式,返回
"rgba8unorm"
或"bgra8unorm"
。
-
GPU
有以下属性:
-
wgslLanguageFeatures
, 类型为 WGSLLanguageFeatures,只读 -
支持的 WGSL 语言扩展的名称。 支持的语言扩展会自动启用。
适配器 可能 随时被 过期。
当系统状态发生任何可能影响任何 requestAdapter()
调用结果的变化时,用户代理 应当 使所有 先前返回的 适配器 过期。例如:
-
物理适配器被添加/移除(通过插拔、驱动更新、死机恢复等)
-
系统电源配置发生变化(如笔记本电脑断电、电源设置更改等)
注意:
用户代理可能会选择经常 过期 适配器,即使系统状态没有发生变化(例如在适配器创建后几秒或几分钟)。
这有助于混淆真实的系统状态变化,并让开发者更加意识到,在调用 requestAdapter()
之前,总是需要重新请求适配器再调用 requestDevice()
。
如果应用遇到这种情况,标准的设备丢失恢复处理应当能够使其恢复。
4.2.1. 适配器能力保证
任何由 GPUAdapter
通过 requestAdapter()
返回的对象都必须提供以下保证:
-
以下至少一项必须为真:
-
如果支持
"texture-compression-bc-sliced-3d"
,则必须支持"texture-compression-bc"
。 -
如果支持
"texture-compression-astc-sliced-3d"
,则必须支持"texture-compression-astc"
。 -
所有alignment-class 类型的限制值必须为2的幂。
-
maxBindingsPerBindGroup
必须大于等于 (每个着色器阶段的最大绑定数 × 每个管线的最大着色器阶段数),其中:-
每个着色器阶段的最大绑定数为 (
maxSampledTexturesPerShaderStage
+maxSamplersPerShaderStage
+maxStorageBuffersPerShaderStage
+maxStorageTexturesPerShaderStage
+maxUniformBuffersPerShaderStage
). -
每个管线的最大着色器阶段数为
2
,因为GPURenderPipeline
同时支持顶点和片元着色器。
注意:
maxBindingsPerBindGroup
并不反映一个基本限制; 实现应通过提高该值来满足这一要求,而不是降低其他限制。 -
-
minUniformBufferOffsetAlignment
和minStorageBufferOffsetAlignment
都必须大于等于 32 字节。注意: 32 字节是
vec4<f64>
的对齐值。参见 WebGPU 着色语言 § 14.4.1 对齐与大小。 -
maxStorageBufferBindingSize
必须为4字节的整数倍。 -
maxVertexBufferArrayStride
必须为4字节的整数倍。 -
maxComputeWorkgroupSizeX
必须小于等于maxComputeInvocationsPerWorkgroup
。 -
maxComputeWorkgroupSizeY
必须小于等于maxComputeInvocationsPerWorkgroup
。 -
maxComputeWorkgroupSizeZ
必须小于等于maxComputeInvocationsPerWorkgroup
。 -
maxComputeInvocationsPerWorkgroup
必须小于等于maxComputeWorkgroupSizeX
×maxComputeWorkgroupSizeY
×maxComputeWorkgroupSizeZ
。
4.2.2. 适配器选择
GPURequestAdapterOptions
为用户代理提供指示,表明哪些配置适合应用程序。
dictionary GPURequestAdapterOptions {DOMString featureLevel = "core";GPUPowerPreference powerPreference ;boolean forceFallbackAdapter =false ;boolean xrCompatible =false ; };
enum {
GPUPowerPreference "low-power" ,"high-performance" , };
GPURequestAdapterOptions
拥有如下成员:
featureLevel
, 类型为 DOMString,默认值为"core"
-
适配器请求的“功能级别”。
允许的 功能级别字符串值为:
- "core"
-
无影响。
- "compatibility"
-
无影响。
注意: 该值为将来引入额外验证限制时保留。 目前应用不应使用此值。
powerPreference
, 类型为 GPUPowerPreference-
可选,为用户代理提供一个提示,指示应从系统可用适配器中选择哪种类别的 适配器。
该提示的值可能影响选择哪个适配器,但不得影响是否返回适配器。
注意: 该提示的主要用途是在多GPU系统上影响所用的GPU。 例如,某些笔记本电脑有低功耗集成GPU和高性能独立GPU。该提示也可能影响所选GPU的电源配置,以匹配请求的电源偏好。
注意: 根据具体硬件配置(如电池状态、外接显示器或可卸载GPU),即使设置了相同的电源偏好,用户代理可能依然选择不同的 适配器。 通常,在相同硬件配置和状态下,且
powerPreference
一致,用户代理通常会选择同一个适配器。必须为以下值之一:
undefined
(或未设置)-
不给用户代理提供任何提示。
"low-power"
-
表示请求优先考虑节能而非性能。
注意: 如果内容渲染需求较低(如每秒只渲染一帧,仅绘制相对简单的几何体和着色器,或只用小型HTML canvas元素),一般应使用该选项。 如果内容允许,鼓励开发者使用此值,因为这可能大幅提升便携设备的电池寿命。
"high-performance"
-
表示请求优先考虑性能而非能耗。
注意: 选择此值时,开发者应注意,对于在所选适配器上创建的 设备,用户代理更可能强制设备丢失,以便切换到低功耗适配器节能。 只有在确有必要时,开发者才应指定此值,因为它可能会大幅降低便携设备的电池寿命。
forceFallbackAdapter
, 类型为 boolean,默认值为false
-
若设为
true
,表示只能返回 回退适配器。如果用户代理不支持 回退适配器,则requestAdapter()
会返回null
。注意: 即使
forceFallbackAdapter
设为false
,requestAdapter()
仍可能返回 回退适配器(当没有其他合适的 适配器可用,或用户代理选择返回回退适配器时)。 希望避免应用在 回退适配器上运行的开发者应在请求GPUDevice
前检查info
.isFallbackAdapter
属性。 xrCompatible
, 类型为 boolean,默认值为false
-
若设为
true
,表示必须返回用于 WebXR会话渲染的最佳 适配器。如果用户代理或系统不支持 WebXR会话,则适配器选择可忽略此值。注意: 如果在请求适配器时
xrCompatible
未设为true
,则从该适配器创建的GPUDevice
无法用于 WebXR会话 渲染。
"high-performance"
GPUAdapter
:
const gpuAdapter= await navigator. gpu. requestAdapter({ powerPreference: 'high-performance' });
4.3. GPUAdapter
GPUAdapter
封装了一个 适配器,
并描述其能力(特性
和 限制)。
要获取一个 GPUAdapter
,
请使用 requestAdapter()
。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUAdapter { [SameObject ]readonly attribute GPUSupportedFeatures features ; [SameObject ]readonly attribute GPUSupportedLimits limits ; [SameObject ]readonly attribute GPUAdapterInfo info ;Promise <GPUDevice >requestDevice (optional GPUDeviceDescriptor descriptor = {}); };
GPUAdapter
拥有以下不可变属性
features
, 类型为 GPUSupportedFeatures,只读-
在
this
.[[adapter]]
.[[features]]
中的值集合。 limits
, 类型为 GPUSupportedLimits,只读-
在
this
.[[adapter]]
.[[limits]]
中的限制。 info
, 类型为 GPUAdapterInfo,只读-
关于该
GPUAdapter
所对应物理适配器的信息。对于同一个
GPUAdapter
, 暴露的GPUAdapterInfo
值在时间上是恒定的。每次返回的都是同一个对象。首次创建该对象的方法如下:
[[adapter]]
,类型为 adapter,只读-
该
GPUAdapter
所引用的 适配器。
GPUAdapter
拥有以下方法:
requestDevice(descriptor)
-
这是一次性操作:如果成功返回了设备,则适配器变为
"consumed"
。调用对象:GPUAdapter
this.参数:
方法 GPUAdapter.requestDevice(descriptor) 的参数。 参数 类型 可为 null 可选 描述 descriptor
GPUDeviceDescriptor
✘ ✔ 请求的 GPUDevice
的描述信息。内容时间线 步骤:
-
令 contentTimeline 为当前 内容时间线。
-
令 promise 为新的 promise。
-
令 adapter 为 this.
[[adapter]]
。 -
对 this 的 设备时间线 执行 初始化步骤。
-
返回 promise。
设备时间线 初始化步骤:-
如果下列任何要求未满足:
-
descriptor.
requiredFeatures
中的值集合 必须是 adapter.[[features]]
的子集。
则在 contentTimeline 上执行下列步骤并返回:
注意: 这与浏览器完全不识别某特性的情况下抛出的错误相同(在其
GPUFeatureName
定义里)。 这使得浏览器不支持某特性和某适配器不支持某特性时的行为一致。 -
-
以下步骤中的所有要求 必须 被满足。
-
adapter.
[[state]]
不得为"consumed"
。 -
对于 descriptor.
requiredLimits
中每个 key、value 对(且 value 不为undefined
):-
key 必须 是 支持的限制的成员名。
-
value 不得比 adapter.
[[limits]]
[key] 更高。
注意: 即使 value 为
undefined
,当 key 未被识别时,用户代理应考虑给出开发者可见的警告。 -
若有未满足项,则在 contentTimeline 上执行下列步骤并返回:
内容时间线 步骤:-
拒绝 promise,并给出
OperationError
。
-
-
如果 adapter.
[[state]]
为"expired"
或用户代理无法完成该请求:-
令 device 为新的 设备。
-
断言 adapter.
[[state]]
为"expired"
。注意: 当发生这种情况时,用户代理应考虑在大多数或所有情况下向开发者发出警告。应用应从
requestAdapter()
开始重新初始化逻辑。
否则:
-
令 device 为带有 descriptor 描述能力的新设备。
-
-
在 contentTimeline 上执行后续步骤。
内容时间线 步骤:-
令 gpuDevice 为新的
GPUDevice
实例。 -
设置 gpuDevice.
[[device]]
为 device。 -
设置 device.
[[content device]]
为 gpuDevice。 -
解决 promise,返回 gpuDevice。
注意: 如果由于适配器无法完成请求而设备已丢失,则 device.
lost
在 promise 解决前已经解决。
-
GPUDevice
:
const gpuAdapter= await navigator. gpu. requestAdapter(); const gpuDevice= await gpuAdapter. requestDevice();
4.3.1. GPUDeviceDescriptor
GPUDeviceDescriptor
描述一个设备请求。
dictionary GPUDeviceDescriptor :GPUObjectDescriptorBase {sequence <GPUFeatureName >requiredFeatures = [];record <DOMString , (GPUSize64 or undefined )>requiredLimits = {};GPUQueueDescriptor defaultQueue = {}; };
GPUDeviceDescriptor
拥有以下成员:
requiredFeatures
, 类型为 sequence<GPUFeatureName>,默认值为[]
-
指定设备请求所需的特性。 如果适配器无法提供这些特性,请求会失败。
API调用的校验只允许恰好指定的特性,不多也不少。
requiredLimits
, 类型为record<DOMString, (GPUSize64 or undefined)>
,默认值为{}
-
指定设备请求所需的限制。 如果适配器无法提供这些限制,请求会失败。
每个非
undefined
值的 key 必须是支持的限制的成员名。在最终设备上的 API 调用会根据该设备的实际限制(不是适配器的限制;见 § 3.6.2 限制)进行校验。
defaultQueue
, 类型为 GPUQueueDescriptor,默认值为{}
-
默认
GPUQueue
的描述符。
"texture-compression-astc"
特性时,请求 GPUDevice
:
const gpuAdapter= await navigator. gpu. requestAdapter(); const requiredFeatures= []; if ( gpuAdapter. features. has( 'texture-compression-astc' )) { requiredFeatures. push( 'texture-compression-astc' ) } const gpuDevice= await gpuAdapter. requestDevice({ requiredFeatures});
GPUDevice
并指定更高的 maxColorAttachmentBytesPerSample
限制:
const gpuAdapter= await navigator. gpu. requestAdapter(); if ( gpuAdapter. limits. maxColorAttachmentBytesPerSample< 64 ) { // 当所需限制不被支持时,采取措施,要么降级代码路径,要么提示用户其设备不满足最低要求。 } // 请求更高的每样本最大颜色附件字节数限制。 const gpuDevice= await gpuAdapter. requestDevice({ requiredLimits: { maxColorAttachmentBytesPerSample: 64 }, });
4.3.1.1. GPUFeatureName
每个 GPUFeatureName
都标识一组功能,如果可用,可使 WebGPU 支持本来无效的额外用法。
enum GPUFeatureName {"core-features-and-limits" ,"depth-clip-control" ,"depth32float-stencil8" ,"texture-compression-bc" ,"texture-compression-bc-sliced-3d" ,"texture-compression-etc2" ,"texture-compression-astc" ,"texture-compression-astc-sliced-3d" ,"timestamp-query" ,"indirect-first-instance" ,"shader-f16" ,"rg11b10ufloat-renderable" ,"bgra8unorm-storage" ,"float32-filterable" ,"float32-blendable" ,"clip-distances" ,"dual-source-blending" ,"subgroups" ,"texture-formats-tier1" ,"texture-formats-tier2" , };
4.4. GPUDevice
要获取一个 GPUDevice
,请使用
requestDevice()
。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUDevice :EventTarget { [SameObject ]readonly attribute GPUSupportedFeatures features ; [SameObject ]readonly attribute GPUSupportedLimits limits ; [SameObject ]readonly attribute GPUAdapterInfo adapterInfo ; [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 ;
features
, 类型为 GPUSupportedFeatures,只读-
包含设备支持的
GPUFeatureName
的集合([[device]]
.[[features]]
)。 limits
, 类型为 GPUSupportedLimits,只读-
该设备支持的限制(
[[device]]
.[[limits]]
)。 queue
, 类型为 GPUQueue,只读-
此设备的主
GPUQueue
。 adapterInfo
, 类型为 GPUAdapterInfo,只读-
创建此 设备的物理适配器的信息,该
GPUDevice
所指向的适配器。对于同一个
GPUDevice
,暴露的GPUAdapterInfo
值在时间上是恒定的。每次返回的都是同一个对象。首次创建该对象的方法如下:
[[device]]
是 GPUDevice
所引用的 设备。
GPUDevice
拥有以下方法:
destroy()
-
销毁该 设备,阻止进一步的操作。所有未完成的异步操作将失败。
注意: 多次销毁同一个设备是合法的。
-
丢失该设备(this.
[[device]]
,"destroyed"
)。
注意: 由于无法在该设备上排队新的操作,实现可以立即中止所有未完成的异步操作并释放资源,包括刚刚解除映射的内存。
-
GPUDevice
的
允许的缓冲区用法 包括:
GPUDevice
的
允许的纹理用法 包括:
4.5. 示例
GPUAdapter
和 GPUDevice
并进行错误处理的示例:
let gpuDevice= null ; async function initializeWebGPU() { // 检查用户代理是否支持 WebGPU。 if ( ! ( 'gpu' in navigator)) { console. error( "用户代理不支持 WebGPU。" ); return false ; } // 请求适配器。 const gpuAdapter= await navigator. gpu. requestAdapter(); // 如果找不到合适的适配器,requestAdapter 可能会 resolve 为 null。 if ( ! gpuAdapter) { console. error( '未找到 WebGPU 适配器。' ); return false ; } // 请求设备。 // 注意:如果给可选字典传递了无效参数,promise 会 reject。为避免 promise 被拒绝, // 总是应在调用 requestDevice() 前检查特性和限制是否被适配器支持。 gpuDevice= await gpuAdapter. requestDevice(); // requestDevice 永远不会返回 null,但如果出于某种原因无法满足有效的设备请求, // 它可能会返回一个已经丢失的设备。 // 此外,设备在创建后可能随时丢失(如:浏览器资源管理、驱动更新), // 因此应始终优雅地处理设备丢失。 gpuDevice. lost. then(( info) => { console. error( `WebGPU 设备已丢失: ${ info. message} ` ); gpuDevice= null ; // 多数设备丢失的原因是临时性的,因此应用应在丢失后尝试获取新设备, // 除非丢失原因是应用主动销毁了设备。注意,所有用旧设备创建的 WebGPU 资源(缓冲区、纹理等) // 都需要用新设备重新创建。 if ( info. reason!= 'destroyed' ) { initializeWebGPU(); } }); onWebGPUInitialized(); return true ; } function onWebGPUInitialized() { // 在这里创建 WebGPU 资源…… } initializeWebGPU();
5. 缓冲区
5.1. GPUBuffer
GPUBuffer
表示一块可用于 GPU 操作的内存块。
数据以线性布局存储,这意味着分配的每个字节都可以通过其相对于 GPUBuffer
起始位置的偏移来寻址,
但具体操作可能有对齐限制。某些 GPUBuffers
可以被映射,使这块内存可以通过一个称为映射的 ArrayBuffer
访问。
GPUBuffer
通过 createBuffer()
创建。
缓冲区可以 mappedAtCreation
。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUBuffer {readonly attribute GPUSize64Out size ;readonly attribute GPUFlagsConstant usage ;readonly attribute GPUBufferMapState mapState ;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 ;enum GPUBufferMapState {"unmapped" ,"pending" ,"mapped" , };
mapState
, 类型为 GPUBufferMapState,只读-
缓冲区的当前
GPUBufferMapState
:"unmapped"
-
缓冲区未被
this
.getMappedRange()
映射使用。 "pending"
-
缓冲区已请求映射,但尚未完成。映射可能成功,也可能在
mapAsync()
校验时失败。 "mapped"
-
缓冲区已映射,可以通过
this
.getMappedRange()
使用。
getter 步骤如下:
内容时间线 步骤:-
如果 this.
[[mapping]]
不为null
,返回"mapped"
。 -
如果 this.
[[pending_map]]
不为null
,返回"pending"
。 -
返回
"unmapped"
。
[[pending_map]]
,类型为Promise
<void> 或null
,初始为null
-
当前挂起的
mapAsync()
调用返回的Promise
。永远不会有多个挂起的映射,因为如果已有请求在进行中,
mapAsync()
会立即拒绝。 [[mapping]]
,类型为 活动缓冲区映射 或null
,初始为null
-
仅当缓冲区当前被
getMappedRange()
映射使用时才设置。否则为 null(即使有[[pending_map]]
)。活动缓冲区映射 是具有以下字段的结构:
- data,类型为 数据块
-
本
GPUBuffer
的映射数据。应用通过ArrayBuffer
视图访问,由getMappedRange()
返回并存储在 views 中。 - mode,类型为
GPUMapModeFlags
-
映射的
GPUMapModeFlags
,由相应mapAsync()
或createBuffer()
调用指定。 - range,类型为元组 [
unsigned long long
,unsigned long long
] -
该
GPUBuffer
被映射的范围。 - views,类型为 list<
ArrayBuffer
> -
通过
getMappedRange()
返回给应用的ArrayBuffer
。这些视图会在unmap()
被调用时被追踪并分离。
要用 mode mode 和 range range 初始化活动缓冲区映射,执行以下 内容时间线 步骤:-
令 size 为 range[1] - range[0]。
-
令 data 为 ? CreateByteDataBlock(size)。
注意:这可能抛出RangeError
。 为了保证一致和可预测性:-
对于
new ArrayBuffer()
在某一时刻能成功的任意 size,此分配 也应 同时成功。 -
对于
new ArrayBuffer()
确定性 抛出RangeError
的任意 size,此分配 也应 抛出。
-
-
返回具有如下内容的 活动缓冲区映射:
[[internal state]]
-
缓冲区的当前内部状态:
5.1.1. GPUBufferDescriptor
dictionary GPUBufferDescriptor :GPUObjectDescriptorBase {required GPUSize64 size ;required GPUBufferUsageFlags usage ;boolean mappedAtCreation =false ; };
GPUBufferDescriptor
拥有以下成员:
size
, 类型为 GPUSize64-
缓冲区的字节大小。
usage
, 类型为 GPUBufferUsageFlags-
缓冲区允许的用法。
mappedAtCreation
, 类型为 boolean,默认值为false
-
如果为
true
,则缓冲区会以已映射状态创建,允许立即调用getMappedRange()
。 即使usage
不包含MAP_READ
或MAP_WRITE
,也可以设置mappedAtCreation
为true
。 这可用于设置缓冲区的初始数据。即使最终缓冲区创建失败,也保证看起来映射范围可读写直到其被解除映射。
5.1.2. 缓冲区用法
typedef [EnforceRange ]unsigned long ; [
GPUBufferUsageFlags Exposed =(Window ,Worker ),SecureContext ]namespace {
GPUBufferUsage const GPUFlagsConstant MAP_READ = 0x0001;const GPUFlagsConstant MAP_WRITE = 0x0002;const GPUFlagsConstant COPY_SRC = 0x0004;const GPUFlagsConstant COPY_DST = 0x0008;const GPUFlagsConstant INDEX = 0x0010;const GPUFlagsConstant VERTEX = 0x0020;const GPUFlagsConstant UNIFORM = 0x0040;const GPUFlagsConstant STORAGE = 0x0080;const GPUFlagsConstant INDIRECT = 0x0100;const GPUFlagsConstant QUERY_RESOLVE = 0x0200; };
GPUBufferUsage
标志决定了 GPUBuffer
创建后可以如何使用:
MAP_READ
-
缓冲区可被映射用于读取。(例如:调用
mapAsync()
并传入GPUMapMode.READ
)只能与
COPY_DST
组合使用。 MAP_WRITE
-
缓冲区可被映射用于写入。(例如:调用
mapAsync()
并传入GPUMapMode.WRITE
)只能与
COPY_SRC
组合使用。 COPY_SRC
-
缓冲区可作为拷贝操作的源。(例如:作为 copyBufferToBuffer() 或
copyBufferToTexture()
调用的source
参数) COPY_DST
-
缓冲区可作为拷贝或写入操作的目标。(例如:作为 copyBufferToBuffer() 或
copyTextureToBuffer()
调用的destination
参数,或作为writeBuffer()
的目标。) INDEX
-
缓冲区可作为索引缓冲区使用。(例如:传递给
setIndexBuffer()
。) VERTEX
-
缓冲区可作为顶点缓冲区使用。(例如:传递给
setVertexBuffer()
。) UNIFORM
-
缓冲区可用作 uniform 缓冲区。(例如:用于
GPUBufferBindingLayout
的绑定组条目,且buffer
.type
为"uniform"
。) STORAGE
-
缓冲区可用作 storage 缓冲区。(例如:用于
GPUBufferBindingLayout
的绑定组条目,且buffer
.type
为"storage"
或"read-only-storage"
。) INDIRECT
-
缓冲区可用于存储间接命令参数。(例如:作为
indirectBuffer
参数传递给drawIndirect()
或dispatchWorkgroupsIndirect()
调用。) QUERY_RESOLVE
-
缓冲区可用于捕获查询结果。(例如:作为
destination
参数传递给resolveQuerySet()
。)
5.1.3. 缓冲区创建
createBuffer(descriptor)
-
创建一个
GPUBuffer
。调用对象:GPUDevice
this。参数:
GPUDevice.createBuffer(descriptor) 方法的参数。 参数 类型 可为 null 可选 描述 descriptor
GPUBufferDescriptor
✘ ✘ 要创建的 GPUBuffer
描述信息。返回:
GPUBuffer
内容时间线 步骤:
-
令 b 为 ! 创建新的 WebGPU 对象(this,
GPUBuffer
, descriptor)。 -
如果 descriptor.
mappedAtCreation
为true
:-
如果 descriptor.
size
不是 4 的倍数,抛出RangeError
。 -
设置 b.
[[mapping]]
为 ? 初始化活动缓冲区映射,mode 为WRITE
,range 为[0, descriptor.
。size
]
-
-
在 this 的 设备时间线 上执行 初始化步骤。
-
返回 b。
设备时间线 初始化步骤:注意: 如果缓冲区创建失败,且 descriptor.
mappedAtCreation
为false
, 任何对mapAsync()
的调用都会被拒绝,因此为支持映射而分配的任何资源都可以被回收。-
如果 descriptor.
mappedAtCreation
为true
:-
设置 b.
[[internal state]]
为 "unavailable"。
否则:
-
设置 b.
[[internal state]]
为 "available"。
-
-
为 b 创建设备分配,并将每个字节置零。
-
const buffer= gpuDevice. createBuffer({ size: 128 , usage: GPUBufferUsage. UNIFORM| GPUBufferUsage. COPY_DST});
5.1.4. 缓冲区销毁
应用如果不再需要某个 GPUBuffer
,可以在垃圾回收前调用
destroy()
主动放弃访问它。
销毁缓冲区还会解除映射,释放为映射分配的内存。
注意: 这样允许用户代理在所有先前提交的与该 GPUBuffer
相关的操作完成后及时回收其 GPU 内存。
GPUBuffer
拥有以下方法:
destroy()
-
销毁该
GPUBuffer
。注意: 多次销毁同一个缓冲区是合法的。
设备时间线 步骤:-
设置 this.
[[internal state]]
为 "destroyed"。
注意: 由于无法继续用该缓冲区排队新操作,实现可以立即释放资源分配,包括刚刚解除映射的内存。
-
5.2. 缓冲区映射
应用可以请求映射 GPUBuffer
,从而通过代表该
GPUBuffer
分配部分的 ArrayBuffer
访问其内容。
映射 GPUBuffer
的请求是通过 mapAsync()
异步进行的,以便用户代理能确保 GPU 在应用访问内容前已完成对该 GPUBuffer
的使用。
被映射的 GPUBuffer
不能被
GPU 使用,必须通过 unmap()
解除映射后才能再次用于 队列时间线的工作提交。
一旦 GPUBuffer
被映射,应用可通过 getMappedRange()
同步访问其内容范围。
返回的 ArrayBuffer
只能被 unmap()
(直接或通过
GPUBuffer
.destroy()
或 GPUDevice
.destroy()
)分离,不能被转移。
任何其它操作试图这样做都会抛出 TypeError
。
typedef [EnforceRange ]unsigned long ; [
GPUMapModeFlags Exposed =(Window ,Worker ),SecureContext ]namespace {
GPUMapMode const GPUFlagsConstant READ = 0x0001;const GPUFlagsConstant WRITE = 0x0002; };
GPUMapMode
标志决定了调用 mapAsync()
时 GPUBuffer
被如何映射:
READ
-
只对创建时带有
MAP_READ
用法的缓冲区有效。映射后,调用
getMappedRange()
将返回包含缓冲区当前值的ArrayBuffer
。对返回的ArrayBuffer
的更改在unmap()
后会被丢弃。 WRITE
-
只对创建时带有
MAP_WRITE
用法的缓冲区有效。映射后,调用
getMappedRange()
将返回包含缓冲区当前值的ArrayBuffer
。对返回的ArrayBuffer
的更改会在unmap()
后写入缓冲区。注意: 由于
MAP_WRITE
用法只能与COPY_SRC
组合,写映射永远不会返回 GPU 产生的数据,返回的ArrayBuffer
只包含初始化为零的数据或网页之前映射写入的数据。
GPUBuffer
拥有以下方法:
mapAsync(mode, offset, size)
-
映射
GPUBuffer
的指定范围,并在缓冲区内容可以通过getMappedRange()
访问时 resolve 返回的Promise
。返回的
Promise
仅表示缓冲区已被映射,不保证其它 内容时间线可见操作完成,特别是不保证其它Promise
(如onSubmittedWorkDone()
或其它mapAsync()
)已 resolve。而
Promise
由onSubmittedWorkDone()
返回则保证在该队列上之前的所有mapAsync()
已完成。调用对象:GPUBuffer
this。参数:
GPUBuffer.mapAsync(mode, offset, size) 方法的参数。 参数 类型 可为 null 可选 描述 mode
GPUMapModeFlags
✘ ✘ 缓冲区应以读或写方式映射。 offset
GPUSize64
✘ ✔ 要映射的范围起始字节偏移。 size
GPUSize64
✘ ✔ 要映射的范围字节大小。 内容时间线步骤:
-
令 contentTimeline 为当前 内容时间线。
-
若 this.
mapState
不为"unmapped"
:-
在 this.
[[device]]
的 设备时间线 上执行 early-reject steps。 -
返回 被拒绝的 promise,错误为
OperationError
。
-
-
令 p 为新的
Promise
。 -
设置 this.
[[pending_map]]
= p。 -
在 this.
[[device]]
的 设备时间线 上执行 validation steps。 -
返回 p。
设备时间线 validation steps:-
如果 size 为
undefined
:-
令 rangeSize = max(0, this.
size
- offset)。
否则:
-
令 rangeSize = size。
-
-
如果下述任一条件不满足:
-
this 必须是 有效的。
-
设置 deviceLost 为
true
。 -
在 contentTimeline 上执行 map failure steps。
-
返回。
-
-
如果下述任一条件不满足:
否则:
-
设置 deviceLost 为
false
。 -
在 contentTimeline 上执行 map failure steps。
-
返回。
-
-
将 this.
[[internal state]]
设为 "unavailable"。注意: 缓冲区被映射后,在解除映射前其内容不会改变。
-
当下述任一事件发生(以先发生者为准),或已发生时:
-
-
在所有当前排队并使用 this 的操作完成后
-
且不晚于所有当前排队操作(不论是否使用 this)完成时
-
-
this.
[[device]]
丢失。
然后在 this.
[[device]]
的 设备时间线 上执行后续步骤。 -
设备时间线 步骤:-
若 this.
[[device]]
已失效,则 deviceLost 设为true
,否则为false
。注意: 设备可能在前后步骤之间丢失。
-
如果 deviceLost:
-
在 contentTimeline 上执行 map failure steps。
否则:
-
令 internalStateAtCompletion = this.
[[internal state]]
。注意: 只有当此时缓冲区因
unmap()
变为 "available" 时,[[pending_map]]
≠ p,后续 mapping 步骤不会成功。 -
令 dataForMappedRegion 为 this 从 offset 开始,长度为 rangeSize 字节的内容。
-
在 contentTimeline 上执行 map success steps。
-
内容时间线 map success steps:-
若 this.
[[pending_map]]
≠ p:注意: 映射已被
unmap()
取消。-
断言 p 已被拒绝。
-
返回。
-
-
断言 p 仍为 pending。
-
断言 internalStateAtCompletion 为 "unavailable"。
-
令 mapping = 初始化活动缓冲区映射,mode 为 mode,range 为
[offset, offset + rangeSize]
。若分配失败:
-
设 this.
[[pending_map]]
=null
,并 拒绝 p,错误为RangeError
。 -
返回。
-
-
将 mapping.data 设为 dataForMappedRegion。
-
设 this.
[[mapping]]
= mapping。 -
设 this.
[[pending_map]]
=null
,并 resolve p。
内容时间线 map failure steps:-
如果 this.
[[pending_map]]
≠ p:注意: 映射已被
unmap()
取消。-
断言 p 已被拒绝。
-
返回。
-
-
断言 p 仍为 pending。
-
设 this.
[[pending_map]]
=null
。 -
如果 deviceLost:
-
拒绝 p 并抛出
AbortError
。注意: 这和用
unmap()
取消 map 时抛出的错误类型一致。
否则:
-
拒绝 p 并抛出
OperationError
。
-
-
getMappedRange(offset, size)
-
返回包含指定范围
GPUBuffer
内容的ArrayBuffer
。调用对象:GPUBuffer
this。参数:
GPUBuffer.getMappedRange(offset, size) 方法的参数。 参数 类型 可为 null 可选 描述 offset
GPUSize64
✘ ✔ 要返回内容的起始字节偏移。 size
GPUSize64
✘ ✔ 要返回的 ArrayBuffer
字节长度。返回值:
ArrayBuffer
内容时间线 步骤:
-
如果 size 未指定:
-
令 rangeSize = max(0, this.
size
- offset)。
否则,rangeSize = size。
-
-
如以下任一条件不满足,则抛出
OperationError
并返回:-
this.
[[mapping]]
不为null
。 -
offset 为 8 的倍数。
-
rangeSize 为 4 的倍数。
-
offset ≥ this.
[[mapping]]
.range[0]。 -
offset + rangeSize ≤ this.
[[mapping]]
.range[1]。 -
[offset, offset + rangeSize) 不与 this.
[[mapping]]
.views 中的其它范围重叠。
注意: 对
GPUBuffer
,即使其为mappedAtCreation
且 无效,只要 内容时间线 未知其无效,依然可以获取映射范围。 -
-
令 data = this.
[[mapping]]
.data。 -
令 view = 创建 ArrayBuffer,大小为 rangeSize,指针可变地引用 data 从 (offset -
[[mapping]]
.range[0]) 开始的内容。注意: 这里不会抛出
RangeError
,因为 data 已在mapAsync()
或createBuffer()
时分配。 -
设置 view.
[[ArrayBufferDetachKey]]
为 "WebGPUBufferMapping"。 -
追加 view 到 this.
[[mapping]]
.views。 -
返回 view。
注意: 若
getMappedRange()
调用未先检查映射状态(如等待mapAsync()
resolve、查询mapState
为"mapped"
或等待onSubmittedWorkDone()
),用户代理应考虑发出开发警告。 -
unmap()
-
解除
GPUBuffer
的映射范围,使其内容重新可被 GPU 使用。调用对象:GPUBuffer
this。返回值:
undefined
内容时间线 步骤:
-
如果 this.
[[pending_map]]
不为null
:-
拒绝 this.
[[pending_map]]
,错误为AbortError
。 -
设 this.
[[pending_map]]
=null
。
-
-
如果 this.
[[mapping]]
为null
:-
返回。
-
-
对于 this.
[[mapping]]
.views 中的每个ArrayBuffer
ab:-
执行 DetachArrayBuffer(ab, "WebGPUBufferMapping")。
-
-
令 bufferUpdate =
null
。 -
如果 this.
[[mapping]]
.mode 包含WRITE
:-
设 bufferUpdate = {
data
: this.[[mapping]]
.data,offset
: this.[[mapping]]
.range[0] }。
注意: 如果缓冲区不是以
WRITE
模式映射,解除映射时应用对映射范围ArrayBuffer
的本地修改会被丢弃,不会影响后续映射内容。 -
-
设 this.
[[mapping]]
=null
。 -
在 this.
[[device]]
的 设备时间线 上执行后续步骤。
设备时间线 步骤:-
如下条件任一不满足则返回:
-
this 可与 this.
[[device]]
安全配合使用。
-
-
断言 this.
[[internal state]]
为 "unavailable"。 -
如果 bufferUpdate 不为
null
:-
在 this.
[[device]]
.queue
的 队列时间线 上执行:队列时间线 步骤:-
用 bufferUpdate.
data
更新 this 从 bufferUpdate.offset
开始的内容。
-
-
-
将 this.
[[internal state]]
设为 "available"。
-
6. 纹理与纹理视图
6.1. GPUTexture
纹理(texture)
由 1d
、
2d
或
3d
的数据数组组成,每个元素可包含多个值用于表示如颜色等信息。纹理的读写方式取决于创建时使用的
GPUTextureUsage
。
例如,纹理可被采样、读写于渲染与计算管线着色器,也可由渲染通道输出写入。纹理在 GPU 内部通常以多维访问优化的布局存储,而非线性存储。
一个 纹理 由一个或多个
纹理子资源(texture
subresource)
组成,每个子资源由 mipmap 级别 唯一标识,
对于 2d
纹理,还包括 数组层 和 aspect(分量)。
纹理子资源 是一种 子资源:每个子资源可在单一 用法范围 内有不同 内部用途。
每个 mipmap 级别 的子资源
在每个空间维度上的尺寸大约是上一级资源的一半
(见 mipmap 级别特定逻辑纹理范围)。
0 级子资源的尺寸等于纹理本身的尺寸,更小的级别通常用于存储同一图像的低分辨率版本。
GPUSampler
与 WGSL 提供了选择与插值 细节级别
的能力,可显式或自动进行。
"2d"
纹理可以是 数组层(array layer)
的集合。
每一层的子资源尺寸都相同。非 2d 纹理的所有子资源的数组层索引都为 0。
每个子资源有一个 aspect(分量)。
彩色纹理只有一个分量:color。
深度或模板格式
的纹理可能有多个分量:
depth 分量,
stencil 分量,或两者皆有,
可被特殊用法所使用,如 depthStencilAttachment
和 "depth"
绑定。
"3d"
纹理可以有多个 切片(slice),每个切片是该纹理在特定
z
值下的二维图像。
切片不是独立的子资源。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUTexture {GPUTextureView createView (optional GPUTextureViewDescriptor descriptor = {});undefined destroy ();readonly attribute GPUIntegerCoordinateOut width ;readonly attribute GPUIntegerCoordinateOut height ;readonly attribute GPUIntegerCoordinateOut depthOrArrayLayers ;readonly attribute GPUIntegerCoordinateOut mipLevelCount ;readonly attribute GPUSize32Out sampleCount ;readonly attribute GPUTextureDimension dimension ;readonly attribute GPUTextureFormat format ;readonly attribute GPUFlagsConstant usage ; };GPUTexture includes GPUObjectBase ;
GPUTexture
拥有如下不可变属性:
width
,类型为 GPUIntegerCoordinateOut,只读-
该
GPUTexture
的宽度。 height
,类型为 GPUIntegerCoordinateOut,只读-
该
GPUTexture
的高度。 depthOrArrayLayers
,类型为 GPUIntegerCoordinateOut,只读-
该
GPUTexture
的深度或层数。 mipLevelCount
,类型为 GPUIntegerCoordinateOut,只读-
该
GPUTexture
的 mip 级别数量。 sampleCount
,类型为 GPUSize32Out,只读-
该
GPUTexture
的采样数。 dimension
,类型为 GPUTextureDimension,只读-
每个子资源的 texel 集的维度。
format
,类型为 GPUTextureFormat,只读-
该
GPUTexture
的格式。 usage
,类型为 GPUFlagsConstant,只读-
该
GPUTexture
允许的用途。 [[viewFormats]]
,类型为 sequence<GPUTextureFormat
>-
为此
GPUTexture
创建视图时可用作GPUTextureViewDescriptor
.format
的GPUTextureFormat
集合。
GPUTexture
拥有如下设备时间线属性:
[[destroyed]]
,类型为boolean
, 初始值为false
-
如果纹理被销毁,它将无法再被用于任何操作,其底层内存可以被释放。
参数:
-
GPUExtent3D
baseSize -
GPUSize32
mipLevel
返回: GPUExtent3DDict
设备时间线步骤:
-
令 extent 为新的
GPUExtent3DDict
对象。 -
设置 extent.
depthOrArrayLayers
为 1。 -
返回 extent。
逻辑 mip 级别特定纹理范围(logical miplevel-specific texture extent) 指的是某个 纹理 在特定 mipLevel 下的 texel 尺寸。 其计算过程如下:
参数:
-
GPUTextureDescriptor
descriptor -
GPUSize32
mipLevel
返回: GPUExtent3DDict
-
令 extent 为新的
GPUExtent3DDict
对象。 -
如果 descriptor.
dimension
为:"1d"
-
-
设 extent.
height
= 1 -
设 extent.
depthOrArrayLayers
= 1
"2d"
-
-
设 extent.
depthOrArrayLayers
= descriptor.size
.depthOrArrayLayers
"3d"
-
-
设 extent.
depthOrArrayLayers
= max(1, descriptor.size
.depthOrArrayLayers ≫ mipLevel)
-
返回 extent。
物理 mip 级别特定纹理范围(physical miplevel-specific texture extent) 指的是某个 纹理 在特定 mipLevel 下的 texel 尺寸,并包含为形成完整texel block而可能补齐的额外填充。其计算过程如下:
参数:
-
GPUTextureDescriptor
descriptor -
GPUSize32
mipLevel
返回: GPUExtent3DDict
-
令 extent 为新的
GPUExtent3DDict
对象。 -
令 logicalExtent = 逻辑 mip 级别特定纹理范围(descriptor, mipLevel)。
-
如果 descriptor.
dimension
为:"1d"
-
-
设 extent.
width
为 logicalExtent.width 向上取整到 descriptor 的 texel block width 的倍数。 -
设 extent.
height
= 1 -
设 extent.
depthOrArrayLayers
= 1
-
"2d"
-
-
设 extent.
width
为 logicalExtent.width 向上取整到 descriptor 的 texel block width 的倍数。 -
设 extent.
height
为 logicalExtent.height 向上取整到 descriptor 的 texel block height 的倍数。 -
设 extent.
depthOrArrayLayers
= logicalExtent.depthOrArrayLayers
-
"3d"
-
-
设 extent.
width
为 logicalExtent.width 向上取整到 descriptor 的 texel block width 的倍数。 -
设 extent.
height
为 logicalExtent.height 向上取整到 descriptor 的 texel block height 的倍数。 -
设 extent.
depthOrArrayLayers
= logicalExtent.depthOrArrayLayers
-
-
返回 extent。
6.1.1. GPUTextureDescriptor
dictionary GPUTextureDescriptor :GPUObjectDescriptorBase {required GPUExtent3D size ;GPUIntegerCoordinate mipLevelCount = 1;GPUSize32 sampleCount = 1;GPUTextureDimension dimension = "2d";required GPUTextureFormat format ;required GPUTextureUsageFlags usage ;sequence <GPUTextureFormat >viewFormats = []; };
GPUTextureDescriptor
拥有如下成员:
size
, 类型为 GPUExtent3D-
纹理的宽度、高度和深度或层数。
mipLevelCount
,类型为 GPUIntegerCoordinate,默认值为1
-
该纹理包含的 mip 级别数量。
sampleCount
,类型为 GPUSize32,默认值为1
-
纹理的采样数。当
sampleCount
>1
时,表示为多重采样纹理。 dimension
,类型为 GPUTextureDimension,默认值为"2d"
-
指定纹理是一维、二维数组层,还是三维纹理。
format
,类型为 GPUTextureFormat-
纹理的格式。
usage
,类型为 GPUTextureUsageFlags-
纹理允许的用途。
viewFormats
,类型为 sequence<GPUTextureFormat>,默认值为[]
-
指定在该纹理上调用
createView()
时,允许作为format
的格式(除了纹理实际的format
外)。注意:添加格式到该列表可能会带来显著的性能影响,因此应避免不必要地添加格式。实际的性能影响高度依赖于目标系统;开发者需在多种系统上测试应用以了解具体影响。例如,在某些系统上,
format
或viewFormats
包含"rgba8unorm-srgb"
时, 性能可能不如仅包含"rgba8unorm"
的纹理。其他格式和格式组合在不同系统上也有类似注意事项。该列表的格式必须与纹理格式 兼容。
两个GPUTextureFormat
, format 和 viewFormat,当且仅当满足以下条件时,纹理视图格式兼容(texture view format compatible):-
format 等于 viewFormat,或
-
format 与 viewFormat 唯一区别在于是否为
srgb
格式(后缀为-srgb
)。
-
enum {
GPUTextureDimension "1d" ,"2d" ,"3d" , };
"1d"
-
指定仅有宽度的一维纹理。
"1d"
纹理不能有 mipmap,不能多重采样,不能使用压缩或深度/模板格式,也不能作为渲染目标。 "2d"
-
指定具有宽度和高度,并可具有层的二维纹理。
"3d"
-
指定具有宽度、高度和深度的三维纹理。
"3d"
纹理不能多重采样,且其格式必须支持 3d 纹理(所有纯色格式和部分打包/压缩格式)。
6.1.2. 纹理用法
typedef [EnforceRange ]unsigned long ; [
GPUTextureUsageFlags Exposed =(Window ,Worker ),SecureContext ]namespace {
GPUTextureUsage const GPUFlagsConstant COPY_SRC = 0x01;const GPUFlagsConstant COPY_DST = 0x02;const GPUFlagsConstant TEXTURE_BINDING = 0x04;const GPUFlagsConstant STORAGE_BINDING = 0x08;const GPUFlagsConstant RENDER_ATTACHMENT = 0x10; };
GPUTextureUsage
标志决定 GPUTexture
创建后可如何使用:
COPY_SRC
-
该纹理可作为拷贝操作的源。(例如:作为
source
参数传递给copyTextureToTexture()
或copyTextureToBuffer()
调用。) COPY_DST
-
该纹理可作为拷贝或写入操作的目标。(例如:作为
destination
参数传递给copyTextureToTexture()
或copyBufferToTexture()
调用,或作为writeTexture()
的目标。) TEXTURE_BINDING
-
该纹理可在着色器中作为采样纹理绑定(例如:作为
GPUTextureBindingLayout
的绑定组项)。 STORAGE_BINDING
-
该纹理可在着色器中作为存储纹理绑定(例如:作为
GPUStorageTextureBindingLayout
的绑定组项)。 RENDER_ATTACHMENT
-
该纹理可作为渲染通道中的颜色或深度/模板附件使用。(例如:作为
GPURenderPassColorAttachment
.view
或GPURenderPassDepthStencilAttachment
.view
。)
参数:
-
GPUTextureDimension
dimension -
GPUTextureDimension
size
6.1.3. 纹理创建
createTexture(descriptor)
-
创建一个
GPUTexture
。调用对象:GPUDevice
this.参数:
参数列表: GPUDevice.createTexture(descriptor) 参数 类型 可为 null 可选 描述 descriptor
GPUTextureDescriptor
✘ ✘ 描述要创建的 GPUTexture
。返回值:
GPUTexture
内容时间线步骤:
-
? 校验 GPUExtent3D 形状(descriptor.
size
)。 -
? 校验纹理格式所需特性 (descriptor.
format
, this.[[device]]
)。 -
? 校验纹理格式所需特性 (对 descriptor.
viewFormats
的每一项, this.[[device]]
)。 -
令 t = ! 创建新的 WebGPU 对象(this,
GPUTexture
, descriptor)。 -
设 t.
depthOrArrayLayers
= descriptor.size
.depthOrArrayLayers。 -
设 t.
mipLevelCount
= descriptor.mipLevelCount
。 -
设 t.
sampleCount
= descriptor.sampleCount
。 -
在 this 的 设备时间线上执行初始化步骤。
-
返回 t。
设备时间线 初始化步骤:-
-
validating GPUTextureDescriptor(this, descriptor) 返回
true
。
-
-
设 t.
[[viewFormats]]
= descriptor.viewFormats
。 -
为 t 创建设备分配,使每个块具有与全零比特表示的块等价的 texel 表示。
-
参数:
-
GPUDevice
this -
GPUTextureDescriptor
descriptor
设备时间线步骤:
-
令 limits = this.
[[limits]]
。 -
仅当所有如下要求都满足时返回
true
,否则返回false
:-
this 不得为 lost。
-
descriptor.
usage
不得为 0。 -
descriptor.
size
.width、 descriptor.size
.height 和 descriptor.size
.depthOrArrayLayers 必须均大于零。 -
descriptor.
mipLevelCount
必须大于零。 -
descriptor.
sampleCount
必须为 1 或 4。 -
如果 descriptor.
dimension
为:"1d"
-
-
descriptor.
size
.width ≤ limits.maxTextureDimension1D
。 -
descriptor.
size
.depthOrArrayLayers 必须为 1。 -
descriptor.
sampleCount
必须为 1。
-
"2d"
-
-
descriptor.
size
.width ≤ limits.maxTextureDimension2D
。 -
descriptor.
size
.height ≤ limits.maxTextureDimension2D
。 -
descriptor.
size
.depthOrArrayLayers ≤ limits.maxTextureArrayLayers
。
-
"3d"
-
-
descriptor.
size
.width ≤ limits.maxTextureDimension3D
。 -
descriptor.
size
.height ≤ limits.maxTextureDimension3D
。 -
descriptor.
size
.depthOrArrayLayers ≤ limits.maxTextureDimension3D
。 -
descriptor.
sampleCount
必须为 1。 -
descriptor.
format
必须支持"3d"
纹理(参见 § 26.1 纹理格式能力)。
-
-
descriptor.
size
.width 必须是 texel block width 的倍数。 -
descriptor.
size
.height 必须是 texel block height 的倍数。 -
如果 descriptor.
sampleCount
> 1:-
descriptor.
mipLevelCount
必须为 1。 -
descriptor.
size
.depthOrArrayLayers 必须为 1。 -
descriptor.
usage
不得包含STORAGE_BINDING
位。 -
descriptor.
usage
必须包含RENDER_ATTACHMENT
位。 -
descriptor.
format
必须支持多重采样(参见 § 26.1 纹理格式能力)。
-
-
descriptor.
mipLevelCount
必须小于等于 最大 mipLevel 数量(descriptor.dimension
, descriptor.size
)。 -
如果 descriptor.
usage
包含RENDER_ATTACHMENT
位: -
如果 descriptor.
usage
包含STORAGE_BINDING
位:-
descriptor.
format
必须在 § 26.1.1 纯色格式表格中有STORAGE_BINDING
支持(至少一种访问模式)。
-
-
对于 descriptor.
viewFormats
中的每个 viewFormat,descriptor.format
与 viewFormat 必须纹理视图格式兼容。注意:如果 viewFormat 与任何usage
位均不兼容, 实现可考虑发出开发者可见的警告,因为该 viewFormat 将不可用。
-
const texture= gpuDevice. createTexture({ size: { width: 16 , height: 16 }, format: 'rgba8unorm' , usage: GPUTextureUsage. TEXTURE_BINDING, });
6.1.4. 纹理销毁
当应用不再需要某个 GPUTexture
时,可以通过调用 destroy()
主动失去对此对象的访问权,而无需等待垃圾回收。
注意: 这样允许用户代理在该 GPUTexture
相关的所有已提交操作完成后,回收其占用的 GPU 内存。
GPUTexture
拥有如下方法:
destroy()
-
销毁该
GPUTexture
。设备时间线步骤:-
将 this.
[[destroyed]]
设为 true。
-
6.2. GPUTextureView
GPUTextureView
是对某个 纹理子资源
子集的视图,由特定 GPUTexture
定义。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUTextureView { };GPUTextureView includes GPUObjectBase ;
GPUTextureView
拥有如下不可变属性:
[[texture]]
,只读-
该视图所属的
GPUTexture
。 [[descriptor]]
,只读-
描述此纹理视图的
GPUTextureViewDescriptor
。所有
GPUTextureViewDescriptor
的可选字段都有定义。 [[renderExtent]]
,只读-
对于可渲染视图,这是渲染时实际使用的
GPUExtent3DDict
。注意:该范围取决于
baseMipLevel
。
[[descriptor]]
为 desc,
是 view.[[texture]]
的子资源子集,其中每个子资源 s 满足:
-
s 的mipmap 级别满足:
≥ desc.
baseMipLevel
且 < desc.baseMipLevel
+ desc.mipLevelCount
。 -
s 的数组层满足:
≥ desc.
baseArrayLayer
且 < desc.baseArrayLayer
+ desc.arrayLayerCount
。
只有当两个 GPUTextureView
的子资源集合有交集时,它们才 视图别名(texture-view-aliasing)。
6.2.1. 纹理视图创建
dictionary :
GPUTextureViewDescriptor GPUObjectDescriptorBase {GPUTextureFormat format ;GPUTextureViewDimension dimension ;GPUTextureUsageFlags usage = 0;GPUTextureAspect aspect = "all";GPUIntegerCoordinate baseMipLevel = 0;GPUIntegerCoordinate mipLevelCount ;GPUIntegerCoordinate baseArrayLayer = 0;GPUIntegerCoordinate arrayLayerCount ; };
GPUTextureViewDescriptor
拥有如下成员:
format
,类型为 GPUTextureFormat-
纹理视图的格式。必须是纹理的
format
或创建时指定的viewFormats
之一。 dimension
,类型为 GPUTextureViewDimension-
视图的维度。
usage
,类型为 GPUTextureUsageFlags,默认值为0
aspect
,类型为 GPUTextureAspect,默认值为"all"
-
视图可访问的纹理
aspect
。 baseMipLevel
,类型为 GPUIntegerCoordinate,默认值为0
-
该视图可访问的第一个(最详细) mipmap 级别。
mipLevelCount
,类型为 GPUIntegerCoordinate-
从
baseMipLevel
开始,该视图可访问的 mipmap 级别数量。 baseArrayLayer
,类型为 GPUIntegerCoordinate,默认值为0
-
该视图可访问的第一个数组层索引。
arrayLayerCount
,类型为 GPUIntegerCoordinate-
从
baseArrayLayer
开始,该视图可访问的数组层数量。
enum {
GPUTextureViewDimension "1d" ,"2d" ,"2d-array" ,"cube" ,"cube-array" ,"3d" , };
"1d"
-
该视图作为一维图像。
对应的 WGSL 类型:
-
texture_1d
-
texture_storage_1d
-
"2d"
-
该视图作为单一的二维图像。
对应的 WGSL 类型:
-
texture_2d
-
texture_storage_2d
-
texture_multisampled_2d
-
texture_depth_2d
-
texture_depth_multisampled_2d
-
"2d-array"
-
该视图作为二维图像数组。
对应的 WGSL 类型:
-
texture_2d_array
-
texture_storage_2d_array
-
texture_depth_2d_array
-
"cube"
-
该视图作为立方体贴图。
该视图有 6 个数组层,分别对应立方体的 6 个面,顺序为
[+X, -X, +Y, -Y, +Z, -Z]
,朝向如下:立方体贴图各面。+U/+V 轴表示各面纹理坐标,也即每个面的 texel copy 内存布局。 注意:从内部看,这是一个左手坐标系,+X 右,+Y 上,+Z 前。
采样时会在立方体各面间无缝进行。
对应的 WGSL 类型:
-
texture_cube
-
texture_depth_cube
-
"cube-array"
-
该视图作为 n 个立方体贴图的打包数组,每个立方体 6 个数组层,总共 6n 层。
对应的 WGSL 类型:
-
texture_cube_array
-
texture_depth_cube_array
-
"3d"
-
该视图作为三维图像。
对应的 WGSL 类型:
-
texture_3d
-
texture_storage_3d
-
每个 GPUTextureAspect
值对应一组 aspect。aspect 集合如下定义:
enum GPUTextureAspect {"all" ,"stencil-only" ,"depth-only" , };
"all"
-
纹理格式的所有可用 aspect 都可被该视图访问。对于颜色格式,可访问 color aspect。对于深度-模板复合格式,可访问 depth 和 stencil 两个 aspect。只有单一 aspect 的深度或模板格式,仅可访问该 aspect。
"stencil-only"
-
仅可访问深度或模板格式的 stencil aspect。
"depth-only"
-
仅可访问深度或模板格式的 depth aspect。
createView(descriptor)
-
创建一个
GPUTextureView
。注意:默认情况下,createView()
会创建一个可以表示整个纹理的视图。例如,在一个具有多个图层的"2d"
纹理上调用createView()
且未指定dimension
时,将会创建一个"2d-array"
GPUTextureView
, 即使指定了arrayLayerCount
为 1。对于那些在开发时无法确定图层数的来源创建的纹理,建议在调用
createView()
时显式提供dimension
,以确保着色器兼容性。调用对象:GPUTexture
this。参数:
参数列表: GPUTexture.createView(descriptor) 参数 类型 可为 null 可选 描述 descriptor
GPUTextureViewDescriptor
✘ ✔ 要创建的 GPUTextureView
的描述。返回值: view,类型为
GPUTextureView
。内容时间线步骤:
-
? 校验纹理格式所需特性(descriptor.
format
, this.[[device]]
)。 -
令 view = ! 创建新的 WebGPU 对象(this,
GPUTextureView
, descriptor)。 -
在 this 的 设备时间线上执行初始化步骤。
-
返回 view。
设备时间线 初始化步骤:-
将 descriptor 设为对 this 和 descriptor 执行 解析 GPUTextureViewDescriptor 默认值 的结果。
-
如下条件有任一不满足,产生校验错误,置为无效并返回 view。
-
this 可用于 valid to use with this.
[[device]]
。 -
-
descriptor.
format
必须等于 this.format
或 this.[[viewFormats]]
中的某一项。
否则:
-
descriptor.
format
必须等于 解析 GPUTextureAspect(this.format
, descriptor.aspect
) 的结果。
-
-
如果 descriptor.
usage
包含RENDER_ATTACHMENT
位: -
如果 descriptor.
usage
包含STORAGE_BINDING
位:-
descriptor.
format
必须在 § 26.1.1 纯色格式表格中有STORAGE_BINDING
支持(至少一种访问模式)。
-
-
descriptor.
mipLevelCount
必须大于 0。 -
descriptor.
baseMipLevel
+ descriptor.mipLevelCount
必须 ≤ this.mipLevelCount
。 -
descriptor.
arrayLayerCount
必须大于 0。 -
descriptor.
baseArrayLayer
+ descriptor.arrayLayerCount
必须 ≤ array layer count。 -
如 this.
sampleCount
> 1,descriptor.dimension
必须为"2d"
。 -
如 descriptor.
dimension
为:"1d"
-
-
descriptor.
arrayLayerCount
必须为1
。
"2d"
-
-
descriptor.
arrayLayerCount
必须为1
。
"2d-array"
"cube"
-
-
descriptor.
arrayLayerCount
必须为6
。
"cube-array"
-
-
descriptor.
arrayLayerCount
必须为6
的倍数。
"3d"
-
-
descriptor.
arrayLayerCount
必须为1
。
-
-
令 view 为新的
GPUTextureView
对象。 -
设 view.
[[texture]]
= this。 -
设 view.
[[descriptor]]
= descriptor。 -
如 descriptor.
usage
包含RENDER_ATTACHMENT
:-
令 renderExtent = 计算渲染范围([this.
width
, this.height
, this.depthOrArrayLayers
], descriptor.baseMipLevel
)。 -
设 view.
[[renderExtent]]
= renderExtent。
-
-
GPUTextureView
texture 和 GPUTextureViewDescriptor
descriptor 执行 解析 GPUTextureViewDescriptor 默认值
时,执行如下设备时间线步骤:
-
令 resolved 为 descriptor 的副本。
-
如果 resolved.
mipLevelCount
未提供: 设置 resolved.mipLevelCount
= texture.mipLevelCount
− resolved.baseMipLevel
。 -
如果 resolved.
arrayLayerCount
未提供,且 resolved.dimension
为:"1d"
、"2d"
、或"3d"
-
设置 resolved.
arrayLayerCount
=1
。 "cube"
-
设置 resolved.
arrayLayerCount
=6
。 "2d-array"
或"cube-array"
-
设置 resolved.
arrayLayerCount
= array layer count(texture) − resolved.baseArrayLayer
。
-
返回 resolved。
GPUTexture
texture 的 array layer count,执行如下步骤:
-
若 texture.
dimension
为:"1d"
或"3d"
-
返回
1
。 "2d"
-
返回 texture.
depthOrArrayLayers
。
6.3. 纹理格式
格式名称指定了分量顺序、每个分量的位数和分量的数据类型。
-
r
、g
、b
、a
= 红、绿、蓝、alpha -
unorm
= 无符号归一化 -
snorm
= 有符号归一化 -
uint
= 无符号整型 -
sint
= 有符号整型 -
float
= 浮点型
如果格式带有 -srgb
后缀,则在着色器中读取和写入颜色值时会应用 sRGB 的 gamma 到线性及其反向转换。压缩纹理格式由 特性 提供。命名应遵循此约定,以纹理名称为前缀,例如 etc2-rgba8unorm
。
texel block(像素块)是像素格式
GPUTextureFormat
下纹理的单一可寻址元素,在区块压缩格式下为单一压缩块。
texel block width(像素块宽度)和 texel block height(像素块高度)指定了一个像素块的尺寸。
-
对于像素格式的
GPUTextureFormat
,像素块宽度和像素块高度总是 1。 -
对于区块压缩的
GPUTextureFormat
,像素块宽度为每个像素块一行的像素数,像素块高度为一块中的行数。详见§ 26.1 纹理格式能力,包含所有格式的取值列表。
texel block copy
footprint指的是某个GPUTextureFormat
中某aspect在像素块拷贝时所占字节数(如适用)。
注意:
像素块内存开销是指存储一个GPUTextureFormat
像素块所需的字节数。不是所有格式都完全定义此值。该值仅作参考,非规范性内容。
enum { // 8-bit formats
GPUTextureFormat ,
"r8unorm" ,
"r8snorm" ,
"r8uint" , // 16-bit formats
"r8sint" ,
"r16unorm" ,
"r16snorm" ,
"r16uint" ,
"r16sint" ,
"r16float" ,
"rg8unorm" ,
"rg8snorm" ,
"rg8uint" , // 32-bit formats
"rg8sint" ,
"r32uint" ,
"r32sint" ,
"r32float" ,
"rg16unorm" ,
"rg16snorm" ,
"rg16uint" ,
"rg16sint" ,
"rg16float" ,
"rgba8unorm" ,
"rgba8unorm-srgb" ,
"rgba8snorm" ,
"rgba8uint" ,
"rgba8sint" ,
"bgra8unorm" , // Packed 32-bit formats
"bgra8unorm-srgb" ,
"rgb9e5ufloat" ,
"rgb10a2uint" ,
"rgb10a2unorm" , // 64-bit formats
"rg11b10ufloat" ,
"rg32uint" ,
"rg32sint" ,
"rg32float" ,
"rgba16unorm" ,
"rgba16snorm" ,
"rgba16uint" ,
"rgba16sint" , // 128-bit formats
"rgba16float" ,
"rgba32uint" ,
"rgba32sint" , // Depth/stencil formats
"rgba32float" ,
"stencil8" ,
"depth16unorm" ,
"depth24plus" ,
"depth24plus-stencil8" , // "depth32float-stencil8" feature
"depth32float" , // 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"
"depth24plus"
和 "depth24plus-stencil8"
格式的 depth 分量可以实现为 24 位深度值,也可以实现为
"depth32float"
值。
stencil8
格式可以实现为真正的 "stencil8",也可以实现为 "depth24stencil8"(此时 depth aspect 是隐藏且不可访问的)。
-
对于 24 位深度,1 ULP 恒等于 1 / (224 − 1)。
-
对于 depth32float,1 ULP 可变,但不会大于 1 / (224)。
格式为 可渲染(renderable)格式,若其为 颜色可渲染格式,或为深度或模板格式。
若某格式在 § 26.1.1 普通颜色格式 中标记了 RENDER_ATTACHMENT
能力,则为颜色可渲染格式。其它格式不是颜色可渲染格式。所有深度或模板格式均为可渲染格式。
可渲染格式若可与渲染管线混合(blending)使用,则也是 可混合(blendable)格式。详见 § 26.1 纹理格式能力。
格式为 可过滤(filterable)格式,若其支持 GPUTextureSampleType
的 "float"
(不只是
"unfilterable-float"
),即该格式可用于
"filtering"
类型 GPUSampler
。详见
§ 26.1 纹理格式能力。
参数:
-
GPUTextureFormat
format -
GPUTextureAspect
aspect
返回值: GPUTextureFormat
或 null
-
若 aspect 为:
"all"
-
返回 format。
"depth-only"
"stencil-only"
-
若 format 为 depth-stencil-format: 返回 aspect-specific format,详见 § 26.1.2 深度/模板格式;如该 format 不含此 aspect,返回
null
。
-
返回
null
。
某些纹理格式的使用需要在 GPUDevice
上启用特性。由于新格式可添加到规范中,所以实现可能不知道这些枚举值。为保证一致性,尝试在未启用相关特性的设备上使用需要特性的格式时会抛出异常,这与实现本身不识别该格式时行为一致。
见 § 26.1 纹理格式能力,了解哪些 GPUTextureFormat
需要特性支持。
GPUTextureFormat
format, 逻辑device
device)
-
若 format 需要特性且 device.
[[features]]
不包含该特性:-
抛出
TypeError
。
-
6.4. GPUExternalTexture
GPUExternalTexture
是一个可采样的二维纹理,用于封装外部视频帧。它是不可变快照;其内容不会随时间变化,无论是来自 WebGPU 内部(仅可采样)还是外部(如视频帧推进)。
GPUExternalTexture
可通过
externalTexture
绑定组布局成员作为绑定项绑定到绑定组。注意该成员会占用多个绑定槽,详见相关定义。
GPUExternalTexture
可以在不复制导入源的情况下实现,但这取决于实现定义因素。底层表示的所有权可能是独占的,也可能与其他所有者(如视频解码器)共享,但这对应用透明。
外部纹理的底层表示不可见(除精确采样行为外),但通常包括:
-
最多三组二维平面(如 RGBA、Y+UV、Y+U+V)。
-
用于采样前坐标转换的元数据(裁剪和旋转)。
-
用于输出到目标色彩空间的元数据(矩阵、gamma、3D LUT)。
实现内部使用的配置在不同时间、系统、用户代理、媒体源、甚至同一个视频资源的帧之间可能不一致。为适应各种可能的实现,每个外部纹理绑定都会保守地占用:
-
三个采样纹理绑定(最多 3 个平面);
-
一个 3D LUT 的采样纹理绑定;
-
一个采样器绑定(用于采样 3D LUT);
-
一个元数据的 uniform buffer 绑定。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUExternalTexture { };GPUExternalTexture includes GPUObjectBase ;
GPUExternalTexture
拥有如下不可变属性:
[[descriptor]]
,类型为GPUExternalTextureDescriptor
,只读-
创建该纹理时所用的 descriptor。
GPUExternalTexture
拥有如下不可变属性:
[[expired]]
,类型为boolean
,初始值为false
-
表示对象是否已过期(不可再用)。
注意: 与
[[destroyed]]
不同,该值可从true
恢复到false
。
6.4.1. 导入外部纹理
外部纹理可通过 importExternalTexture()
从外部视频对象创建。
由 HTMLVideoElement
创建的外部纹理会在导入后自动过期(即销毁),而不像其他资源那样需要手动或等垃圾回收。外部纹理过期时,其 [[expired]]
属性变为 true
。
由 VideoFrame
创建的外部纹理会在且仅在源 VideoFrame
被关闭时过期(无论是通过 close()
还是其他方式)。
注意:如 decode()
所述,开发者应在输出 VideoFrame
上调用 close()
,以避免解码器阻塞。如果导入的
VideoFrame
被丢弃但未关闭,导入的 GPUExternalTexture
会保持其存活,直到它也被丢弃。只有两者都被丢弃后,VideoFrame
才能被垃圾回收。由于垃圾回收不可预测,这仍然可能导致解码器阻塞。
一旦 GPUExternalTexture
过期,必须再次调用 importExternalTexture()
。不过,用户代理可能会取消过期,返回同一个
GPUExternalTexture
,而不是新建一个。通常只有应用调度与视频帧率同步(如用
requestVideoFrameCallback()
)时才会避免返回同一个对象。如返回同一对象,二者相等,且引用旧对象的 GPUBindGroup
、GPURenderBundle
等依然有效。
dictionary :
GPUExternalTextureDescriptor GPUObjectDescriptorBase {required (HTMLVideoElement or VideoFrame )source ;PredefinedColorSpace colorSpace = "srgb"; };
GPUExternalTextureDescriptor
字典含如下成员:
source
,类型为(HTMLVideoElement or VideoFrame)
-
要导入为外部纹理的视频源。源尺寸详见外部源尺寸表。
colorSpace
,类型为 PredefinedColorSpace,默认"srgb"
-
读取时,
source
的图像内容会被转换到的色彩空间。
importExternalTexture(descriptor)
-
创建一个包裹所提供图像源的
GPUExternalTexture
。调用对象:GPUDevice
this。参数:
GPUDevice.importExternalTexture(descriptor) 方法参数 参数 类型 可为 null 可选 描述 descriptor
GPUExternalTextureDescriptor
✘ ✘ 提供外部图像源对象及相关创建选项。 内容时间线步骤:
-
令 source = descriptor.
source
。 -
若 source 的当前图像内容与最近一次用同一 descriptor(忽略
label
)调用importExternalTexture()
相同,且用户代理选择复用:-
令 previousResult 为上次返回的
GPUExternalTexture
。 -
置 previousResult.
[[expired]]
为false
,恢复底层资源所有权。 -
令 result = previousResult。
注意:这样应用可检测重复导入,避免重新创建依赖对象(如
GPUBindGroup
)。实现仍需支持同一帧被多个GPUExternalTexture
包裹,因为导入元数据如colorSpace
可变。否则:
-
如 source 不为 origin-clean,抛出
SecurityError
并返回。 -
如 usability 非
good
: -
令 data 为将 source 当前图像内容转换为 descriptor.
colorSpace
(未预乘 alpha)所得。此 可能导致超出 [0,1] 范围的值。如需裁剪,可采样后再做。
注意:虽描述为拷贝,也可实现为指向只读底层数据和元数据的引用。
-
令 result 为包裹 data 的新
GPUExternalTexture
。
-
-
如 source 是
HTMLVideoElement
,排队自动过期任务,内容包括:-
置 result.
[[expired]]
为true
,释放底层资源所有权。
注意:应在采样同一任务中导入
HTMLVideoElement
,建议结合requestVideoFrameCallback
或requestAnimationFrame()
使用,否则纹理可能在应用用完前被销毁。 -
-
如 source 是
VideoFrame
,则当 source 关闭时,执行:-
置 result.
[[expired]]
为true
。
-
-
返回 result。
-
const videoElement= document. createElement( 'video' ); // ... 设置 videoElement,等待其就绪 ... function frame() { requestAnimationFrame( frame); // 每帧都重新导入视频,因为导入的纹理很可能已过期。 // 浏览器可能缓存并复用旧帧,如复用会返回同一个 GPUExternalTexture。 // 这时旧的 bind group 依然有效。 const externalTexture= gpuDevice. importExternalTexture({ source: videoElement}); // ... 使用 externalTexture 渲染 ... } requestAnimationFrame( frame);
requestVideoFrameCallback
,则以视频帧率渲染 video 元素外部纹理:
const videoElement= document. createElement( 'video' ); // ... 设置 videoElement ... function frame() { videoElement. requestVideoFrameCallback( frame); // 帧已推进,需重新导入 const externalTexture= gpuDevice. importExternalTexture({ source: videoElement}); // ... 使用 externalTexture 渲染 ... } videoElement. requestVideoFrameCallback( frame);
6.5. 采样外部纹理绑定
externalTexture
绑定点允许绑定 GPUExternalTexture
对象(来自视频等动态图像源)。同时也支持 GPUTexture
和
GPUTextureView
。
注意:
当 GPUTexture
或
GPUTextureView
被绑定到 externalTexture
绑定点时,其行为等同于单一 RGBA plane、无裁剪、无旋转、无颜色转换的 GPUExternalTexture
。
外部纹理在 WGSL 中以 texture_external
表示,可通过 textureLoad
和
textureSampleBaseClampToEdge
读取。
textureSampleBaseClampToEdge
所用的 sampler
用于采样底层纹理。
当绑定资源类型为 GPUExternalTexture
时,采样结果在 colorSpace
设置的色彩空间中。对于具体外部纹理,采样器(及其过滤操作)是在底层值转换到指定色彩空间之前还是之后应用,是实现相关的。
注意: 若内部表示为 RGBA 平面,则采样行为与常规 2D 纹理一致。若有多个底层平面(如 Y+UV),采样器会分别对每个底层纹理采样,再进行 YUV 到指定色彩空间的转换。
7. 采样器(Samplers)
7.1. GPUSampler
GPUSampler
用于编码可在着色器中解释纹理资源数据的变换与过滤信息。
GPUSampler
通过 createSampler()
创建。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUSampler { };GPUSampler includes GPUObjectBase ;
GPUSampler
拥有如下不可变属性:
[[descriptor]]
,类型为GPUSamplerDescriptor
,只读-
创建
GPUSampler
时使用的GPUSamplerDescriptor
。 [[isComparison]]
,类型为boolean
,只读-
该
GPUSampler
是否为比较采样器。 [[isFiltering]]
,类型为boolean
,只读-
该
GPUSampler
是否对纹理的多个采样结果加权(即支持过滤)。
7.1.1. GPUSamplerDescriptor
GPUSamplerDescriptor
指定了创建 GPUSampler
时应使用的选项。
dictionary :
GPUSamplerDescriptor GPUObjectDescriptorBase {GPUAddressMode addressModeU = "clamp-to-edge";GPUAddressMode addressModeV = "clamp-to-edge";GPUAddressMode addressModeW = "clamp-to-edge";GPUFilterMode magFilter = "nearest";GPUFilterMode minFilter = "nearest";GPUMipmapFilterMode mipmapFilter = "nearest";float lodMinClamp = 0;float lodMaxClamp = 32;GPUCompareFunction compare ; [Clamp ]unsigned short maxAnisotropy = 1; };
addressModeU
, 类型为 GPUAddressMode,默认值为"clamp-to-edge"
addressModeV
, 类型为 GPUAddressMode,默认值为"clamp-to-edge"
addressModeW
, 类型为 GPUAddressMode,默认值为"clamp-to-edge"
-
分别指定纹理在宽度、高度和深度坐标方向上的
地址模式
。 magFilter
, 类型为 GPUFilterMode,默认值为"nearest"
-
指定当采样区域小于等于一个纹素时的采样行为。
minFilter
, 类型为 GPUFilterMode,默认值为"nearest"
-
指定当采样区域大于一个纹素时的采样行为。
mipmapFilter
, 类型为 GPUMipmapFilterMode,默认值为"nearest"
-
指定在 mipmap 层级之间采样时的行为。
lodMinClamp
, 类型为 float,默认值为0
lodMaxClamp
, 类型为 float,默认值为32
-
分别指定采样纹理时内部使用的最小和最大细节层级(LOD)。
compare
, 类型为 GPUCompareFunction-
如果提供,则采样器将被设为比较采样器,并使用指定的
GPUCompareFunction
。注意:比较采样器可以使用过滤,但采样结果依赖于实现,可能不同于普通过滤规则。
maxAnisotropy
, 类型为 unsigned short,默认值为1
-
指定采样器使用的最大各向异性值上限。当
maxAnisotropy
大于 1 且实现支持时,启用各向异性过滤。各向异性过滤可提高在斜视角下采样纹理的图像质量。更高的
maxAnisotropy
值表示过滤时支持的最大各向异性比。
细节层级(Level of detail,LOD) 描述了采样纹理时选用的 mip 层级。可以通过 textureSampleLevel 等着色器方法显式指定,也可以由纹理坐标导数隐式决定。
注意:参考 Scale Factor Operation, LOD Operation and Image Level Selection(Vulkan 1.3 规范)了解隐式 LOD 如何计算。
GPUAddressMode
描述了采样纹理时纹素超出纹理边界时的采样器行为。
enum {
GPUAddressMode "clamp-to-edge" ,"repeat" ,"mirror-repeat" , };
"clamp-to-edge"
-
纹理坐标被限制在 0.0 到 1.0 区间内。
"repeat"
-
纹理坐标将在纹理另一侧环绕。
"mirror-repeat"
-
纹理坐标将在纹理另一侧环绕,但当坐标的整数部分为奇数时,纹理会翻转。
GPUFilterMode
和 GPUMipmapFilterMode
描述采样区域不正好覆盖一个纹素时采样器的行为。
注意:参考 Texel Filtering(Vulkan 1.3 规范)了解采样器如何确定在不同过滤模式下采样哪些纹素。
enum {
GPUFilterMode "nearest" ,"linear" , };enum {
GPUMipmapFilterMode ,
"nearest" , };
"linear"
"nearest"
-
返回最接近纹理坐标的纹素值。
"linear"
-
每个维度选择两个纹素,并返回它们值的线性插值。
GPUCompareFunction
指定比较采样器的行为。如果在着色器中使用比较采样器,depth_ref
会与获取到的纹素值进行比较,生成比较结果(通过则为 1.0f
,未通过为
0.0f
)。
比较后,如果启用纹理过滤,则会进行过滤步骤,使多个比较结果混合,结果在 [0, 1]
区间。过滤应当如常处理,但可能以更低精度或不做混合。
enum {
GPUCompareFunction "never" ,"less" ,"equal" ,"less-equal" ,"greater" ,"not-equal" ,"greater-equal" ,"always" , };
"never"
-
比较测试始终不通过。
"less"
-
当提供值小于采样值时,比较测试通过。
"equal"
-
当提供值等于采样值时,比较测试通过。
"less-equal"
-
当提供值小于等于采样值时,比较测试通过。
"greater"
-
当提供值大于采样值时,比较测试通过。
"not-equal"
-
当提供值不等于采样值时,比较测试通过。
"greater-equal"
-
当提供值大于等于采样值时,比较测试通过。
"always"
-
比较测试始终通过。
7.1.2. 采样器创建
createSampler(descriptor)
-
创建一个
GPUSampler
。调用对象:GPUDevice
this。参数:
参数表:GPUDevice.createSampler(descriptor) 方法。 参数名 类型 可为 null 可选 描述 descriptor
GPUSamplerDescriptor
✘ ✔ 要创建的 GPUSampler
的描述信息。返回:
GPUSampler
内容时间线步骤:
-
令 s = ! 创建新的 WebGPU 对象(this,
GPUSampler
, descriptor)。 -
在 设备时间线 上对 this 执行 初始化步骤。
-
返回 s。
设备时间线 初始化步骤:-
如果下列任一条件不满足,则生成校验错误,使 s 无效 并返回。
-
this 不能被丢失。
-
descriptor.
lodMinClamp
≥ 0。 -
descriptor.
lodMaxClamp
≥ descriptor.lodMinClamp
。 -
descriptor.
maxAnisotropy
≥ 1。注意:大多数实现支持
maxAnisotropy
取值范围为 1 到 16(含)。所提供的maxAnisotropy
值会被限制在平台支持的最大值。 -
如果 descriptor.
maxAnisotropy
> 1:-
descriptor.
magFilter
, descriptor.minFilter
, 和 descriptor.mipmapFilter
必须都为"linear"
。
-
-
-
设置 s.
[[descriptor]]
为 descriptor。 -
如果 s.
[[descriptor]]
的compare
属性为null
或未定义,则设置 s.[[isComparison]]
为false
。否则设置为true
。 -
如果
minFilter
、magFilter
、mipmapFilter
都不是"linear"
,则设置 s.[[isFiltering]]
为false
;否则设为true
。
-
GPUSampler
:
const sampler= gpuDevice. createSampler({ addressModeU: 'repeat' , addressModeV: 'repeat' , magFilter: 'linear' , minFilter: 'linear' , mipmapFilter: 'linear' , });
8. 资源绑定
8.1. GPUBindGroupLayout
GPUBindGroupLayout
定义了绑定在 GPUBindGroup
中的一组资源与着色器阶段可访问性的接口关系。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUBindGroupLayout { };GPUBindGroupLayout includes GPUObjectBase ;
GPUBindGroupLayout
具有以下不可变属性:
[[descriptor]]
,类型为GPUBindGroupLayoutDescriptor
, 只读
8.1.1. 绑定组布局创建
GPUBindGroupLayout
通过 GPUDevice.createBindGroupLayout()
创建。
dictionary :
GPUBindGroupLayoutDescriptor GPUObjectDescriptorBase {required sequence <GPUBindGroupLayoutEntry >entries ; };
GPUBindGroupLayoutDescriptor
字典包含以下成员:
entries
,类型为 sequence<GPUBindGroupLayoutEntry>-
用于描述绑定组内着色器资源绑定的条目列表。
GPUBindGroupLayoutEntry
描述了要包含在 GPUBindGroupLayout
中的单个着色器资源绑定。
dictionary {
GPUBindGroupLayoutEntry required GPUIndex32 binding ;required GPUShaderStageFlags visibility ;GPUBufferBindingLayout buffer ;GPUSamplerBindingLayout sampler ;GPUTextureBindingLayout texture ;GPUStorageTextureBindingLayout storageTexture ;GPUExternalTextureBindingLayout externalTexture ; };
GPUBindGroupLayoutEntry
字典包含以下成员:
binding
,类型为 GPUIndex32-
绑定组布局内资源绑定的唯一标识符,对应于
GPUBindGroupEntry.binding
以及GPUShaderModule
中的 @binding 属性。 visibility
,类型为 GPUShaderStageFlags-
GPUShaderStage
各成员组成的位集合。每个被设置的位表示该资源在对应着色器阶段可访问。 buffer
,类型为 GPUBufferBindingLayoutsampler
,类型为 GPUSamplerBindingLayouttexture
,类型为 GPUTextureBindingLayoutstorageTexture
,类型为 GPUStorageTextureBindingLayoutexternalTexture
,类型为 GPUExternalTextureBindingLayout-
这些成员中必须且只能设置一个,表示绑定类型。该成员的内容指定该类型的选项。
createBindGroup()
中对应的资源必须为该绑定类型的binding resource type。
typedef [EnforceRange ]unsigned long ; [
GPUShaderStageFlags Exposed =(Window ,Worker ),SecureContext ]namespace {
GPUShaderStage const GPUFlagsConstant VERTEX = 0x1;const GPUFlagsConstant FRAGMENT = 0x2;const GPUFlagsConstant COMPUTE = 0x4; };
GPUShaderStage
包含以下标志,指示此 GPUBindGroupEntry
对应的 GPUBindGroupLayoutEntry
可见于哪些着色器阶段:
VERTEX
-
绑定组条目在顶点着色器中可访问。
FRAGMENT
-
绑定组条目在片元着色器中可访问。
COMPUTE
-
绑定组条目在计算着色器中可访问。
GPUBindGroupLayoutEntry
的 binding member 由其定义的成员决定:
buffer
、
sampler
、
texture
、
storageTexture
,
或 externalTexture
。
每个 GPUBindGroupLayoutEntry
只能定义一个成员。
每个成员有其对应的 GPUBindingResource
类型,每个绑定类型对应一个内部用法,见下表:
GPUBindGroupLayoutEntry
值 entries
超出绑定槽限制(exceeds the binding slot limits),指当用于某一限制的槽数超过 支持的限制 limits
中的支持值时。
每个 entry 可能会占用多个限制的多个槽。
设备时间线步骤:
-
对于 entries 中的每个 entry,如果:
- entry.
buffer
?.type
为"uniform"
且 entry.buffer
?.hasDynamicOffset
为true
-
视为使用了 1 个
maxDynamicUniformBuffersPerPipelineLayout
槽。 - entry.
buffer
?.type
为"storage"
且 entry.buffer
?.hasDynamicOffset
为true
-
视为使用了 1 个
maxDynamicStorageBuffersPerPipelineLayout
槽。
- entry.
-
对于每个着色器阶段 stage,即 «
VERTEX
,FRAGMENT
,COMPUTE
»:-
对于每个 entries 中 entry,若其 entry.
visibility
包含 stage,则:- entry.
buffer
?.type
为"uniform"
-
视为使用了 1 个
maxUniformBuffersPerShaderStage
槽。 - entry.
buffer
?.type
为"storage"
或"read-only-storage"
-
视为使用了 1 个
maxStorageBuffersPerShaderStage
槽。 - entry.
sampler
存在(provided) -
视为使用了 1 个
maxSamplersPerShaderStage
槽。 - entry.
texture
存在 -
视为使用了 1 个
maxSampledTexturesPerShaderStage
槽。 - entry.
storageTexture
存在 -
视为使用了 1 个
maxStorageTexturesPerShaderStage
槽。 - entry.
externalTexture
存在 -
视为使用 4 个
maxSampledTexturesPerShaderStage
槽, 1 个maxSamplersPerShaderStage
槽,以及 1 个maxUniformBuffersPerShaderStage
槽。注意:详见
GPUExternalTexture
相关说明。
- entry.
-
enum {
GPUBufferBindingType ,
"uniform" ,
"storage" , };
"read-only-storage" dictionary {
GPUBufferBindingLayout GPUBufferBindingType type = "uniform";boolean hasDynamicOffset =false ;GPUSize64 minBindingSize = 0; };
GPUBufferBindingLayout
字典包含以下成员:
type
,类型为 GPUBufferBindingType,默认值为"uniform"
-
指示绑定到该绑定点的缓冲区所需的类型。
hasDynamicOffset
,类型为 boolean,默认值为false
-
指示该绑定是否需要动态偏移。
minBindingSize
,类型为 GPUSize64,默认值为0
-
指示与该绑定点使用的缓冲区绑定的最小
size
。在
createBindGroup()
中总会对绑定进行该尺寸的校验。若该值不为
0
,则管线创建时还会额外校验 该值是否大于等于变量的最小缓冲区绑定大小。若该值为
0
,则管线创建时忽略,转而由 draw/dispatch 指令 校验绑定组中每个绑定是否满足变量的最小缓冲区绑定大小。注意: 理论上,类似的运行时校验也可用于其它用于早期校验的绑定相关字段,如
sampleType
和format
,但目前仅在管线创建时校验。 不过这样的运行时校验可能开销大或不必要复杂,因此仅对minBindingSize
启用,因为它对易用性影响最大。
enum {
GPUSamplerBindingType ,
"filtering" ,
"non-filtering" , };
"comparison" dictionary {
GPUSamplerBindingLayout GPUSamplerBindingType type = "filtering"; };
GPUSamplerBindingLayout
字典包含以下成员:
type
,类型为 GPUSamplerBindingType,默认值为"filtering"
-
指示绑定到此绑定点所需采样器的类型。
enum {
GPUTextureSampleType ,
"float" ,
"unfilterable-float" ,
"depth" ,
"sint" , };
"uint" dictionary {
GPUTextureBindingLayout GPUTextureSampleType sampleType = "float";GPUTextureViewDimension viewDimension = "2d";boolean multisampled =false ; };
GPUTextureBindingLayout
字典包含以下成员:
sampleType
,类型为 GPUTextureSampleType,默认值为"float"
-
指示绑定到该绑定点的纹理视图所需的类型。
viewDimension
,类型为 GPUTextureViewDimension,默认值为"2d"
-
指示绑定到该绑定点的纹理视图所需的
dimension
。 multisampled
,类型为 boolean,默认值为false
-
指示绑定到该绑定点的纹理视图是否必须为多重采样。
enum {
GPUStorageTextureAccess ,
"write-only" ,
"read-only" , };
"read-write" dictionary {
GPUStorageTextureBindingLayout GPUStorageTextureAccess access = "write-only";required GPUTextureFormat format ;GPUTextureViewDimension viewDimension = "2d"; };
GPUStorageTextureBindingLayout
字典包含以下成员:
access
,类型为 GPUStorageTextureAccess,默认值为"write-only"
-
此绑定的访问模式,指示可读性和可写性。
format
,类型为 GPUTextureFormat-
绑定到此绑定点的纹理视图所需的
format
。 viewDimension
,类型为 GPUTextureViewDimension,默认值为"2d"
-
绑定到此绑定点的纹理视图所需的
dimension
。
dictionary { };
GPUExternalTextureBindingLayout
GPUBindGroupLayout
对象拥有以下设备时间线属性:
[[entryMap]]
,类型为 有序映射<GPUSize32
,GPUBindGroupLayoutEntry
>, 只读-
指向该
GPUBindGroupLayout
所描述的GPUBindGroupLayoutEntry
的绑定索引映射表。 [[dynamicOffsetCount]]
,类型为GPUSize32
, 只读-
此
GPUBindGroupLayout
中具有动态偏移的缓冲区绑定数量。 [[exclusivePipeline]]
,类型为GPUPipelineBase
? ,只读-
如果是作为默认管线布局一部分创建的,则为创建该
GPUBindGroupLayout
的管线。若不为null
,则用该GPUBindGroupLayout
创建的GPUBindGroup
只能与指定的GPUPipelineBase
一起使用。
createBindGroupLayout(descriptor)
-
创建一个
GPUBindGroupLayout
。调用对象:GPUDevice
this。参数:
GPUDevice.createBindGroupLayout(descriptor) 方法参数。 参数 类型 可为 null 可选 描述 descriptor
GPUBindGroupLayoutDescriptor
✘ ✘ 要创建的 GPUBindGroupLayout
的描述信息。内容时间线步骤:
-
对于 descriptor.
entries
中的每个GPUBindGroupLayoutEntry
entry:-
如果 entry.
storageTexture
已提供:-
? 校验纹理格式所需特性,针对 entry.
storageTexture
.format
及 this.[[device]]
。
-
-
-
令 layout = ! 创建 WebGPU 对象(this,
GPUBindGroupLayout
, descriptor)。 -
在 this 的 设备时间线上执行 初始化步骤。
-
返回 layout。
设备时间线 初始化步骤:-
若下列任意条件不满足,则生成校验错误,使 layout 无效并返回。
-
this 不能被丢失。
-
令 limits = this.
[[device]]
.[[limits]]
。 -
descriptor 中每个 entry 的
binding
必须唯一。 -
descriptor 中每个 entry 的
binding
必须小于 limits.maxBindingsPerBindGroup
。 -
descriptor.
entries
必须不能超出绑定槽限制(exceed the binding slot limits) limits。 -
对于 descriptor.
entries
中的每个GPUBindGroupLayoutEntry
entry:-
entry.
buffer
、 entry.sampler
、 entry.texture
、 entry.storageTexture
、 entry.externalTexture
必须且只能有一个 被提供。 -
entry.
visibility
仅包含GPUShaderStage
中定义的位。 -
若 entry.
visibility
包含VERTEX
:-
若 entry.
buffer
被提供, entry.buffer
.type
必须为"uniform"
或"read-only-storage"
。 -
若 entry.
storageTexture
被提供, entry.storageTexture
.access
必须为"read-only"
。
-
-
若 entry.
texture
?.multisampled
为true
:-
entry.
texture
.viewDimension
为"2d"
。 -
entry.
texture
.sampleType
不能为"float"
。
-
-
若 entry.
storageTexture
被提供:-
entry.
storageTexture
.viewDimension
不能为"cube"
或"cube-array"
。 -
entry.
storageTexture
.format
必须为可支持所给 entry.storageTexture
.access
存储用法的格式,详见 § 26.1.1 普通颜色格式表格。
-
-
-
-
设置 layout.
[[descriptor]]
为 descriptor。 -
设置 layout.
[[dynamicOffsetCount]]
为 descriptor 中buffer
被提供,且buffer
.hasDynamicOffset
为true
的条目数量。 -
设置 layout.
[[exclusivePipeline]]
为null
。 -
对于 descriptor.
entries
中的每个GPUBindGroupLayoutEntry
entry:-
以 entry.
binding
作为 key,将 entry 插入 layout.[[entryMap]]
。
-
-
8.1.2. 兼容性
GPUBindGroupLayout
对象 a 和 b 被认为是 组等价(group-equivalent)
当且仅当满足以下所有条件:
-
对任意绑定号 binding,有如下条件之一满足:
-
在 a.
[[entryMap]]
和 b.[[entryMap]]
中都不存在; -
a.
[[entryMap]]
[binding] == b.[[entryMap]]
[binding]
-
如果绑定组布局是组等价的,则它们可以在所有场合下互换使用。
8.2. GPUBindGroup
GPUBindGroup
定义了一组要共同绑定的资源,以及这些资源在着色器阶段的使用方式。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUBindGroup { };GPUBindGroup includes GPUObjectBase ;
GPUBindGroup
具有以下设备时间线属性:
[[layout]]
,类型为GPUBindGroupLayout
, 只读-
与该
GPUBindGroup
相关联的GPUBindGroupLayout
。 [[entries]]
,类型为 sequence<GPUBindGroupEntry
>, 只读-
该
GPUBindGroup
所描述的所有GPUBindGroupEntry
集合。 [[usedResources]]
,类型为 usage scope,只读
GPUBindGroup
bindGroup 的 已绑定缓冲区范围(bound buffer ranges),
给定 list<GPUBufferDynamicOffset> dynamicOffsets,按如下方式计算:
-
令 result 为新的 集合<(
GPUBindGroupLayoutEntry
,GPUBufferBinding
)>。 -
令 dynamicOffsetIndex 为 0。
-
对 bindGroup.
[[entries]]
中每个GPUBindGroupEntry
bindGroupEntry(按 bindGroupEntry.binding
排序):-
令 bindGroupLayoutEntry = bindGroup.
[[layout]]
.[[entryMap]]
[bindGroupEntry.binding
]。 -
令 bound = get as buffer binding(bindGroupEntry.
resource
)。 -
若 bindGroupLayoutEntry.
buffer
.hasDynamicOffset
:-
将 bound.
offset
增加 dynamicOffsets[dynamicOffsetIndex]。 -
dynamicOffsetIndex 增加 1。
-
-
将 (bindGroupLayoutEntry, bound) 添加到 result。
-
-
返回 result。
8.2.1. 绑定组创建
GPUBindGroup
通过 GPUDevice.createBindGroup()
创建。
dictionary :
GPUBindGroupDescriptor GPUObjectDescriptorBase {required GPUBindGroupLayout layout ;required sequence <GPUBindGroupEntry >entries ; };
GPUBindGroupDescriptor
字典包含以下成员:
layout
,类型为 GPUBindGroupLayout-
该绑定组条目所遵循的
GPUBindGroupLayout
。 entries
,类型为 sequence<GPUBindGroupEntry>-
描述要为
layout
所描述的每个绑定暴露给着色器的资源条目的列表。
typedef (GPUSampler or GPUTexture or GPUTextureView or GPUBuffer or GPUBufferBinding or GPUExternalTexture );
GPUBindingResource dictionary {
GPUBindGroupEntry required GPUIndex32 binding ;required GPUBindingResource resource ; };
GPUBindGroupEntry
描述要绑定到 GPUBindGroup
的单个资源,包含以下成员:
binding
,类型为 GPUIndex32-
该绑定组内资源绑定的唯一标识符,对应于
GPUBindGroupLayoutEntry.binding
以及GPUShaderModule
中的 @binding 属性。 resource
,类型为 GPUBindingResource-
要绑定的资源,可以是
GPUSampler
、GPUTexture
、GPUTextureView
、GPUBuffer
、GPUBufferBinding
, 或GPUExternalTexture
。
GPUBindGroupEntry
具有以下设备时间线属性:
[[prevalidatedSize]]
,类型为boolean
-
该绑定条目在创建时其缓冲区大小是否已被校验。
dictionary {
GPUBufferBinding required GPUBuffer buffer ;GPUSize64 offset = 0;GPUSize64 size ; };
GPUBufferBinding
描述了要作为资源绑定的缓冲区及可选范围,包含以下成员:
buffer
,类型为 GPUBuffer-
要绑定的
GPUBuffer
。 offset
,类型为 GPUSize64,默认值为0
-
以字节为单位,
buffer
起始到绑定暴露给着色器的范围起点的偏移量。 size
,类型为 GPUSize64
createBindGroup(descriptor)
-
创建一个
GPUBindGroup
。调用对象:GPUDevice
this。参数:
GPUDevice.createBindGroup(descriptor) 方法参数。 参数 类型 可为 null 可选 描述 descriptor
GPUBindGroupDescriptor
✘ ✘ 要创建的 GPUBindGroup
的描述信息。返回:
GPUBindGroup
内容时间线步骤:
-
令 bindGroup = ! 创建新的 WebGPU 对象(this,
GPUBindGroup
, descriptor)。 -
在 this 的 设备时间线上执行 初始化步骤。
-
返回 bindGroup。
设备时间线 初始化步骤:-
令 limits = this.
[[device]]
.[[limits]]
。 -
若下列任一条件不满足,则生成校验错误,使 bindGroup 无效并返回。
对于 descriptor.
entries
中的每个GPUBindGroupEntry
bindingDescriptor:-
令 resource = bindingDescriptor.
resource
。 -
在 descriptor.
layout
.entries
中,存在且仅存在一个GPUBindGroupLayoutEntry
layoutBinding 满足 layoutBinding.binding
等于 bindingDescriptor.binding
。 -
若 layoutBinding 的定义binding member 为:
sampler
-
-
resource 是
GPUSampler
。 -
resource 可与 this 配合使用。
-
若 layoutBinding.
sampler
.type
为:"filtering"
-
resource.
[[isComparison]]
为false
。 "non-filtering"
-
resource.
[[isFiltering]]
为false
,且 resource.[[isComparison]]
为false
。 "comparison"
-
resource.
[[isComparison]]
为true
。
-
texture
-
-
resource 是
GPUTexture
或GPUTextureView
。 -
resource 可与 this 配合使用。
-
令 textureView = get as texture view(resource)。
-
令 texture = textureView.
[[texture]]
。 -
layoutBinding.
texture
.viewDimension
等于 textureView 的dimension
。 -
layoutBinding.
texture
.sampleType
与 textureView 的format
兼容。 -
textureView.
[[descriptor]]
.usage
包含TEXTURE_BINDING
。 -
如果 layoutBinding.
texture
.multisampled
为true
,则 texture 的sampleCount
大于 1,否则为 1。
-
storageTexture
-
-
resource 是
GPUTexture
或GPUTextureView
。 -
resource 可与 this 配合使用。
-
令 storageTextureView = get as texture view(resource)。
-
令 texture = storageTextureView.
[[texture]]
。 -
layoutBinding.
storageTexture
.viewDimension
等于 storageTextureView 的dimension
。 -
layoutBinding.
storageTexture
.format
等于 storageTextureView.[[descriptor]]
.format
。 -
storageTextureView.
[[descriptor]]
.usage
包含STORAGE_BINDING
。 -
storageTextureView.
[[descriptor]]
.mipLevelCount
必须为 1。
-
buffer
-
-
resource 是
GPUBuffer
或GPUBufferBinding
。 -
令 bufferBinding = get as buffer binding(resource)。
-
bufferBinding.
buffer
可与 this 配合使用。 -
由 bufferBinding.
offset
和 bufferBinding.size
决定的绑定部分位于缓冲区内部且大小非零。 -
effective buffer binding size(bufferBinding) ≥ layoutBinding.
buffer
.minBindingSize
。 -
若 layoutBinding.
buffer
.type
为:"uniform"
-
-
effective buffer binding size(bufferBinding) ≤ limits.
maxUniformBufferBindingSize
。 -
bufferBinding.
offset
是 limits.minUniformBufferOffsetAlignment
的倍数。
"storage"
或"read-only-storage"
-
-
effective buffer binding size(bufferBinding) ≤ limits.
maxStorageBufferBindingSize
。 -
effective buffer binding size(bufferBinding) 是 4 的倍数。
-
bufferBinding.
offset
是 limits.minStorageBufferOffsetAlignment
的倍数。
-
externalTexture
-
-
resource 是
GPUExternalTexture
、GPUTexture
或GPUTextureView
。 -
resource 可与 this 配合使用。
-
若 resource 为:
GPUTexture
或GPUTextureView
-
-
令 view = get as texture view(resource)。
-
view.
[[descriptor]]
.usage
必须包含TEXTURE_BINDING
。 -
view.
[[descriptor]]
.dimension
必须为"2d"
。 -
view.
[[descriptor]]
.mipLevelCount
必须为 1。 -
view.
[[descriptor]]
.format
必须为"rgba8unorm"
、"bgra8unorm"
或"rgba16float"
。 -
view.
[[texture]]
.sampleCount
必须为 1。
-
-
-
-
令 bindGroup.
[[layout]]
= descriptor.layout
。 -
令 bindGroup.
[[entries]]
= descriptor.entries
。 -
令 bindGroup.
[[usedResources]]
= {}。 -
对 descriptor.
entries
中的每个GPUBindGroupEntry
bindingDescriptor:-
令 internalUsage 为 layoutBinding 的绑定用法。
-
resource 所见的每个子资源,都以 internalUsage 形式添加到
[[usedResources]]
。 -
若 layoutBinding 的 binding member 为
buffer
且 layoutBinding.buffer
.minBindingSize
为0
,则 bindingDescriptor.[[prevalidatedSize]]
设为false
,否则设为true
。
-
-
参数:
-
GPUBindingResource
resource
返回: GPUTextureView
-
断言 resource 必须为
GPUTexture
或GPUTextureView
。 -
如果 resource 为:
GPUTexture
-
-
返回 resource.
createView()
。
-
GPUTextureView
-
-
返回 resource。
-
参数:
-
GPUBindingResource
resource
返回: GPUBufferBinding
-
断言 resource 必须为
GPUBuffer
或GPUBufferBinding
。 -
如果 resource 为:
GPUBuffer
-
-
令 bufferBinding 为新的
GPUBufferBinding
。 -
设置 bufferBinding.
buffer
为 resource。 -
返回 bufferBinding。
-
GPUBufferBinding
-
-
返回 resource。
-
GPUBufferBinding
对象 a 和 b 被认为是 缓冲区绑定别名(buffer-binding-aliasing),当且仅当满足以下全部条件:
注意:进行该计算时,任何动态偏移已应用到范围上。
8.3. GPUPipelineLayout
GPUPipelineLayout
定义了在命令编码期间通过 setBindGroup() 设置的所有 GPUBindGroup
对象的资源,与通过 GPURenderCommandsMixin.setPipeline
或 GPUComputePassEncoder.setPipeline
设置的管线着色器之间的映射关系。
资源的完整绑定地址可以定义为以下三元组:
-
资源可见的着色器阶段掩码
-
绑定组索引(bind group index)
-
绑定号(binding number)
该地址的各分量也可视为管线的绑定空间。一个 GPUBindGroup
(与相应的 GPUBindGroupLayout
一起)
覆盖了某个固定绑定组索引的空间。其包含的绑定需要是该绑定组索引上着色器所用资源的超集。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUPipelineLayout { };GPUPipelineLayout includes GPUObjectBase ;
GPUPipelineLayout
具有以下设备时间线属性:
[[bindGroupLayouts]]
,类型为 list<GPUBindGroupLayout
>, 只读-
在创建时通过
GPUPipelineLayoutDescriptor.bindGroupLayouts
提供的GPUBindGroupLayout
对象列表。
注意:为多个 GPURenderPipeline
或 GPUComputePipeline
管线复用同一个 GPUPipelineLayout
可确保在切换这些管线时,用户代理无需在内部重新绑定资源。
GPUComputePipeline
对象 X 是用 GPUPipelineLayout.bindGroupLayouts
A、B、C 创建的。GPUComputePipeline
对象 Y 是用 GPUPipelineLayout.bindGroupLayouts
A、D、C 创建的。假设命令编码顺序有两次 dispatch:
-
setBindGroup(0, ...)
-
setBindGroup(1, ...)
-
setBindGroup(2, ...)
-
setPipeline
(X) -
setBindGroup(1, ...)
-
setPipeline
(Y)
在该场景中,即使 GPUPipelineLayout.bindGroupLayouts
索引 2 处的 GPUBindGroupLayout
或槽 2 处的 GPUBindGroup
都未变化,用户代理仍需为第二次 dispatch 重新绑定组槽 2。
注意: GPUPipelineLayout
的建议用法是将最常用且最少变动的绑定组放在布局“底部”,即绑定组槽号较低的位置(如 0 或 1)。绑定组在绘制调用间变动越频繁,其索引应越高。该通用建议有助于用户代理最小化绘制调用间的状态切换,从而降低 CPU
开销。
8.3.1. 管线布局创建
GPUPipelineLayout
通过 GPUDevice.createPipelineLayout()
创建。
dictionary :
GPUPipelineLayoutDescriptor GPUObjectDescriptorBase {required sequence <GPUBindGroupLayout ?>bindGroupLayouts ; };
GPUPipelineLayoutDescriptor
字典定义了管线所用的所有 GPUBindGroupLayout
,包含以下成员:
bindGroupLayouts
,类型为sequence<GPUBindGroupLayout?>
-
管线将使用的可选
GPUBindGroupLayout
列表。每个元素对应GPUShaderModule
中的 @group 属性,第 N 个元素对应@group(N)
。
createPipelineLayout(descriptor)
-
创建一个
GPUPipelineLayout
。调用对象:GPUDevice
this。参数:
GPUDevice.createPipelineLayout(descriptor) 方法参数。 参数 类型 可为 null 可选 描述 descriptor
GPUPipelineLayoutDescriptor
✘ ✘ 要创建的 GPUPipelineLayout
的描述信息。内容时间线步骤:
-
令 pl = ! 创建新的 WebGPU 对象(this,
GPUPipelineLayout
, descriptor)。 -
在 this 的 设备时间线上执行 初始化步骤。
-
返回 pl。
设备时间线 初始化步骤:-
令 limits = this.
[[device]]
.[[limits]]
。 -
令 bindGroupLayouts 为一个包含
null
的GPUBindGroupLayout
列表, 大小等于 limits.maxBindGroups
。 -
对 descriptor.
bindGroupLayouts
中每个索引 i 的 bindGroupLayout:-
如果 bindGroupLayout 非
null
且 bindGroupLayout.[[descriptor]]
.entries
非空:-
设置 bindGroupLayouts[i] 为 bindGroupLayout。
-
-
-
令 allEntries 为所有非
null
bgl 的 bgl.[[descriptor]]
.entries
拼接后的结果。 -
若下列任一条件不满足,则生成校验错误,使 pl 无效并返回。
-
bindGroupLayouts 中每个非
null
的GPUBindGroupLayout
必须可与 this 配合使用,且其[[exclusivePipeline]]
为null
。 -
descriptor.
bindGroupLayouts
的大小必须小于等于 limits.maxBindGroups
。 -
allEntries 不能超出绑定槽限制 limits。
-
-
设置 pl.
[[bindGroupLayouts]]
为 bindGroupLayouts。
-
注意: 若两个 GPUPipelineLayout
的内部 [[bindGroupLayouts]]
序列中包含的每个 GPUBindGroupLayout
对象两两 组等价,则它们对任意用途都是等价的。
8.4. 示例
GPUBindGroupLayout
,描述具有 uniform buffer、纹理和采样器的绑定。
然后使用该 GPUBindGroupLayout
创建 GPUBindGroup
和 GPUPipelineLayout
。
const bindGroupLayout= gpuDevice. createBindGroupLayout({ entries: [{ binding: 0 , visibility: GPUShaderStage. VERTEX| GPUShaderStage. FRAGMENT, buffer: {} }, { binding: 1 , visibility: GPUShaderStage. FRAGMENT, texture: {} }, { binding: 2 , visibility: GPUShaderStage. FRAGMENT, sampler: {} }] }); const bindGroup= gpuDevice. createBindGroup({ layout: bindGroupLayout, entries: [{ binding: 0 , resource: { buffer: buffer}, }, { binding: 1 , resource: texture}, { binding: 2 , resource: sampler}] }); const pipelineLayout= gpuDevice. createPipelineLayout({ bindGroupLayouts: [ bindGroupLayout] });
9. 着色器模块
9.1. GPUShaderModule
[Exposed =(Window ,Worker ),SecureContext ]interface GPUShaderModule {Promise <GPUCompilationInfo >getCompilationInfo (); };GPUShaderModule includes GPUObjectBase ;
GPUShaderModule
是对内部着色器模块对象的引用。
9.1.1. 着色器模块创建
dictionary :
GPUShaderModuleDescriptor GPUObjectDescriptorBase {required USVString code ;sequence <GPUShaderModuleCompilationHint >compilationHints = []; };
code
,类型为 USVString-
该着色器模块的 WGSL 源代码。
compilationHints
,类型为 sequence<GPUShaderModuleCompilationHint>,默认值为[]
-
GPUShaderModuleCompilationHint
的列表。应用程序提供的任何 hint 应当 包含有关将来会从该入口创建管线的某个 entry point 的信息。
实现 应当 使用
GPUShaderModuleCompilationHint
中的任何信息,尽可能在createShaderModule()
内完成编译。除了类型检查外,这些 hint 不会以任何方式被校验。
注意:在compilationHints
中提供信息不会产生除性能以外的可观察效果。为从未创建的管线提供 hint 可能对性能有害。由于单个着色器模块可以包含多个入口点,并且可以从一个着色器模块创建多个管线,因此实现只在
createShaderModule()
时尽可能多地编译会更高效,而不是在多次createComputePipeline()
或createRenderPipeline()
时多次编译。hint 只应用于其明确命名的入口点。与
GPUProgrammableStage.entryPoint
不同,即使模块中只有一个入口点,这里也没有默认值。注意: hint 不会以可观察方式被校验,但用户代理 可以 向开发者(比如在浏览器开发者工具)展示可识别错误(如未知入口点名或不兼容的管线布局)。
createShaderModule(descriptor)
-
创建一个
GPUShaderModule
。调用对象:GPUDevice
this。参数:
GPUDevice.createShaderModule(descriptor) 方法参数。 参数 类型 可为 null 可选 描述 descriptor
GPUShaderModuleDescriptor
✘ ✘ 要创建的 GPUShaderModule
的描述信息。返回:
GPUShaderModule
内容时间线步骤:
-
令 sm = ! 创建新的 WebGPU 对象(this,
GPUShaderModule
, descriptor)。 -
在 this 的 设备时间线上执行 初始化步骤。
-
返回 sm。
设备时间线 初始化步骤:-
令 error 为使用 WGSL 源 descriptor.
code
创建着色器模块时产生的任何错误,若无错误则为null
。 -
若下列任一要求不满足,则生成校验错误,使 sm 无效并返回。
-
this 不能丢失。
-
error 不能为 shader-creation program error。
-
对 descriptor.
code
中每个enable
扩展,对应的GPUFeatureName
必须被启用(见 特性索引)。
注意: 未分类错误不会在着色器模块创建时出现。实现如果在着色器模块创建阶段检测到此类错误,必须表现为着色器模块有效,并将错误推迟到管线创建阶段再暴露。
-
注意:用户代理不应在此处校验错误的message
文本中包含详细的编译器错误消息或着色器代码文本:这些详情可通过getCompilationInfo()
访问。用户代理应为开发者提供易读、格式化的错误详情(比如在浏览器开发者工具中以可展开警告展示完整着色器源码)。由于生产环境中着色器编译错误应该很罕见,用户代理可以选择无论错误处理方式如何(GPU 错误作用域 或
uncapturederror
事件处理器),都向开发者展示这些错误,例如以可展开警告形式。 如果不这样做,应当提供并记录其他方式让开发者访问这些可读错误详情,比如添加一个复选框总是显示错误,或在控制台记录GPUCompilationInfo
对象时显示可读详情。 -
GPUShaderModule
:
// 一个简单的 vertex 和 fragment 着色器对,将用红色填充视口。 const shaderSource= ` var<private> pos : array<vec2<f32>, 3> = array<vec2<f32>, 3>( vec2(-1.0, -1.0), vec2(-1.0, 3.0), vec2(3.0, -1.0)); @vertex fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> @builtin(position) vec4<f32> { return vec4(pos[vertexIndex], 1.0, 1.0); } @fragment fn fragmentMain() -> @location(0) vec4<f32> { return vec4(1.0, 0.0, 0.0, 1.0); } ` ; const shaderModule= gpuDevice. createShaderModule({ code: shaderSource, });
9.1.1.1. 着色器模块编译提示
着色器模块编译提示是可选的附加信息,用于指明某个 GPUShaderModule
的入口点将来如何被使用。对于某些实现,这些信息可以帮助更早完成着色器模块编译,从而提升性能。
dictionary {
GPUShaderModuleCompilationHint required USVString ; (
entryPoint GPUPipelineLayout or GPUAutoLayoutMode )layout ; };
layout
,类型为(GPUPipelineLayout or GPUAutoLayoutMode)
-
一个
GPUPipelineLayout
,表示GPUShaderModule
在后续createComputePipeline()
或createRenderPipeline()
调用中可能会与之配合使用。 如果设置为"auto"
,则会为该 hint 关联的入口点使用默认管线布局。
createShaderModule()
和 createComputePipeline()
/
createRenderPipeline()
之间提供一致的信息。
如果应用在调用 createShaderModule()
时无法提供 hint 信息,通常不应因此推迟调用 createShaderModule()
,而应在
compilationHints
序列或单个 GPUShaderModuleCompilationHint
成员中省略未知信息。省略该信息可能导致编译被延迟到 createComputePipeline()
/ createRenderPipeline()
。
如果作者无法确保传给 createShaderModule()
的 hint 信息会与后续 createComputePipeline()
/
createRenderPipeline()
使用的信息一致,则应避免向 createShaderModule()
提供该信息,因为不匹配的 hint 可能导致不必要的编译发生。
9.1.2. 着色器模块编译信息
enum {
GPUCompilationMessageType ,
"error" ,
"warning" , }; [
"info" Exposed =(Window ,Worker ),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 ,Worker ),Serializable ,SecureContext ]interface {
GPUCompilationInfo readonly attribute FrozenArray <GPUCompilationMessage >; };
messages
GPUCompilationMessage
是 GPUShaderModule
编译器生成的信息、警告或错误消息。这些消息面向开发者、可读性强,用于帮助诊断着色器 code
中的问题。每条消息可能对应着色器代码中的某个具体位置、某段子串,或根本不对应代码中的任何具体位置。
GPUCompilationMessage
具有以下属性:
message
,类型为 DOMString,只读-
该编译消息的人类可读、可本地化文本。
注意:
message
应遵循字符串语言和方向元信息最佳实践,包括未来可能出现的相关标准。编者注: 截至目前,还没有兼容并与传统 API 保持一致的语言/方向推荐方案,未来如有应正式采纳。
type
,类型为 GPUCompilationMessageType,只读-
消息的严重级别。
如果
type
为"error"
, 则该消息对应 shader-creation error。 lineNum
,类型为 unsigned long long,只读-
消息对应的着色器
code
的行号。值为 1 起始,1
表示第一行。行由换行符分隔。如果
message
对应某个子串,则此处为子串起始行。若消息不对应代码中任何具体点,则为0
。 linePos
,类型为 unsigned long long,只读-
从第
lineNum
行起始到消息对应点或子串起始的 UTF-16 单元偏移量。值为 1 起始,linePos
为1
表示该行第一个单元。如对应子串,则指向子串第一个 UTF-16 单元。若消息不对应代码中任何具体点,则为
0
。 offset
,类型为 unsigned long long,只读-
从着色器
code
起始到消息对应点或子串起始的 UTF-16 单元偏移量。必须与lineNum
和linePos
指向同一位置。若消息不对应代码中任何具体点,则为0
。 length
,类型为 unsigned long long,只读-
消息对应子串的 UTF-16 单元数量。若消息不对应子串则为
0
。
注意: GPUCompilationMessage
.lineNum
和 GPUCompilationMessage
.linePos
都是从 1 起始,便于与大多数文本编辑器的行列号一致。
注意: GPUCompilationMessage
.offset
和 GPUCompilationMessage
.length
可直接传给 substr()
,取出消息对应的着色器 code
子串。
getCompilationInfo()
-
返回
GPUShaderModule
编译期间的所有消息。消息的位置、顺序和内容均为实现自定义,不保证以
lineNum
排序。设备时间线 同步步骤:-
令 event 在 this 的着色器模块创建完成(无论成功与否)时发生。
-
监听时间线事件 event 于 this.
[[device]]
, 后续步骤在 contentTimeline 上执行。
内容时间线步骤:-
令 info 为新的
GPUCompilationInfo
。 -
令 messages 为 this 的着色器模块创建期间产生的所有错误、警告或信息消息(如设备丢失则为
[]
)。 -
对于 messages 中每条 message:
-
令 m 为新的
GPUCompilationMessage
。 -
设置 m.
message
为 message 的文本。
-
-
resolve promise 为 info。
-
10. 管线
管线(pipeline),无论是 GPUComputePipeline
还是 GPURenderPipeline
,
都代表由 GPU 硬件、驱动和用户代理共同完成的完整功能流程:处理绑定和顶点缓冲区等输入数据,并产生输出(比如输出渲染目标的颜色)。
结构上,管线由一系列可编程阶段(着色器)和固定功能状态(如混合模式)组成。
注意: 在内部,具体实现平台可能会把部分固定功能状态转换成着色器代码,并与用户提供的着色器链接。这种链接是管线对象必须整体创建的原因之一。
这种组合状态作为单个对象创建(GPUComputePipeline
或 GPURenderPipeline
),
并可通过单条指令切换(分别为 GPUComputePassEncoder
.setPipeline()
或 GPURenderCommandsMixin
.setPipeline()
)。
创建管线有两种方式:
- 同步(即时)管线创建
-
createComputePipeline()
和createRenderPipeline()
返回可立即在 pass encoder 中使用的管线对象。注意: 返回的是句柄对象,但实际管线创建并非同步。如果管线创建耗时较长,可能在从创建到首次
setPipeline()
使用、finish()
、或submit()
之间的某一处导致 设备时间线 阻塞,具体点未规定。 - 异步管线创建
-
createComputePipelineAsync()
和createRenderPipelineAsync()
返回Promise
,管线创建完成时解析为管线对象。失败时,
Promise
拒绝并返回GPUPipelineError
。
GPUPipelineError
描述管线创建失败。
[Exposed =(Window ,Worker ),SecureContext ,Serializable ]interface GPUPipelineError :DOMException {constructor (optional DOMString message = "",GPUPipelineErrorInit options );readonly attribute GPUPipelineErrorReason reason ; };dictionary {
GPUPipelineErrorInit required GPUPipelineErrorReason ; };
reason enum GPUPipelineErrorReason {"validation" ,"internal" , };
GPUPipelineError
构造函数:
constructor()
-
参数:
GPUPipelineError.constructor() 方法参数。 参数 类型 可为 null 可选 描述 message
DOMString
✘ ✔ 基础 DOMException
的错误消息。options
GPUPipelineErrorInit
✘ ✘ 特定于 GPUPipelineError
的选项。内容时间线步骤:
GPUPipelineError
具有以下属性:
reason
,类型为 GPUPipelineErrorReason,只读-
只读slot-backed 属性,暴露管线创建中遇到的错误类型,为
GPUPipelineErrorReason
:
-
按
DOMException
的序列化步骤处理 value 和 serialized。
-
按
DOMException
的反序列化步骤处理 value 和 serialized。
10.1. 基础管线
enum {
GPUAutoLayoutMode , };
"auto" dictionary :
GPUPipelineDescriptorBase GPUObjectDescriptorBase {required (GPUPipelineLayout or GPUAutoLayoutMode )layout ; };
layout
,类型为(GPUPipelineLayout or GPUAutoLayoutMode)
-
本管线的
GPUPipelineLayout
, 或"auto"
以自动生成管线布局。注意: 若使用
"auto"
, 则此管线无法与其它管线共享GPUBindGroup
。
interface mixin { [
GPUPipelineBase NewObject ]GPUBindGroupLayout getBindGroupLayout (unsigned long index ); };
GPUPipelineBase
具有以下设备时间线属性:
[[layout]]
,类型为GPUPipelineLayout
-
定义可与
this
配合使用的资源布局。
GPUPipelineBase
具有以下方法:
getBindGroupLayout(index)
-
获取与
GPUPipelineBase
在index
处的GPUBindGroupLayout
兼容的GPUBindGroupLayout
。调用对象:GPUPipelineBase
this参数:
GPUPipelineBase.getBindGroupLayout(index) 方法参数。 参数 类型 可为 null 可选 描述 index
unsigned long
✘ ✘ 管线布局 [[bindGroupLayouts]]
序列的索引。内容时间线步骤:
-
令 layout 为新的
GPUBindGroupLayout
对象。 -
在 this 的 设备时间线上执行 初始化步骤。
-
返回 layout。
设备时间线 初始化步骤:-
令 limits = this.
[[device]]
.[[limits]]
。 -
若下列任一条件不满足,则生成校验错误,使 layout 无效并返回。
-
this 必须有效。
-
index < limits.
maxBindGroups
。
-
-
初始化 layout 使其为 this.
[[layout]]
.[[bindGroupLayouts]]
[index] 的副本。注意:
GPUBindGroupLayout
永远是按值使用,不按引用,因此等价于返回同一个内部对象并创建新WebGPU 接口。每次都返回新GPUBindGroupLayout
WebGPU 接口,以避免 内容时间线与 设备时间线之间的往返。
-
10.1.1. 默认管线布局
如果 GPUPipelineBase
对象在创建时 layout
设置为 "auto"
,则会自动创建并使用一个默认布局。
注意: 默认布局为简易管线提供便利,大多数场景推荐显式布局。由默认布局创建的绑定组无法与其他管线共享,且默认布局结构在着色器变更时可能发生变化,导致绑定组创建异常。
为 GPUPipelineBase
pipeline 创建默认管线布局的
设备时间线步骤如下:
-
令 groupCount = 0。
-
令 groupDescs 为 device.
[[limits]]
.maxBindGroups
个新的GPUBindGroupLayoutDescriptor
对象序列。 -
对每个 groupDesc in groupDescs:
-
对创建 pipeline 时描述中的每个
GPUProgrammableStage
stageDesc:-
令 shaderStage 为 stageDesc 在 pipeline 中对应的
GPUShaderStageFlags
。 -
令 entryPoint = get the entry point(shaderStage, stageDesc)。断言 entryPoint 非
null
。 -
对 entryPoint 静态使用的每个资源 resource:
-
令 group 为 resource 的 "group" 标注。
-
令 binding 为 resource 的 "binding" 标注。
-
令 entry 为新的
GPUBindGroupLayoutEntry
。 -
设置 entry.
binding
为 binding。 -
设置 entry.
visibility
为 shaderStage。 -
若 resource 为采样器绑定:
-
令 samplerLayout 为新的
GPUSamplerBindingLayout
。 -
设置 entry.
sampler
为 samplerLayout。
-
-
若 resource 为比较采样器绑定:
-
令 samplerLayout 为新的
GPUSamplerBindingLayout
。 -
设置 samplerLayout.
type
为"comparison"
。 -
设置 entry.
sampler
为 samplerLayout。
-
-
若 resource 为缓冲区绑定:
-
令 bufferLayout 为新的
GPUBufferBindingLayout
。 -
设置 bufferLayout.
minBindingSize
为 resource 的最小缓冲绑定大小。 -
如果 resource 为只读存储缓冲区:
-
设置 bufferLayout.
type
为"read-only-storage"
。
-
-
如果 resource 为存储缓冲区:
-
设置 entry.
buffer
为 bufferLayout。
-
-
若 resource 为采样纹理绑定:
-
令 textureLayout 为新的
GPUTextureBindingLayout
。 -
如果 resource 为深度纹理绑定:
-
设置 textureLayout.
sampleType
为"depth"
。
否则,根据 resource 采样类型:
f32
且存在对 resource 的静态使用,且在带采样器的纹理内建函数调用中-
设置 textureLayout.
sampleType
为"float"
。 f32
否则-
设置 textureLayout.
sampleType
为"unfilterable-float"
。 i32
-
设置 textureLayout.
sampleType
为"sint"
。 u32
-
设置 textureLayout.
sampleType
为"uint"
。
-
-
设置 textureLayout.
viewDimension
为 resource 的维度。 -
若 resource 为多采样纹理:
-
设置 textureLayout.
multisampled
为true
。
-
-
设置 entry.
texture
为 textureLayout。
-
-
若 resource 为存储纹理绑定:
-
令 storageTextureLayout 为新的
GPUStorageTextureBindingLayout
。 -
设置 storageTextureLayout.
format
为 resource 的格式。 -
设置 storageTextureLayout.
viewDimension
为 resource 的维度。 -
若访问模式为:
read
-
设置 textureLayout.
access
为"read-only"
。 write
-
设置 textureLayout.
access
为"write-only"
。 read_write
-
设置 textureLayout.
access
为"read-write"
。
-
设置 entry.
storageTexture
为 storageTextureLayout。
-
-
设置 groupCount = max(groupCount, group + 1)。
-
若 groupDescs[group] 已存在
binding
等于 binding 的条目 previousEntry:-
若 entry 的
visibility
不同于 previousEntry:-
将 entry.
visibility
的比特位并入 previousEntry.visibility
。
-
-
若 resource 为缓冲区绑定且 entry 的
buffer
.minBindingSize
大于 previousEntry:-
设置 previousEntry.
buffer
.minBindingSize
为 entry.buffer
.minBindingSize
。
-
-
若 resource 为采样纹理绑定且 entry 的
texture
.sampleType
与 previousEntry 不同,且二者均为"float"
或"unfilterable-float"
:-
设置 previousEntry.
texture
.sampleType
为"float"
。
-
-
如 entry 与 previousEntry 其他属性不同:
-
返回
null
(导致管线创建失败)。
-
-
若 resource 为存储纹理绑定,entry.storageTexture.
access
为"read-write"
,previousEntry.storageTexture.access
为"write-only"
,且格式兼容,见 § 26.1.1 普通色彩格式表:-
设置 previousEntry.storageTexture.
access
为"read-write"
。
-
-
-
否则
-
将 entry 添加到 groupDescs[group]。
-
-
-
-
令 groupLayouts 为新 列表。
-
对 i 从 0 到 groupCount - 1:
-
令 groupDesc = groupDescs[i]。
-
令 bindGroupLayout = device.
createBindGroupLayout()
(groupDesc)。 -
设置 bindGroupLayout.
[[exclusivePipeline]]
为 pipeline。 -
将 bindGroupLayout 添加到 groupLayouts。
-
-
令 desc 为新的
GPUPipelineLayoutDescriptor
。 -
设置 desc.
bindGroupLayouts
为 groupLayouts。 -
返回 device.
createPipelineLayout()
(desc)。
10.1.2. GPUProgrammableStage
GPUProgrammableStage
描述了用户提供的 GPUShaderModule
中控制 管线某个可编程阶段的入口点。
入口点名称遵循 WGSL 标识符对比的规则。
dictionary GPUProgrammableStage {required GPUShaderModule module ;USVString entryPoint ;record <USVString ,GPUPipelineConstantValue >constants = {}; };typedef double GPUPipelineConstantValue ; // 可表示 WGSL 的 bool、f32、i32、u32、以及启用时的 f16。
GPUProgrammableStage
具有以下成员:
module
,类型为 GPUShaderModule-
包含本可编程阶段将要执行代码的
GPUShaderModule
。 entryPoint
,类型为 USVString-
本阶段执行时将使用的
module
中的函数名。注意: 虽然
entryPoint
不是必填项,消费GPUProgrammableStage
的方法必须使用“获取入口点”算法确定实际入口点。 constants
,类型为 record<USVString, GPUPipelineConstantValue>,默认值为{}
-
指定着色器模块
module
中 可被管线重写(pipeline-overridable) 常量的值。每个此类 可重写常量都唯一由一个 可重写常量标识符字符串标识, 代表其声明指定的 管线常量 ID,否则为常量名称。
每个键值对的 key 必须等于对应常量的 标识符字符串,其对比规则见WGSL 标识符对比。管线执行时,该常量将取指定值。
值类型为
GPUPipelineConstantValue
,即double
。会转换为常量的 WGSL 类型(bool/i32/u32/f32/f16)。转换失败会生成校验错误。WGSL 中定义的管线可重写常量:@id ( 0 ) override has_point_light : bool= true ; // 算法控制。 @id ( 1200 ) override specular_param : f32= 2.3 ; // 数值控制。 @id ( 1300 ) override gain : f32; // 必须重写。 override width : f32= 0.0 ; // 通过 API 使用名字 "width" 指定 // override depth : f32; // 通过 API 使用名字 "depth" 指定,必须重写。 override height = 2 * depth ; // 默认值依赖另一个可重写常量。 对应的 JavaScript 代码,仅传递必须重写(无默认值)的常量:
{ // ... constants: { 1300 : 2.0 , // "gain" depth: - 1 , // "depth" } } 对应的 JavaScript 代码,重写所有常量:
{ // ... constants: { 0 : false , // "has_point_light" 1200 : 3.0 , // "specular_param" 1300 : 2.0 , // "gain" width: 20 , // "width" depth: - 1 , // "depth" height: 15 , // "height" } }
GPUShaderStage
stage,
GPUProgrammableStage
descriptor),请执行如下设备时间线步骤:
-
如果 descriptor.
entryPoint
已提供:-
如果 descriptor.
module
包含名称与 descriptor.entryPoint
相等且着色器阶段等于 stage 的入口点,则返回该入口点。否则,返回
null
。
否则:
-
如果 descriptor.
module
中着色器阶段等于 stage 的入口点恰好有一个,则返回该入口点。否则,返回
null
。
-
参数:
-
GPUShaderStage
stage -
GPUProgrammableStage
descriptor -
GPUPipelineLayout
layout -
GPUDevice
device
以下所有步骤中的要求都必须满足。若有任一不满足,则返回 false
;全部满足则返回 true
。
-
令 entryPoint = 获取入口点(stage, descriptor)。
-
entryPoint 必须不为
null
。 -
对 entryPoint 静态使用的每个 binding:
-
验证着色器绑定(validating shader binding)(binding, layout) 必须返回
true
。
-
-
对 entryPoint 所在着色器阶段所有函数中的每个纹理内建函数调用,若同时使用了 sampled texture 或 depth texture 类型的 textureBinding 以及类型为
sampler
(排除sampler_comparison
)的 samplerBinding:-
令 texture 为 textureBinding 对应的
GPUBindGroupLayoutEntry
。 -
令 sampler 为 samplerBinding 对应的
GPUBindGroupLayoutEntry
。 -
若 sampler.
type
为"filtering"
, 则 texture.sampleType
必须为"float"
。
注意:
"comparison"
采样器只能用于"depth"
纹理,因为只有该类型能绑定到 WGSLtexture_depth_*
绑定点。 -
-
对 descriptor.
constants
的每个 key → value:-
key 必须等于着色器模块 descriptor.
module
中某个 可重写常量(pipeline-overridable) 的 标识符字符串(判断规则见 WGSL 标识符对比)。管线可重写常量无需被 entryPoint 静态使用。令该常量类型为 T。 -
将 IDL 值 value 转换为 WGSL 类型 T 时不得抛出
TypeError
。
-
-
对 entryPoint 静态使用的每个管线可重写常量 key:
参数:
-
着色器绑定声明 variable,为从着色器模块反射得到的模块作用域变量声明
-
GPUPipelineLayout
layout
令 bindGroup 为绑定组索引,bindIndex 为绑定索引,均来自着色器绑定声明 variable。
当且仅当下列所有条件满足时,返回 true
:
-
layout.
[[bindGroupLayouts]]
[bindGroup] 包含 一个GPUBindGroupLayoutEntry
entry,满足 entry.binding
== bindIndex。 -
若 entry 的binding member为:
buffer
-
"uniform"
-
variable 声明于地址空间
uniform
。 "storage"
-
variable 声明于地址空间
storage
且访问模式为read_write
。 "read-only-storage"
-
variable 声明于地址空间
storage
且访问模式为read
。
若 entry.
buffer
.minBindingSize
非0
, 则其必须不少于着色器中对应缓冲绑定变量的最小缓冲绑定大小。 sampler
-
"filtering"
或"non-filtering"
-
variable 类型为
sampler
。 "comparison"
-
variable 类型为
sampler_comparison
。
texture
-
当且仅当 entry.
texture
.multisampled
为true
时,variable 类型为texture_multisampled_2d<T>
或texture_depth_multisampled_2d<T>
。若 entry.
texture
.sampleType
为:"float"
,"unfilterable-float"
,"sint"
或"uint"
-
variable 类型为:
-
texture_1d<T>
-
texture_2d<T>
-
texture_2d_array<T>
-
texture_cube<T>
-
texture_cube_array<T>
-
texture_3d<T>
-
texture_multisampled_2d<T>
若 entry.
texture
.sampleType
为:"float"
或"unfilterable-float"
-
采样类型
T
为f32
。 "sint"
-
采样类型
T
为i32
。 "uint"
-
采样类型
T
为u32
。
-
"depth"
-
variable 类型为下列之一:
-
texture_2d<T>
-
texture_2d_array<T>
-
texture_cube<T>
-
texture_cube_array<T>
-
texture_multisampled_2d<T>
-
texture_depth_2d
-
texture_depth_2d_array
-
texture_depth_cube
-
texture_depth_cube_array
-
texture_depth_multisampled_2d
其中采样类型
T
为f32
。 -
若 entry.
texture
.viewDimension
为:"1d"
-
variable 类型为
texture_1d<T>
。 "2d"
-
variable 类型为
texture_2d<T>
或texture_multisampled_2d<T>
。 "2d-array"
-
variable 类型为
texture_2d_array<T>
。 "cube"
-
variable 类型为
texture_cube<T>
。 "cube-array"
-
variable 类型为
texture_cube_array<T>
。 "3d"
-
variable 类型为
texture_3d<T>
。
storageTexture
-
若 entry.
storageTexture
.viewDimension
为:"1d"
-
variable 类型为
texture_storage_1d<T, A>
。 "2d"
-
variable 类型为
texture_storage_2d<T, A>
。 "2d-array"
-
variable 类型为
texture_storage_2d_array<T, A>
。 "3d"
-
variable 类型为
texture_storage_3d<T, A>
。
若 entry.
storageTexture
.access
为:"write-only"
-
访问模式
A
为write
。 "read-only"
-
访问模式
A
为read
。 "read-write"
-
访问模式
A
为read_write
或write
。
纹素格式
T
必须等于 entry.storageTexture
.format
。
-
令 T 为 var 的存储类型(store type)。
-
若 T 是运行时尺寸数组,或包含运行时尺寸数组,则将该
array<E>
替换为array<E, 1>
。注意: 这样确保至少有一个元素内存,允许数组索引被限制在实际长度范围内,从而保证内存访问安全。
-
返回 SizeOf(T)。
注意: 强制此下限可确保通过缓冲变量的读写只会访问缓冲区界限内的内存。
10.2. GPUComputePipeline
GPUComputePipeline
是一种管线,控制计算着色器阶段,
并可用于 GPUComputePassEncoder
。
计算输入和输出均通过绑定传递,受指定的 GPUPipelineLayout
控制。
输出对应类型为 "storage"
的 buffer
绑定,
以及类型为 "write-only"
或 "read-write"
的 storageTexture
绑定。
计算管线的阶段:
-
计算着色器(Compute shader)
[Exposed =(Window ,Worker ),SecureContext ]interface GPUComputePipeline { };GPUComputePipeline includes GPUObjectBase ;GPUComputePipeline includes GPUPipelineBase ;
10.2.1. 计算管线的创建
GPUComputePipelineDescriptor
描述了一个计算管线。更多细节参见§ 23.1 计算。
dictionary :
GPUComputePipelineDescriptor GPUPipelineDescriptorBase {required GPUProgrammableStage compute ; };
GPUComputePipelineDescriptor
具有以下成员:
compute
,类型为 GPUProgrammableStage-
描述该管线的计算着色器入口点。
createComputePipeline(descriptor)
-
使用同步管线创建方式创建一个
GPUComputePipeline
。调用对象:GPUDevice
this.参数:
GPUDevice.createComputePipeline(descriptor) 方法参数。 参数 类型 可为 null 可选 描述 descriptor
GPUComputePipelineDescriptor
✘ ✘ 要创建的 GPUComputePipeline
的描述信息。内容时间线步骤:
-
令 pipeline = ! 创建新 WebGPU 对象(create a new WebGPU object)(this,
GPUComputePipeline
, descriptor)。 -
在 this 的 设备时间线上执行 初始化步骤。
-
返回 pipeline。
设备时间线 初始化步骤:-
若 descriptor.
layout
为"auto"
, 则令 layout 为 默认管线布局; 否则,layout = descriptor.layout
。 -
以下所有步骤要求都必须满足。若有不满足,则生成校验错误,使 pipeline 无效并返回。
-
layout 必须可与 this 配合使用。
-
验证 GPUProgrammableStage(
COMPUTE
, descriptor.compute
, layout, this) 必须成功。 -
令 entryPoint = 获取入口点(
COMPUTE
, descriptor.compute
)。断言 entryPoint 不为
null
。 -
令 workgroupStorageUsed 为 roundUp(16, SizeOf(T)) 的和, 其中 T 为 entryPoint 静态使用的所有地址空间为 "workgroup" 的变量类型。
workgroupStorageUsed 必须 ≤ device.limits.
maxComputeWorkgroupStorageSize
。 -
entryPoint 必须每个工作组内使用的线程数 ≤ device.limits.
maxComputeInvocationsPerWorkgroup
。 -
entryPoint 的
workgroup_size
属性的每个分量 必须 ≤ [device.limits.maxComputeWorkgroupSizeX
, device.limits.maxComputeWorkgroupSizeY
, device.limits.maxComputeWorkgroupSizeZ
]。
-
-
如实现管线创建过程中产生了任何管线创建未分类错误, 生成内部错误,使 pipeline 无效并返回。
注意: 即便实现已在着色器模块创建时检测到未分类错误,也会在此处抛出。
-
设置 pipeline.
[[layout]]
= layout。
-
createComputePipelineAsync(descriptor)
-
使用异步管线创建方式创建
GPUComputePipeline
。 返回的Promise
会在管线准备好可用时 resolve。若管线创建失败,返回的
Promise
将 reject,并返回GPUPipelineError
。 (此时不会向 device 派发GPUError
。)注意: 建议尽可能使用本方法,可避免阻塞队列时间线的管线编译工作。
调用对象:GPUDevice
this.参数:
GPUDevice.createComputePipelineAsync(descriptor) 方法参数。 参数 类型 可为 null 可选 描述 descriptor
GPUComputePipelineDescriptor
✘ ✘ 要创建的 GPUComputePipeline
的描述信息。返回:
Promise
<GPUComputePipeline
>内容时间线步骤:
设备时间线 初始化步骤:-
令 pipeline 为新建的
GPUComputePipeline
, 类似于调用 this.createComputePipeline()
时传入 descriptor,但将产生的错误捕获为 error,而不是派发到 device。 -
令 event 在 pipeline 的管线创建(无论成功与否)完成时发生。
-
监听时间线事件 event 于 this.
[[device]]
, 后续步骤于 设备时间线执行。
设备时间线步骤:-
-
在 contentTimeline 上执行下列步骤:
-
返回。
注意: 设备丢失不会产生错误。参见 § 22 错误与调试。
-
-
若 pipeline 无效 且 error 为 内部错误,在 contentTimeline 上执行下列步骤并返回:
内容时间线步骤:-
reject promise,返回
GPUPipelineError
,reason
为"internal"
。
-
-
若 pipeline 无效 且 error 为 校验错误,在 contentTimeline 上执行下列步骤并返回:
内容时间线步骤:-
reject promise,返回
GPUPipelineError
,reason
为"validation"
。
-
-
GPUComputePipeline
:
const computePipeline= gpuDevice. createComputePipeline({ layout: pipelineLayout, compute: { module: computeShaderModule, entryPoint: 'computeMain' , } });
10.3. GPURenderPipeline
GPURenderPipeline
是一种管线,控制顶点和片元着色器阶段,并可用于 GPURenderPassEncoder
以及 GPURenderBundleEncoder
。
渲染管线的输入包括:
-
绑定,根据指定的
GPUPipelineLayout
-
顶点和索引缓冲区,由
GPUVertexState
描述 -
颜色附件,由
GPUColorTargetState
描述 -
(可选)深度-模板附件,由
GPUDepthStencilState
描述
渲染管线的输出包括:
-
storageTexture
绑定,其access
为"write-only"
或"read-write"
-
颜色附件,由
GPUColorTargetState
描述 -
(可选)深度-模板附件,由
GPUDepthStencilState
描述
渲染管线包含以下渲染阶段(render stages):
-
顶点抓取,由
GPUVertexState.buffers
控制 -
顶点着色器,由
GPUVertexState
控制 -
图元组装,由
GPUPrimitiveState
控制 -
光栅化,由
GPUPrimitiveState
、GPUDepthStencilState
、 以及GPUMultisampleState
控制 -
片元着色器,由
GPUFragmentState
控制 -
模板测试和操作,由
GPUDepthStencilState
控制 -
深度测试与写入,由
GPUDepthStencilState
控制 -
输出合并,由
GPUFragmentState.targets
控制
[Exposed =(Window ,Worker ),SecureContext ]interface GPURenderPipeline { };GPURenderPipeline includes GPUObjectBase ;GPURenderPipeline includes GPUPipelineBase ;
GPURenderPipeline
具有以下设备时间线属性:
[[descriptor]]
,类型为GPURenderPipelineDescriptor
, 只读-
描述此管线的
GPURenderPipelineDescriptor
。所有可选字段均已定义。
[[writesDepth]]
,类型为boolean
, 只读-
如果管线会写入深度/模板附件的深度分量,则为 true。
[[writesStencil]]
,类型为boolean
, 只读-
如果管线会写入深度/模板附件的模板分量,则为 true。
10.3.1. 渲染管线的创建
GPURenderPipelineDescriptor
通过配置各渲染阶段描述一个渲染管线。详见 § 23.2 渲染。
dictionary :
GPURenderPipelineDescriptor GPUPipelineDescriptorBase {required GPUVertexState vertex ;GPUPrimitiveState primitive = {};GPUDepthStencilState depthStencil ;GPUMultisampleState multisample = {};GPUFragmentState fragment ; };
GPURenderPipelineDescriptor
具有以下成员:
vertex
,类型为 GPUVertexState-
描述管线的顶点着色器入口点和其输入缓冲区布局。
primitive
,类型为 GPUPrimitiveState,默认值为{}
-
描述管线的图元相关属性。
depthStencil
,类型为 GPUDepthStencilState-
描述可选的深度-模板属性,包括测试、操作和偏移。
multisample
,类型为 GPUMultisampleState,默认值为{}
-
描述管线的多重采样属性。
fragment
,类型为 GPUFragmentState-
描述管线的片元着色器入口点及其输出颜色。如未提供,则启用§ 23.2.8 无颜色输出模式。
createRenderPipeline(descriptor)
-
使用同步管线创建方式创建
GPURenderPipeline
。调用对象:GPUDevice
this.参数:
GPUDevice.createRenderPipeline(descriptor) 方法参数。 参数 类型 可为 null 可选 描述 descriptor
GPURenderPipelineDescriptor
✘ ✘ 要创建的 GPURenderPipeline
描述信息。内容时间线步骤:
-
-
遍历 descriptor.
fragment
.targets
的所有非null
colorState:-
? 校验纹理格式所需特性 用 colorState.
format
和 this.[[device]]
。
-
-
-
若 descriptor.
depthStencil
已提供:-
? 校验纹理格式所需特性 用 descriptor.
depthStencil
.format
和 this.[[device]]
。
-
-
令 pipeline = ! 创建新 WebGPU 对象(this,
GPURenderPipeline
, descriptor)。 -
在 this 的 设备时间线上执行 初始化步骤。
-
返回 pipeline。
设备时间线 初始化步骤:-
若 descriptor.
layout
为"auto"
, 则令 layout 为 默认管线布局, 否则 layout = descriptor.layout
。 -
以下步骤要求全部必须满足。如有不满足,则生成校验错误、使 pipeline 无效并返回。
-
layout 必须可与 this 配合使用。
-
验证 GPURenderPipelineDescriptor(descriptor, layout, this) 必须成功。
-
令 vertexBufferCount 为 descriptor.
vertex
.buffers
中最后一个非 null 项的索引加 1,如无则为 0。 -
layout.
[[bindGroupLayouts]]
.size + vertexBufferCount 必须 ≤ this.[[device]]
.[[limits]]
.maxBindGroupsPlusVertexBuffers
。
-
-
如实现管线创建过程中产生任何管线创建未分类错误, 生成内部错误、使 pipeline 无效并返回。
注意: 即使着色器模块创建时检测到未分类错误,错误也会在此处抛出。
-
设置 pipeline.
[[descriptor]]
= descriptor。 -
设置 pipeline.
[[writesDepth]]
= false。 -
设置 pipeline.
[[writesStencil]]
= false。 -
令 depthStencil = descriptor.
depthStencil
。 -
如 depthStencil 非 null:
-
如 depthStencil.
depthWriteEnabled
已提供:-
设置 pipeline.
[[writesDepth]]
= depthStencil.depthWriteEnabled
。
-
-
如 depthStencil.
stencilWriteMask
非 0:-
令 stencilFront = depthStencil.
stencilFront
。 -
令 stencilBack = depthStencil.
stencilBack
。 -
如 cullMode 不为
"front"
,且 stencilFront.passOp
、 stencilFront.depthFailOp
、 stencilFront.failOp
任意一项非"keep"
:-
设置 pipeline.
[[writesStencil]]
= true。
-
-
如 cullMode 不为
"back"
,且 stencilBack.passOp
、 stencilBack.depthFailOp
、 stencilBack.failOp
任意一项非"keep"
:-
设置 pipeline.
[[writesStencil]]
= true。
-
-
-
-
设置 pipeline.
[[layout]]
= layout。
-
createRenderPipelineAsync(descriptor)
-
使用异步管线创建方式创建
GPURenderPipeline
。 返回的Promise
会在管线准备好可用时 resolve。若管线创建失败,返回的
Promise
将 reject,并返回GPUPipelineError
。 (不会向 device 派发GPUError
。)注意: 建议尽量使用本方法,可避免阻塞队列时间线的管线编译工作。
调用对象:GPUDevice
this.参数:
GPUDevice.createRenderPipelineAsync(descriptor) 方法参数。 参数 类型 可为 null 可选 描述 descriptor
GPURenderPipelineDescriptor
✘ ✘ 要创建的 GPURenderPipeline
描述信息。返回:
Promise
<GPURenderPipeline
>内容时间线步骤:
设备时间线 初始化步骤:-
令 pipeline 为新建的
GPURenderPipeline
, 类似于调用 this.createRenderPipeline()
时传入 descriptor,但将产生的错误捕获为 error,而不是派发到 device。 -
令 event 在 pipeline 的管线创建(无论成功与否)完成时发生。
-
监听时间线事件 event 于 this.
[[device]]
, 后续步骤于 设备时间线执行。
设备时间线步骤:-
-
在 contentTimeline 上执行下列步骤:
-
返回。
注意: 设备丢失不会产生错误。参见 § 22 错误与调试。
-
-
若 pipeline 无效 且 error 为 内部错误,在 contentTimeline 上执行下列步骤并返回:
内容时间线步骤:-
reject promise,返回
GPUPipelineError
,reason
为"internal"
。
-
-
若 pipeline 无效 且 error 为 校验错误,在 contentTimeline 上执行下列步骤并返回:
内容时间线步骤:-
reject promise,返回
GPUPipelineError
,reason
为"validation"
。
-
-
参数:
-
GPURenderPipelineDescriptor
descriptor -
GPUPipelineLayout
layout -
GPUDevice
device
设备时间线步骤:
-
若下列所有条件均满足则返回
true
:-
验证 GPUVertexState(device, descriptor.
vertex
, layout) 成功。 -
-
验证 GPUFragmentState(device, descriptor.
fragment
, layout) 成功。 -
若 sample_mask 内建变量为 descriptor.
fragment
的 着色器阶段输出:-
descriptor.
multisample
.alphaToCoverageEnabled
为false
。
-
-
若 frag_depth 内建变量为 descriptor.
fragment
的 着色器阶段输出:-
descriptor.
depthStencil
已提供,且 descriptor.depthStencil
.format
必须带有 深度通道。
-
-
-
验证 GPUPrimitiveState(descriptor.
primitive
, device) 成功。 -
如 descriptor.
depthStencil
已提供:-
验证 GPUDepthStencilState(descriptor.
depthStencil
, descriptor.primitive
.topology
) 成功。
-
-
验证 GPUMultisampleState(descriptor.
multisample
) 成功。 -
如 descriptor.
multisample
.alphaToCoverageEnabled
为 true: -
必须至少存在一个附件:
-
存在 descriptor.
depthStencil
。
-
验证阶段间接口(validating inter-stage interfaces)(device, descriptor) 返回
true
。
-
参数:
-
GPUDevice
device -
GPURenderPipelineDescriptor
descriptor
返回值: boolean
设备时间线步骤:
-
令 maxVertexShaderOutputVariables = device.limits.
maxInterStageShaderVariables
。 -
令 maxVertexShaderOutputLocation = device.limits.
maxInterStageShaderVariables
- 1。 -
如 descriptor.
primitive
.topology
为"point-list"
:-
令 maxVertexShaderOutputVariables 减 1。
-
-
如 clip_distances 在 descriptor.
vertex
的输出中声明:-
令 clipDistancesSize 为 clip_distances 的数组大小。
-
令 maxVertexShaderOutputVariables 减 ceil(clipDistancesSize / 4)。
-
令 maxVertexShaderOutputLocation 减 ceil(clipDistancesSize / 4)。
-
-
如下要求有任意一项不满足则返回
false
:-
用户自定义顶点输出数量不超过 maxVertexShaderOutputVariables。
-
每个用户自定义顶点输出的location ≤ maxVertexShaderOutputLocation。
-
-
-
令 maxFragmentShaderInputVariables = device.limits.
maxInterStageShaderVariables
。 -
如
front_facing
、sample_index
或sample_mask
内建变量为 descriptor.fragment
的输入:-
令 maxFragmentShaderInputVariables 减 1。
-
-
如有下列任一项不满足则返回
false
: -
断言每个用户自定义片元输入的location均小于 device.limits.
maxInterStageShaderVariables
。(由上规则推得)
-
-
返回
true
。
GPURenderPipeline
:
const renderPipeline= gpuDevice. createRenderPipeline({ layout: pipelineLayout, vertex: { module: shaderModule, entryPoint: 'vertexMain' }, fragment: { module: shaderModule, entryPoint: 'fragmentMain' , targets: [{ format: 'bgra8unorm' , }], } });
10.3.2. 图元状态(Primitive State)
dictionary {
GPUPrimitiveState GPUPrimitiveTopology topology = "triangle-list";GPUIndexFormat stripIndexFormat ;GPUFrontFace frontFace = "ccw";GPUCullMode cullMode = "none"; // 需要 "depth-clip-control" 特性。boolean unclippedDepth =false ; };
GPUPrimitiveState
拥有以下成员,描述 GPURenderPipeline
如何根据顶点输入构造和光栅化图元:
topology
,类型为 GPUPrimitiveTopology,默认值为"triangle-list"
-
由顶点输入生成的图元类型。
stripIndexFormat
, 类型为 GPUIndexFormat-
用于带 strip 拓扑 (
"line-strip"
或"triangle-strip"
) 的管线, 决定索引缓冲区格式和图元重启值 ("uint16"
/0xFFFF
或"uint32"
/0xFFFFFFFF
)。 非 strip 拓扑管线不允许设置此项。注意: 某些实现需要提前知道图元重启值,以编译管线状态对象。
若 strip 拓扑管线用于带索引的绘制调用 (
drawIndexed()
或drawIndexedIndirect()
), 则必须设置该值,并且要与 draw 调用所用索引缓冲区格式(setIndexBuffer()
设置)一致。详见 § 23.2.3 图元组装。
frontFace
,类型为 GPUFrontFace,默认值为"ccw"
-
定义哪些多边形被视为正面(front-facing)。
cullMode
,类型为 GPUCullMode,默认值为"none"
-
定义哪些多边形朝向会被裁剪(cull),如有的话。
unclippedDepth
, 类型为 boolean,默认值为false
-
如为 true,表示深度裁剪(depth clipping)被禁用。
需要启用
"depth-clip-control"
特性。
-
GPUPrimitiveState
descriptor -
GPUDevice
device
设备时间线步骤:
-
如果下列所有条件都满足则返回
true
:-
如 descriptor.
topology
非"line-strip"
或"triangle-strip"
:-
descriptor.
stripIndexFormat
不得提供。
-
-
如 descriptor.
unclippedDepth
为true
:-
"depth-clip-control"
必须启用于 device。
-
-
enum {
GPUPrimitiveTopology "point-list" ,"line-list" ,"line-strip" ,"triangle-list" ,"triangle-strip" , };
GPUPrimitiveTopology
定义了 GPURenderPipeline
的绘制调用会使用的图元类型。详见 § 23.2.5 光栅化:
"point-list"
-
每个顶点定义一个点图元。
"line-list"
-
每两个连续顶点组成一个线段图元。
"line-strip"
-
第一个顶点后,每个顶点与前一个顶点组成一个线段图元。
"triangle-list"
-
每三个连续顶点组成一个三角形图元。
"triangle-strip"
-
前两个顶点后,每个顶点与前两个顶点组成一个三角形图元。
enum {
GPUFrontFace "ccw" ,"cw" , };
GPUFrontFace
定义 GPURenderPipeline
视为正面(front-facing)的多边形。详见 § 23.2.5.4 多边形光栅化:
enum {
GPUCullMode "none" ,"front" ,"back" , };
GPUPrimitiveTopology
定义了哪些多边形会被 GPURenderPipeline
的绘制调用裁剪。详见 § 23.2.5.4 多边形光栅化:
注意: GPUFrontFace
和 GPUCullMode
对于 "point-list"
、
"line-list"
、
"line-strip"
拓扑无效。
10.3.3. 多重采样状态(Multisample State)
dictionary {
GPUMultisampleState GPUSize32 count = 1;GPUSampleMask mask = 0xFFFFFFFF;boolean alphaToCoverageEnabled =false ; };
GPUMultisampleState
拥有以下成员,描述 GPURenderPipeline
如何与渲染通道的多重采样附件进行交互。
count
,类型为 GPUSize32,默认值为1
-
每像素的采样数。该
GPURenderPipeline
仅与colorAttachments
和depthStencilAttachment
中sampleCount
匹配的附件纹理兼容。 mask
,类型为 GPUSampleMask,默认值0xFFFFFFFF
-
决定哪些采样点会被写入的掩码。
alphaToCoverageEnabled
, 类型为 boolean,默认值false
-
为
true
时,表示片元的 alpha 通道用于生成采样覆盖掩码。
-
GPUMultisampleState
descriptor
设备时间线步骤:
-
若下列所有条件均满足则返回
true
:-
descriptor.
count
必须为 1 或 4。 -
如 descriptor.
alphaToCoverageEnabled
为true
:-
descriptor.
count
> 1。
-
-
10.3.4. 片元状态(Fragment State)
dictionary :
GPUFragmentState GPUProgrammableStage {required sequence <GPUColorTargetState ?>targets ; };
targets
,类型为sequence<GPUColorTargetState?>
-
一个
GPUColorTargetState
列表,定义本管线写入的颜色目标的格式和行为。
参数:
-
GPUDevice
device -
GPUFragmentState
descriptor -
GPUPipelineLayout
layout
设备时间线步骤:
-
若下列所有要求都满足则返回
true
:-
验证 GPUProgrammableStage(
FRAGMENT
, descriptor, layout, device) 成功。 -
descriptor.
targets
.size 必须 ≤ device.[[limits]]
.maxColorAttachments
。 -
令 usesDualSourceBlending =
false
。 -
遍历 descriptor.
targets
的每个包含非null
值 colorState 的 index:-
colorState.
format
必须在 § 26.1.1 普通颜色格式中列出,并具有RENDER_ATTACHMENT
能力。 -
colorState.
writeMask
必须小于 16。 -
-
colorState.
blend
.color
必须为有效 GPUBlendComponent。 -
colorState.
blend
.alpha
必须为有效 GPUBlendComponent。 -
如 colorState.
blend
.color
.srcFactor
或 colorState.blend
.color
.dstFactor
或 colorState.blend
.alpha
.srcFactor
或 colorState.blend
.alpha
.dstFactor
使用了对应混合单元的第二输入(即任一为"src1"
、"one-minus-src1"
、"src1-alpha"
、"one-minus-src1-alpha"
):-
将 usesDualSourceBlending 设为
true
。
-
-
对于 着色器阶段输出值 output,其 location 属性等于 index:
-
对于 colorState.
format
的每个分量,output 中必须有对应分量。 (即 RGBA 需 vec4,RGB 需 vec3 或 vec4,RG 需 vec2 或 vec3 或 vec4。) -
如 colorState.
format
的GPUTextureSampleType
(见 § 26.1 纹理格式能力)为:"float"
和/或"unfilterable-float"
-
output 必须为浮点标量类型。
"sint"
-
output 必须为有符号整数标量类型。
"uint"
-
output 必须为无符号整数标量类型。
-
如 colorState.
blend
已提供,且 colorState.blend
.color
.srcFactor
或 .dstFactor
使用了源 alpha (即任一为"src-alpha"
、"one-minus-src-alpha"
、"src-alpha-saturated"
、"src1-alpha"
、"one-minus-src1-alpha"
):-
output 必须有 alpha 通道(即为 vec4)。
-
-
-
如 colorState.
writeMask
非 0:
-
-
如 usesDualSourceBlending 为
true
: -
验证 GPUFragmentState 的 color attachment bytes per sample(device, descriptor.
targets
) 成功。
-
参数:
-
GPUDevice
device -
sequence<
GPUColorTargetState
?> targets
设备时间线步骤:
-
令 formats 为一个空的 list<
GPUTextureFormat
?> -
遍历 targets 中的每个 target:
-
计算 color attachment bytes per sample(formats) 必须 ≤ device.
[[limits]]
.maxColorAttachmentBytesPerSample
。
注意: 片元着色器可输出的值可能多于管线实际使用的颜色输出,未被使用的值会被忽略。
GPUBlendComponent
component 是一个 有效 GPUBlendComponent(valid GPUBlendComponent),在逻辑
device device 上,需满足以下要求:
10.3.5. 颜色目标状态(Color Target State)
dictionary {
GPUColorTargetState required GPUTextureFormat format ;GPUBlendState blend ;GPUColorWriteFlags writeMask = 0xF; // GPUColorWrite.ALL };
format
,类型为 GPUTextureFormat-
该颜色目标的
GPUTextureFormat
。管线只与 在对应颜色附件中使用该格式的GPURenderPassEncoder
的GPUTextureView
兼容。 blend
,类型为 GPUBlendState-
该颜色目标的混合行为。如未定义,则禁用该颜色目标的混合。
writeMask
,类型为 GPUColorWriteFlags,默认值0xF
-
控制绘制到该颜色目标时写入哪些通道的位掩码。
dictionary {
GPUBlendState required GPUBlendComponent color ;required GPUBlendComponent alpha ; };
color
,类型为 GPUBlendComponent-
定义对应渲染目标颜色通道的混合行为。
alpha
,类型为 GPUBlendComponent-
定义对应渲染目标 alpha 通道的混合行为。
typedef [EnforceRange ]unsigned long ; [
GPUColorWriteFlags Exposed =(Window ,Worker ),SecureContext ]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 operation = "add";GPUBlendFactor srcFactor = "one";GPUBlendFactor dstFactor = "zero"; };
GPUBlendComponent
拥有以下成员,描述片元的颜色或 alpha 分量是如何混合的:
operation
,类型为 GPUBlendOperation,默认值为"add"
-
定义用于计算写入目标附件分量值的
GPUBlendOperation
。 srcFactor
,类型为 GPUBlendFactor,默认值为"one"
-
定义对来自片元着色器的值执行的
GPUBlendFactor
操作。 dstFactor
,类型为 GPUBlendFactor,默认值为"zero"
-
定义对来自目标附件的值执行的
GPUBlendFactor
操作。
下表说明了用于描述片元位置的颜色分量的符号:
RGBAsrc
| 片元着色器输出到颜色附件的颜色。 如果着色器没有返回 alpha 通道,则不能使用 src-alpha 混合因子。 |
RGBAsrc1
| 片元着色器输出到带有
"@blend_src" 属性为 1 的颜色附件的颜色。
如果着色器没有返回 alpha 通道,则不能使用 src1-alpha 混合因子。
|
RGBAdst
| 当前颜色附件中的颜色。
缺失的绿色/蓝色/alpha 通道分别默认 0, 0, 1 。
|
RGBAconst
| 当前 [[blendConstant]] 。
|
RGBAsrcFactor
| 由 srcFactor
定义的源混合因子分量。
|
RGBAdstFactor
| 由 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" ,"src1" ,"one-minus-src1" ,"src1-alpha" ,"one-minus-src1-alpha" , };
GPUBlendFactor
定义了源或目标混合因子的计算方式:
GPUBlendFactor | 混合因子 RGBA 分量 | 特性 |
---|---|---|
"zero"
| (0, 0, 0, 0)
| |
"one"
| (1, 1, 1, 1)
| |
"src"
| (Rsrc, Gsrc, Bsrc, Asrc)
| |
"one-minus-src"
| (1 - Rsrc, 1 - Gsrc, 1 - Bsrc, 1 - Asrc)
| |
"src-alpha"
| (Asrc, Asrc, Asrc, Asrc)
| |
"one-minus-src-alpha"
| (1 - Asrc, 1 - Asrc, 1 - Asrc, 1 - Asrc)
| |
"dst"
| (Rdst, Gdst, Bdst, Adst)
| |
"one-minus-dst"
| (1 - Rdst, 1 - Gdst, 1 - Bdst, 1 - Adst)
| |
"dst-alpha"
| (Adst, Adst, Adst, Adst)
| |
"one-minus-dst-alpha"
| (1 - Adst, 1 - Adst, 1 - Adst, 1 - Adst)
| |
"src-alpha-saturated"
| (min(Asrc, 1 - Adst), min(Asrc, 1 - Adst), min(Asrc, 1 - Adst), 1)
| |
"constant"
| (Rconst, Gconst, Bconst, Aconst)
| |
"one-minus-constant"
| (1 - Rconst, 1 - Gconst, 1 - Bconst, 1 - Aconst)
| |
"src1"
| (Rsrc1, Gsrc1, Bsrc1, Asrc1)
| dual-source-blending
|
"one-minus-src1"
| (1 - Rsrc1, 1 - Gsrc1, 1 - Bsrc1, 1 - Asrc1)
| |
"src1-alpha"
| (Asrc1, Asrc1, Asrc1, Asrc1)
| |
"one-minus-src1-alpha"
| (1 - Asrc1, 1 - Asrc1, 1 - Asrc1, 1 - Asrc1)
|
enum {
GPUBlendOperation "add" ,"subtract" ,"reverse-subtract" ,"min" ,"max" , };
GPUBlendOperation
定义了用于组合源和目标混合因子的算法:
GPUBlendOperation | RGBA 分量 |
---|---|
"add"
| RGBAsrc × RGBAsrcFactor + RGBAdst × RGBAdstFactor
|
"subtract"
| RGBAsrc × RGBAsrcFactor - RGBAdst × RGBAdstFactor
|
"reverse-subtract"
| RGBAdst × RGBAdstFactor - RGBAsrc × RGBAsrcFactor
|
"min"
| min(RGBAsrc, RGBAdst)
|
"max"
| max(RGBAsrc, RGBAdst)
|
10.3.6. 深度/模板状态(Depth/Stencil State)
dictionary {
GPUDepthStencilState required GPUTextureFormat format ;boolean depthWriteEnabled ;GPUCompareFunction depthCompare ;GPUStencilFaceState stencilFront = {};GPUStencilFaceState stencilBack = {};GPUStencilValue stencilReadMask = 0xFFFFFFFF;GPUStencilValue stencilWriteMask = 0xFFFFFFFF;GPUDepthBias depthBias = 0;float depthBiasSlopeScale = 0;float depthBiasClamp = 0; };
GPUDepthStencilState
拥有以下成员,描述 GPURenderPipeline
如何影响渲染通道的 depthStencilAttachment
:
format
,类型为 GPUTextureFormat-
该
GPURenderPipeline
可兼容的depthStencilAttachment
的format
。 depthWriteEnabled
,类型为 boolean-
指示该
GPURenderPipeline
是否可以修改depthStencilAttachment
的深度值。 depthCompare
,类型为 GPUCompareFunction-
用于将片元深度与
depthStencilAttachment
深度值进行比较的操作。 stencilFront
,类型为 GPUStencilFaceState,默认值为{}
-
定义前面图元的模板比较和操作方式。
stencilBack
,类型为 GPUStencilFaceState,默认值为{}
-
定义背面图元的模板比较和操作方式。
stencilReadMask
,类型为 GPUStencilValue,默认值0xFFFFFFFF
-
控制执行模板测试时读取
depthStencilAttachment
模板值哪些位的位掩码。 stencilWriteMask
,类型为 GPUStencilValue,默认值0xFFFFFFFF
-
控制执行模板操作时写入
depthStencilAttachment
模板值哪些位的位掩码。 depthBias
,类型为 GPUDepthBias,默认值0
-
加到每个三角形片元的恒定深度偏移。详见 带偏移的片元深度(biased fragment depth)。
depthBiasSlopeScale
,类型为 float,默认值0
-
随三角形片元斜率变化的深度偏移。详见 带偏移的片元深度(biased fragment depth)。
depthBiasClamp
,类型为 float,默认值0
-
三角形片元的最大深度偏移。详见 带偏移的片元深度(biased fragment depth)。
注意: depthBias
、
depthBiasSlopeScale
、
depthBiasClamp
对 "point-list"
、
"line-list"
、
"line-strip"
图元无效,且必须为 0。
GPUDepthStencilState
state 绘制时写入 depthStencilAttachment
attachment 的片元,计算方式如下(队列时间线步骤):
-
令 r 为 format 转为 32 位 float 后大于
0
的最小正可表示值。 -
令 maxDepthSlope 为片元深度值的水平和垂直斜率中的最大值。
-
如 format 为 unorm 格式:
-
令 bias 为
(float)state.
。depthBias
* r + state.depthBiasSlopeScale
* maxDepthSlope
-
-
否则,如 format 为 float 格式:
-
令 bias 为
(float)state.
。depthBias
* 2^(exp(primitive 最大深度) - r) + state.depthBiasSlopeScale
* maxDepthSlope
-
-
如 state.
depthBiasClamp
>0
:-
将 bias 设为
min(state.
。depthBiasClamp
, bias)
-
-
否则如 state.
depthBiasClamp
<0
:-
将 bias 设为
max(state.
。depthBiasClamp
, bias)
-
-
如 state.
depthBias
≠0
或 state.depthBiasSlopeScale
≠0
:-
将片元深度值设为
片元深度值 + bias
-
参数:
-
GPUDepthStencilState
descriptor -
GPUPrimitiveTopology
topology
设备时间线步骤:
-
当且仅当下列所有条件都满足时返回
true
:-
如 descriptor.
depthWriteEnabled
为true
,或 descriptor.depthCompare
已提供且不为"always"
:-
descriptor.
format
必须包含深度分量。
-
-
如 descriptor.
stencilFront
或 descriptor.stencilBack
非默认值:-
descriptor.
format
必须包含模板分量。
-
-
如 descriptor.
format
含有深度分量:-
descriptor.
depthWriteEnabled
必须已提供。 -
如满足以下任一条件,descriptor.
depthCompare
必须已提供:-
descriptor.
depthWriteEnabled
为true
,或 -
descriptor.
stencilFront
.depthFailOp
非"keep"
,或 -
descriptor.
stencilBack
.depthFailOp
非"keep"
。
-
-
-
如 topology 为
"point-list"
、"line-list"
、"line-strip"
:-
descriptor.
depthBias
必须为 0。 -
descriptor.
depthBiasSlopeScale
必须为 0。 -
descriptor.
depthBiasClamp
必须为 0。
-
dictionary {
GPUStencilFaceState GPUCompareFunction compare = "always";GPUStencilOperation failOp = "keep";GPUStencilOperation depthFailOp = "keep";GPUStencilOperation passOp = "keep"; };
GPUStencilFaceState
拥有以下成员,描述模板比较和操作的方式:
compare
,类型为 GPUCompareFunction,默认值为"always"
-
在用
[[stencilReference]]
的值与片元depthStencilAttachment
的模板值进行测试时使用的GPUCompareFunction
。 failOp
,类型为 GPUStencilOperation,默认值为"keep"
-
如片元模板比较测试(由
compare
描述)失败,则执行的GPUStencilOperation
操作。 depthFailOp
,类型为 GPUStencilOperation,默认值为"keep"
-
如片元深度比较(由
depthCompare
描述)失败,则执行的GPUStencilOperation
操作。 passOp
,类型为 GPUStencilOperation,默认值为"keep"
-
如片元模板比较测试(由
compare
描述)通过,则执行的GPUStencilOperation
操作。
enum {
GPUStencilOperation "keep" ,"zero" ,"replace" ,"invert" ,"increment-clamp" ,"decrement-clamp" ,"increment-wrap" ,"decrement-wrap" , };
GPUStencilOperation
定义了以下操作:
"keep"
-
保持当前模板值。
"zero"
-
将模板值设为
0
。 "replace"
-
将模板值设为
[[stencilReference]]
。 "invert"
-
对当前模板值取按位非。
"increment-clamp"
-
将当前模板值加一,并钳制到
depthStencilAttachment
模板分量的最大可表示值。 "decrement-clamp"
-
将当前模板值减一,并钳制到
0
。 "increment-wrap"
-
将当前模板值加一,如超过
depthStencilAttachment
模板分量最大可表示值,则回绕为 0。 "decrement-wrap"
-
将当前模板值减一,如小于
0
,则回绕为depthStencilAttachment
模板分量最大可表示值。
10.3.7. 顶点状态(Vertex State)
enum {
GPUIndexFormat "uint16" ,"uint32" , };
索引格式(index format)决定了缓冲区中索引值的数据类型,并且在用于 strip 图元拓扑("line-strip"
或
"triangle-strip"
)时,也指定了图元重启值(primitive
restart value)。图元重启值(primitive restart value)
表示哪个索引值意味着应当新建一个图元,而不是继续用先前的索引顶点构建三角带。
GPUPrimitiveState
指定 strip 图元拓扑时,若用于带索引绘制,必须指定
stripIndexFormat
,
以便在管线创建时就明确将使用的图元重启值。
指定 list 图元拓扑的
GPUPrimitiveState
在索引渲染时会使用 setIndexBuffer()
传递的索引格式。
索引格式(Index format) | 字节数(Byte size) | 图元重启值(Primitive restart value) |
---|---|---|
"uint16"
| 2 | 0xFFFF |
"uint32"
| 4 | 0xFFFFFFFF |
10.3.7.1. 顶点格式(Vertex Formats)
GPUVertexFormat
指定顶点属性的数据格式,决定如何从顶点缓冲区读取数据并传递到着色器。格式名表明了分量的顺序、每个分量的比特数,以及该分量的顶点数据类型。
每种顶点数据类型(vertex data type) 都可以映射到任意同基类型的WGSL 标量类型,无论每个分量有多少位:
顶点格式前缀(Vertex format prefix) | 顶点数据类型(Vertex data type) | 兼容 WGSL 类型(Compatible WGSL types) |
---|---|---|
uint
| unsigned int(无符号整数) | u32
|
sint
| signed int(有符号整数) | i32
|
unorm
| unsigned normalized(无符号归一化) | f16 , f32
|
snorm
| signed normalized(有符号归一化) | |
float
| floating point(浮点数) |
多分量格式的“x”后面的数字表示分量数量。顶点格式和着色器类型的分量数不一致是允许的,多余分量会被丢弃,不足分量则用默认值补齐。
"unorm8x2"
,字节值为 [0x7F, 0xFF]
,可在着色器中通过如下类型访问:
着色器类型(Shader type) | 着色器值(Shader value) |
---|---|
f16
| 0.5h
|
f32
| 0.5f
|
vec2<f16>
| vec2(0.5h, 1.0h)
|
vec2<f32>
| vec2(0.5f, 1.0f)
|
vec3<f16>
| vec2(0.5h, 1.0h, 0.0h)
|
vec3<f32>
| vec2(0.5f, 1.0f, 0.0f)
|
vec4<f16>
| vec2(0.5h, 1.0h, 0.0h, 1.0h)
|
vec4<f32>
| vec2(0.5f, 1.0f, 0.0f, 1.0f)
|
关于顶点格式如何在着色器中暴露,详见 § 23.2.2 顶点处理。
enum {
GPUVertexFormat "uint8" ,"uint8x2" ,"uint8x4" ,"sint8" ,"sint8x2" ,"sint8x4" ,"unorm8" ,"unorm8x2" ,"unorm8x4" ,"snorm8" ,"snorm8x2" ,"snorm8x4" ,"uint16" ,"uint16x2" ,"uint16x4" ,"sint16" ,"sint16x2" ,"sint16x4" ,"unorm16" ,"unorm16x2" ,"unorm16x4" ,"snorm16" ,"snorm16x2" ,"snorm16x4" ,"float16" ,"float16x2" ,"float16x4" ,"float32" ,"float32x2" ,"float32x3" ,"float32x4" ,"uint32" ,"uint32x2" ,"uint32x3" ,"uint32x4" ,"sint32" ,"sint32x2" ,"sint32x3" ,"sint32x4" ,"unorm10-10-10-2" ,"unorm8x4-bgra" , };
顶点格式(Vertex format) | 数据类型(Data type) | 分量数(Components) | 字节数(byteSize) | 示例 WGSL 类型(Example WGSL type) |
---|---|---|---|---|
"uint8"
| 无符号整数(unsigned int) | 1 | 1 | u32
|
"uint8x2"
| 无符号整数 | 2 | 2 | vec2<u32>
|
"uint8x4"
| 无符号整数 | 4 | 4 | vec4<u32>
|
"sint8"
| 有符号整数(signed int) | 1 | 1 | i32
|
"sint8x2"
| 有符号整数 | 2 | 2 | vec2<i32>
|
"sint8x4"
| 有符号整数 | 4 | 4 | vec4<i32>
|
"unorm8"
| 无符号归一化(unsigned normalized) | 1 | 1 | f32
|
"unorm8x2"
| 无符号归一化 | 2 | 2 | vec2<f32>
|
"unorm8x4"
| 无符号归一化 | 4 | 4 | vec4<f32>
|
"snorm8"
| 有符号归一化(signed normalized) | 1 | 1 | f32
|
"snorm8x2"
| 有符号归一化 | 2 | 2 | vec2<f32>
|
"snorm8x4"
| 有符号归一化 | 4 | 4 | vec4<f32>
|
"uint16"
| 无符号整数 | 1 | 2 | u32
|
"uint16x2"
| 无符号整数 | 2 | 4 | vec2<u32>
|
"uint16x4"
| 无符号整数 | 4 | 8 | vec4<u32>
|
"sint16"
| 有符号整数 | 1 | 2 | i32
|
"sint16x2"
| 有符号整数 | 2 | 4 | vec2<i32>
|
"sint16x4"
| 有符号整数 | 4 | 8 | vec4<i32>
|
"unorm16"
| 无符号归一化 | 1 | 2 | f32
|
"unorm16x2"
| 无符号归一化 | 2 | 4 | vec2<f32>
|
"unorm16x4"
| 无符号归一化 | 4 | 8 | vec4<f32>
|
"snorm16"
| 有符号归一化 | 1 | 2 | f32
|
"snorm16x2"
| 有符号归一化 | 2 | 4 | vec2<f32>
|
"snorm16x4"
| 有符号归一化 | 4 | 8 | vec4<f32>
|
"float16"
| 浮点数(float) | 1 | 2 | f32
|
"float16x2"
| 浮点数 | 2 | 4 | vec2<f16>
|
"float16x4"
| 浮点数 | 4 | 8 | vec4<f16>
|
"float32"
| 浮点数 | 1 | 4 | f32
|
"float32x2"
| 浮点数 | 2 | 8 | vec2<f32>
|
"float32x3"
| 浮点数 | 3 | 12 | vec3<f32>
|
"float32x4"
| 浮点数 | 4 | 16 | vec4<f32>
|
"uint32"
| 无符号整数 | 1 | 4 | u32
|
"uint32x2"
| 无符号整数 | 2 | 8 | vec2<u32>
|
"uint32x3"
| 无符号整数 | 3 | 12 | vec3<u32>
|
"uint32x4"
| 无符号整数 | 4 | 16 | vec4<u32>
|
"sint32"
| 有符号整数 | 1 | 4 | i32
|
"sint32x2"
| 有符号整数 | 2 | 8 | vec2<i32>
|
"sint32x3"
| 有符号整数 | 3 | 12 | vec3<i32>
|
"sint32x4"
| 有符号整数 | 4 | 16 | vec4<i32>
|
"unorm10-10-10-2"
| 无符号归一化 | 4 | 4 | vec4<f32>
|
"unorm8x4-bgra"
| 无符号归一化 | 4 | 4 | vec4<f32>
|
enum {
GPUVertexStepMode "vertex" ,"instance" , };
步进模式(step mode)配置了如何根据当前的顶点索引或实例索引计算顶点缓冲区数据的地址:
"vertex"
-
每个顶点地址按
arrayStride
递增, 在不同实例之间重置。 "instance"
-
每个实例地址按
arrayStride
递增。
dictionary :
GPUVertexState GPUProgrammableStage {sequence <GPUVertexBufferLayout ?>buffers = []; };
buffers
,类型为sequence<GPUVertexBufferLayout?>
,默认值为[]
-
一个
GPUVertexBufferLayout
列表,定义了本管线所用顶点缓冲区中顶点属性数据的布局。
顶点缓冲区(vertex
buffer)在概念上是对缓冲区内存的视图,把它看作“结构体数组”。arrayStride
是该数组中每个元素(结构)之间的字节跨度。每个顶点缓冲区的元素就像一个结构体,其内存布局由 attributes
定义,attributes 描述了结构体成员。
每个 GPUVertexAttribute
描述了该成员的 format
以及在结构体中的 offset
字节偏移量。
每个 attribute 在顶点着色器中表现为一个独立输入,绑定一个数值类型的 location,由 shaderLocation
指定。每个 location 在 GPUVertexState
内必须唯一。
dictionary {
GPUVertexBufferLayout required GPUSize64 arrayStride ;GPUVertexStepMode stepMode = "vertex";required sequence <GPUVertexAttribute >attributes ; };
arrayStride
,类型为 GPUSize64-
该数组元素之间的字节跨度。
stepMode
,类型为 GPUVertexStepMode,默认值为"vertex"
-
该数组每个元素是按顶点还是按实例计(per-vertex 或 per-instance)。
attributes
,类型为 sequence<GPUVertexAttribute>-
定义每个元素内各顶点属性(结构体成员)的数组。
dictionary {
GPUVertexAttribute required GPUVertexFormat format ;required GPUSize64 offset ;required GPUIndex32 shaderLocation ; };
format
,类型为 GPUVertexFormat-
该属性的
GPUVertexFormat
。 offset
,类型为 GPUSize64-
从该结构体起始到该属性数据的字节偏移量。
shaderLocation
,类型为 GPUIndex32-
该属性关联的数值 location,需与 "@location" 属性 在
vertex
.module
中对应。
参数:
-
GPUDevice
device -
GPUVertexBufferLayout
descriptor
设备时间线步骤:
-
当且仅当下列所有条件都满足时,返回
true
:-
descriptor.
arrayStride
≤ device.[[device]]
.[[limits]]
.maxVertexBufferArrayStride
。 -
descriptor.
arrayStride
是 4 的倍数。 -
对于 descriptor.
attributes
列表中的每个属性 attrib:-
如果 descriptor.
arrayStride
为 0:-
attrib.
offset
+ byteSize(attrib.format
) ≤ device.[[device]]
.[[limits]]
.maxVertexBufferArrayStride
。
否则:
-
attrib.
offset
+ byteSize(attrib.format
) ≤ descriptor.arrayStride
。
-
-
attrib.
shaderLocation
必须小于 device.[[device]]
.[[limits]]
.maxVertexAttributes
。
-
-
参数:
-
GPUDevice
device -
GPUVertexState
descriptor -
GPUPipelineLayout
layout
设备时间线步骤:
-
断言(Assert) entryPoint 不为
null
。 -
以下所有要求 必须满足:
-
验证 GPUProgrammableStage(
VERTEX
, descriptor, layout, device) 必须成功。 -
descriptor.
buffers
.size 必须 ≤ device.[[device]]
.[[limits]]
.maxVertexBuffers
。 -
列表 descriptor.
buffers
中的每个 vertexBuffer 描述符 必须通过 验证 GPUVertexBufferLayout(device, vertexBuffer)。 -
所有 vertexBuffer.
attributes
.size 之和, 必须 ≤ device.[[device]]
.[[limits]]
.maxVertexAttributes
。 -
对于 entryPoint 静态使用的每个顶点属性声明(位置 location,类型 T), 必须存在且仅存在一组 (i, j) 使得 descriptor.
buffers
[i]? .attributes
[j] .shaderLocation
== location。令 attrib 为该
GPUVertexAttribute
。 -
T 必须与 attrib.
format
的 顶点数据类型(vertex data type)兼容:- "unorm"、"snorm" 或 "float"
-
T 必须是
f32
或vecN<f32>
。 - "uint"
-
T 必须是
u32
或vecN<u32>
。 - "sint"
-
T 必须是
i32
或vecN<i32>
。
-
11. 复制(Copies)
11.1. 缓冲区复制(Buffer Copies)
缓冲区复制操作基于原始字节执行。
WebGPU 提供了“缓冲式” GPUCommandEncoder
命令:
以及“即时” GPUQueue
操作:
-
writeBuffer()
, 用于ArrayBuffer
到GPUBuffer
的写入
11.2. 纹素复制(Texel Copies)
纹素复制(Texel copy)操作针对的是纹理/图像数据,而不是字节。
WebGPU 提供“缓冲式” GPUCommandEncoder
命令:
以及“即时” GPUQueue
操作:
-
writeTexture()
, 用于ArrayBuffer
到GPUTexture
的写入 -
copyExternalImageToTexture()
, 用于从 Web 平台图片源复制到纹理
在纹素复制过程中,纹素会以等价纹素表示(equivalent texel representation)被复制。 纹素复制仅保证源中的有效、正常数字值在目标中具有相同的数值,但可能不会保留以下值的位表示:
-
snorm 类型值的 -1.0 可能被表示为 -127 或 -128。
-
零值的符号可能不会被保留。
-
非正规浮点值可能会被替换为 -0.0 或 +0.0。
-
任何 NaN 或 Infinity 都是无效值,可能会被替换为不确定值(indeterminate value)。
注意: 复制操作可能通过 WGSL 着色器实现,所以可能会观察到任何文档中描述的 WGSL 浮点行为。
下列定义被这些方法所用:
11.2.1. GPUTexelCopyBufferLayout
"GPUTexelCopyBufferLayout
"
描述了在“缓冲区”字节(GPUBuffer
或 AllowSharedBufferSource
)
中的纹素在“纹素复制”操作中的“布局”。
dictionary GPUTexelCopyBufferLayout {GPUSize64 offset = 0;GPUSize32 bytesPerRow ;GPUSize32 rowsPerImage ; };
纹素图像(texel image)由一行或多行纹素块组成,这里称为纹素块行(texel block
row)。每个texel image
的texel block row
数量相同,且所有纹素块的GPUTextureFormat
一致。
GPUTexelCopyBufferLayout
描述了线性内存中多个texel image
的布局。当在texture
与GPUBuffer
之间复制数据,或通过GPUQueue
写入texture
时会用到。
在字节数组与纹理之间的复制操作总是以整个 纹素块为单位。无法只更新一个纹素块的一部分。
纹素块在每个texel block row
中在内存中紧密排列,每个相邻的纹素块之间无填充,包括对深度或模板纹理特定
aspect 的复制:模板值以字节数组紧密排列,深度值以相应类型("depth16unorm" 或
"depth32float")数组紧密排列。
offset
,类型为 GPUSize64,默认值为0
-
从纹素数据源(如
GPUTexelCopyBufferInfo.buffer
) 起始到纹素数据起始位置的字节偏移量。 bytesPerRow
,类型为 GPUSize32-
若存在多个 纹素块行(即复制高度或深度大于一个块)时为必填项。
rowsPerImage
,类型为 GPUSize32-
每个 纹素图像 包含的 纹素块行数量。
rowsPerImage
×bytesPerRow
即为每个 纹素图像 起始到下一个 纹素图像 起始的字节跨度。若存在多个 纹素图像(即复制深度大于 1)时为必填项。
11.2.2. GPUTexelCopyBufferInfo
"GPUTexelCopyBufferInfo
"
描述了作为“缓冲区”源或目标的 GPUBuffer
和
GPUTexelCopyBufferLayout
的“参数信息”,用于“纹素复制”操作。
它与 copySize
一起描述了 GPUBuffer
中某一区域纹素的内存布局。
dictionary GPUTexelCopyBufferInfo :GPUTexelCopyBufferLayout {required GPUBuffer buffer ; };
buffer
,类型为 GPUBuffer-
根据所调用的方法,该缓冲区要么包含要被复制的纹素数据,要么用于存储被复制的纹素数据。
参数:
-
GPUTexelCopyBufferInfo
imageCopyBuffer
返回: boolean
设备时间线步骤:
-
当且仅当下列所有条件都满足时返回
true
:-
imageCopyBuffer.
bytesPerRow
必须是 256 的倍数。
11.2.3. GPUTexelCopyTextureInfo
"GPUTexelCopyTextureInfo
"
描述了作为“纹理”源或目标的 GPUTexture
等对象在“纹素复制”操作中的“参数信息”。
它和 copySize
一起描述了纹理的一个子区域(跨越同一 mip-map 层级的一个或多个连续纹理子资源)。
dictionary GPUTexelCopyTextureInfo {required GPUTexture texture ;GPUIntegerCoordinate mipLevel = 0;GPUOrigin3D origin = {};GPUTextureAspect aspect = "all"; };
texture
,类型为 GPUTexture-
要复制到或从其复制的纹理。
mipLevel
,类型为 GPUIntegerCoordinate,默认值为0
-
要复制到或从其复制的
texture
的 mip-map 层级。 origin
,类型为 GPUOrigin3D,默认值为{}
-
定义复制的起点——要复制到或从其复制的纹理子区域的最小角落。与
copySize
一起,定义完整的复制子区域。 aspect
,类型为 GPUTextureAspect,默认值为"all"
-
定义要复制到/从其复制的
texture
的哪些 aspect。
GPUTexelCopyTextureInfo
copyTexture 的深度切片或数组层 index,按如下步骤确定:
GPUTexelCopyBufferLayout
bufferLayout 描述的数据,纹素块
x、y 在 GPUTexture
texture 的深度切片或数组层 z,按如下步骤确定:
-
令 imageOffset = (z × bufferLayout.
rowsPerImage
× bufferLayout.bytesPerRow
) + bufferLayout.offset
。 -
令 rowOffset = (y × bufferLayout.
bytesPerRow
) + imageOffset。 -
令 blockOffset = (x × blockBytes) + rowOffset。
-
返回 blockOffset。
参数:
-
GPUTexelCopyTextureInfo
texelCopyTextureInfo -
GPUExtent3D
copySize
返回: boolean
设备时间线步骤:
-
当且仅当下列所有条件满足时返回
true
:-
验证纹理复制范围(texelCopyTextureInfo, copySize) 返回
true
。 -
texelCopyTextureInfo.
texture
必须是一个 有效的GPUTexture
。 -
texelCopyTextureInfo.
mipLevel
必须小于 texelCopyTextureInfo.texture
.mipLevelCount
。 -
若下述任一条件为真,则 GPUTexelCopyTextureInfo 物理子资源尺寸等于 copySize:
-
texelCopyTextureInfo.
texture
.sampleCount
> 1。
-
参数:
-
GPUTexelCopyTextureInfo
texelCopyTextureInfo -
GPUTexelCopyBufferLayout
bufferLayout -
GPUSize64Out
dataLength -
GPUExtent3D
copySize -
GPUTextureUsage
textureUsage -
boolean
aligned
返回: boolean
设备时间线步骤:
-
令 texture = texelCopyTextureInfo.
texture
-
令 aspectSpecificFormat = texture.
format
。 -
当且仅当下列所有条件满足时返回
true
:-
验证 GPUTexelCopyTextureInfo(texelCopyTextureInfo, copySize) 返回
true
。 -
texture.
sampleCount
为 1。 -
texture.
usage
包含 textureUsage。 -
-
如果 textureUsage 是:
COPY_SRC
-
该 aspect 必须根据 § 26.1.2 深度模板格式 是有效的纹素复制源。
COPY_DST
-
该 aspect 必须根据 § 26.1.2 深度模板格式 是有效的纹素复制目标。
-
根据 § 26.1.2 深度模板格式,将 aspectSpecificFormat 设为aspect-specific format。
-
将 offsetAlignment 设为 4。
-
如果 aligned 为
true
:-
bufferLayout.
offset
必须是 offsetAlignment 的倍数。
-
-
验证线性纹理数据(bufferLayout, dataLength, aspectSpecificFormat, copySize) 成功。
-
11.2.4.
GPUCopyExternalImageDestInfo
WebGPU 纹理保存的是原始数值数据,并没有附带描述颜色的语义元数据。
然而,copyExternalImageToTexture()
复制自带有颜色描述信息的源。
"GPUCopyExternalImageDestInfo
"
描述了 "copyExternalImageToTexture()" 操作中 "目标(dest)" 的
"参数信息(info)"。
它是一个 GPUTexelCopyTextureInfo
,但额外带有色彩空间/编码和
alpha 预乘元数据,以便在复制过程中保留语义色彩数据。
这些元数据仅影响复制操作的语义,不影响目标纹理对象本身的状态或语义。
dictionary GPUCopyExternalImageDestInfo :GPUTexelCopyTextureInfo {PredefinedColorSpace colorSpace = "srgb";boolean premultipliedAlpha =false ; };
colorSpace
,类型为 PredefinedColorSpace,默认值为"srgb"
-
描述写入目标纹理时使用的色彩空间和编码。
这可能导致超出 [0, 1] 范围的值被写入目标纹理(如果其格式可以表示这些值)。 否则,结果会被裁剪到目标纹理格式的允许范围内。
注意: 如果
colorSpace
与源图像一致,则可能无需进行转换。详见 § 3.10.2 色彩空间转换省略。 premultipliedAlpha
, 类型为 boolean,默认值为false
-
描述写入目标纹理时,RGB 通道是否应由 alpha 通道进行预乘。
如果此选项为
true
,且source
也为预乘,则即使 RGB 分量超过其对应的 alpha 分量,也必须保留源 RGB 值。注意: 如果
premultipliedAlpha
与源图像一致,则可能无需进行转换。详见 § 3.10.2 色彩空间转换省略。
11.2.5.
GPUCopyExternalImageSourceInfo
"GPUCopyExternalImageSourceInfo
"
描述了 "copyExternalImageToTexture()" 操作中 "源(source)" 的
"参数信息(info)"。
typedef (ImageBitmap or ImageData or HTMLImageElement or HTMLVideoElement or VideoFrame or HTMLCanvasElement or OffscreenCanvas );
GPUCopyExternalImageSource dictionary GPUCopyExternalImageSourceInfo {required GPUCopyExternalImageSource source ;GPUOrigin2D origin = {};boolean flipY =false ; };
GPUCopyExternalImageSourceInfo
有如下成员:
source
,类型为 GPUCopyExternalImageSource-
纹素复制的源。 复制源数据会在调用
copyExternalImageToTexture()
时被捕获。源尺寸由外部源尺寸表给出。 origin
,类型为 GPUOrigin2D,默认值为{}
-
定义复制起点——要复制的源子区域的最小(左上)角。与
copySize
一起定义完整的复制区域。 flipY
,类型为 boolean,默认值为false
-
描述源图像是否需要垂直翻转。
如果该选项为
true
,则复制时会进行垂直翻转:源区域的最后一行被复制到目标区域的第一行,依此类推。origin
仍然以源图像的左上角为原点,向下递增。
当外部源被用来创建或复制到纹理时,外部源尺寸(external source dimensions) 由源类型决定,见下表:
11.2.6. 子程序(Subroutines)
参数:
-
GPUTexelCopyTextureInfo
texelCopyTextureInfo
返回: GPUExtent3D
GPUTexelCopyTextureInfo 物理子资源尺寸的计算如下:
其 width、height 和 depthOrArrayLayers 分别为
texelCopyTextureInfo.texture
子资源(subresource) 在 mipmap 级别
texelCopyTextureInfo.mipLevel
的物理 mip 层特定纹理范围的宽度、高度和深度。
参数:
GPUTexelCopyBufferLayout
layout-
线性纹理数据的布局。
GPUSize64
byteSize-
线性数据的总字节数。
GPUTextureFormat
format-
纹理的格式。
GPUExtent3D
copyExtent-
要复制的纹理范围。
设备时间线步骤:
-
令:
-
若未满足下述输入校验要求则失败:
-
如果 heightInBlocks > 1, layout.
bytesPerRow
必须被指定。 -
如果 copyExtent.depthOrArrayLayers > 1, layout.
bytesPerRow
和 layout.rowsPerImage
必须被指定。 -
如果指定,layout.
bytesPerRow
必须 ≥ bytesInLastRow。 -
如果指定,layout.
rowsPerImage
必须 ≥ heightInBlocks。
-
-
令:
-
bytesPerRow = layout.
bytesPerRow
?? 0。 -
rowsPerImage = layout.
rowsPerImage
?? 0。
注意: 这些默认值没有实际影响,因为总是被乘以 0。
-
-
令 requiredBytesInCopy = 0。
-
若 copyExtent.depthOrArrayLayers > 0:
-
requiredBytesInCopy 增加 bytesPerRow × rowsPerImage × (copyExtent.depthOrArrayLayers − 1)。
-
如果 heightInBlocks > 0:
-
requiredBytesInCopy 增加 bytesPerRow × (heightInBlocks − 1) + bytesInLastRow。
-
-
-
若未满足下述条件则失败:
-
布局应在线性数据范围内: layout.
offset
+ requiredBytesInCopy ≤ byteSize。
-
参数:
GPUTexelCopyTextureInfo
texelCopyTextureInfo-
要复制到的纹理子资源及复制起点。
GPUExtent3D
copySize-
纹理的尺寸。
设备时间线步骤:
-
令 subresourceSize = GPUTexelCopyTextureInfo 物理子资源尺寸。
-
返回下述所有条件是否满足:
-
(texelCopyTextureInfo.
origin
.x + copySize.width) ≤ subresourceSize.width -
(texelCopyTextureInfo.
origin
.y + copySize.height) ≤ subresourceSize.height -
(texelCopyTextureInfo.
origin
.z + copySize.depthOrArrayLayers) ≤ subresourceSize.depthOrArrayLayers -
copySize.width 必须是 blockWidth 的倍数。
-
copySize.height 必须是 blockHeight 的倍数。
注意: 纹理复制范围针对 物理(向上取整)尺寸进行校验(对于压缩格式),允许复制操作访问未完全位于纹理内的纹理块。
-
GPUTextureFormat
format1 和 format2 当且仅当以下条件满足时为可复制兼容(copy-compatible):
-
format1 等于 format2,或
-
format1 和 format2 仅在是否为
srgb
格式(即是否有-srgb
后缀)上不同。
texture
的子资源子集,满足如下条件的每个子资源 s:
12. 命令缓冲区(Command Buffers)
命令缓冲区是预先记录的GPU 命令(队列时间轴步骤块)的列表,可以提交到 GPUQueue
执行。
每个 GPU 命令 表示要在
队列时间轴
上执行的任务,如设置状态、绘制、资源拷贝等。
一个 GPUCommandBuffer
只能提交一次,提交后即被失效。
若需要跨多次提交复用渲染命令,请使用 GPURenderBundle
。
12.1.
GPUCommandBuffer
[Exposed =(Window ,Worker ),SecureContext ]interface GPUCommandBuffer { };GPUCommandBuffer includes GPUObjectBase ;
GPUCommandBuffer
具有以下设备时间轴属性:
-
[[command_list]]
,类型为 list<GPU 命令>,只读 -
[[renderState]]
,类型为 RenderState,初始值为null
-
任何渲染通道命令正在执行时所使用的当前状态。
12.1.1. 命令缓冲区创建(Command Buffer Creation)
dictionary :
GPUCommandBufferDescriptor GPUObjectDescriptorBase { };
13. 命令编码(Command Encoding)
13.1.
GPUCommandsMixin
GPUCommandsMixin
定义了所有编码命令接口的通用状态。它没有方法。
interface mixin GPUCommandsMixin { };
GPUCommandsMixin
具有以下设备时间轴属性:
-
[[state]]
,类型为 encoder state,初始值为 "open" -
编码器的当前状态。
-
[[commands]]
,类型为 list<GPU 命令>,初始值为[]
-
一个 列表,包含当包含这些命令的
GPUCommandBuffer
被提交时将在队列时间轴上执行的 GPU 命令。
编码器状态(encoder state) 可能为以下之一:
- "open"
-
编码器可用于编码新命令。
- "locked"
-
编码器无法使用,因为它被子编码器锁定:它是一个
GPUCommandEncoder
,且有一个GPURenderPassEncoder
或GPUComputePassEncoder
处于活动状态。 当通道结束时,编码器重新变为“open”状态。在此状态下发出的任何命令都会使编码器失效。
- "ended"
-
编码器已结束,无法再编码新命令。
在此状态下发出的任何命令都会产生验证错误。
GPUCommandsMixin
encoder,执行以下设备时间轴步骤:
GPUCommandsMixin
encoder,该命令将执行 GPU 命令
command 的步骤,执行以下设备时间轴步骤:
-
追加 command 至 encoder 的
[[commands]]
。 -
当 command 作为
GPUCommandBuffer
的一部分执行时:-
执行 command 的步骤。
-
13.2.
GPUCommandEncoder
[Exposed =(Window ,Worker ),SecureContext ]interface GPUCommandEncoder {GPURenderPassEncoder beginRenderPass (GPURenderPassDescriptor descriptor );GPUComputePassEncoder beginComputePass (optional GPUComputePassDescriptor descriptor = {});undefined copyBufferToBuffer (GPUBuffer ,
source GPUBuffer ,
destination optional GPUSize64 );
size undefined copyBufferToBuffer (GPUBuffer source ,GPUSize64 sourceOffset ,GPUBuffer destination ,GPUSize64 destinationOffset ,optional GPUSize64 size );undefined copyBufferToTexture (GPUTexelCopyBufferInfo source ,GPUTexelCopyTextureInfo destination ,GPUExtent3D copySize );undefined copyTextureToBuffer (GPUTexelCopyTextureInfo source ,GPUTexelCopyBufferInfo destination ,GPUExtent3D copySize );undefined copyTextureToTexture (GPUTexelCopyTextureInfo source ,GPUTexelCopyTextureInfo destination ,GPUExtent3D copySize );undefined clearBuffer (GPUBuffer buffer ,optional GPUSize64 offset = 0,optional GPUSize64 size );undefined resolveQuerySet (GPUQuerySet querySet ,GPUSize32 firstQuery ,GPUSize32 queryCount ,GPUBuffer destination ,GPUSize64 destinationOffset );GPUCommandBuffer finish (optional GPUCommandBufferDescriptor descriptor = {}); };GPUCommandEncoder includes GPUObjectBase ;GPUCommandEncoder includes GPUCommandsMixin ;GPUCommandEncoder includes GPUDebugCommandsMixin ;
13.2.1. 命令编码器创建(Command Encoder Creation)
dictionary :
GPUCommandEncoderDescriptor GPUObjectDescriptorBase { };
-
createCommandEncoder(descriptor)
-
创建一个
GPUCommandEncoder
。调用者:GPUDevice
this.参数:
GPUDevice.createCommandEncoder(descriptor) 方法参数。 参数 类型 可为 null 可选 描述 descriptor
GPUCommandEncoderDescriptor
✘ ✔ 要创建的 GPUCommandEncoder
的描述信息。-
令 e 为 ! 创建一个新的 WebGPU 对象(this,
GPUCommandEncoder
, descriptor)。 -
在 this 的设备时间轴上执行 初始化步骤。
-
返回 e。
-
GPUCommandEncoder
,
编码清空缓冲区的命令,完成编码器生成 GPUCommandBuffer
,
并提交到 GPUQueue
。
const commandEncoder= gpuDevice. createCommandEncoder(); commandEncoder. clearBuffer( buffer); const commandBuffer= commandEncoder. finish(); gpuDevice. queue. submit([ commandBuffer]);
13.3. 通道编码(Pass Encoding)
-
beginRenderPass(descriptor)
-
开始编码由 descriptor 描述的渲染通道。
调用者:GPUCommandEncoder
this。参数:
GPUCommandEncoder.beginRenderPass(descriptor) 方法参数。 参数 类型 可为 null 可选 描述 descriptor
GPURenderPassDescriptor
✘ ✘ 要创建的 GPURenderPassEncoder
的描述信息。-
对 descriptor.
colorAttachments
中每一个非null
的 colorAttachment:-
如果 colorAttachment.
clearValue
已提供:-
? 校验 GPUColor 形状 (colorAttachment.
clearValue
)。
-
-
-
令 pass 为一个新的
GPURenderPassEncoder
对象。 -
在 this 的设备时间轴上执行 初始化步骤。
-
返回 pass。
设备时间轴 初始化步骤:-
验证编码器状态(Validate the encoder state)this。 如果返回 false,使 pass 失效并返回。
-
令 attachmentRegions 为 [纹理子资源,
depthSlice
?] 对的列表,初始为空。每个对描述要渲染到的纹理区域,对于"3d"
纹理仅包含一个 depth slice。 -
对 descriptor.
colorAttachments
中每一个非null
的 colorAttachment:-
将 [colorAttachment.
view
, colorAttachment.depthSlice
??null
] 添加到 attachmentRegions。 -
如果 colorAttachment.
resolveTarget
不为null
:-
将 [colorAttachment.
resolveTarget
,undefined
] 添加到 attachmentRegions。
-
-
-
如未满足以下任一要求,使 pass 失效并返回。
-
descriptor 必须符合设备 this.
[[device]]
的 有效用法(Valid Usage) 规则。 -
attachmentRegions 中的纹理区域集合必须两两不相交,即任何两个区域都不能重叠。
-
-
将 attachmentRegions 中的每个纹理子资源以 attachment 用法添加到 pass.
[[usage scope]]
。 -
令 depthStencilAttachment 为 descriptor.
depthStencilAttachment
。 -
如果 depthStencilAttachment 不为
null
:-
令 depthStencilView 为 depthStencilAttachment.
view
。 -
将 depthStencilView 的depth 子资源(如有)以 attachment-read 用法(若 depthStencilAttachment.
depthReadOnly
为 true),否则以 attachment 用法,添加到 pass.[[usage scope]]
。 -
将 depthStencilView 的stencil 子资源(如有)以 attachment-read 用法(若 depthStencilAttachment.
stencilReadOnly
为 true),否则以 attachment 用法,添加到 pass.[[usage scope]]
。 -
设置 pass.
[[depthReadOnly]]
为 depthStencilAttachment.depthReadOnly
。 -
设置 pass.
[[stencilReadOnly]]
为 depthStencilAttachment.stencilReadOnly
。
-
-
设置 pass.
[[layout]]
为 derive render targets layout from pass(descriptor)。 -
如果 descriptor.
timestampWrites
已提供:-
令 timestampWrites 为 descriptor.
timestampWrites
。 -
如果 timestampWrites.
beginningOfPassWriteIndex
已提供,则追加一个包含以下步骤的GPU 命令到 this.[[commands]]
:-
在通道命令开始执行前,将当前队列时间戳写入 timestampWrites.
beginningOfPassWriteIndex
索引的 timestampWrites.querySet
。
-
-
如果 timestampWrites.
endOfPassWriteIndex
已提供,则设置 pass.[[endTimestampWrite]]
为一个包含如下步骤的GPU 命令:-
在通道命令执行完后,将当前队列时间戳写入 timestampWrites.
endOfPassWriteIndex
索引的 timestampWrites.querySet
。
-
-
-
设置 pass.
[[drawCount]]
为 0。 -
设置 pass.
[[maxDrawCount]]
为 descriptor.maxDrawCount
。 -
设置 pass.
[[maxDrawCount]]
为 descriptor.maxDrawCount
。 -
入队命令(Enqueue a command)到 this,执行时在队列时间轴上执行后续步骤。
队列时间轴 步骤:-
令当前正在执行的
[[renderState]]
的GPUCommandBuffer
成为一个新的 RenderState。 -
设置
[[renderState]]
.[[colorAttachments]]
为 descriptor.colorAttachments
。 -
设置
[[renderState]]
.[[depthStencilAttachment]]
为 descriptor.depthStencilAttachment
。 -
对 descriptor.
colorAttachments
中每一个非null
的 colorAttachment:-
令 colorView 为 colorAttachment.
view
。 -
如果 colorView.
[[descriptor]]
.dimension
为:"3d"
-
令 colorSubregion 为 colorAttachment.
depthSlice
的 colorView。 - 否则
-
令 colorSubregion 为 colorView。
-
如果 colorAttachment.
loadOp
为:
-
-
如果 depthStencilAttachment 不为
null
:-
如果 depthStencilAttachment.
depthLoadOp
为: -
如果 depthStencilAttachment.
stencilLoadOp
为:
-
注意: 只读深度-模板(Read-only depth-stencil)附件会被隐式视为采用
"load"
操作。需要只读附件未提供 load op 的验证在 GPURenderPassDepthStencilAttachment 有效用法中进行。 -
-
beginComputePass(descriptor)
-
开始编码由 descriptor 描述的计算通道(compute pass)。
调用者:GPUCommandEncoder
this。参数:
GPUCommandEncoder.beginComputePass(descriptor) 方法参数。 参数 类型 可为 null 可选 描述 descriptor
GPUComputePassDescriptor
✘ ✔ 内容时间轴步骤:
-
令 pass 为一个新的
GPUComputePassEncoder
对象。 -
在 this 的设备时间轴上执行 初始化步骤。
-
返回 pass。
设备时间轴 初始化步骤:-
验证编码器状态(Validate the encoder state)this。 如果返回 false,使 pass 失效并返回。
-
如未满足以下任一要求,使 pass 失效并返回。
-
如果 descriptor.
timestampWrites
已提供:-
校验 timestampWrites (this.
[[device]]
, descriptor.timestampWrites
) 必须返回 true。
-
-
-
如果 descriptor.
timestampWrites
已提供:-
令 timestampWrites 为 descriptor.
timestampWrites
。 -
如果 timestampWrites.
beginningOfPassWriteIndex
已提供,则追加一个包含以下步骤的GPU 命令到 this.[[commands]]
:-
在通道命令开始执行前,将当前队列时间戳写入 timestampWrites.
beginningOfPassWriteIndex
索引的 timestampWrites.querySet
。
-
-
如果 timestampWrites.
endOfPassWriteIndex
已提供,则设置 pass.[[endTimestampWrite]]
为一个包含如下步骤的GPU 命令:-
在通道命令执行完后,将当前队列时间戳写入 timestampWrites.
endOfPassWriteIndex
索引的 timestampWrites.querySet
。
-
-
-
13.4. 缓冲区拷贝命令(Buffer Copy Commands)
copyBufferToBuffer() 有两个重载:
-
copyBufferToBuffer(source, destination, size)
-
copyBufferToBuffer(source, sourceOffset, destination, destinationOffset, size)
-
向
GPUCommandEncoder
编码一个命令, 将数据从一个GPUBuffer
的子区域复制到另一个GPUBuffer
的子区域。调用者:GPUCommandEncoder
this。参数:
GPUCommandEncoder.copyBufferToBuffer(source, sourceOffset, destination, destinationOffset, size) 方法参数。 参数 类型 可为 null 可选 描述 source
GPUBuffer
✘ ✘ 要拷贝的 GPUBuffer
。sourceOffset
GPUSize64
✘ ✘ 源 buffer 的起始偏移(字节)。 destination
GPUBuffer
✘ ✘ 目标 GPUBuffer
。destinationOffset
GPUSize64
✘ ✘ 目标 buffer 的写入起始偏移(字节)。 size
GPUSize64
✘ ✔ 要拷贝的字节数。 返回:
undefined
内容时间轴步骤:
-
在 this.
[[device]]
的设备时间轴上执行后续步骤。
设备时间轴步骤:-
验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。
-
如果 size 为
undefined
,则设为 source.size
− sourceOffset。 -
如未满足以下任一条件,使 this 失效并返回。
-
入队命令(Enqueue a command)到 this,执行时在队列时间轴上执行后续步骤。
队列时间轴步骤:-
将 source 从 sourceOffset 起的 size 字节复制到 destination 的 destinationOffset 起始位置。
-
-
clearBuffer(buffer, offset, size)
-
向
GPUCommandEncoder
编码一个命令,将GPUBuffer
的子区域填充为零。调用者:GPUCommandEncoder
this。参数:
GPUCommandEncoder.clearBuffer(buffer, offset, size) 方法参数。 参数 类型 可为 null 可选 描述 buffer
GPUBuffer
✘ ✘ 要清零的 GPUBuffer
。offset
GPUSize64
✘ ✔ 清零子区域的起始偏移(字节)。 size
GPUSize64
✘ ✔ 要清零的子区域字节数。默认为 buffer 大小减去 offset。 返回:
undefined
内容时间轴步骤:
-
在 this.
[[device]]
的设备时间轴上执行后续步骤。
设备时间轴步骤:-
验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。
-
如果 size 未指定,则设 size =
max(0, buffer.
。size
- offset) -
如未满足以下任一条件,使 this 失效并返回。
-
入队命令(Enqueue a command)到 this,执行时在队列时间轴上执行后续步骤。
队列时间轴步骤:-
将 buffer 从 offset 起的 size 字节设置为
0
。
-
13.5. 像素块拷贝命令(Texel Copy Commands)
-
copyBufferToTexture(source, destination, copySize)
-
向
GPUCommandEncoder
编码一个命令, 将数据从GPUBuffer
的子区域复制到一个或多个连续的纹理子资源的子区域。调用者:GPUCommandEncoder
this。参数:
GPUCommandEncoder.copyBufferToTexture(source, destination, copySize) 方法参数。 参数 类型 可为 null 可选 描述 source
GPUTexelCopyBufferInfo
✘ ✘ 结合 copySize,定义源 buffer 区域。 destination
GPUTexelCopyTextureInfo
✘ ✘ 结合 copySize,定义目标纹理子资源 区域。 copySize
GPUExtent3D
✘ ✘ 返回:
undefined
内容时间轴步骤:
-
? 校验 GPUOrigin3D 形状(destination.
origin
)。 -
? 校验 GPUExtent3D 形状(copySize)。
-
在 this.
[[device]]
的设备时间轴上执行后续步骤。
设备时间轴步骤:-
验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。
-
令 aligned 为
true
。 -
如未满足以下任一条件,使 this 失效并返回。
-
校验 GPUTexelCopyBufferInfo(source) 返回
true
。 -
校验纹理-缓冲区拷贝(destination, source, dataLength, copySize,
COPY_DST
, aligned) 返回true
。
-
-
入队命令(Enqueue a command)到 this,执行时在队列时间轴上执行后续步骤。
队列时间轴步骤:-
令 blockWidth 为 destination.
texture
的texel block width。 -
令 blockHeight 为 destination.
texture
的texel block height。 -
令 dstOrigin 为 destination.
origin
。 -
令 dstBlockOriginX = (dstOrigin.x ÷ blockWidth)。
-
令 dstBlockOriginY = (dstOrigin.y ÷ blockHeight)。
-
令 blockColumns = (copySize.width ÷ blockWidth)。
-
令 blockRows = (copySize.height ÷ blockHeight)。
-
断言 dstBlockOriginX、dstBlockOriginY、blockColumns 和 blockRows 均为整数。
-
对于 z 属于区间 [0, copySize.depthOrArrayLayers − 1]:
-
对于 y 属于区间 [0, blockRows − 1]:
-
-
copyTextureToBuffer(source, destination, copySize)
-
向
GPUCommandEncoder
编码一个命令, 将数据从一个或多个连续纹理子资源的子区域复制到GPUBuffer
的子区域中。调用者:GPUCommandEncoder
this。参数:
GPUCommandEncoder.copyTextureToBuffer(source, destination, copySize) 方法参数。 参数 类型 可为 null 可选 描述 source
GPUTexelCopyTextureInfo
✘ ✘ 结合 copySize,定义源纹理子资源区域。 destination
GPUTexelCopyBufferInfo
✘ ✘ 结合 copySize,定义目标 buffer 区域。 copySize
GPUExtent3D
✘ ✘ 返回:
undefined
内容时间轴步骤:
-
? 校验 GPUOrigin3D 形状(source.
origin
)。 -
? 校验 GPUExtent3D 形状(copySize)。
-
在 this.
[[device]]
的设备时间轴上执行后续步骤。
设备时间轴步骤:-
验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。
-
令 aligned 为
true
。 -
如未满足以下任一条件,使 this 失效并返回。
-
校验 GPUTexelCopyBufferInfo(destination) 返回
true
。 -
校验纹理-缓冲区拷贝(source, destination, dataLength, copySize,
COPY_SRC
, aligned) 返回true
。
-
-
入队命令(Enqueue a command)到 this,执行时在队列时间轴上执行后续步骤。
队列时间轴步骤:-
令 blockWidth 为 source.
texture
的texel block width。 -
令 blockHeight 为 source.
texture
的texel block height。 -
令 srcOrigin 为 source.
origin
。 -
令 srcBlockOriginX = (srcOrigin.x ÷ blockWidth)。
-
令 srcBlockOriginY = (srcOrigin.y ÷ blockHeight)。
-
令 blockColumns = (copySize.width ÷ blockWidth)。
-
令 blockRows = (copySize.height ÷ blockHeight)。
-
断言 srcBlockOriginX、srcBlockOriginY、blockColumns、blockRows 均为整数。
-
对于 z 属于区间 [0, copySize.depthOrArrayLayers − 1]:
-
-
copyTextureToTexture(source, destination, copySize)
-
向
GPUCommandEncoder
编码一个命令, 将数据从一个或多个连续纹理子资源的子区域复制到另一个或多个连续纹理子资源的子区域。调用者:GPUCommandEncoder
this。参数:
GPUCommandEncoder.copyTextureToTexture(source, destination, copySize) 方法参数。 参数 类型 可为 null 可选 描述 source
GPUTexelCopyTextureInfo
✘ ✘ 结合 copySize,定义源纹理子资源区域。 destination
GPUTexelCopyTextureInfo
✘ ✘ 结合 copySize,定义目标纹理子资源区域。 copySize
GPUExtent3D
✘ ✘ 返回:
undefined
内容时间轴步骤:
-
? 校验 GPUOrigin3D 形状(source.
origin
)。 -
? 校验 GPUOrigin3D 形状(destination.
origin
)。 -
? 校验 GPUExtent3D 形状(copySize)。
-
在 this.
[[device]]
的设备时间轴上执行后续步骤。
设备时间轴步骤:-
验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。
-
如未满足以下任一条件,使 this 失效并返回。
-
令 srcTexture 为 source.
texture
。 -
令 dstTexture 为 destination.
texture
。 -
校验 GPUTexelCopyTextureInfo(source, copySize) 返回
true
。 -
校验 GPUTexelCopyTextureInfo(destination, copySize) 返回
true
。 -
srcTexture.
sampleCount
等于 dstTexture.sampleCount
。 -
srcTexture.
format
和 dstTexture.format
必须是可拷贝兼容(copy-compatible)。 -
如果 srcTexture.
format
是深度/模板格式: -
纹理拷贝的子资源集合(source, copySize) 和 纹理拷贝的子资源集合(destination, copySize) 两者必须不相交。
-
-
入队命令(Enqueue a command)到 this,执行时在队列时间轴上执行后续步骤。
队列时间轴步骤:-
令 srcOrigin 为 source.
origin
。 -
令 srcBlockOriginX = (srcOrigin.x ÷ blockWidth)。
-
令 srcBlockOriginY = (srcOrigin.y ÷ blockHeight)。
-
令 dstOrigin 为 destination.
origin
。 -
令 dstBlockOriginX = (dstOrigin.x ÷ blockWidth)。
-
令 dstBlockOriginY = (dstOrigin.y ÷ blockHeight)。
-
令 blockColumns = (copySize.width ÷ blockWidth)。
-
令 blockRows = (copySize.height ÷ blockHeight)。
-
断言 srcBlockOriginX、srcBlockOriginY、dstBlockOriginX、dstBlockOriginY、blockColumns、blockRows 均为整数。
-
对于 z 属于区间 [0, copySize.depthOrArrayLayers − 1]:
-
对于 y 属于区间 [0, blockRows − 1]:
-
13.6. 查询(Queries)
-
resolveQuerySet(querySet, firstQuery, queryCount, destination, destinationOffset)
-
将
GPUQuerySet
的查询结果解析(resolve)到指定范围的GPUBuffer
中。调用者:GPUCommandEncoder
this。参数:
GPUCommandEncoder.resolveQuerySet(querySet, firstQuery, queryCount, destination, destinationOffset) 方法参数。 参数 类型 可为 null 可选 描述 querySet
GPUQuerySet
✘ ✘ firstQuery
GPUSize32
✘ ✘ queryCount
GPUSize32
✘ ✘ destination
GPUBuffer
✘ ✘ destinationOffset
GPUSize64
✘ ✘ 返回:
undefined
内容时间轴步骤:
-
在 this.
[[device]]
的设备时间轴上执行后续步骤。
设备时间轴步骤:-
验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。
-
如未满足以下任一条件,使 this 失效并返回。
-
querySet 可与 this 有效共用。
-
destination 可与 this 有效共用。
-
destination.
usage
包含QUERY_RESOLVE
。 -
firstQuery < querySet 的查询数量。
-
(firstQuery + queryCount) ≤ querySet 的查询数量。
-
destinationOffset 是 256 的倍数。
-
destinationOffset + 8 × queryCount ≤ destination.
size
。
-
-
入队命令(Enqueue a command)到 this,执行时在队列时间轴上执行后续步骤。
队列时间轴步骤:-
令 queryIndex = firstQuery。
-
令 offset = destinationOffset。
-
当 queryIndex < firstQuery + queryCount 时:
-
将 destination 从 offset 起的 8 字节设置为 querySet 在 queryIndex 位置的值。
-
令 queryIndex = queryIndex + 1。
-
令 offset = offset + 8。
-
-
13.7. 终结(Finalization)
通过调用 finish()
,可以创建包含由
GPUCommandEncoder
录制的命令的
GPUCommandBuffer
。
一旦 finish()
被调用,该命令编码器将无法再被使用。
-
finish(descriptor)
-
完成命令序列的录制,并返回对应的
GPUCommandBuffer
。调用者:GPUCommandEncoder
this。参数:
GPUCommandEncoder.finish(descriptor) 方法参数。 参数 类型 可为 null 可选 描述 descriptor
GPUCommandBufferDescriptor
✘ ✔ 返回:
GPUCommandBuffer
内容时间轴步骤:
-
令 commandBuffer 为一个新的
GPUCommandBuffer
。 -
在 this.
[[device]]
的设备时间轴上执行 finish steps。 -
返回 commandBuffer。
设备时间轴 finish steps:-
令 validationSucceeded =
true
,如果以下所有要求都满足,否则为false
。-
this 必须 有效。
-
this.
[[debug_group_stack]]
必须为空。
-
-
如果 validationSucceeded ==
false
,则: -
设置 commandBuffer.
[[command_list]]
为 this.[[commands]]
。
-
14. 可编程通道(Programmable Passes)
interface mixin {
GPUBindingCommandsMixin undefined setBindGroup (GPUIndex32 index ,GPUBindGroup ?bindGroup ,optional sequence <GPUBufferDynamicOffset >dynamicOffsets = []);undefined setBindGroup (GPUIndex32 index ,GPUBindGroup ?bindGroup , [AllowShared ]Uint32Array dynamicOffsetsData ,GPUSize64 dynamicOffsetsDataStart ,GPUSize32 dynamicOffsetsDataLength ); };
GPUBindingCommandsMixin
假设同一对象上存在 GPUObjectBase
和 GPUCommandsMixin
成员。
它只能被同时包含了这些 mixin 的接口所包含。
GPUBindingCommandsMixin
具有如下设备时间轴属性:
-
[[bind_groups]]
, 类型为 有序映射 <GPUIndex32
,GPUBindGroup
>,初始为空 -
每个索引当前的
GPUBindGroup
。 -
[[dynamic_offsets]]
, 类型为 有序映射 <GPUIndex32
, 列表 <GPUBufferDynamicOffset
>>,初始为空 -
每个
[[bind_groups]]
条目的当前动态偏移。
14.1. 绑定组(Bind Groups)
setBindGroup() 有两个重载:
-
setBindGroup(index, bindGroup, dynamicOffsets)
-
设置给定索引处的当前
GPUBindGroup
。调用者:GPUBindingCommandsMixin
this。参数:
-
index
, 类型GPUIndex32
,不可为 null,必填 -
要设置绑定组的索引。
-
bindGroup
, 类型GPUBindGroup
,可为 null,必填 -
后续渲染或计算命令要用的绑定组。
-
dynamicOffsets
, 类型 sequence<GPUBufferDynamicOffset
>,不可为 null,默认[]
-
对于 bindGroup 中各
buffer
.hasDynamicOffset
为 true 的条目,按GPUBindGroupLayoutEntry
.binding
顺序给出 buffer 偏移(字节)。详见 说明。
返回:
undefined
内容时间轴步骤:
-
在 this.
[[device]]
的设备时间轴上执行后续步骤。
设备时间轴步骤:-
验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。
-
令 dynamicOffsetCount = 0,若
bindGroup
为null
,否则为 bindGroup.[[layout]]
.[[dynamicOffsetCount]]
。 -
如未满足以下任一要求,使 this 失效并返回。
-
index 必须小于 this.
[[device]]
.[[limits]]
.maxBindGroups
。 -
dynamicOffsets.size 必须等于 dynamicOffsetCount。
-
-
如果 bindGroup 为
null
:-
移除 this.
[[bind_groups]]
[index]。 -
移除 this.
[[dynamic_offsets]]
[index]。
否则:
-
如未满足以下任一要求,使 this 失效并返回。
-
bindGroup 必须 可与 this 有效共用。
-
对于每个动态绑定 (bufferBinding, bufferLayout, dynamicOffsetIndex) in bindGroup:
-
bufferBinding.
offset
+ dynamicOffsets[dynamicOffsetIndex] + bufferLayout.minBindingSize
必须 ≤ bufferBinding.buffer
.size
。 -
如果 bufferLayout.
type
为"uniform"
:-
dynamicOffset 必须是
minUniformBufferOffsetAlignment
的倍数。
-
-
如果 bufferLayout.
type
为"storage"
或"read-only-storage"
:-
dynamicOffset 必须是
minStorageBufferOffsetAlignment
的倍数。
-
-
-
-
设置 this.
[[bind_groups]]
[index] 为 bindGroup。 -
设置 this.
[[dynamic_offsets]]
[index] 为 dynamicOffsets 的拷贝。 -
如果 this 是
GPURenderCommandsMixin
:-
对 this.
[[bind_groups]]
中每个 bindGroup,合并 bindGroup.[[usedResources]]
到 this.[[usage scope]]
。
-
-
-
-
setBindGroup(index, bindGroup, dynamicOffsetsData, dynamicOffsetsDataStart, dynamicOffsetsDataLength)
-
设置给定索引处的当前
GPUBindGroup
,动态偏移通过Uint32Array
的子集指定。调用者:GPUBindingCommandsMixin
this。参数:
GPUBindingCommandsMixin.setBindGroup(index, bindGroup, dynamicOffsetsData, dynamicOffsetsDataStart, dynamicOffsetsDataLength) 方法参数。 参数 类型 可为 null 可选 描述 index
GPUIndex32
✘ ✘ 要设置绑定组的索引。 bindGroup
GPUBindGroup?
✔ ✘ 后续渲染或计算命令要用的绑定组。 dynamicOffsetsData
Uint32Array
✘ ✘ 对于 bindGroup 中各 buffer
.hasDynamicOffset
为 true 的条目,按GPUBindGroupLayoutEntry
.binding
顺序给出 buffer 偏移(字节)。详见 说明。dynamicOffsetsDataStart
GPUSize64
✘ ✘ dynamicOffsetsData 中 buffer 偏移数据起始的元素偏移。 dynamicOffsetsDataLength
GPUSize32
✘ ✘ 要从 dynamicOffsetsData 读取的 buffer 偏移数量。 返回:
undefined
内容时间轴步骤:
-
如未满足以下任一要求,抛出
RangeError
并返回。-
dynamicOffsetsDataStart 必须 ≥ 0。
-
dynamicOffsetsDataStart + dynamicOffsetsDataLength 必须 ≤ dynamicOffsetsData.
length
。
-
-
令 dynamicOffsets 为 列表,内容为 dynamicOffsetsData 拷贝的 dynamicOffsetsDataStart 起 dynamicOffsetsDataLength 个元素。
-
调用 this.
setBindGroup
(index, bindGroup, dynamicOffsets)。
-
GPUBindGroupLayoutEntry
.binding
顺序应用。
这意味着,如果 dynamic bindings
是 GPUBindGroupLayoutEntry
的列表,列表中每个成员的 buffer
?.hasDynamicOffset
被设置为 true
,并按 GPUBindGroupLayoutEntry
.binding
排序,则 dynamic offset[i]
(传给 setBindGroup() 的)对应
dynamic bindings[i]
。
GPUBindGroupLayout
:
// 注意:数组内绑定顺序可以乱序,最终会按 binding index 排序。 let layout= gpuDevice. createBindGroupLayout({ entries: [{ binding: 1 , buffer: {}, }, { binding: 2 , buffer: { dynamicOffset: true }, }, { binding: 0 , buffer: { dynamicOffset: true }, }] });
再通过如下方式创建的 GPUBindGroup
使用:
// 和上面一样,这里的数组顺序无关紧要。 // 甚至不需要和 layout 里的顺序一致。 let bindGroup= gpuDevice. createBindGroup({ layout: layout, entries: [{ binding: 1 , resource: { buffer: bufferA, offset: 256 }, }, { binding: 2 , resource: { buffer: bufferB, offset: 512 }, }, { binding: 0 , resource: { buffer: bufferC}, }] });
并使用如下方式绑定:
pass. setBindGroup( 0 , bindGroup, [ 1024 , 2048 ]);
则实际生效的 buffer 偏移如下:
Binding | Buffer | Offset |
---|---|---|
0 | bufferC | 1024(动态) |
1 | bufferA | 256(静态) |
2 | bufferB | 2560(静态 + 动态) |
GPUBindGroup
bindGroup 上遍历每个动态绑定偏移(Iterate over each dynamic binding
offset),
并对每个动态偏移执行指定 steps,按如下设备时间轴步骤:
-
令 dynamicOffsetIndex =
0
。 -
令 layout = bindGroup.
[[layout]]
。 -
对 bindGroup.
[[entries]]
中每个GPUBindGroupEntry
entry, 按 entry.binding
升序遍历:-
令 bindingDescriptor = layout.
[[entryMap]]
[entry.binding
]。 -
如果 bindingDescriptor.
buffer
?.hasDynamicOffset
为true
:-
令 bufferBinding = get as buffer binding(entry.
resource
)。 -
令 bufferLayout = bindingDescriptor.
buffer
。 -
以 bufferBinding、bufferLayout、dynamicOffsetIndex 调用 steps。
-
令 dynamicOffsetIndex = dynamicOffsetIndex +
1
。
-
-
参数:
-
GPUBindingCommandsMixin
encoder -
要校验绑定组的编码器。
-
GPUPipelineBase
pipeline -
要校验 encoder 绑定组兼容性的管线。
Device timeline steps:
-
如未满足以下任一条件,返回
false
:-
pipeline 不得为
null
。 -
所有 pipeline 使用的绑定组必须已设置且与 pipeline layout 兼容: 对 pipeline.
[[layout]]
.[[bindGroupLayouts]]
中每对 (GPUIndex32
index,GPUBindGroupLayout
bindGroupLayout):-
如果 bindGroupLayout 为
null
,continue。 -
令 bindGroup = encoder.
[[bind_groups]]
[index]。 -
令 dynamicOffsets = encoder.
[[dynamic_offsets]]
[index]。 -
bindGroup 不得为
null
。 -
bindGroup.
[[layout]]
必须与 bindGroupLayout group-equivalent。 -
令 dynamicOffsetIndex = 0。
-
对 bindGroup.
[[entries]]
中每个GPUBindGroupEntry
bindGroupEntry,按 bindGroupEntry.binding
升序遍历:-
令 bindGroupLayoutEntry = bindGroup.
[[layout]]
.[[entryMap]]
[bindGroupEntry.binding
]。 -
如果 bindGroupLayoutEntry.
buffer
未提供,continue。 -
令 bound = get as buffer binding(bindGroupEntry.
resource
)。 -
如果 bindGroupLayoutEntry.
buffer
.hasDynamicOffset
:-
将 bound.
offset
增加 dynamicOffsets[dynamicOffsetIndex]。 -
dynamicOffsetIndex 增加 1。
-
-
如果 bindGroupEntry.
[[prevalidatedSize]]
为false
:-
effective buffer binding size(bound) 必须 ≥ minimum buffer binding size,即 pipeline 着色器中与 bindGroupEntry 对应的变量的要求。
-
-
-
-
Encoder bind groups alias a writable resource(encoder, pipeline) 必须为
false
。
-
否则返回 true
。
GPUTextureView
对象)。
Note: 此算法限制了 usage scope storage exception 的使用。
参数:
-
GPUBindingCommandsMixin
encoder -
要校验绑定组的编码器。
-
GPUPipelineBase
pipeline -
要校验 encoder 绑定组兼容性的管线。
Device timeline steps:
-
对于 stage 属于 [
VERTEX
,FRAGMENT
,COMPUTE
]:-
令 bufferBindings 为 (
GPUBufferBinding
,boolean
) 对的列表,后者表示资源是否作为可写使用。 -
令 textureViews 为 (
GPUTextureView
,boolean
) 对的列表,后者表示资源是否作为可写使用。 -
对于 pipeline.
[[layout]]
.[[bindGroupLayouts]]
中每一对 (GPUIndex32
bindGroupIndex,GPUBindGroupLayout
bindGroupLayout):-
令 bindGroup = encoder.
[[bind_groups]]
[bindGroupIndex]。 -
令 bindGroupLayoutEntries = bindGroupLayout.
[[descriptor]]
.entries
。 -
令 bufferRanges 为 bindGroup 的已绑定 buffer 范围,使用动态偏移 encoder.
[[dynamic_offsets]]
[bindGroupIndex]。 -
对于 bufferRanges 中每一对 (
GPUBindGroupLayoutEntry
bindGroupLayoutEntry,GPUBufferBinding
resource),其中 bindGroupLayoutEntry.visibility
包含 stage:-
令 resourceWritable = (bindGroupLayoutEntry.
buffer
.type
=="storage"
)。 -
对于 bufferBindings 中每一对 (
GPUBufferBinding
pastResource,boolean
pastResourceWritable):-
如果 (resourceWritable 或 pastResourceWritable) 为 true,且 pastResource 和 resource buffer-binding-aliasing,返回
true
。
-
-
追加 (resource, resourceWritable) 到 bufferBindings。
-
-
对于 bindGroupLayoutEntries 中每个
GPUBindGroupLayoutEntry
bindGroupLayoutEntry 及 bindGroup 中对应的GPUTextureView
resource,其中 bindGroupLayoutEntry.visibility
包含 stage:-
如果 bindGroupLayoutEntry.
storageTexture
未提供,continue。 -
令 resourceWritable 为 bindGroupLayoutEntry.
storageTexture
.access
是否为可写访问模式。 -
对于 textureViews 中每一对 (
GPUTextureView
pastResource,boolean
pastResourceWritable):-
如果 (resourceWritable 或 pastResourceWritable) 为 true,且 pastResource 和 resource texture-view-aliasing,返回
true
。
-
-
追加 (resource, resourceWritable) 到 textureViews。
-
-
-
-
返回
false
。
Note: 强烈建议实现做此算法的优化。
15. 调试标记(Debug Markers)
GPUDebugCommandsMixin
提供用于给一组命令应用调试标签或在命令序列中插入单个标签的方法。
调试组可以嵌套,从而形成有层次的标记命令,且必须成对平衡。
与 对象标签
类似,这些标签没有强制行为,但可能会显示在错误消息、浏览器开发者工具中,也可能传递给底层原生 API。
interface mixin GPUDebugCommandsMixin {undefined pushDebugGroup (USVString groupLabel );undefined popDebugGroup ();undefined insertDebugMarker (USVString markerLabel ); };
GPUDebugCommandsMixin
假设同一对象上存在 GPUObjectBase
和 GPUCommandsMixin
成员。它只能被同时包含了这些 mixin 的接口所包含。
GPUDebugCommandsMixin
具有如下设备时间轴属性:
-
[[debug_group_stack]]
,类型为 stack<USVString
> -
当前活跃调试组标签的栈。
GPUDebugCommandsMixin
具有如下方法:
-
pushDebugGroup(groupLabel)
-
开始一个包含后续命令的调试组。
Called on:GPUDebugCommandsMixin
this。参数:
GPUDebugCommandsMixin.pushDebugGroup(groupLabel) 方法参数。 参数 类型 可为 null 可选 描述 groupLabel
USVString
✘ ✘ 命令组的标签。 返回:
undefined
内容时间轴步骤:
-
在 this.
[[device]]
的设备时间轴上执行后续步骤。
Device timeline steps:-
验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。
-
Push groupLabel 到 this.
[[debug_group_stack]]
栈顶。
-
-
popDebugGroup()
-
结束最近一次
pushDebugGroup()
启动的调试组。Device timeline steps:-
验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。
-
如未满足以下要求,使 this 失效并返回。
-
this.
[[debug_group_stack]]
不得为空。
-
-
Pop 从 this.
[[debug_group_stack]]
弹出一项。
-
-
insertDebugMarker(markerLabel)
-
在命令流中插入一个带标签的标记点。
Called on:GPUDebugCommandsMixin
this。参数:
GPUDebugCommandsMixin.insertDebugMarker(markerLabel) 方法参数。 参数 类型 可为 null 可选 描述 markerLabel
USVString
✘ ✘ 要插入的标签。 返回:
undefined
内容时间轴步骤:
-
在 this.
[[device]]
的设备时间轴上执行后续步骤。
Device timeline steps:-
验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。
-
16. 计算通道(Compute Passes)
16.1.
GPUComputePassEncoder
[Exposed =(Window ,Worker ),SecureContext ]interface GPUComputePassEncoder {undefined setPipeline (GPUComputePipeline pipeline );undefined dispatchWorkgroups (GPUSize32 workgroupCountX ,optional GPUSize32 workgroupCountY = 1,optional GPUSize32 workgroupCountZ = 1);undefined dispatchWorkgroupsIndirect (GPUBuffer indirectBuffer ,GPUSize64 indirectOffset );undefined end (); };GPUComputePassEncoder includes GPUObjectBase ;GPUComputePassEncoder includes GPUCommandsMixin ;GPUComputePassEncoder includes GPUDebugCommandsMixin ;GPUComputePassEncoder includes GPUBindingCommandsMixin ;
GPUComputePassEncoder
具有如下设备时间轴属性:
-
[[command_encoder]]
,类型为GPUCommandEncoder
,只读 -
创建此计算通道编码器的
GPUCommandEncoder
。 -
[[endTimestampWrite]]
,类型为 GPU command?,只读,默认null
-
用于在通道结束时写入时间戳的 GPU command(如有)。
-
[[pipeline]]
,类型为GPUComputePipeline
,初始为null
-
当前的
GPUComputePipeline
。
16.1.1. 计算通道编码器的创建(Compute Pass Encoder Creation)
dictionary {
GPUComputePassTimestampWrites required GPUQuerySet querySet ;GPUSize32 beginningOfPassWriteIndex ;GPUSize32 endOfPassWriteIndex ; };
-
querySet
,类型 GPUQuerySet -
要写入查询结果的
GPUQuerySet
,类型为"timestamp"
。 -
beginningOfPassWriteIndex
,类型 GPUSize32 -
如指定,表示计算通道开始时写入时间戳的
querySet
中的查询索引。 -
endOfPassWriteIndex
,类型 GPUSize32 -
如指定,表示计算通道结束时写入时间戳的
querySet
中的查询索引。
注意: 时间戳查询值以纳秒为单位写入,但数值的含义是实现定义的,且可能不是单调递增。详情见§ 20.4 时间戳查询。
dictionary :
GPUComputePassDescriptor GPUObjectDescriptorBase {GPUComputePassTimestampWrites timestampWrites ; };
-
timestampWrites
,类型 GPUComputePassTimestampWrites -
定义此通道需要写入哪些时间戳以及写入位置。
16.1.2. 调度(Dispatch)
-
setPipeline(pipeline)
-
设置当前的
GPUComputePipeline
。调用者:GPUComputePassEncoder
this。参数:
GPUComputePassEncoder.setPipeline(pipeline) 方法参数。 参数 类型 可为 null 可选 描述 pipeline
GPUComputePipeline
✘ ✘ 后续调度命令使用的计算管线。 返回:
undefined
内容时间轴步骤:
-
在 this.
[[device]]
的设备时间轴上执行后续步骤。
Device timeline steps:-
验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。
-
如未满足以下条件,使 this 失效并返回。
-
pipeline 必须 可与 this 有效共用。
-
-
设置 this.
[[pipeline]]
为 pipeline。
-
-
dispatchWorkgroups(workgroupCountX, workgroupCountY, workgroupCountZ)
-
使用当前
GPUComputePipeline
派发工作。详见§ 23.1 计算。调用者:GPUComputePassEncoder
this。参数:
GPUComputePassEncoder.dispatchWorkgroups(workgroupCountX, workgroupCountY, workgroupCountZ) 方法参数。 参数 类型 可为 null 可选 描述 workgroupCountX
GPUSize32
✘ ✘ 待派发 workgroup 网格的 X 维度。 workgroupCountY
GPUSize32
✘ ✔ 待派发 workgroup 网格的 Y 维度。 workgroupCountZ
GPUSize32
✘ ✔ 待派发 workgroup 网格的 Z 维度。 注意:x
、y
和z
传递给dispatchWorkgroups()
和dispatchWorkgroupsIndirect()
的值,是每个维度需要派发的 workgroup 数量,不是每个维度的着色器调用(shader invocation)数量。这与现代原生 GPU API 的行为一致,但与 OpenCL 不同。例如,如果一个
GPUShaderModule
的入口点定义了@workgroup_size(4, 4)
,并用computePass.dispatchWorkgroups(8, 8);
派发,则总共会调用 4*4*8*8=1024 次:即 4x4 的 workgroup 在 X、Y 两轴各派发 8 次。返回:
undefined
内容时间轴步骤:
-
在 this.
[[device]]
的设备时间轴上执行后续步骤。
Device timeline steps:-
验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。
-
令 usageScope 为一个空的usage scope。
-
对 this.
[[bind_groups]]
中每个 bindGroup,合并 bindGroup.[[usedResources]]
到 this.[[usage scope]]
。 -
如未满足以下条件,使 this 失效并返回。
-
usageScope 必须满足usage scope 校验。
-
Validate encoder bind groups(this, this.
[[pipeline]]
) 为true
。 -
workgroupCountX、workgroupCountY、workgroupCountZ 均 ≤ this.device.limits.
maxComputeWorkgroupsPerDimension
。
-
-
令 bindingState 为 this 的当前状态快照。
-
Enqueue a command 到 this,该命令将在队列时间轴上执行后续步骤。
Queue timeline steps:-
以 [workgroupCountX, workgroupCountY, workgroupCountZ] 维度、bindingState.
[[pipeline]]
以及 bindingState.[[bind_groups]]
执行 workgroup 网格。
-
-
dispatchWorkgroupsIndirect(indirectBuffer, indirectOffset)
-
使用当前
GPUComputePipeline
,从GPUBuffer
读取参数派发工作。详见§ 23.1 计算。缓冲区中编码的 indirect dispatch parameters 必须是3 个 32 位无符号整数(共 12 字节)的紧凑块,顺序与
dispatchWorkgroups()
参数一致。例如:let dispatchIndirectParameters= new Uint32Array( 3 ); dispatchIndirectParameters[ 0 ] = workgroupCountX; dispatchIndirectParameters[ 1 ] = workgroupCountY; dispatchIndirectParameters[ 2 ] = workgroupCountZ; 调用者:GPUComputePassEncoder
this。参数:
GPUComputePassEncoder.dispatchWorkgroupsIndirect(indirectBuffer, indirectOffset) 方法参数。 参数 类型 可为 null 可选 描述 indirectBuffer
GPUBuffer
✘ ✘ 包含间接调度参数的缓冲区。 indirectOffset
GPUSize64
✘ ✘ 缓冲区 indirectBuffer 内调度数据起始的字节偏移。 返回:
undefined
内容时间轴步骤:
-
在 this.
[[device]]
的设备时间轴上执行后续步骤。
Device timeline steps:-
验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。
-
令 usageScope 为一个空的usage scope。
-
对 this.
[[bind_groups]]
中每个 bindGroup,合并 bindGroup.[[usedResources]]
到 this.[[usage scope]]
。 -
如未满足以下条件,使 this 失效并返回。
-
usageScope 必须满足usage scope 校验。
-
Validate encoder bind groups(this, this.
[[pipeline]]
) 为true
。 -
indirectBuffer 必须 可与 this 有效共用。
-
indirectOffset 必须是 4 的倍数。
-
-
令 bindingState 为 this 的当前状态快照。
-
Enqueue a command 到 this,该命令将在队列时间轴上执行后续步骤。
Queue timeline steps:-
令 workgroupCountX 为从 indirectBuffer 的 indirectOffset 字节处读取的无符号 32 位整数。
-
令 workgroupCountY 为从 indirectBuffer 的 indirectOffset+4 字节处读取的无符号 32 位整数。
-
令 workgroupCountZ 为从 indirectBuffer 的 indirectOffset+8 字节处读取的无符号 32 位整数。
-
如果 workgroupCountX、workgroupCountY 或 workgroupCountZ 大于 this.device.limits.
maxComputeWorkgroupsPerDimension
,则返回。 -
以 [workgroupCountX, workgroupCountY, workgroupCountZ] 维度、bindingState.
[[pipeline]]
以及 bindingState.[[bind_groups]]
执行 workgroup 网格。
-
16.1.3. 结束(Finalization)
计算通道编码器可以通过调用 end()
结束,表示用户已完成本通道的命令录制。一旦调用 end()
,该计算通道编码器不可再使用。
-
end()
-
完成本计算通道命令序列的录制。
Device timeline steps:-
令 parentEncoder = this.
[[command_encoder]]
。 -
如未满足以下任一要求,生成校验错误并返回。
-
如未满足以下任一要求,使 parentEncoder 失效并返回。
-
this 必须 有效。
-
this.
[[debug_group_stack]]
必须为空。
-
-
扩展 parentEncoder.
[[commands]]
,追加 this.[[commands]]
。 -
如果 this.
[[endTimestampWrite]]
不为null
:-
扩展 parentEncoder.
[[commands]]
,追加 this.[[endTimestampWrite]]
。
-
-
17. 渲染通道(Render Passes)
17.1.
GPURenderPassEncoder
[Exposed =(Window ,Worker ),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 end (); };GPURenderPassEncoder includes GPUObjectBase ;GPURenderPassEncoder includes GPUCommandsMixin ;GPURenderPassEncoder includes GPUDebugCommandsMixin ;GPURenderPassEncoder includes GPUBindingCommandsMixin ;GPURenderPassEncoder includes GPURenderCommandsMixin ;
GPURenderPassEncoder
具有如下设备时间轴属性:
-
[[command_encoder]]
,类型为GPUCommandEncoder
,只读 -
创建此渲染通道编码器的
GPUCommandEncoder
。 -
[[attachment_size]]
,只读 -
设置为以下范围:
-
width, height
= 通道渲染附件的尺寸
-
-
[[occlusion_query_set]]
,类型为GPUQuerySet
,只读 -
用于存储本通道遮挡查询结果的
GPUQuerySet
,在通道创建时由GPURenderPassDescriptor
.occlusionQuerySet
初始化。 -
[[endTimestampWrite]]
,类型为 GPU command?,只读,默认null
-
用于在通道结束时写入时间戳的 GPU command(如有)。
-
[[maxDrawCount]]
,类型为GPUSize64
,只读 -
本通道允许的最大绘制次数。
-
[[occlusion_query_active]]
,类型为boolean
-
本通道的
[[occlusion_query_set]]
是否正被写入。
在作为 GPUCommandBuffer
一部分执行编码的渲染通道命令时,会使用内部 RenderState 对象来跟踪渲染所需的当前状态。
RenderState 具有如下队列时间轴属性:
-
[[occlusionQueryIndex]]
,类型为GPUSize32
-
在
[[occlusion_query_set]]
中存储遮挡查询结果的索引。 -
[[viewport]]
-
当前视口矩形和深度范围。初始值如下:
-
x, y
=0.0, 0.0
-
width, height
= 通道渲染目标的尺寸 -
minDepth, maxDepth
=0.0, 1.0
-
-
[[scissorRect]]
-
当前剪裁矩形,初始值如下:
-
x, y
=0, 0
-
width, height
= 通道渲染目标的尺寸
-
-
[[blendConstant]]
,类型为GPUColor
-
当前混合常量,初始为
[0, 0, 0, 0]
。 -
[[stencilReference]]
,类型为GPUStencilValue
-
当前模板参考值,初始为
0
。 -
[[colorAttachments]]
,类型为 sequence<GPURenderPassColorAttachment
?> -
本渲染通道的颜色附件及其状态。
-
[[depthStencilAttachment]]
,类型为GPURenderPassDepthStencilAttachment
? -
本渲染通道的深度/模板附件及其状态。
渲染通道还具有 帧缓冲内存(framebuffer memory),用于存储由绘制命令写入、混合和深度/模板测试读取的每个附件的texel数据。
注意: 根据 GPU 硬件,帧缓冲内存 可能是附件纹理分配的内存,也可能是一个独立区域,纹理数据需被拷贝至/从该区域(如 tile-based 架构)。
17.1.1. 渲染通道编码器的创建(Render Pass Encoder Creation)
dictionary {
GPURenderPassTimestampWrites required GPUQuerySet querySet ;GPUSize32 beginningOfPassWriteIndex ;GPUSize32 endOfPassWriteIndex ; };
-
querySet
,类型 GPUQuerySet -
要写入查询结果的
GPUQuerySet
,类型为"timestamp"
。 -
beginningOfPassWriteIndex
,类型 GPUSize32 -
如指定,表示渲染通道开始时写入时间戳的
querySet
中的查询索引。 -
endOfPassWriteIndex
,类型 GPUSize32 -
如指定,表示渲染通道结束时写入时间戳的
querySet
中的查询索引。
注意: 时间戳查询值以纳秒为单位写入,但数值的含义是实现定义的,且可能不是单调递增。详情见§ 20.4 时间戳查询。
dictionary :
GPURenderPassDescriptor GPUObjectDescriptorBase {required sequence <GPURenderPassColorAttachment ?>colorAttachments ;GPURenderPassDepthStencilAttachment depthStencilAttachment ;GPUQuerySet occlusionQuerySet ;GPURenderPassTimestampWrites timestampWrites ;GPUSize64 maxDrawCount = 50000000; };
-
colorAttachments
,类型sequence<GPURenderPassColorAttachment?>
-
该序列中的
GPURenderPassColorAttachment
集合定义了此渲染通道执行时输出到哪些颜色附件。受用法兼容性限制,任一颜色附件不得与其他附件或渲染通道中使用的任何资源混用(alias)。
-
depthStencilAttachment
,类型 GPURenderPassDepthStencilAttachment -
GPURenderPassDepthStencilAttachment
值,定义此渲染通道执行时输出和测试的深度/模板附件。受用法兼容性限制,可写深度/模板附件不得与其他附件或渲染通道中使用的任何资源混用(alias)。
-
occlusionQuerySet
,类型 GPUQuerySet -
GPUQuerySet
,定义本通道遮挡查询结果的存储位置。 -
timestampWrites
,类型 GPURenderPassTimestampWrites -
定义此通道将写入哪些时间戳及其位置。
-
maxDrawCount
,类型 GPUSize64,默认50000000
-
本渲染通道允许的最大绘制(draw)调用次数。某些实现会利用此值分配渲染通道前需要的资源。除非确定会有更多绘制调用,保持默认值即可。
对于给定 GPUDevice
device 和 GPURenderPassDescriptor
this,需要满足如下校验规则:
-
this.
colorAttachments
.size 必须 ≤ device.[[limits]]
.maxColorAttachments
。 -
对 this.
colorAttachments
中每个非null
的 colorAttachment:-
如果 colorAttachment.
resolveTarget
已 提供:-
colorAttachment.
resolveTarget
必须 可与 device 有效共用。
-
-
colorAttachment 必须满足 GPURenderPassColorAttachment 有效用法 规则。
-
若 this.
depthStencilAttachment
已 提供:-
this.
depthStencilAttachment
.view
必须 可与 device 有效共用。 -
this.
depthStencilAttachment
必须满足 GPURenderPassDepthStencilAttachment 有效用法 规则。
-
-
必须至少存在一个附件,满足下列之一:
-
this.
colorAttachments
中有非null
的值,或 -
this.
depthStencilAttachment
。
-
-
校验 GPURenderPassDescriptor 的 color attachment 每采样字节数(device, this.
colorAttachments
) 成功。 -
this.
colorAttachments
所有非null
的view
,以及如有的 this.depthStencilAttachment
.view
,其sampleCount
必须相等。 -
对 this.
colorAttachments
所有非null
的view
及如有的 this.depthStencilAttachment
.view
,其[[renderExtent]]
必须一致。 -
若 this.
occlusionQuerySet
已 提供:-
this.
occlusionQuerySet
必须 可与 device 有效共用。 -
this.
occlusionQuerySet
.type
必须为occlusion
。
-
-
若 this.
timestampWrites
已 提供:-
校验 timestampWrites(device, this.
timestampWrites
) 必须返回 true。
-
参数:
-
GPUDevice
device -
sequence<
GPURenderPassColorAttachment
?> colorAttachments
设备时间轴步骤:
-
令 formats 为一个空的列表<
GPUTextureFormat
?>。 -
对 colorAttachments 中每个 colorAttachment:
-
若 colorAttachment 为
undefined
,continue。 -
追加 colorAttachment.
view
.[[descriptor]]
.format
到 formats。
-
-
计算 color attachment 每采样字节数(formats) 必须 ≤ device.
[[limits]]
.maxColorAttachmentBytesPerSample
。
17.1.1.1. 颜色附件(Color Attachments)
dictionary {
GPURenderPassColorAttachment required (GPUTexture or GPUTextureView )view ;GPUIntegerCoordinate depthSlice ; (GPUTexture or GPUTextureView )resolveTarget ;GPUColor clearValue ;required GPULoadOp loadOp ;required GPUStoreOp storeOp ; };
-
view
,类型(GPUTexture or GPUTextureView)
-
描述此颜色附件要输出到的纹理子资源(subresource)。子资源由 get as texture view(
view
) 决定。 -
depthSlice
,类型 GPUIntegerCoordinate -
resolveTarget
,类型(GPUTexture or GPUTextureView)
-
描述当
view
为多重采样时,用于接收解析后输出的纹理子资源。子资源由 get as texture view(resolveTarget
) 决定。 -
clearValue
,类型 GPUColor -
表示在执行渲染通道前,将
view
清除到的值。若未提供,则默认为{r: 0, g: 0, b: 0, a: 0}
。若loadOp
不为"clear"
,则忽略此项。clearValue
的各分量均为 double 值,会转换为与渲染附件匹配的纹理格式的 texel 值。转换失败会产生校验错误。 -
loadOp
,类型 GPULoadOp -
表示在执行渲染通道前,对
view
执行的加载操作。注意: 推荐优先使用清除操作;详见
"clear"
。 -
storeOp
,类型 GPUStoreOp -
在执行渲染通道后,对
view
执行的存储操作。
给定 GPURenderPassColorAttachment
this:
-
令 renderViewDescriptor = this.
view
.[[descriptor]]
。 -
令 renderTexture = this.
view
.[[texture]]
。 -
必须满足以下所有要求:
-
this.
view
必须是可渲染纹理视图(renderable texture view)。 -
如果 renderViewDescriptor.
dimension
为"3d"
:-
this.
depthSlice
必须提供,且 depthOrArrayLayers 小于 当前 miplevel 逻辑纹理范围(renderTexture 在 mipmap level renderViewDescriptor.baseMipLevel
)的深度或数组层数。
否则:
-
this.
depthSlice
不得被提供。
-
-
-
将 IDL 值 this.
clearValue
转换为纹理格式的 texel 值 renderViewDescriptor.format
时不得抛出TypeError
。注意: 若超出格式范围但仍在 WGSL 基元类型(
f32
、i32
、u32
)范围内,不会报错。
-
-
若 this.
resolveTarget
被提供:-
令 resolveViewDescriptor = this.
resolveTarget
.[[descriptor]]
。 -
令 resolveTexture = this.
resolveTarget
.[[texture]]
。 -
renderTexture.
sampleCount
必须大于 1。 -
resolveTexture.
sampleCount
必须为 1。 -
this.
resolveTarget
必须是非 3D 的可渲染纹理视图。 -
this.
resolveTarget
.[[renderExtent]]
和 this.view
.[[renderExtent]]
必须相等。 -
resolveViewDescriptor.
format
必须等于 renderViewDescriptor.format
。 -
resolveViewDescriptor.
format
必须支持§ 26.1.1 普通颜色格式中的解析。
-
GPUTextureView
view 是可渲染纹理视图(renderable texture view),若满足以下设备时间轴步骤的所有要求:
-
令 descriptor = view.
[[descriptor]]
。 -
descriptor.
usage
必须包含RENDER_ATTACHMENT
。 -
descriptor.
dimension
必须为"2d"
、"2d-array"
或"3d"
。 -
descriptor.
mipLevelCount
必须为 1。 -
descriptor.
arrayLayerCount
必须为 1。 -
descriptor.
aspect
必须包含 view.[[texture]]
的全部aspect。
参数:
-
sequence<
GPUTextureFormat
?> formats
返回: GPUSize32
-
令 total = 0。
-
对 formats 中每个非 null 的 format:
-
令 renderTargetPixelByteCost 为 format 的render target pixel byte cost。
-
令 renderTargetComponentAlignment 为 format 的render target component alignment。
-
将 total 向上取整到不小于 total 的 renderTargetComponentAlignment 的最小倍数。
-
将 renderTargetPixelByteCost 加到 total 上。
-
返回 total。
17.1.1.2. 深度/模板附件(Depth/Stencil Attachments)
dictionary {
GPURenderPassDepthStencilAttachment required (GPUTexture or GPUTextureView )view ;float depthClearValue ;GPULoadOp depthLoadOp ;GPUStoreOp depthStoreOp ;boolean depthReadOnly =false ;GPUStencilValue stencilClearValue = 0;GPULoadOp stencilLoadOp ;GPUStoreOp stencilStoreOp ;boolean stencilReadOnly =false ; };
-
view
,类型(GPUTexture or GPUTextureView)
-
描述此深度/模板附件将要输出和读取的纹理子资源。子资源由 get as texture view(
view
) 决定。 -
depthClearValue
,类型 float -
表示在执行渲染通道前,将
view
的深度分量清除到的值。若depthLoadOp
不为"clear"
,则忽略此项。必须在 0.0 到 1.0 之间(含)。 -
depthLoadOp
,类型 GPULoadOp -
表示在执行渲染通道前,对
view
深度分量执行的加载操作。注意: 推荐优先使用清除操作;详见
"clear"
。 -
depthStoreOp
,类型 GPUStoreOp -
在执行渲染通道后,对
view
深度分量执行的存储操作。 -
depthReadOnly
,类型 boolean,默认false
-
表示
view
的深度分量只读。 -
stencilClearValue
,类型 GPUStencilValue,默认0
-
表示在执行渲染通道前,将
view
的模板分量清除到的值。若stencilLoadOp
不为"clear"
,则忽略此项。该值会被转换为 view 模板 aspect 类型,即取与一个texel 模板位数相同的低位。
-
stencilLoadOp
,类型 GPULoadOp -
表示在执行渲染通道前,对
view
模板分量执行的加载操作。注意: 推荐优先使用清除操作;详见
"clear"
。 -
stencilStoreOp
,类型 GPUStoreOp -
在执行渲染通道后,对
view
模板分量执行的存储操作。 -
stencilReadOnly
,类型 boolean,默认false
-
表示
view
的模板分量只读。
给定 GPURenderPassDepthStencilAttachment
this,需要满足以下校验规则:
-
令 format = this.
view
.[[descriptor]]
.format
。 -
如果 this.
depthLoadOp
为"clear"
,则 this.depthClearValue
必须被提供且在 [0.0, 1.0] 区间内。 -
若 format 有深度 aspect 且 this.
depthReadOnly
为false
:-
this.
depthLoadOp
必须被提供。 -
this.
depthStoreOp
必须被提供。
否则:
-
this.
depthLoadOp
不得被提供。 -
this.
depthStoreOp
不得被提供。
-
-
若 format 有模板 aspect 且 this.
stencilReadOnly
为false
:-
this.
stencilLoadOp
必须被提供。 -
this.
stencilStoreOp
必须被提供。
否则:
-
this.
stencilLoadOp
不得被提供。 -
this.
stencilStoreOp
不得被提供。
-
17.1.1.3. 加载与存储操作(Load & Store Operations)
enum {
GPULoadOp "load" ,"clear" , };
-
"load"
-
将该附件的现有值加载到渲染通道中。
-
"clear"
-
将该附件的清除值加载到渲染通道中。
注意: 在某些 GPU 硬件(主要是移动端)上,
"clear"
的开销明显更低,因为它避免了从主内存加载数据到 tile 本地内存。 在其他 GPU 上,两者差别不大。因此,推荐在初始值无关紧要(如渲染目标会被天空盒等覆盖清除)的情况下,优先使用"clear"
而不是"load"
。
enum {
GPUStoreOp "store" ,"discard" , };
-
"store"
-
将渲染通道该附件的结果值存储下来。
-
"discard"
-
丢弃渲染通道该附件的结果值。
注意: 被丢弃的附件表现为被清零,但实现并不要求在通道结束时执行清零。未显式清零的实现必须在附件内容首次被读取(如采样、拷贝、后续渲染通道用
"load"
附加、显示或回读 canvas 等)前延迟清零。
17.1.1.4. 渲染通道布局(Render Pass Layout)
GPURenderPassLayout
声明了 GPURenderBundle
的渲染目标布局。
它也被用于内部描述 GPURenderPassEncoder
布局
和 GPURenderPipeline
布局。
它决定了渲染通道、渲染包和渲染管线之间的兼容性。
dictionary :
GPURenderPassLayout GPUObjectDescriptorBase {required sequence <GPUTextureFormat ?>colorFormats ;GPUTextureFormat depthStencilFormat ;GPUSize32 sampleCount = 1; };
-
colorFormats
,类型sequence<GPUTextureFormat?>
-
本通道或渲染包的颜色附件的
GPUTextureFormat
列表。 -
depthStencilFormat
,类型 GPUTextureFormat -
本通道或渲染包的深度/模板附件的
GPUTextureFormat
。 -
sampleCount
,类型 GPUSize32,默认1
-
本通道或渲染包的每像素采样数。
GPURenderPassLayout
被认为相等(equal),当且仅当:
-
它们的
depthStencilFormat
和sampleCount
相等,并且 -
它们的
colorFormats
相等(忽略末尾的null
)。
参数:
-
GPURenderPassDescriptor
descriptor
设备时间轴步骤:
-
令 layout 为新的
GPURenderPassLayout
对象。 -
对 descriptor.
colorAttachments
中每个 colorAttachment:-
如果 colorAttachment 不为
null
:-
设置 layout.
sampleCount
为 colorAttachment.view
.[[texture]]
.sampleCount
。 -
将 colorAttachment.
view
.[[descriptor]]
.format
追加到 layout.colorFormats
。
-
-
否则:
-
向 layout.
colorFormats
追加null
。
-
-
-
令 depthStencilAttachment = descriptor.
depthStencilAttachment
。 -
如果 depthStencilAttachment 不为
null
:-
令 view = depthStencilAttachment.
view
。 -
设置 layout.
sampleCount
为 view.[[texture]]
.sampleCount
。 -
设置 layout.
depthStencilFormat
为 view.[[descriptor]]
.format
。
-
-
返回 layout。
参数:
-
GPURenderPipelineDescriptor
descriptor
设备时间轴步骤:
-
令 layout 为新的
GPURenderPassLayout
对象。 -
设置 layout.
sampleCount
为 descriptor.multisample
.count
。 -
如果 descriptor.
depthStencil
已提供:-
设置 layout.
depthStencilFormat
为 descriptor.depthStencil
.format
。
-
-
-
对 descriptor.
fragment
.targets
中每个 colorTarget:-
若 colorTarget 不为
null
,则将 colorTarget.format
追加到 layout.colorFormats
,否则追加null
。
-
-
-
返回 layout。
17.1.2. 结束(Finalization)
渲染通道编码器可以通过调用 end()
结束,表示用户已完成本通道的命令录制。一旦调用 end()
,该渲染通道编码器不可再使用。
-
end()
-
完成本渲染通道命令序列的录制。
设备时间轴步骤:-
令 parentEncoder = this.
[[command_encoder]]
。 -
如未满足以下任一要求,生成校验错误并返回:
-
如未满足以下任一要求,使 parentEncoder 失效并返回:
-
this 必须 有效。
-
this.
[[usage scope]]
必须通过usage scope 校验。 -
this.
[[debug_group_stack]]
必须为空。 -
this.
[[occlusion_query_active]]
必须为false
。 -
this.
[[drawCount]]
必须 ≤ this.[[maxDrawCount]]
。
-
-
扩展 parentEncoder.
[[commands]]
,追加 this.[[commands]]
。 -
如果 this.
[[endTimestampWrite]]
不为null
:-
扩展 parentEncoder.
[[commands]]
,追加 this.[[endTimestampWrite]]
。
-
队列时间轴步骤:-
对 renderState.
[[colorAttachments]]
中每个非null
的 colorAttachment:-
令 colorView = colorAttachment.
view
。 -
若 colorView.
[[descriptor]]
.dimension
为:"3d"
-
令 colorSubregion = colorAttachment.
depthSlice
。 - 否则
-
令 colorSubregion = colorView。
-
若 colorAttachment.
resolveTarget
不为null
:-
将 colorSubregion 的每个texel 的多重采样解析为单采样,并拷贝到 colorAttachment.
resolveTarget
。
-
-
若 colorAttachment.
loadOp
为:
-
-
令 depthStencilAttachment = renderState.
[[depthStencilAttachment]]
。 -
若 depthStencilAttachment 不为
null
:-
若 depthStencilAttachment.
depthLoadOp
为: -
若 depthStencilAttachment.
stencilLoadOp
为:
-
-
令 renderState =
null
。
注意: 被丢弃的附件表现为被清零,但实现并不要求在通道结束时执行清零。详情见
"discard"
的说明。注意: 只读深度/模板附件可以被视为隐式使用
"store"
操作,但由于其内容在渲染通道内并未变化,实际实现无需更新附件。只读附件不允许指定 storeOp 的校验在 GPURenderPassDepthStencilAttachment 有效用法中完成。 -
17.2.
GPURenderCommandsMixin
GPURenderCommandsMixin
定义了 GPURenderPassEncoder
和 GPURenderBundleEncoder
共有的渲染命令。
interface mixin GPURenderCommandsMixin {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 ); };
GPURenderCommandsMixin
假定对象上同时存在 GPUObjectBase
、GPUCommandsMixin
和 GPUBindingCommandsMixin
成员。它只能被同样包含这些 mixin 的接口包含。
GPURenderCommandsMixin
具有如下设备时间轴属性:
-
[[layout]]
,类型GPURenderPassLayout
,只读 -
渲染通道的布局。
-
[[depthReadOnly]]
,类型boolean
,只读 -
如为
true
,表示深度分量未被修改。 -
[[stencilReadOnly]]
,类型boolean
,只读 -
如为
true
,表示模板分量未被修改。 -
[[usage scope]]
,类型 usage scope,初始为空 -
本渲染通道或渲染包的用法范围(usage scope)。
-
[[pipeline]]
,类型GPURenderPipeline
,初始为null
-
当前的
GPURenderPipeline
。 -
[[index_buffer]]
,类型GPUBuffer
,初始为null
-
当前用于读取索引数据的缓冲区。
-
[[index_format]]
,类型GPUIndexFormat
-
[[index_buffer]]
中索引数据的格式。 -
[[index_buffer_offset]]
,类型GPUSize64
-
当前设置的
[[index_buffer]]
区段在字节上的偏移量。 -
[[index_buffer_size]]
,类型GPUSize64
-
当前设置的
[[index_buffer]]
区段的字节大小,初始为0
。 -
[[vertex_buffers]]
,类型 有序映射<slot,GPUBuffer
>,初始为空 -
每个 slot 当前用于读取顶点数据的
GPUBuffer
。 -
[[vertex_buffer_sizes]]
,类型 有序映射<slot,GPUSize64
>,初始为空 -
每个 slot 当前设置的
GPUBuffer
区段的字节大小。 -
[[drawCount]]
,类型GPUSize64
-
本编码器录制的绘制命令数。
GPURenderCommandsMixin
encoder 上入队一个渲染命令(Enqueue a render command),以 GPU Command command 和
RenderState
renderState:
-
追加 command 到 encoder.
[[commands]]
。 -
当 command 作为
GPUCommandBuffer
commandBuffer 的一部分被执行时:-
以 commandBuffer.
[[renderState]]
作为 renderState,执行 command 的步骤。
-
17.2.1. 绘制(Drawing)
-
setPipeline(pipeline)
-
设置当前的
GPURenderPipeline
。调用者:GPURenderCommandsMixin
this。参数:
参数说明:GPURenderCommandsMixin.setPipeline(pipeline) 参数 类型 可为 null 可选 描述 pipeline
GPURenderPipeline
✘ ✘ 后续绘制命令用到的渲染管线。 返回:
undefined
内容时间轴步骤:
-
在 this.
[[device]]
的设备时间轴上执行后续步骤。
设备时间轴步骤:-
校验编码器状态。如返回 false,则返回。
-
令 pipelineTargetsLayout = 从管线推导渲染目标布局(pipeline.
[[descriptor]]
)。 -
如未满足以下任一条件,使 this 失效并返回:
-
pipeline 可与 this 有效共用。
-
this.
[[layout]]
等于 pipelineTargetsLayout。 -
若 pipeline.
[[writesDepth]]
,则 this.[[depthReadOnly]]
必须为false
。 -
若 pipeline.
[[writesStencil]]
,则 this.[[stencilReadOnly]]
必须为false
。
-
-
设置 this.
[[pipeline]]
为 pipeline。
-
-
setIndexBuffer(buffer, indexFormat, offset, size)
-
设置当前索引缓冲区。
调用者:GPURenderCommandsMixin
this。参数:
参数说明:GPURenderCommandsMixin.setIndexBuffer(buffer, indexFormat, offset, size) 参数 类型 可为 null 可选 描述 buffer
GPUBuffer
✘ ✘ 后续绘制命令要用到的索引数据缓冲区。 indexFormat
GPUIndexFormat
✘ ✘ buffer 中索引数据的格式。 offset
GPUSize64
✘ ✔ 索引数据在 buffer 中的字节偏移,默认 0
。size
GPUSize64
✘ ✔ 索引数据在 buffer 中的字节大小,默认 buffer 大小减去 offset。 返回:
undefined
内容时间轴步骤:
-
在 this.
[[device]]
的设备时间轴上执行后续步骤。
设备时间轴步骤:-
校验编码器状态。如返回 false,则返回。
-
如未指定 size,则设 size = max(0, buffer.
size
- offset)。 -
如未满足以下任一条件,使 this 失效并返回:
-
buffer 可与 this 有效共用。
-
offset 是 indexFormat 字节大小的整数倍。
-
offset + size ≤ buffer.
size
。
-
-
添加 buffer 到
[[usage scope]]
,用法为 input。 -
设置 this.
[[index_buffer]]
为 buffer。 -
设置 this.
[[index_format]]
为 indexFormat。 -
设置 this.
[[index_buffer_offset]]
为 offset。 -
设置 this.
[[index_buffer_size]]
为 size。
-
-
setVertexBuffer(slot, buffer, offset, size)
-
为指定的 slot 设置当前顶点缓冲区。
调用者:GPURenderCommandsMixin
this。参数:
参数说明:GPURenderCommandsMixin.setVertexBuffer(slot, buffer, offset, size) 参数 类型 可为 null 可选 描述 slot
GPUIndex32
✘ ✘ 要设置顶点缓冲区的 slot。 buffer
GPUBuffer?
✔ ✘ 后续绘制命令用到的顶点数据缓冲区。 offset
GPUSize64
✘ ✔ 顶点数据在 buffer 中的字节偏移,默认为 0
。size
GPUSize64
✘ ✔ 顶点数据在 buffer 中的字节大小,默认为缓冲区大小减去 offset。 返回:
undefined
内容时间轴步骤:
-
在 this.
[[device]]
的设备时间轴上执行后续步骤。
设备时间轴步骤:-
校验编码器状态。如返回 false,则返回。
-
若 buffer 为
null
,则 bufferSize = 0,否则 bufferSize = buffer.size
。 -
如未提供 size,则设 size = max(0, bufferSize - offset)。
-
如未满足以下任一条件,使 this 失效并返回:
-
slot 必须小于 this.
[[device]]
.[[limits]]
.maxVertexBuffers
。 -
offset 必须为 4 的倍数。
-
offset + size 必须 ≤ bufferSize。
-
-
若 buffer 为
null
:-
移除 this.
[[vertex_buffers]]
[slot]。 -
移除 this.
[[vertex_buffer_sizes]]
[slot]。
否则:
-
如未满足以下任一条件,使 this 失效并返回:
-
buffer 可与 this 有效共用。
-
-
添加 buffer 到
[[usage scope]]
,用法为 input。 -
设置 this.
[[vertex_buffers]]
[slot] 为 buffer。 -
设置 this.
[[vertex_buffer_sizes]]
[slot] 为 size。
-
-
draw(vertexCount, instanceCount, firstVertex, firstInstance)
-
绘制图元。 详细规范见 § 23.2 渲染。
调用于:GPURenderCommandsMixin
this.参数:
方法 GPURenderCommandsMixin.draw(vertexCount, instanceCount, firstVertex, firstInstance) 的参数。 参数 类型 可为 null 可选 描述 vertexCount
GPUSize32
✘ ✘ 要绘制的顶点数。 instanceCount
GPUSize32
✘ ✔ 要绘制的实例数。 firstVertex
GPUSize32
✘ ✔ 从顶点缓冲区的哪个偏移(单位:顶点)开始绘制。 firstInstance
GPUSize32
✘ ✔ 要绘制的第一个实例。 返回值:
undefined
内容时间线 步骤:
-
在 设备时间线 上对 this.
[[device]]
执行后续步骤。
设备时间线 步骤:-
验证 this 的 编码器状态。如果返回 false,则返回。
-
以下步骤中的所有要求 必须 满足。 如有未满足,失效 this 并返回。
-
用 this 绘制必须有效。
-
令 buffers 为 this.
[[pipeline]]
.[[descriptor]]
.vertex
.buffers
。 -
对于每一个
GPUIndex32
slot,从0
到 buffers.size(不包含):-
如果 buffers[slot] 为
null
,继续。 -
令 bufferSize 为 this.
[[vertex_buffer_sizes]]
[slot]。 -
令 stride 为 buffers[slot].
arrayStride
。 -
令 attributes 为 buffers[slot].
attributes
-
令 lastStride 为 attributes 中每个 attribute 的 (
offset
+ byteSize(attribute.format
)) 的最大值,若 attributes 为空,则为 0。 -
根据 buffers[slot].
stepMode
计算 strideCount:"vertex"
-
firstVertex + vertexCount
"instance"
-
firstInstance + instanceCount
-
如果 strideCount ≠
0
:-
(strideCount −
1
) × stride + lastStride 必须 ≤ bufferSize。
-
-
-
-
this.
[[drawCount]]
增加 1。 -
令 bindingState 为 this 当前状态的快照。
队列时间线 步骤:-
绘制 instanceCount 个实例,从 firstInstance 开始, 每个实例由 vertexCount 个顶点组成,从 firstVertex 开始, 使用 bindingState 和 renderState 中的状态。
-
drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance)
-
绘制带索引的图元。 详细规范见 § 23.2 渲染。
调用于:GPURenderCommandsMixin
this.参数:
方法 GPURenderCommandsMixin.drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance) 的参数。 参数 类型 可为 null 可选 描述 indexCount
GPUSize32
✘ ✘ 要绘制的索引数。 instanceCount
GPUSize32
✘ ✔ 要绘制的实例数。 firstIndex
GPUSize32
✘ ✔ 从索引缓冲区的哪个偏移(单位:索引)开始绘制。 baseVertex
GPUSignedOffset32
✘ ✔ 在索引访问顶点缓冲区前,每个索引值要加上的偏移量。 firstInstance
GPUSize32
✘ ✔ 要绘制的第一个实例。 返回值:
undefined
内容时间线 步骤:
-
在 设备时间线 上对 this.
[[device]]
执行后续步骤。
设备时间线 步骤:-
验证 this 的 编码器状态。如果返回 false,则返回。
-
如有下列任一条件不满足,失效 this 并返回。
-
用 this 绘制索引必须有效。
-
firstIndex + indexCount ≤ this.
[[index_buffer_size]]
÷ this.[[index_format]]
的字节大小; -
令 buffers 为 this.
[[pipeline]]
.[[descriptor]]
.vertex
.buffers
。 -
对于每一个
GPUIndex32
slot,从0
到 buffers.size(不包含):-
如果 buffers[slot] 为
null
,继续。 -
令 bufferSize 为 this.
[[vertex_buffer_sizes]]
[slot]。 -
令 stride 为 buffers[slot].
arrayStride
。 -
令 lastStride 为 buffers[slot].
attributes
中每个 attribute 的 (offset
+ byteSize(attribute.format
)) 的最大值。 -
令 strideCount 为 firstInstance + instanceCount。
-
如果 buffers[slot].
stepMode
是"instance"
且 strideCount ≠0
:-
确保 (strideCount −
1
) × stride + lastStride ≤ bufferSize。
-
-
-
-
this.
[[drawCount]]
增加 1。 -
令 bindingState 为 this 当前状态的快照。
队列时间线 步骤:-
绘制 instanceCount 个实例,从 firstInstance 开始, 每个实例由 indexCount 个带索引的顶点组成,从索引 firstIndex(对应顶点 baseVertex)开始, 使用 bindingState 和 renderState 中的状态。
注意: WebGPU 应用不应使用超出任意绑定顶点缓冲区(
GPUVertexStepMode
"vertex"
)范围的索引数据。 不同 WebGPU 实现对这种行为的处理方式不同,因此允许多种行为:要么整个绘制调用被丢弃,要么对越界属性的访问由 WGSL 的 无效内存引用 描述。 -
drawIndirect(indirectBuffer, indirectOffset)
-
使用从
GPUBuffer
读取的参数绘制图元。 详细规范见 § 23.2 渲染。缓冲区中编码的 间接绘制参数 必须是一个紧凑排列的四个 32 位无符号整数值(总共 16 字节),顺序与
draw()
方法参数一致。 例如:let drawIndirectParameters= new Uint32Array( 4 ); drawIndirectParameters[ 0 ] = vertexCount; drawIndirectParameters[ 1 ] = instanceCount; drawIndirectParameters[ 2 ] = firstVertex; drawIndirectParameters[ 3 ] = firstInstance; 对应
firstInstance
的值必须为 0,除非启用了"indirect-first-instance"
特性。如果未启用"indirect-first-instance"
特性 且firstInstance
不为 0,则drawIndirect()
调用会被视为无操作。调用于:GPURenderCommandsMixin
this.参数:
方法 GPURenderCommandsMixin.drawIndirect(indirectBuffer, indirectOffset) 的参数。 参数 类型 可为 null 可选 描述 indirectBuffer
GPUBuffer
✘ ✘ 包含间接绘制参数的缓冲区。 indirectOffset
GPUSize64
✘ ✘ indirectBuffer 中绘制数据起始的字节偏移。 返回值:
undefined
内容时间线 步骤:
-
在 设备时间线 上对 this.
[[device]]
执行后续步骤。
设备时间线 步骤:-
验证 this 的 编码器状态。如果返回 false,则返回。
-
如有下列任一条件不满足,失效 this 并返回。
-
将 indirectBuffer 以input 用法加入
[[usage scope]]
。 -
this.
[[drawCount]]
增加 1。 -
令 bindingState 为 this 当前状态的快照。
队列时间线 步骤:-
令 vertexCount 为从 indirectBuffer 的 indirectOffset 字节位置读取的无符号 32 位整数。
-
令 instanceCount 为从 indirectBuffer 的 (indirectOffset + 4) 字节读取的无符号 32 位整数。
-
令 firstVertex 为从 indirectBuffer 的 (indirectOffset + 8) 字节读取的无符号 32 位整数。
-
令 firstInstance 为从 indirectBuffer 的 (indirectOffset + 12) 字节读取的无符号 32 位整数。
-
绘制 instanceCount 个实例,从 firstInstance 开始, 每个实例由 vertexCount 个顶点组成,从 firstVertex 开始, 使用 bindingState 和 renderState 中的状态。
-
drawIndexedIndirect(indirectBuffer, indirectOffset)
-
使用从
GPUBuffer
读取的参数绘制带索引的图元。 详细规范见 § 23.2 渲染。缓冲区中编码的 间接 drawIndexed 参数 必须是一个紧凑排列的五个 32 位值(共 20 字节),顺序与
drawIndexed()
方法参数一致。 其中baseVertex
为有符号 32 位整数,其他均为无符号 32 位整数。例如:let drawIndexedIndirectParameters= new Uint32Array( 5 ); let drawIndexedIndirectParametersSigned= new Int32Array( drawIndexedIndirectParameters. buffer); drawIndexedIndirectParameters[ 0 ] = indexCount; drawIndexedIndirectParameters[ 1 ] = instanceCount; drawIndexedIndirectParameters[ 2 ] = firstIndex; // baseVertex 是有符号值。 drawIndexedIndirectParametersSigned[ 3 ] = baseVertex; drawIndexedIndirectParameters[ 4 ] = firstInstance; 对应
firstInstance
的值必须为 0,除非启用了"indirect-first-instance"
特性。如果未启用"indirect-first-instance"
特性 且firstInstance
不为 0,则drawIndexedIndirect()
调用会被视为无操作。调用于:GPURenderCommandsMixin
this.参数:
方法 GPURenderCommandsMixin.drawIndexedIndirect(indirectBuffer, indirectOffset) 的参数。 参数 类型 可为 null 可选 描述 indirectBuffer
GPUBuffer
✘ ✘ 包含间接 drawIndexed 参数的缓冲区。 indirectOffset
GPUSize64
✘ ✘ indirectBuffer 中绘制数据起始的字节偏移。 返回值:
undefined
内容时间线 步骤:
-
在 设备时间线 上对 this.
[[device]]
执行后续步骤。
设备时间线 步骤:-
验证 this 的 编码器状态。如果返回 false,则返回。
-
如有下列任一条件不满足,失效 this 并返回。
-
将 indirectBuffer 以input 用法加入
[[usage scope]]
。 -
this.
[[drawCount]]
增加 1。 -
令 bindingState 为 this 当前状态的快照。
队列时间线 步骤:-
令 indexCount 为从 indirectBuffer 的 indirectOffset 字节位置读取的无符号 32 位整数。
-
令 instanceCount 为从 indirectBuffer 的 (indirectOffset + 4) 字节读取的无符号 32 位整数。
-
令 firstIndex 为从 indirectBuffer 的 (indirectOffset + 8) 字节读取的无符号 32 位整数。
-
令 baseVertex 为从 indirectBuffer 的 (indirectOffset + 12) 字节读取的有符号 32 位整数。
-
令 firstInstance 为从 indirectBuffer 的 (indirectOffset + 16) 字节读取的无符号 32 位整数。
-
绘制 instanceCount 个实例,从 firstInstance 开始, 每个实例由 indexCount 个带索引的顶点组成,从索引 firstIndex(对应顶点 baseVertex)开始, 使用 bindingState 和 renderState 中的状态。
-
GPURenderCommandsMixin
encoder 进行有效绘制(valid to draw),请执行以下设备时间轴步骤:
-
如未满足以下任一条件,则返回
false
:-
校验编码器绑定组(encoder, encoder.
[[pipeline]]
) 必须为true
。 -
令 pipelineDescriptor = encoder.
[[pipeline]]
.[[descriptor]]
。 -
对每个
GPUIndex32
slot,从0
到 pipelineDescriptor.vertex
.buffers
.size:-
如果 pipelineDescriptor.
vertex
.buffers
[slot] 不为null
,则 encoder.[[vertex_buffers]]
必须包含 slot。
-
-
校验
maxBindGroupsPlusVertexBuffers
:-
令 bindGroupSpaceUsed 为 encoder.
[[bind_groups]]
的最大 key + 1。 -
令 vertexBufferSpaceUsed 为 encoder.
[[vertex_buffers]]
的最大 key + 1。 -
bindGroupSpaceUsed + vertexBufferSpaceUsed 必须小于等于 encoder.
[[device]]
.[[limits]]
.maxBindGroupsPlusVertexBuffers
。
-
-
-
否则返回
true
。
GPURenderCommandsMixin
encoder 进行有效索引绘制(valid to draw indexed),请执行以下设备时间轴步骤:
-
如未满足以下任一条件,则返回
false
:-
对 encoder 有效绘制。
-
encoder.
[[index_buffer]]
不为null
。 -
令 topology = encoder.
[[pipeline]]
.[[descriptor]]
.primitive
.topology
。 -
如果 topology 为
"line-strip"
或"triangle-strip"
:-
encoder.
[[index_format]]
必须等于 encoder.[[pipeline]]
.[[descriptor]]
.primitive
.stripIndexFormat
。
-
-
-
否则返回
true
。
17.2.2. 光栅化状态(Rasterization state)
GPURenderPassEncoder
拥有多种方法影响本编码器用于绘制命令的附件的光栅化过程。
-
setViewport(x, y, width, height, minDepth, maxDepth)
-
设置光栅化阶段用于线性映射从归一化设备坐标到视口坐标的视口。
调用者:GPURenderPassEncoder
this。参数:
参数说明:GPURenderPassEncoder.setViewport(x, y, width, height, minDepth, maxDepth) 参数 类型 可为 null 可选 描述 x
float
✘ ✘ 视口的最小 X 像素值。 y
float
✘ ✘ 视口的最小 Y 像素值。 width
float
✘ ✘ 视口宽度(像素)。 height
float
✘ ✘ 视口高度(像素)。 minDepth
float
✘ ✘ 视口的最小深度值。 maxDepth
float
✘ ✘ 视口的最大深度值。 返回:
undefined
内容时间轴步骤:
-
在 this.
[[device]]
的设备时间轴上执行后续步骤。
设备时间轴步骤:-
校验编码器状态。如返回 false,则返回。
-
令 maxViewportRange = this.
limits
.maxTextureDimension2D
×2
。 -
如未满足以下任一条件,使 this 失效并返回:
-
x ≥ -maxViewportRange
-
y ≥ -maxViewportRange
-
0
≤ width ≤ this.limits
.maxTextureDimension2D
-
0
≤ height ≤ this.limits
.maxTextureDimension2D
-
x + width ≤ maxViewportRange −
1
-
y + height ≤ maxViewportRange −
1
-
0.0
≤ minDepth ≤1.0
-
0.0
≤ maxDepth ≤1.0
-
minDepth ≤ maxDepth
-
队列时间轴步骤:-
将 x、y、width 和 height 四者以不低于整数精度统一取整。
-
设置 renderState.
[[viewport]]
为范围 x、y、width、height、minDepth、maxDepth。
-
-
setScissorRect(x, y, width, height)
-
设置光栅化阶段使用的裁剪矩形。经过视口坐标变换后,所有落在裁剪矩形外的片元将被丢弃。
调用者:GPURenderPassEncoder
this。参数:
参数说明:GPURenderPassEncoder.setScissorRect(x, y, width, height) 参数 类型 可为 null 可选 描述 x
GPUIntegerCoordinate
✘ ✘ 裁剪矩形的最小 X 像素值。 y
GPUIntegerCoordinate
✘ ✘ 裁剪矩形的最小 Y 像素值。 width
GPUIntegerCoordinate
✘ ✘ 裁剪矩形的宽度(像素)。 height
GPUIntegerCoordinate
✘ ✘ 裁剪矩形的高度(像素)。 返回:
undefined
内容时间轴步骤:
-
在 this.
[[device]]
的设备时间轴上执行后续步骤。
设备时间轴步骤:-
校验编码器状态。如返回 false,则返回。
-
如未满足以下任一条件,使 this 失效并返回:
-
x+width ≤ this.
[[attachment_size]]
.width。 -
y+height ≤ this.
[[attachment_size]]
.height。
-
队列时间轴步骤:-
设置 renderState.
[[scissorRect]]
为范围 x、y、width、height。
-
-
setBlendConstant(color)
-
设置用于
"constant"
和"one-minus-constant"
GPUBlendFactor
的常数混合颜色和 alpha 值。调用者:GPURenderPassEncoder
this。参数:
参数说明:GPURenderPassEncoder.setBlendConstant(color) 参数 类型 可为 null 可选 描述 color
GPUColor
✘ ✘ 用于混合的颜色。 返回:
undefined
内容时间轴步骤:
-
? 校验 GPUColor 结构(color)。
-
在 this.
[[device]]
的设备时间轴上执行后续步骤。
队列时间轴步骤:-
设置 renderState.
[[blendConstant]]
为 color。
-
-
setStencilReference(reference)
-
设置模板测试中
"replace"
GPUStencilOperation
时使用的[[stencilReference]]
值。调用者:GPURenderPassEncoder
this。参数:
参数说明:GPURenderPassEncoder.setStencilReference(reference) 参数 类型 可为 null 可选 描述 reference
GPUStencilValue
✘ ✘ 新的模板参考值。 返回:
undefined
内容时间轴步骤:
-
在 this.
[[device]]
的设备时间轴上执行后续步骤。
队列时间轴步骤:-
设置 renderState.
[[stencilReference]]
为 reference。
-
17.2.3. 查询(Queries)
-
beginOcclusionQuery(queryIndex)
-
调用者:
GPURenderPassEncoder
this。参数:
参数说明:GPURenderPassEncoder.beginOcclusionQuery(queryIndex) 参数 类型 可为 null 可选 描述 queryIndex
GPUSize32
✘ ✘ 在查询集内的查询索引。 返回:
undefined
内容时间轴步骤:
-
在 this.
[[device]]
的设备时间轴上执行后续步骤。
设备时间轴步骤:-
校验编码器状态。如返回 false,则返回。
-
如未满足以下任一条件,使 this 失效并返回:
-
this.
[[occlusion_query_set]]
不为null
。 -
queryIndex < this.
[[occlusion_query_set]]
.count
。 -
本次通道内相同 queryIndex 的查询尚未被写入。
-
this.
[[occlusion_query_active]]
为false
。
-
-
设置 this.
[[occlusion_query_active]]
为true
。
队列时间轴步骤:-
设置 renderState.
[[occlusionQueryIndex]]
为 queryIndex。
-
-
endOcclusionQuery()
-
设备时间轴步骤:
-
校验编码器状态。如返回 false,则返回。
-
如未满足以下任一条件,使 this 失效并返回:
-
this.
[[occlusion_query_active]]
为true
。
-
-
设置 this.
[[occlusion_query_active]]
为false
。
队列时间轴步骤:-
如自对应
beginOcclusionQuery()
执行以来有任意片元样本通过所有每片元测试,则 passingFragments 非零,否则为零。注意: 如果没有发生任何 draw 调用,passingFragments 为零。
-
将 passingFragments 写入 this.
[[occlusion_query_set]]
的 renderState.[[occlusionQueryIndex]]
处。
-
17.2.4. 渲染包(Bundles)
-
executeBundles(bundles)
-
在本渲染通道中执行此前录制到给定
GPURenderBundle
列表中的命令。当执行
GPURenderBundle
时,不会继承渲染通道的管线、绑定组、顶点和索引缓冲区。每次GPURenderBundle
执行完毕后,渲染通道的管线、绑定组和顶点/索引缓冲区状态都会被清除(重置为初始空值)。注意: 状态是被清除,而不是恢复到之前的状态。即便执行 0 个
GPURenderBundles
,也会发生清除。调用者:GPURenderPassEncoder
this。参数:
参数说明:GPURenderPassEncoder.executeBundles(bundles) 参数 类型 可为 null 可选 描述 bundles
sequence<GPURenderBundle>
✘ ✘ 要执行的渲染包列表。 返回:
undefined
内容时间轴步骤:
-
在 this.
[[device]]
的设备时间轴上执行后续步骤。
设备时间轴步骤:-
校验编码器状态。如返回 false,则返回。
-
如未满足以下任一条件,使 this 失效并返回:
-
对于 bundles 中每一个 bundle:
-
bundle 可 与 this 有效共用。
-
this.
[[layout]]
等于 bundle.[[layout]]
。 -
如果 this.
[[depthReadOnly]]
为 true,则 bundle.[[depthReadOnly]]
也必须为 true。 -
如果 this.
[[stencilReadOnly]]
为 true,则 bundle.[[stencilReadOnly]]
也必须为 true。
-
-
-
对于 bundles 中每一个 bundle:
-
将 this.
[[drawCount]]
增加 bundle.[[drawCount]]
。 -
合并 bundle.
[[usage scope]]
到 this.[[usage scope]]
。 -
将渲染命令入队到 this,该命令将在队列时间轴以 renderState 执行如下步骤:
队列时间轴步骤:-
以 renderState 执行 bundle.
[[command_list]]
中的每个命令。注意: 执行渲染包时,renderState 不能被改变。绑定状态在包编码时已捕获,执行包时不再使用。
-
-
-
重置渲染通道绑定状态(Reset the render pass binding state)
-
GPURenderPassEncoder
encoder 执行以下设备时间轴步骤:
-
清空 encoder.
[[bind_groups]]
。 -
设置 encoder.
[[pipeline]]
为null
。 -
设置 encoder.
[[index_buffer]]
为null
。 -
清空 encoder.
[[vertex_buffers]]
。
18. 渲染包(Bundles)
渲染包(bundle)是一种部分的、受限的通道,可以被编码一次、随后多次作为后续通道编码器的一部分执行,而不像典型的命令缓冲区那样使用后即失效。对于反复发出且内容不变的命令,这可以减少编码和提交的开销。
18.1.
GPURenderBundle
[Exposed =(Window ,Worker ),SecureContext ]interface GPURenderBundle { };GPURenderBundle includes GPUObjectBase ;
-
[[command_list]]
, 类型为 list<GPU command> -
一个 列表,包含在执行
GPURenderBundle
时需提交给GPURenderPassEncoder
的 GPU 命令。 -
[[usage scope]]
, 类型为 usage scope,初始为空 -
该渲染包的 usage scope,用于后续合并到
GPURenderPassEncoder
的[[usage scope]]
,见executeBundles()
。 -
[[layout]]
, 类型为GPURenderPassLayout
-
渲染包的布局。
-
[[depthReadOnly]]
, 类型为boolean
-
若为
true
,表示执行该渲染包时不会修改深度分量。 -
[[stencilReadOnly]]
, 类型为boolean
-
若为
true
,表示执行该渲染包时不会修改模板分量。 -
[[drawCount]]
, 类型为GPUSize64
-
该
GPURenderBundle
内的绘制命令数。
18.1.1. 渲染包创建(Render Bundle Creation)
dictionary :
GPURenderBundleDescriptor GPUObjectDescriptorBase { };
[Exposed =(Window ,Worker ),SecureContext ]interface {
GPURenderBundleEncoder GPURenderBundle finish (optional GPURenderBundleDescriptor descriptor = {}); };GPURenderBundleEncoder includes GPUObjectBase ;GPURenderBundleEncoder includes GPUCommandsMixin ;GPURenderBundleEncoder includes GPUDebugCommandsMixin ;GPURenderBundleEncoder includes GPUBindingCommandsMixin ;GPURenderBundleEncoder includes GPURenderCommandsMixin ;
-
createRenderBundleEncoder(descriptor)
-
创建一个
GPURenderBundleEncoder
。调用者:GPUDevice
this。参数:
参数说明:GPUDevice.createRenderBundleEncoder(descriptor) 参数 类型 可为 null 可选 描述 descriptor
GPURenderBundleEncoderDescriptor
✘ ✘ 要创建的 GPURenderBundleEncoder
的描述信息。内容时间轴步骤:
-
? 校验纹理格式所需特性,对 descriptor.
colorFormats
的每个非null
元素,使用 this.[[device]]
。 -
如 descriptor.
depthStencilFormat
被提供:-
? 校验纹理格式所需特性,对 descriptor.
depthStencilFormat
,使用 this.[[device]]
。
-
-
令 e = ! 创建新的 WebGPU 对象(this,
GPURenderBundleEncoder
, descriptor)。 -
在 this 的设备时间轴上执行 初始化步骤。
-
返回 e。
设备时间轴 初始化步骤:-
-
this 不得 丢失。
-
descriptor.
colorFormats
.size ≤ this.[[limits]]
.maxColorAttachments
。 -
对 descriptor.
colorFormats
中每个非null
的 colorFormat:-
colorFormat 必须是可作为颜色渲染的格式。
-
-
计算颜色附件每采样字节数(descriptor.
colorFormats
) ≤ this.[[limits]]
.maxColorAttachmentBytesPerSample
。 -
如 descriptor.
depthStencilFormat
被提供:-
descriptor.
depthStencilFormat
必须是深度或模板格式。
-
-
必须至少存在一个附件,满足下列之一:
-
descriptor.
colorFormats
中有非null
值,或 -
descriptor.
depthStencilFormat
存在。
-
-
-
设置 e.
[[layout]]
为 descriptor(包含的GPURenderPassLayout
接口)的副本。 -
设置 e.
[[depthReadOnly]]
为 descriptor.depthReadOnly
。 -
设置 e.
[[stencilReadOnly]]
为 descriptor.stencilReadOnly
。 -
设置 e.
[[drawCount]]
为 0。
-
18.1.2. 编码(Encoding)
dictionary :
GPURenderBundleEncoderDescriptor GPURenderPassLayout {boolean depthReadOnly =false ;boolean stencilReadOnly =false ; };
-
depthReadOnly
, 类型为 boolean,默认值为false
-
为
true
时,表示渲染包不会修改其被执行所在任意渲染通道的GPURenderPassDepthStencilAttachment
的深度分量。参见 只读深度-模板。
-
stencilReadOnly
, 类型为 boolean,默认值为false
-
为
true
时,表示渲染包不会修改其被执行所在任意渲染通道的GPURenderPassDepthStencilAttachment
的模板分量。参见 只读深度-模板。
18.1.3. 渲染包终结(Finalization)
-
finish(descriptor)
-
完成渲染包命令序列的录制。
调用者:GPURenderBundleEncoder
this。参数:
参数说明:GPURenderBundleEncoder.finish(descriptor) 参数 类型 可为 null 可选 描述 descriptor
GPURenderBundleDescriptor
✘ ✔ 返回:
GPURenderBundle
内容时间轴步骤:
-
创建新
GPURenderBundle
,记为 renderBundle。 -
在 this.
[[device]]
的设备时间轴上执行 finish steps。 -
返回 renderBundle。
设备时间轴 finish steps:-
若满足以下全部要求,则 validationSucceeded 为
true
,否则为false
。-
this 必须 有效。
-
this.
[[usage scope]]
必须通过 usage scope 校验。 -
this.
[[debug_group_stack]]
必须为空。
-
-
若 validationSucceeded 为
false
:-
返回 失效的
GPURenderBundle
。
-
设置 renderBundle.
[[command_list]]
为 this.[[commands]]
。 -
设置 renderBundle.
[[usage scope]]
为 this.[[usage scope]]
。 -
设置 renderBundle.
[[drawCount]]
为 this.[[drawCount]]
。
-
19. 队列
19.1. GPUQueueDescriptor
GPUQueueDescriptor
描述了一个队列请求。
dictionary GPUQueueDescriptor :GPUObjectDescriptorBase { };
19.2. GPUQueue
[Exposed =(Window ,Worker ),SecureContext ]interface GPUQueue {undefined submit (sequence <GPUCommandBuffer >commandBuffers );Promise <undefined >onSubmittedWorkDone ();undefined writeBuffer (GPUBuffer buffer ,GPUSize64 bufferOffset ,AllowSharedBufferSource data ,optional GPUSize64 dataOffset = 0,optional GPUSize64 size );undefined writeTexture (GPUTexelCopyTextureInfo destination ,AllowSharedBufferSource data ,GPUTexelCopyBufferLayout dataLayout ,GPUExtent3D size );undefined copyExternalImageToTexture (GPUCopyExternalImageSourceInfo source ,GPUCopyExternalImageDestInfo destination ,GPUExtent3D copySize ); };GPUQueue includes GPUObjectBase ;
GPUQueue
拥有以下方法:
writeBuffer(buffer, bufferOffset, data, dataOffset, size)
-
对指定的数据发起写操作,将其写入到
GPUBuffer
中。调用对象:GPUQueue
this.参数说明:
方法 GPUQueue.writeBuffer(buffer, bufferOffset, data, dataOffset, size) 的参数。 参数 类型 可为 null 可选 说明 buffer
GPUBuffer
✘ ✘ 要写入的缓冲区。 bufferOffset
GPUSize64
✘ ✘ 在 buffer 中开始写入的字节偏移。 data
AllowSharedBufferSource
✘ ✘ 要写入 buffer 的数据。 dataOffset
GPUSize64
✘ ✔ 在 data 中开始写入的偏移量。如果 data 是 TypedArray
,则以元素为单位,否则以字节为单位。size
GPUSize64
✘ ✔ 要从 data 写入到 buffer 的内容大小。如果 data 是 TypedArray
,则以元素为单位,否则以字节为单位。返回值:
undefined
内容时间线 步骤:
-
如果 data 是
ArrayBuffer
或DataView
, 则元素类型为“byte”。 否则,data 是 TypedArray,元素类型为 TypedArray 的类型。 -
令 dataSize 为 data 的大小(以元素计)。
-
如果 size 缺失, 则 contentsSize = dataSize − dataOffset; 否则,contentsSize = size。
-
如果下列任一条件不满足, 抛出
OperationError
并返回。-
contentsSize ≥ 0。
-
dataOffset + contentsSize ≤ dataSize。
-
contentsSize(以字节计)是 4 字节的倍数。
-
-
令 dataContents 为 数据源 data 所持有字节的副本。
-
令 contents 为 dataContents 从 dataOffset 元素开始的 contentsSize 个元素。
-
在 设备时间线 上执行后续步骤。
设备时间线 步骤:队列时间线 步骤:-
将 contents 从 bufferOffset 起写入 buffer。
-
writeTexture(destination, data, dataLayout, size)
-
对指定的数据发起写操作,将其写入到
GPUTexture
中。调用对象:GPUQueue
this.参数说明:
方法 GPUQueue.writeTexture(destination, data, dataLayout, size) 的参数。 参数 类型 可为 null 可选 说明 destination
GPUTexelCopyTextureInfo
✘ ✘ 要写入的纹理子资源及其起始位置。 data
AllowSharedBufferSource
✘ ✘ 要写入 destination 的数据。 dataLayout
GPUTexelCopyBufferLayout
✘ ✘ data 中内容的布局。 size
GPUExtent3D
✘ ✘ 要从 data 写入到 destination 的内容范围。 返回值:
undefined
内容时间线 步骤:
-
? 校验 GPUOrigin3D 形状(destination.
origin
)。 -
? 校验 GPUExtent3D 形状(size)。
-
令 dataBytes 为 数据源 data 所持有字节的副本。
注意:本步骤描述为将所有 data 复制到设备时间线, 但实际上 data 可能远大于实际所需。实现时应当优化,仅复制必要的字节。
-
在 设备时间线 上执行后续步骤。
设备时间线 步骤:-
令 aligned =
false
。 -
令 dataLength = dataBytes.长度。
-
如果下列任一条件不满足, 生成校验错误 并返回。
-
destination.
texture
.[[destroyed]]
为false
。 -
有效的纹理缓冲区拷贝(destination, dataLayout, dataLength, size,
COPY_DST
, aligned) 返回true
。
注意:与
GPUCommandEncoder
.copyBufferToTexture()
不同,本方法对 dataLayout.bytesPerRow
或 dataLayout.offset
没有对齐要求。 -
-
在 队列时间线 上执行后续步骤。
队列时间线 步骤:-
令 dstOrigin 为 destination.
origin
; -
令 dstBlockOriginX = (dstOrigin.x ÷ blockWidth)。
-
令 dstBlockOriginY = (dstOrigin.y ÷ blockHeight)。
-
令 blockColumns = (copySize.width ÷ blockWidth)。
-
令 blockRows = (copySize.height ÷ blockHeight)。
-
断言 dstBlockOriginX、 dstBlockOriginY、blockColumns 和 blockRows 都为整数。
-
对每个 z 属于区间 [0, copySize.depthOrArrayLayers − 1]:
-
对每个 y 属于区间 [0, blockRows − 1]:
-
copyExternalImageToTexture(source, destination, copySize)
-
对平台图片/canvas 的内容执行拷贝操作,将其复制到目标纹理中。
该操作会按照
GPUCopyExternalImageDestInfo
的参数,将数据执行颜色编码,转换为目标编码。拷贝到
-srgb
纹理中时,其结果纹理的字节内容与对应的非-srgb
格式拷贝相同,但解码值会不同。 因此,拷贝完成后,采样目标纹理的结果会因格式是否为-srgb
而不同,其他条件不变。注意:当从"webgl"
/"webgl2"
上下文的 canvas 拷贝时, WebGL 绘制缓冲区 在帧显示周期的某些时间点(如图像被送到合成器显示后)可能不存在。 为避免此问题,可以:-
在与 WebGL 渲染操作相同的 task 内调用
copyExternalImageToTexture()
, 以确保拷贝发生在 WebGL canvas 显示前。 -
如果无法做到,可在
WebGLContextAttributes
中设置preserveDrawingBuffer
选项为true
,这样帧内容在显示后缓冲区中仍保留一份副本。 注意,这样会有额外的性能开销。
调用对象:GPUQueue
this.参数说明:
方法 GPUQueue.copyExternalImageToTexture(source, destination, copySize) 的参数。 参数 类型 可为 null 可选 说明 source
GPUCopyExternalImageSourceInfo
✘ ✘ 要拷贝的源图像及其起始位置。 destination
GPUCopyExternalImageDestInfo
✘ ✘ 要写入的纹理子资源及其起始位置及编码元数据。 copySize
GPUExtent3D
✘ ✘ 要从 source 写入到 destination 的内容范围。 返回值:
undefined
内容时间线 步骤:
-
? 校验 GPUOrigin2D 形状(source.
origin
)。 -
? 校验 GPUOrigin3D 形状(destination.
origin
)。 -
? 校验 GPUExtent3D 形状(copySize)。
-
令 sourceImage 为 source.
source
-
如果 sourceImage 不是同源, 抛出
SecurityError
并返回。 -
如果下列任一条件不满足,抛出
OperationError
并返回。-
copySize.depthOrArrayLayers 必须 ≤ 1。
-
在 设备时间线 上执行后续步骤。
设备时间线 步骤:-
令 texture 为 destination.
texture
。 -
如果下列任一条件不满足,生成校验错误 并返回。
-
usability 必须为
good
。 -
texture.
[[destroyed]]
必须为false
。 -
texture 必须可与 this 一起使用。
-
校验 GPUTexelCopyTextureInfo(destination, copySize) 必须返回
true
。 -
texture.
usage
必须同时包含RENDER_ATTACHMENT
和COPY_DST
。 -
texture.
sampleCount
必须为 1。 -
texture.
format
必须是以下格式之一(均支持RENDER_ATTACHMENT
用法):
-
-
如果 copySize.depthOrArrayLayers > 0,则在 队列时间线 上执行后续步骤。
-
submit(commandBuffers)
-
安排 GPU 在此队列上执行命令缓冲区。
已提交的命令缓冲区不可再次使用。
调用对象:GPUQueue
this.参数说明:
方法 GPUQueue.submit(commandBuffers) 的参数。 参数 类型 可为 null 可选 说明 commandBuffers
sequence<GPUCommandBuffer>
✘ ✘ 返回值:
undefined
内容时间线 步骤:
-
在 设备时间线 上执行后续步骤:
设备时间线 步骤:-
如果下列任一条件不满足,生成校验错误, 使每个
GPUCommandBuffer
在 commandBuffers 中失效并返回。-
commandBuffers 中的每个
GPUCommandBuffer
必须可与 this 一起使用。 -
commandBuffers 中的每个
GPUCommandBuffer
必须唯一。 -
若 commandBuffers 中任一命令用到了下列类型的资源:
GPUBuffer
b-
b.
[[internal state]]
必须为 "available"。 GPUTexture
t-
t.
[[destroyed]]
必须为false
。 GPUExternalTexture
et-
et.
[[expired]]
必须为false
。 GPUQuerySet
qs-
qs.
[[destroyed]]
必须为false
。
注意: 对于遮挡查询,
occlusionQuerySet
仅在beginRenderPass()
被beginOcclusionQuery()
使用时才被视为“已使用”。
-
-
对 commandBuffers 中每个 commandBuffer:
-
使 commandBuffer 失效。
-
-
在 队列时间线 上执行后续步骤:
队列时间线 步骤:-
对 commandBuffers 中每个 commandBuffer:
-
执行 commandBuffer.
[[command_list]]
中的每条命令。
-
-
onSubmittedWorkDone()
-
返回一个
Promise
,当队列处理完目前为止提交的所有工作后,该 Promise 会被 resolve。该
Promise
resolve 意味着在此之前调用过的mapAsync()
并且最后只在该队列上独占使用过的GPUBuffer
的操作也已完成。
20. 查询(Queries)
20.1. GPUQuerySet
[Exposed =(Window ,Worker ),SecureContext ]interface GPUQuerySet {undefined destroy ();readonly attribute GPUQueryType type ;readonly attribute GPUSize32Out count ; };GPUQuerySet includes GPUObjectBase ;
GPUQuerySet
拥有以下不可变属性:
type
, 类型为 GPUQueryType,只读-
此
GPUQuerySet
管理的查询的类型。 count
, 类型为 GPUSize32Out,只读-
此
GPUQuerySet
管理的查询数量。
GPUQuerySet
拥有以下设备时间线属性:
[[destroyed]]
, 类型为boolean
, 初始值为false
-
如果查询集被销毁,则不能再用于任何操作,其底层内存可被释放。
20.1.1. 查询集创建(QuerySet Creation)
GPUQuerySetDescriptor
指定用于创建 GPUQuerySet
时的选项。
dictionary :
GPUQuerySetDescriptor GPUObjectDescriptorBase {required GPUQueryType type ;required GPUSize32 count ; };
type
, 类型为 GPUQueryType-
此
GPUQuerySet
管理的查询类型。 count
, 类型为 GPUSize32-
此
GPUQuerySet
管理的查询数量。
createQuerySet(descriptor)
-
创建一个
GPUQuerySet
。调用对象:GPUDevice
this.参数说明:
方法 GPUDevice.createQuerySet(descriptor) 的参数。 参数 类型 可为 null 可选 说明 descriptor
GPUQuerySetDescriptor
✘ ✘ 要创建的 GPUQuerySet
的描述信息。返回值:
GPUQuerySet
内容时间线 步骤:
-
如果 descriptor.
type
为"timestamp"
, 但"timestamp-query"
没有为 this 启用:-
抛出
TypeError
。
-
-
令 q 为 ! 创建新的 WebGPU 对象(this,
GPUQuerySet
, descriptor). -
在 设备时间线 上执行 初始化步骤。
-
返回 q。
-
GPUQuerySet
。
const querySet= gpuDevice. createQuerySet({ type: 'occlusion' , count: 32 });
20.1.2. 查询集销毁(Query Set Destruction)
应用在不再需要 GPUQuerySet
时,可以通过调用 destroy()
主动失去对其的访问权,无需等到垃圾回收。
GPUQuerySet
拥有以下方法:
destroy()
-
销毁该
GPUQuerySet
。设备时间线 步骤:-
将 this.
[[destroyed]]
设为true
。
-
20.2. 查询类型(QueryType)
enum {
GPUQueryType ,
"occlusion" , };
"timestamp"
20.3. 遮挡查询(Occlusion Query)
遮挡查询仅可在渲染通道(render pass)中使用,用于统计一组绘制命令中所有片元通过所有片元测试(包括剪裁、采样掩码、透明度覆盖、模板和深度测试)后,实际输出合并阶段的片元采样数量。查询结果为非零时,表示至少有一个采样通过测试并到达渲染管线的输出合并阶段;为 0 时,表示没有采样通过测试。
在开始一个渲染通道时,必须设置 GPURenderPassDescriptor
.occlusionQuerySet
,以便在该通道内使用遮挡查询。遮挡查询需成对调用 beginOcclusionQuery()
和
endOcclusionQuery()
,且不可嵌套,并通过 GPUBuffer
由 GPUCommandEncoder
.resolveQuerySet()
解析为64 位无符号整数。
20.4. 时间戳查询(Timestamp Query)
时间戳查询允许应用通过以下方式将时间戳写入 GPUQuerySet
:
然后通过 GPUCommandEncoder
.resolveQuerySet()
将时间戳值(以纳秒为单位,64 位无符号整数)解析到 GPUBuffer
。
时间戳值是实现定义的,并不保证单调递增。物理设备可能偶尔重置时间戳计数器,这会导致时间戳出现非预期的数值(如本应递增却出现负间隔)。这种情况应较为罕见,可以安全忽略。应用不应因意外的时间戳值而导致程序失败。
时间戳查询由高精度计时器实现(参见 § 2.1.7.2 设备/队列时间线计时)。 为降低安全性和隐私风险,其精度必须被降低:
-
返回对 fineTimestamp 调用 coarsen time 的结果, 其中
crossOriginIsolatedCapability
设为false
。
注意:由于跨域隔离通常不适用于
设备时间线
或 队列时间线,
crossOriginIsolatedCapability
永远不会设为 true
。
参数:
-
GPUDevice
device -
(
timestampWritesGPUComputePassTimestampWrites
orGPURenderPassTimestampWrites
)
设备时间线 步骤:
-
若满足以下要求则返回
true
,否则返回false
:-
"timestamp-query"
必须为 device 启用。 -
timestampWrites.
querySet
必须 可与 device 一起使用。 -
timestampWrites.
querySet
.type
必须为"timestamp"
。 -
在 timestampWrites 的写入索引成员 (
beginningOfPassWriteIndex
、endOfPassWriteIndex
)中:
-
21. 画布渲染(Canvas Rendering)
21.1. HTMLCanvasElement.getContext()
GPUCanvasContext
对象是通过
getContext()
方法(传入字符串字面量 'webgpu'
作为 contextType
参数)在 HTMLCanvasElement
实例上创建的。
HTMLCanvasElement
获取 GPUCanvasContext
:
const canvas= document. createElement( 'canvas' ); const context= canvas. getContext( 'webgpu' );
与 WebGL 或 2D 上下文创建不同,HTMLCanvasElement.getContext()
或
OffscreenCanvas.getContext()
的第二个参数(上下文创建属性字典 options
)会被忽略。
请改用 GPUCanvasContext.configure()
,
该方法允许在不替换画布的情况下改变画布配置。
HTMLCanvasElement
或 OffscreenCanvas
canvas),请执行以下
内容时间线步骤:
-
令 context 为一个新的
GPUCanvasContext
。 -
设置 context.
canvas
为 canvas。 -
替换 context 的绘制缓冲区。
-
返回 context。
注意: 当调用 getContext()
获取 WebGPU
画布上下文时,如果传入了被忽略的 options
参数,用户代理应考虑向开发者发出可见警告。
21.2. GPUCanvasContext
[Exposed =(Window ,Worker ),SecureContext ]interface {
GPUCanvasContext readonly attribute (HTMLCanvasElement or OffscreenCanvas )canvas ;undefined configure (GPUCanvasConfiguration configuration );undefined unconfigure ();GPUCanvasConfiguration ?getConfiguration ();GPUTexture getCurrentTexture (); };
GPUCanvasContext
拥有以下内容时间线属性:
canvas
, 类型为(HTMLCanvasElement 或 OffscreenCanvas)
,只读-
此上下文创建自的画布对象。
[[configuration]]
,类型为GPUCanvasConfiguration
? ,初始值为null
-
此上下文当前配置所用的参数。
如果上下文尚未配置或已经调用
unconfigure()
,则为null
。 [[textureDescriptor]]
,类型为GPUTextureDescriptor
? ,初始值为null
-
当前配置的纹理描述符,由
[[configuration]]
和画布生成。若上下文尚未配置或已
unconfigure()
,则为null
。 [[drawingBuffer]]
,一个图片对象,初始为 与画布同尺寸的透明黑色图像-
绘制缓冲区是画布的工作副本图像数据。 通过
[[currentTexture]]
(由getCurrentTexture()
返回)可获得可写视图。绘制缓冲区用于获取上下文图像内容副本 (如画布显示或读取时)。即使
[[configuration]]
.alphaMode
是"opaque"
,绘制缓冲区仍可能为透明。alphaMode
仅影响“获取上下文图像内容副本”算法的结果。绘制缓冲区的生命周期超出
[[currentTexture]]
,即使画布已显示,之前渲染的内容也仍然保留。只有在替换绘制缓冲区时才会清除。每当读取绘制缓冲区时,必须确保所有之前提交的写入操作(例如队列提交)都已通过
[[currentTexture]]
完成。 [[currentTexture]]
,类型为GPUTexture
? ,初始为null
-
当前帧要绘制的
GPUTexture
。 它提供了底层[[drawingBuffer]]
的可写视图。getCurrentTexture()
若该槽为null
则填充后返回。在可见画布的稳定状态下,通过 currentTexture 对绘制缓冲区的更改在更新 WebGPU 画布渲染时被显示。 此时或之前,纹理会被销毁,
[[currentTexture]]
被置为null
,下次调用getCurrentTexture()
时会重新创建。销毁
currentTexture 不影响绘制缓冲区内容,只是提前终止了对该缓冲区的写访问。 在同一帧内,getCurrentTexture()
依然返回相同的已销毁纹理。过期当前纹理会把 currentTexture 置为
null
。 它由configure()
、 画布尺寸变更、显示、transferToImageBitmap()
等调用。 [[lastPresentedImage]]
,类型为(readonly image)?
,初始为null
-
最近一次在“更新 WebGPU 画布渲染”中展示的图片。 如果设备丢失或被销毁,该图片 可以 作为“获取上下文图像内容副本”的回退,以防画布变空白。
注意: 只有实现了回退机制的实现才需要有该属性,这不是强制的。
GPUCanvasContext
拥有以下方法:
configure(configuration)
-
为该画布上下文配置参数。 这会把绘制缓冲区清为透明黑(见 替换绘制缓冲区)。
调用对象:GPUCanvasContext
this.参数说明:
方法 GPUCanvasContext.configure(configuration) 的参数。 参数 类型 可为 null 可选 说明 configuration
GPUCanvasConfiguration
✘ ✘ 上下文的期望配置。 返回值: undefined
内容时间线步骤:
-
令 device = configuration.
device
。 -
? 校验纹理格式所需特性 (configuration.
format
, device.[[device]]
)。 -
? 校验纹理格式所需特性(对 configuration.
viewFormats
的每一个元素, device.[[device]]
)。 -
令 descriptor = 为画布和配置生成 GPUTextureDescriptor(this.
canvas
, configuration)。 -
设置 this.
[[configuration]]
为 configuration。注意:本规范要求通过toneMapping
选项支持 HDR。 如果用户代理仅支持toneMapping: "standard"
, 那么toneMapping
属性不应存在于GPUCanvasConfiguration
, 因此不会出现在getConfiguration()
返回值,也不会被configure()
访问。 这允许网站检测功能支持。 -
设置 this.
[[textureDescriptor]]
为 descriptor。 -
在 设备时间线 上执行后续步骤。
设备时间线步骤:-
若下列任一条件不满足,生成校验错误并返回。
-
校验 GPUTextureDescriptor(device, descriptor) 必须为 true。
注意: 该早期校验在下次
configure()
调用前有效,但对size
校验例外,画布尺寸变更时需重新校验。 -
-
unconfigure()
-
移除上下文配置,并销毁所有在配置期间创建的纹理。
调用对象:GPUCanvasContext
this.返回值: undefined
内容时间线步骤:
-
将 this.
[[configuration]]
置为null
。 -
将 this.
[[textureDescriptor]]
置为null
。
-
getConfiguration()
-
返回上下文配置。
调用对象:GPUCanvasContext
this.返回值:
GPUCanvasConfiguration
或null
内容时间线步骤:
-
令 configuration 为 this.
[[configuration]]
的副本。 -
返回 configuration。
注意:在getConfiguration()
显示toneMapping
已实现且 dynamic-range 媒体查询指示支持 HDR 时,WebGPU 画布应使用完整 HDR 范围渲染内容,而不是将值钳制在 HDR 显示的 SDR 范围内。 -
getCurrentTexture()
-
获取即将由
GPUCanvasContext
合成到文档的GPUTexture
。注意:应用应在绘制到画布纹理的同一个任务中调用getCurrentTexture()
。否则,该纹理可能会在应用渲染完成前被下面这些步骤销毁。过期任务(定义见下)是可选实现的。即使实现了,任务源优先级不是规范定义的,可能最快在下一个任务发生,也可能等到所有任务源为空才发生(见 automatic expiry task source)。 只有在可见画布被显示时(更新 WebGPU 画布渲染)及其他 "过期当前纹理" 调用方才保证过期。
调用对象:GPUCanvasContext
this.返回值:
GPUTexture
内容时间线步骤:
-
如果 this.
[[configuration]]
为null
, 抛出InvalidStateError
并返回。 -
断言 this.
[[textureDescriptor]]
不为null
。 -
令 device 为 this.
[[configuration]]
.device
。 -
如果 this.
[[currentTexture]]
为null
:-
设置 this.
[[currentTexture]]
为调用 device.createTexture()
并传入 this.[[textureDescriptor]]
的结果,但GPUTexture
底层存储指向 this.[[drawingBuffer]]
。注意: 如果纹理无法创建(如校验失败或内存不足),则会抛出错误并返回无效化的
GPUTexture
。 这里的部分校验与configure()
中的校验重复,实现不得跳过这些校验。
-
可选,排队自动过期任务,参数为 device device 和下列步骤:
-
注意: 如果在 更新 WebGPU 画布渲染 时已发生则无影响。
-
-
返回 this.
[[currentTexture]]
。
注意: 每次调用
getCurrentTexture()
都会返回同一个GPUTexture
对象,直到执行“过期当前纹理”,即使该纹理被销毁、校验失败或分配失败也如此。 -
参数:
-
context:
GPUCanvasContext
返回: 图像内容
内容时间线 步骤:
-
令 snapshot 为一个与 context.
canvas
尺寸相同的透明黑图片。 -
令 configuration 为 context.
[[configuration]]
。 -
如果 configuration 为
null
:-
返回 snapshot。
注意: 当上下文尚未配置或已被
unconfigure()
时,configuration 会是null
。这与画布没有上下文时的行为一致。 -
-
确保所有已提交的工作项(如队列提交)都已通过 context.
[[currentTexture]]
完成对图像的写入。 -
如果 configuration.
device
被认为有效:-
将 snapshot 设为 context.
[[drawingBuffer]]
的副本。
否则,如果 context.
[[lastPresentedImage]]
不为null
:-
可选,将 snapshot 设为 context.
[[lastPresentedImage]]
的副本。注意: 这是可选的,因为
[[lastPresentedImage]]
可能已不存在,取决于设备丢失的原因。即使实现仍可访问该图像,也可以选择跳过此步骤。
-
-
令 alphaMode 为 configuration.
alphaMode
。 -
- 如果 alphaMode 为
"opaque"
: -
-
将 snapshot 的 alpha 通道清为 1.0。
-
将 snapshot 标记为 opaque。
注意: 如果
[[currentTexture]]
(若有)已被销毁(如在“过期当前纹理”时),alpha 通道是不可观察的,实现可以就地清除 alpha。 -
- 否则:
-
将 snapshot 按 alphaMode 标记。
- 如果 alphaMode 为
-
将 snapshot 按 configuration 的
colorSpace
和toneMapping
标记。 -
返回 snapshot。
GPUCanvasContext
context 执行如下 内容时间线 步骤:
-
令 configuration 为 context.
[[configuration]]
。 -
将 context.
[[drawingBuffer]]
设为与 context.canvas
尺寸相同的透明黑图片。-
如果 configuration 为 null,绘制缓冲区用颜色空间
"srgb"
标记。在此情况下,缓冲区会保持空白直到配置上下文。 -
否则,绘制缓冲区拥有指定的 configuration.
format
,并用指定的 configuration.colorSpace
和 configuration.toneMapping
标记。
注意: configuration.
alphaMode
在“获取上下文图像内容副本”前会被忽略。注意:新替换的绘制缓冲区图像表现为被清为透明黑,但如同"discard"
一样,实现可以按需惰性清除,只有在必要时才清除。注意: 如果绘制缓冲区已清空且配置正确,则通常这不会有实际效果。
-
GPUCanvasContext
context 执行如下 内容时间线 步骤:
-
如果 context.
[[currentTexture]]
不为null
:-
调用 context.
[[currentTexture]]
.destroy()
(不销毁 context.[[drawingBuffer]]
), 以终止对图像的写入访问。 -
将 context.
[[currentTexture]]
设为null
。
-
21.3. HTML 规范挂钩
下列算法“挂钩”到 HTML 规范中的相关算法,并必须在指定时机运行。
GPUCanvasContext
context 的 HTMLCanvasElement
或 OffscreenCanvas
读取 “bitmap” 时,执行如下 内容时间线 步骤:
-
当
HTMLCanvasElement
的渲染被更新时。-
包括当该画布作为 OffscreenCanvas 占位画布元素 时。
-
-
当
transferToImageBitmap()
从 bitmap 创建ImageBitmap
时。 (参见 transferToImageBitmap from WebGPU。) -
当用其他 Web API(如
drawImage()
、texImage2D()
、texSubImage2D()
、toDataURL()
、toBlob()
等)读取 WebGPU 画布内容时。
如果 alphaMode
为 "opaque"
,则会清除
alpha 通道。若实现能以忽略 alpha 通道的方式读取或显示图像,则可跳过此步骤。
如果应用仅为互操作(非展示)目的使用画布,不需要时应避免 "opaque"
。
HTMLCanvasElement
或 OffscreenCanvas
)
并带有 GPUCanvasContext
context 时,在取得画布图像内容之前,于 事件循环处理模型 的以下子步骤:
-
“更新该
Document
的渲染或用户界面” -
“更新该专用 worker 的渲染”
注意:
Service worker 和 Shared worker 没有“更新渲染”步骤,因为它们不能渲染用户可见画布。
requestAnimationFrame()
在 ServiceWorkerGlobalScope
和 SharedWorkerGlobalScope
不可用,
OffscreenCanvas
由 transferControlToOffscreen()
创建后不能发送到这些 worker。
执行以下 内容时间线 步骤:
-
注意: 如果之前已在
getCurrentTexture()
排队的任务中执行,则本步骤无实际效果。 -
将 context.
[[lastPresentedImage]]
设为 context.[[drawingBuffer]]
。注意: 这里只是引用,不是副本;当前纹理过期后,绘制缓冲区内容不可再原地更改。
注意:
这不会发生在独立创建的 OffscreenCanvas
(例如 new OffscreenCanvas()
)上。
当在带有 GPUCanvasContext
context 的画布上调用 transferToImageBitmap()
后,从画布的 bitmap 创建 ImageBitmap
,执行如下 内容时间线 步骤:
注意: 这使得 transferToImageBitmap()
等价于“移动”图像内容(可能包括清除 alpha),而无需复制。
-
更新画布大小算法。
21.4. GPUCanvasConfiguration
支持的上下文格式是以下
集合中的
GPUTextureFormat
:
«"bgra8unorm"
、
"rgba8unorm"
、
"rgba16float"
»。
当这些格式被指定为
GPUCanvasConfiguration
.format
时,无论 GPUCanvasConfiguration
.device
如何,都必须被支持。
注意: 画布配置不能使用 srgb
格式,如 "bgra8unorm-srgb"
。
应该使用非 srgb
的等价格式(如 "bgra8unorm"
),
在 viewFormats
中指定 srgb
格式,
并通过 createView()
创建一个 srgb
格式的视图。
enum GPUCanvasAlphaMode {"opaque" ,"premultiplied" , };enum GPUCanvasToneMappingMode {"standard" ,"extended" , };dictionary {
GPUCanvasToneMapping GPUCanvasToneMappingMode = "standard"; };
mode dictionary {
GPUCanvasConfiguration required GPUDevice device ;required GPUTextureFormat format ;GPUTextureUsageFlags usage = 0x10; // GPUTextureUsage.RENDER_ATTACHMENTsequence <GPUTextureFormat >viewFormats = [];PredefinedColorSpace colorSpace = "srgb";GPUCanvasToneMapping toneMapping = {};GPUCanvasAlphaMode alphaMode = "opaque"; };
GPUCanvasConfiguration
拥有以下成员:
device
,类型为 GPUDevice-
通过
getCurrentTexture()
返回的纹理将与该GPUDevice
兼容。 format
,类型为 GPUTextureFormat-
通过
getCurrentTexture()
返回的纹理的格式。必须为支持的上下文格式之一。 usage
,类型为 GPUTextureUsageFlags,默认值为0x10
-
通过
getCurrentTexture()
返回的纹理的用途。RENDER_ATTACHMENT
为默认用途,但如果显式设置 usage,则不会自动包含。若需将 getCurrentTexture() 返回的纹理作为渲染通道的颜色目标,请确保包含RENDER_ATTACHMENT
。 viewFormats
,类型为 sequence<GPUTextureFormat>,默认值为[]
-
通过
getCurrentTexture()
返回的纹理所创建视图允许使用的格式。 colorSpace
,类型为 PredefinedColorSpace,默认值为"srgb"
-
写入到通过
getCurrentTexture()
返回纹理的值将以该色彩空间显示。 toneMapping
,类型为 GPUCanvasToneMapping,默认值为{}
-
色调映射决定通过
getCurrentTexture()
返回纹理的内容如何显示。注意: 如果实现不支持 HDR WebGPU 画布,则也不应暴露该成员,以便特性检测。参见
getConfiguration()
。 alphaMode
,类型为 GPUCanvasAlphaMode,默认值为"opaque"
-
决定 alpha 值在通过
getCurrentTexture()
返回纹理被读取、显示或用作图像源时的效果。
GPUCanvasContext
以和指定的 GPUDevice
配合使用,并采用此上下文的首选格式:
const canvas= document. createElement( 'canvas' ); const context= canvas. getContext( 'webgpu' ); context. configure({ device: gpuDevice, format: navigator. gpu. getPreferredCanvasFormat(), });
HTMLCanvasElement
或 OffscreenCanvas
)
canvas,
GPUCanvasConfiguration
configuration)
是一个 GPUTextureDescriptor
,具有以下成员:
-
size
: [canvas.width, canvas.height, 1]。 -
viewFormats
: configuration.viewFormats
。
其它成员均使用默认值。
canvas.width 指 HTMLCanvasElement
.width
或 OffscreenCanvas
.width
。
canvas.height 指 HTMLCanvasElement
.height
或 OffscreenCanvas
.height
。
21.4.1. 画布色彩空间
在展示时,画布中的颜色值会被转换到屏幕的色彩空间。
toneMapping
决定了在屏幕色彩空间内对超出 [0, 1]
区间的值的处理方式。
21.4.2. 画布上下文尺寸
除画布的分辨率(由 canvas 的 width
和 height
设置)外,所有画布配置都通过 configure()
进行设置。
注意: 与 WebGL 和 2D 画布类似,调整 WebGPU 画布大小会丢失当前绘制缓冲区的内容。在 WebGPU 中,这是通过替换绘制缓冲区实现的。
GPUCanvasContext
context 的 HTMLCanvasElement
或 OffscreenCanvas
canvas 设置了 width
或 height
属性时,
更新画布大小,执行以下内容时间线步骤:
-
令 configuration 为 context.
[[configuration]]
。 -
如果 configuration 不为
null
:-
将 context.
[[textureDescriptor]]
设为 为画布和配置生成 GPUTextureDescriptor(canvas, configuration)。
-
注意: 这可能会生成一个超出设备 GPUTextureDescriptor
maxTextureDimension2D
限制的纹理描述符,此时在 getCurrentTexture()
内部校验会失败。
注意: 只要设置了 canvas 的 width
或
height
属性,无论值有无变化,该算法都会运行。
21.5. GPUCanvasToneMappingMode
该枚举指定颜色值如何显示到屏幕。
"standard"
-
在屏幕标准动态范围内的颜色值保持不变,所有其它颜色值被投影到屏幕的标准动态范围内。
注意: 这种投影通常通过将颜色空间内的颜色值钳制到
[0, 1]
区间来实现。 "extended"
-
在屏幕扩展动态范围内的颜色值保持不变,所有其它颜色值被投影到屏幕的扩展动态范围内。
注意: 这种投影通常通过将颜色空间内的颜色值钳制到屏幕可显示的值区间来实现,该区间可能包括大于
1
的值。
21.6. GPUCanvasAlphaMode
该枚举选择画布内容在读取、显示到屏幕或用作图像源 时(如在 drawImage、toDataURL 等)如何解释。
下文中,src
表示画布纹理中的一个值,dst
表示画布被合成到的目标图像(如 HTML 页面渲染或 2D 画布)。
"opaque"
-
以不透明方式读取 RGB,忽略 alpha 值。如果内容本身不是不透明的,则在“获取上下文图像内容副本”时将 alpha 通道清为 1.0。
"premultiplied"
-
以预乘方式读取 RGBA:颜色值已乘以其 alpha。100% 红色,50% alpha 时为
[0.5, 0, 0, 0.5]
。如果画布纹理在内容读取时包含超色域预乘 RGBA 值,行为取决于画布的用途:
- 作为图像源
-
值会保留,详情见色彩空间转换。
- 显示到屏幕
-
合成结果未定义。
注意: 即使色彩空间转换本可在合成前产生在色域内的值,合成的中间格式未指定,因此结果未定义。
22. 错误与调试
在 WebGPU 的正常操作过程中,通过 分发错误(dispatch error) 抛出错误。
在设备 丢失 后,尽可能不再抛出错误。 从此时起,实现不再需要执行校验或错误跟踪:
-
设备上的对象有效性变得不可观察。
-
popErrorScope()
和uncapturederror
停止报告错误。 (设备丢失本身不会生成错误。相反,GPUDevice
.lost
Promise 被解析,表示设备已丢失。) -
所有向 内容时间线 发送消息的操作都将跳过其通常步骤。 大多数操作看起来会成功,唯一的例外是
mapAsync()
, 此时会抛出错误,因为设备丢失后无法提供正确的映射数据。这让其他类型的操作(不返回消息的操作)是否真正执行变得不可观察。
22.1. 致命错误
enum {
GPUDeviceLostReason ,
"unknown" , }; [
"destroyed" Exposed =(Window ,Worker ),SecureContext ]interface {
GPUDeviceLostInfo readonly attribute GPUDeviceLostReason ;
reason readonly attribute DOMString ; };
message partial interface GPUDevice {readonly attribute Promise <GPUDeviceLostInfo >lost ; };
GPUDevice
拥有以下额外属性:
lost
,类型为 Promise<GPUDeviceLostInfo>,只读-
一个槽支持属性,其值为设备创建时即产生、在设备生命周期内保持挂起,设备丢失时被解析的 promise。
初始化时,该属性被设置为一个新的 promise。
22.2. GPUError
[Exposed =(Window ,Worker ),SecureContext ]interface GPUError {readonly attribute DOMString message ; };
GPUError
是所有
popErrorScope()
和 uncapturederror
事件抛出的错误的基类。
只有那些在各自算法中明确说明可能抛出错误条件及其子类型的操作,才会生成错误。
丢失的设备不会生成任何错误。参见 § 22 错误与调试。
注意: GPUError
在本规范未来版本中可能会增加新的子类型。应用应处理此种可能性,优先仅使用错误的 message
,如需特殊处理可用
instanceof
。如果需要序列化错误(如用于 JSON 或调试报告),可用 error.constructor.name
。
message
,类型为 DOMString,只读-
一条人类可读、可本地化文本消息,提供关于发生错误的信息。
注意: 此消息通常用于应用开发者调试及收集调试报告信息,不应直接呈现给终端用户。
注意: 用户代理不应在此消息中包含机器可解析的信息,如
"out-of-memory"
时的系统内存剩余情况,或其他内存耗尽相关细节。注意:
message
应遵循语言和方向信息最佳实践,包括未来标准关于字符串语言和方向元数据的规范。编辑注: 截至本文撰写时,还没有既兼容又与旧 API 保持一致的语言/方向推荐方案,未来出现时应正式采用。
[Exposed =(Window ,Worker ),SecureContext ]interface :
GPUValidationError GPUError {(
constructor DOMString ); };
message
GPUValidationError
是 GPUError
的子类型,表示某操作未满足所有校验要求。校验错误总是应用错误的表现,假定使用相同
[[features]]
和 [[limits]]
,应在所有设备上以同样方式失败。
GPUDevice
device 生成校验错误,请执行以下步骤:
设备时间线 步骤:
-
令 error 为带有合适错误信息的新
GPUValidationError
。 -
分发错误 error 给 device。
[Exposed =(Window ,Worker ),SecureContext ]interface :
GPUOutOfMemoryError GPUError {(
constructor DOMString ); };
message
GPUOutOfMemoryError
是 GPUError
的子类型,表示没有足够的空闲内存完成请求的操作。若用更低内存需求(如更小的纹理尺寸)重试,或先释放其他资源占用的内存,操作可能会成功。
GPUDevice
device
生成内存不足错误,请执行以下步骤:
设备时间线 步骤:
-
令 error 为带有合适错误信息的新
GPUOutOfMemoryError
。 -
分发错误 error 给 device。
[Exposed =(Window ,Worker ),SecureContext ]interface :
GPUInternalError GPUError {(
constructor DOMString ); };
message
GPUInternalError
是 GPUError
的子类型,表示即使满足所有校验要求,操作仍因系统或实现特定原因失败。例如,操作可能超出了实现能力,而这些无法被支持的限制准确描述。同一操作在其他设备或不同情形下可能成功。
GPUDevice
device 生成内部错误,请执行以下步骤:
设备时间线 步骤:
-
令 error 为带有合适错误信息的新
GPUInternalError
。 -
分发错误 error 给 device。
22.3. 错误作用域(Error Scopes)
GPU 错误作用域
会捕获在该 GPU 错误作用域 当前时生成的
GPUError
。
错误作用域用于隔离一组 WebGPU 调用过程中发生的错误,通常用于调试或使操作更加容错。
[[errors]]
,类型为 list<GPUError
>,初始值为 [][[filter]]
,类型为GPUErrorFilter
enum {
GPUErrorFilter "validation" ,"out-of-memory" ,"internal" , };partial interface GPUDevice {undefined pushErrorScope (GPUErrorFilter filter );Promise <GPUError ?>popErrorScope (); };
GPUErrorFilter
定义了调用 pushErrorScope()
时要捕获的错误类型:
"validation"
-
表示该错误作用域将捕获
GPUValidationError
。 "out-of-memory"
-
表示该错误作用域将捕获
GPUOutOfMemoryError
。 "internal"
-
表示该错误作用域将捕获
GPUInternalError
。
GPUError
error 和 GPUDevice
device,通过对 device 的设备时间线执行以下步骤确定:
设备时间线步骤:
-
如果 error 是以下类型的实例:
GPUValidationError
-
令 type 为 "validation"。
GPUOutOfMemoryError
-
令 type 为 "out-of-memory"。
GPUInternalError
-
令 type 为 "internal"。
-
令 scope 为 device.
[[errorScopeStack]]
的最后一个项。 -
当 scope 不为
undefined
时:-
如果 scope.
[[filter]]
等于 type,则返回 scope。 -
将 scope 设为 device.
[[errorScopeStack]]
的前一项。
-
-
返回
undefined
。
GPUError
error 到 GPUDevice
device,请执行以下设备时间线步骤:
注意: 丢失的设备不会生成错误。 如果在device已丢失时调用本算法,应用将无法观察到该错误。 参见§ 22 错误与调试。
-
令 scope 为error和device的当前错误作用域。
-
如果 scope 不为
undefined
:-
追加 error 到 scope.
[[errors]]
。 -
返回。
-
-
否则,执行以下内容时间线步骤:
-
如用户代理选择,为 GPUDevice device 排队全局任务,步骤如下:
-
在 device 上触发一个名为 "
uncapturederror
" 的GPUUncapturedErrorEvent
, 其error
为 error。
-
注意:
派发事件后,用户代理应当将未捕获的错误暴露给开发者,例如在浏览器开发者控制台中作为警告,除非事件的
defaultPrevented
为 true。换句话说,调用 preventDefault()
可以阻止控制台警告。
注意: 用户代理可选择限制 GPUUncapturedErrorEvent
的数量,以防过多错误处理或日志影响性能。
pushErrorScope(filter)
-
将一个新的GPU 错误作用域压入 this 的
[[errorScopeStack]]
。调用对象:GPUDevice
this。参数:
参数列表:GPUDevice.pushErrorScope(filter) 参数 类型 可为 null 可选 说明 filter
GPUErrorFilter
✘ ✘ 该错误作用域关注的错误类型。 返回:
undefined
内容时间线步骤:
-
在 this 的设备时间线上执行以下步骤。
设备时间线步骤:-
令 scope 为新的GPU 错误作用域。
-
将 scope.
[[filter]]
设为 filter。 -
压入 scope 到 this.
[[errorScopeStack]]
。
-
popErrorScope()
-
从 this 的
[[errorScopeStack]]
弹出一个GPU 错误作用域, 并返回该作用域期间捕获的任意GPUError
,无则为null
。Promise 解析顺序不保证。
设备时间线 check steps:-
如果 this 已丢失:
-
在 contentTimeline 上执行:
-
返回。
注意: 丢失的设备不会生成错误。参见§ 22 错误与调试。
-
-
若下列要求之一未满足:
-
this.
[[errorScopeStack]]
.size 必须 > 0。
则在 contentTimeline 上执行:
内容时间线步骤:-
拒绝 promise 并抛出
OperationError
。
-
-
令 scope 为从 this.
[[errorScopeStack]]
中弹出的项。 -
令 error 为 scope.
[[errors]]
中任意一个元素,无则为null
。对于列表中的任意两项 E1 和 E2,若 E2 由 E1 导致,则不应选择 E2。
注意: 例如,若 E1 来源于
t
=createTexture()
, E2 来源于t
.createView()
因t
invalid, 应优先选择 E1,使开发者更易理解问题所在。两者都是GPUValidationError
,差别仅在于message
字段。 -
在当前或未来某个未指定时间点,在 contentTimeline 上执行:
注意: 允许
popErrorScope()
的解析顺序和选取错误无关,允许实现异步校验(比如 shader 编译可在后台线程异步完成),只要依赖状态的观察在合适时机完成即可。
-
GPUDevice
操作中的校验错误:
gpuDevice. pushErrorScope( 'validation' ); let sampler= gpuDevice. createSampler({ maxAnisotropy: 0 , // 非法,maxAnisotropy 至少为 1。 }); gpuDevice. popErrorScope(). then(( error) => { if ( error) { // 创建采样器出错,丢弃。 sampler= null ; console. error( `创建采样器时发生错误: ${ error. message} ` ); } });
例如,只包含单个资源(如纹理或缓冲区)创建的错误作用域可用于检测如内存不足的情况,此时应用可尝试释放部分资源再重试分配。
错误作用域无法标识具体哪条命令失败。因此,若整个模型加载过程所有命令都包裹在同一作用域内,就无法判断是否由于内存约束导致失败,通常释放资源并不能解决问题,更合适的做法是降级到其他模型或警告用户无法加载该模型。如果需要响应内存约束,可以将分配内存的操作包裹在更小的嵌套错误作用域中。
22.4. 遥测(Telemetry)
当生成了未被任何GPU 错误作用域捕获的 GPUError
时,用户代理可以在 GPUDevice
上,使用
GPUUncapturedErrorEvent
,触发事件,事件名为 uncapturederror
。
注意: uncapturederror
事件用于遥测和报告意外错误。它们未必针对所有未捕获错误都会派发(如错误数量可能有限制),不应用于处理应用正常运行时已知的错误场景。此类情况请优先使用 pushErrorScope()
和
popErrorScope()
。
[Exposed =(Window ,Worker ),SecureContext ]interface :
GPUUncapturedErrorEvent Event {(
constructor DOMString ,
type GPUUncapturedErrorEventInit ); [
gpuUncapturedErrorEventInitDict SameObject ]readonly attribute GPUError error ; };dictionary :
GPUUncapturedErrorEventInit EventInit {required GPUError ; };
error
GPUUncapturedErrorEvent
拥有以下属性:
error
,类型为 GPUError,只读-
一个槽支持属性,表示未捕获的错误对象。其类型与
popErrorScope()
返回的错误相同。
partial interface GPUDevice {attribute EventHandler onuncapturederror ; };
onuncapturederror
,类型为 EventHandler-
用于
uncapturederror
事件类型的事件处理 IDL 属性。
GPUDevice
的未捕获错误:
gpuDevice. addEventListener( 'uncapturederror' , ( event) => { // 重新输出错误,因为添加事件监听器可能会屏蔽控制台日志。 console. error( '捕获到未被捕获的 WebGPU 错误:' , event. error); myEngineDebugReport. uncapturedErrors. push({ type: event. error. constructor . name, message: event. error. message, }); });
23. 详细操作
本节描述了各类 GPU 操作的详细过程。
23.1. 计算(Computing)
计算操作直接访问 GPU 的可编程硬件。计算着色器没有着色器阶段输入或输出;其结果通过向被绑定为
GPUBufferBindingLayout
并设置 GPUBufferBindingType
为 "storage"
的存储绑定,或以 GPUStorageTextureBindingLayout
方式,写入数据产生副作用。
这些操作通过 GPUComputePassEncoder
编码,包括:
主要的计算算法如下:
参数:
-
descriptor:当前
GPUComputePipeline
的描述信息。 -
dispatchCall:分发调用参数。可来自函数参数或
INDIRECT
缓冲区。
-
令 computeStage 为 descriptor.
compute
。 -
令 workgroupSize 为 computeStage.
entryPoint
应用 computeStage.constants
到 computeStage.module
后计算得到的工作组大小。 -
对 workgroupX 遍历
[0, dispatchCall.
区间:workgroupCountX
]-
对 workgroupY 遍历
[0, dispatchCall.
区间:workgroupCountY
]-
对 workgroupZ 遍历
[0, dispatchCall.
区间:workgroupCountZ
]-
对 localX 遍历
[0, workgroupSize.
区间:x
]-
对 localY 遍历
[0, workgroupSize.
区间:y
]-
对 localZ 遍历
[0, workgroupSize.
区间:z
]-
令 invocation 为
{ computeStage, workgroupX, workgroupY, workgroupZ, localX, localY, localZ }
-
追加 invocation 到 computeInvocations。
-
-
-
-
-
-
-
对 computeInvocations 中每个 invocation,以设备选择的任意顺序(可并行):
-
设置着色器内建变量(builtins):
-
如果需要,设置 num_workgroups 内建变量为
(
dispatchCall.workgroupCountX
,
dispatchCall.workgroupCountY
,
dispatchCall.workgroupCountZ
) -
如果需要,设置 workgroup_id 内建变量为
(
invocation.workgroupX,
invocation.workgroupY,
invocation.workgroupZ
) -
如果需要,设置 local_invocation_id 内建变量为
(
invocation.localX,
invocation.localY,
invocation.localZ
) -
如果需要,设置 global_invocation_id 内建变量为
(
。
invocation.workgroupX * workgroupSize.x
+ invocation.localX,
invocation.workgroupY * workgroupSize.y
+ invocation.localY,
invocation.workgroupZ * workgroupSize.z
+ invocation.localZ
) -
如果需要,设置 local_invocation_index 内建变量为
invocation.localX + (invocation.localY * workgroupSize.
x
) + (invocation.localZ * workgroupSize.x
* workgroupSize.y
)
-
-
调用 invocation.computeStage 描述的计算着色器入口点。
-
注意: 着色器调用没有顺序保证,通常会根据设备能力并行执行。开发者不应假设任一调用或工作组会在其他调用开始前完成。有些设备看似顺序一致,但这一行为不可依赖,因为不同设备表现不一。需要跨调用同步的着色器必须使用 同步内建函数进行协调。
如果着色器执行未在合理时间内结束(由用户代理决定),设备可能会丢失。
23.2. 渲染(Rendering)
渲染由一组在 GPURenderPassEncoder
中执行的 GPU 操作完成,
这些操作会修改被渲染通道附件(render pass attachments)查看的纹理数据。
这些操作包括:
注意: 渲染是 GPU 的传统用途,并且由硬件中的多个固定功能块支持。
主要渲染算法如下:
参数:
-
pipeline:当前的
GPURenderPipeline
。 -
drawCall:绘制调用参数。可来自函数参数,也可来自
INDIRECT
缓冲区。 -
state:RenderState,即在
GPURenderCommandsMixin
中发起 draw 调用时的状态。
-
令 descriptor 为 pipeline.
[[descriptor]]
。 -
索引解析(Resolve indices)。参见 § 23.2.1 索引解析。
令 vertexList 为 resolve indices(drawCall, state) 的结果。
-
顶点处理(Process vertices)。参见 § 23.2.2 顶点处理。
执行 process vertices(vertexList, drawCall, descriptor.
vertex
, state)。 -
图元组装(Assemble primitives)。参见 § 23.2.3 图元组装。
执行 assemble primitives(vertexList, drawCall, descriptor.
primitive
)。 -
图元裁剪(Clip primitives)。参见 § 23.2.4 图元裁剪。
令 primitiveList 为此阶段的输出。
-
光栅化(Rasterize)。参见 § 23.2.5 光栅化。
令 rasterizationList 为 rasterize(primitiveList, state) 的结果。
-
片元处理(Process fragments)。参见 § 23.2.6 片元处理。
收集 fragments 列表,其由遍历 rasterizationList 中每个 rasterPoint,执行 process fragment(rasterPoint, descriptor, state) 产生。
-
写像素(Write pixels)。参见 § 23.2.7 输出合并。
对于 fragments 中每个非 null 的 fragment:
-
执行 process depth stencil(fragment, pipeline, state)。
-
执行 process color attachments(fragment, pipeline, state)。
-
23.2.1. 索引解析(Index Resolution)
在渲染的首个阶段,管线会为每个实例构建要处理的顶点列表。
参数:
-
drawCall:绘制调用参数。可来自函数参数或
INDIRECT
缓冲区。 -
state:绘制调用时
GPURenderCommandsMixin
的状态快照。
返回: 整型索引列表。
-
令 vertexIndexList 为一个空索引列表。
-
如果 drawCall 是索引绘制调用:
-
用 drawCall.indexCount 个整数初始化 vertexIndexList。
-
对于 i 从 0 到 drawCall.indexCount(不含)循环:
-
令 relativeVertexIndex = fetch index(i + drawCall.
firstIndex
, state.[[index_buffer]]
). -
如果 relativeVertexIndex 为特殊值
"out of bounds"
, 则返回空列表。注意: 实现可选择在此情况下显示警告,特别是在容易检测的场景(如非 indirect 索引绘制)。
-
将 drawCall.
baseVertex
+ relativeVertexIndex 追加到 vertexIndexList。
-
-
-
否则:
-
用 drawCall.vertexCount 个整数初始化 vertexIndexList。
-
将每个 vertexIndexList 项 i 设为 drawCall.firstVertex + i。
-
-
返回 vertexIndexList。
注意:
对于间接绘制调用,indexCount
、vertexCount
等属性从 indirect 缓冲区读取,而不是从绘制命令本身。
参数:
-
i:要获取的顶点索引的索引号。
-
state:绘制调用时
GPURenderCommandsMixin
的状态快照。
返回: 无符号整数或 "out of bounds"
-
令 indexSize 由 state.
[[index_format]]
决定: -
如果 state.
[[index_buffer_offset]]
+ |i + 1| × indexSize > state.[[index_buffer_size]]
, 返回特殊值"out of bounds"
。 -
将 state.
[[index_buffer]]
中,从偏移 state.[[index_buffer_offset]]
+ i × indexSize 处,大小为 indexSize 字节的数据,按无符号整数解释并返回。
23.2.2. 顶点处理(Vertex Processing)
顶点处理阶段是渲染管线的可编程阶段, 用于处理顶点属性数据,并为§ 23.2.4 图元裁剪生成裁剪空间位置,以及为 § 23.2.6 片元处理生成其他数据。
参数:
-
vertexIndexList:要处理的顶点索引列表(可变引用传递)。
-
drawCall:绘制调用参数,可来自函数参数或
INDIRECT
缓冲区。 -
desc:类型为
GPUVertexState
的描述符。 -
state:绘制调用时
GPURenderCommandsMixin
的状态快照。
每个 vertexIndexList 中的顶点 vertexIndex,在每个 rawInstanceIndex 实例下,均独立处理。
rawInstanceIndex 的范围为 0 到 drawCall.instanceCount - 1。
此处理可并行发生,诸如对 GPUBufferBindingType
"storage"
绑定的写入等副作用可无序发生。
-
令 instanceIndex = rawInstanceIndex + drawCall.firstInstance。
-
对 desc.
buffers
列表中每个非null
的 vertexBufferLayout:-
令 i 为该 buffer layout 在列表中的索引。
-
令 vertexBuffer、vertexBufferOffset、vertexBufferBindingSize 分别为 state.
[[vertex_buffers]]
在槽 i 处的 buffer、offset 和 size。 -
令 vertexElementIndex 根据 vertexBufferLayout.
stepMode
决定:"vertex"
-
vertexIndex
"instance"
-
instanceIndex
-
令 drawCallOutOfBounds 为
false
。 -
对 vertexBufferLayout.
attributes
中每个 attributeDesc:-
令 attributeOffset = vertexBufferOffset + vertexElementIndex * vertexBufferLayout.
arrayStride
+ attributeDesc.offset
。 -
如果 attributeOffset + byteSize(attributeDesc.
format
) > vertexBufferOffset + vertexBufferBindingSize:-
将 drawCallOutOfBounds 设为
true
。 -
实现可选(implementation-defined), 清空 vertexIndexList 并返回,取消本次绘制调用。
注意: 这允许实现提前检测索引缓冲区的越界值,而不是等到 无效内存引用 行为时才发现。
-
-
-
对 vertexBufferLayout.
attributes
中每个 attributeDesc:-
如果 drawCallOutOfBounds 为
true
:-
根据 WGSL 的无效内存引用行为从 vertexBuffer 加载属性 data。
注意: 无效内存引用 允许多种实现,包括即使 drawCallOutOfBounds 为
true
但单个属性在范围内时依然返回“正确”值。
否则:
-
令 attributeOffset = vertexBufferOffset + vertexElementIndex * vertexBufferLayout.
arrayStride
+ attributeDesc.offset
。 -
从 vertexBuffer 的 attributeOffset 处加载格式为 attributeDesc.
format
的属性 data。 组件按x
,y
,z
,w
顺序从内存加载。
-
-
根据通道格式规则,将 data 转换为着色器可见格式。
-
将 data 调整为着色器类型:
-
若二者均为标量,或均为同维度向量,无需调整。
-
若 data 为向量而着色器为标量,仅取首个分量。
-
若均为向量且 data 维度更高,则截断多余分量。
-
若着色器为高维向量或 data 为标量,缺失分量用
vec4<*>(0, 0, 0, 1)
填充。
-
-
将 data 绑定到顶点着色器输入位置 attributeDesc.
shaderLocation
。
-
-
-
对 state.
[[bind_groups]]
中每个GPUBindGroup
group(索引为 index):-
对该 bind group 中每个
GPUBindingResource
资源:-
令 entry 为该资源对应的
GPUBindGroupLayoutEntry
。 -
若 entry.
visibility
包含VERTEX
:-
将资源绑定到着色器的 group index 和 binding
GPUBindGroupLayoutEntry.binding
处。
-
-
-
-
设置着色器内建变量:
-
如有,设置
vertex_index
内建变量为 vertexIndex。 -
如有,设置
instance_index
内建变量为 instanceIndex。
-
-
调用 desc 描述的顶点着色器入口点。
注意: 目标平台可能缓存顶点着色器调用结果, 同一 vertexIndex 多次出现不保证会多次调用,也不保证只调用一次。
23.2.3. 图元组装(Primitive Assembly)
图元的组装由 GPU 的固定功能阶段完成。
参数:
-
vertexIndexList:待处理的顶点索引列表。
-
drawCall:绘制调用参数。可来自函数参数或
INDIRECT
缓冲区。 -
desc:类型为
GPUPrimitiveState
的描述符。
对于每个实例,图元根据 vertexIndexList,从着色器处理过的顶点组装而成。
-
首先,如果图元拓扑是 strip(即 desc.
stripIndexFormat
不为 undefined), 且 drawCall 是索引绘制,则以 desc.stripIndexFormat
的最大值为分隔符,将 vertexIndexList 拆分为若干子列表。示例:vertexIndexList 值为
[1, 2, 65535, 4, 5, 6]
,类型为"uint16"
, 拆分后的子列表为[1, 2]
和[4, 5, 6]
。 -
对于每个子列表 vl,根据 desc.
topology
类型生成图元:"line-list"
-
线段图元由 (vl.0, vl.1),(vl.2, vl.3),(vl.4, vl.5) 等依次组成。 每个后续图元消耗 2 个顶点。
"line-strip"
-
线段图元由 (vl.0, vl.1),(vl.1, vl.2),(vl.2, vl.3) 等组成。 每个后续图元消耗 1 个顶点。
"triangle-list"
-
三角形图元由 (vl.0, vl.1, vl.2), (vl.3, vl.4, vl.5),(vl.6, vl.7, vl.8) 等组成。 每个后续图元消耗 3 个顶点。
"triangle-strip"
-
三角形图元由 (vl.0, vl.1, vl.2), (vl.2, vl.1, vl.3),(vl.2, vl.3, vl.4), (vl.4, vl.3, vl.5) 等组成。 每个后续图元消耗 1 个顶点。
不完整的图元会被丢弃。
23.2.4. 图元裁剪(Primitive Clipping)
顶点着色器必须生成一个内建的 position(类型为 vec4<f32>
),
它表示顶点在裁剪空间坐标中的裁剪位置。
图元会被裁剪到裁剪体积内,对于任何属于图元内的裁剪位置 p,该体积由以下不等式定义:
-
−p.w ≤ p.x ≤ p.w
-
−p.w ≤ p.y ≤ p.w
-
0 ≤ p.z ≤ p.w(深度裁剪(depth clipping))
当 "clip-distances"
特性启用时,该裁剪体积可通过用户定义的半空间进一步收紧,可在顶点阶段输出声明
clip_distances。该数组中的每个值会在图元内线性插值,插值结果小于 0 的部分会被裁剪。
若 descriptor.primitive
.unclippedDepth
为 true
,则不进行深度裁剪:裁剪体积在 z 轴无限制。
若图元所有边都完全处于裁剪体积内,则此阶段图元保持不变。
若图元边与裁剪体积边界相交,则交点会以新边连通,且新边位于裁剪体积边界上。
对于三角形图元(descriptor.primitive
.topology
为 "triangle-list"
或 "triangle-strip"
),
此重连可能在多边形内部引入新顶点。
若图元与裁剪体积边界相交,裁剪后的多边形必须包含该边界上的点。
若顶点着色器输出其它浮点值(标量或向量)并声明为 "perspective" 插值,则这些值也会被裁剪。 处于裁剪体积内的顶点的输出值不受裁剪影响。若图元被裁剪,则新生成顶点的输出值也需按裁剪规则处理。
对于被裁剪的顶点边 a 到 b 生成的新顶点 c,定义 t 为边上比例: c.p = t × a.p + (1 - t) × b.p, 其中 x.p 是顶点 x 的裁剪位置。
对每个有片元输入的顶点输出值 "v",a.v 和 b.v 分别为 a 和 b 顶点的输出。 剪裁后新顶点 c.v 的值根据插值限定符产生:
- flat
-
flat 插值不受影响,参照激发顶点(provoking vertex), 由着色器声明的插值采样模式(interpolation sampling)决定。输出对整个图元相同,等于激发顶点的输出。
- linear
-
插值比例会基于裁剪位置的透视坐标调整,使结果在屏幕空间内线性。
- perspective
-
在裁剪空间内线性插值,得到透视校正值。
图元裁剪的结果是一组新的图元,均包含在裁剪体积内。
23.2.5. 光栅化(Rasterization)
光栅化是硬件处理阶段,将生成的图元映射到 帧缓冲区(framebuffer) 的二维渲染区域——即当前 GPURenderPassEncoder
的渲染附件集合。
该渲染区域被划分为均匀的像素网格。
帧缓冲区的坐标从渲染目标的左上角开始。 每个单位正好对应一个像素。详见 § 3.3 坐标系统。
光栅化决定哪些像素会被图元影响。若开启多重采样,每个像素会进一步被分割为
descriptor.multisample
.count
个样本。
标准采样模式如下,
每个样本的位置都以像素左上角为原点的帧缓冲坐标系给出,像素范围为 (0,0) 到 (1,1):
multisample .count
| 样本位置 |
---|---|
1 | 样本0: (0.5, 0.5) |
4 |
样本0: (0.375, 0.125) 样本1: (0.875, 0.375) 样本2: (0.125, 0.625) 样本3: (0.625, 0.875) |
实现必须在光栅化时,为指定的 标准采样模式使用对应 multisample
.count
。
定义 FragmentDestination,其包含:
- position
-
以帧缓冲坐标表示的二维像素位置
- sampleIndex
-
若 § 23.2.10 每样本着色 激活则为整数,否则为
null
我们还用到归一化设备坐标(NDC)。其范围为 X/Y:-1 到 1,Z:0 到 1。
光栅化产生一组 RasterizationPoint,每项包含:
- destination
- coverageMask
-
多重采样覆盖掩码,见 § 23.2.11 样本掩码
- frontFacing
-
为 true 表示该点在图元正面
- perspectiveDivisor
-
指跨图元插值的 1.0 ÷ W
- depth
-
在视口坐标中的深度,即
[[viewport]]
的minDepth
和maxDepth
之间。 - primitiveVertices
-
组成该图元的顶点输出列表
- barycentricCoordinates
参数:
-
primitiveList:待光栅化的图元列表。
-
state:当前 RenderState。
返回: RasterizationPoint 列表。
primitiveList 中每个图元独立处理,但图元顺序会影响后续深度/模板操作和像素写入。
-
首先,将裁剪后的顶点变换为归一化设备坐标(NDC)。 假设输出位置为 p,则 NDC 坐标与透视除数为:
ndc(p) = vector(p.x ÷ p.w, p.y ÷ p.w, p.z ÷ p.w)
divisor(p) = 1.0 ÷ p.w
-
令 vp = state.
[[viewport]]
。 将 NDC 位置 n 映射到视口坐标:-
根据渲染目标偏移和尺寸计算帧缓冲区坐标:
framebufferCoords(n) = vector(vp.
x
+ 0.5 × (n.x + 1) × vp.width
, vp.y
+ 0.5 × (−n.y + 1) × vp.height
) -
深度按线性映射 [0, 1] 到视口深度范围:
depth(n) = vp.
minDepth
+ n.z
× ( vp.maxDepth
- vp.minDepth
)
-
-
令 rasterizationPoints 为点集,每个点的属性(
divisor(p)
、framebufferCoords(n)
、depth(n)
等)按其在图元上的位置插值,与 § 23.2.4 图元裁剪同理。若为用户自定义属性(非内建输出),则使用 WGSL 插值类型,由 @interpolate 属性指定。 -
根据
primitive
.topology
,采用相应的光栅化算法:"point-list"
-
未被 § 23.2.4 图元裁剪过滤的点进入 § 23.2.5.1 点光栅化。
"line-list"
或"line-strip"
-
被 § 23.2.4 图元裁剪裁剪的线条进入 § 23.2.5.2 线光栅化。
"triangle-list"
或"triangle-strip"
-
由 § 23.2.4 图元裁剪生成的多边形进入 § 23.2.5.4 多边形光栅化。
-
移除所有 rasterizationPoints 中 rp,使其 destination.position 不在 state.
[[scissorRect]]
范围内。 -
返回 rasterizationPoints。
23.2.5.1. 点光栅化(Point Rasterization)
在包含该点帧缓冲区坐标的像素内,选择一个FragmentDestination。
覆盖掩码(coverage mask)取决于多重采样模式:
- 样本频率(sample-frequency)
-
coverageMask = 1 ≪
sampleIndex
- 像素频率多重采样(pixel-frequency multi-sampling)
-
coverageMask = 1 ≪ descriptor.
multisample
.count
− 1 - 无多重采样(no multi-sampling)
-
coverageMask = 1
23.2.5.2. 线光栅化(Line Rasterization)
线光栅化的具体算法没有规定,不同实现可能不同。例如,可以用 § 23.2.5.4 多边形光栅化 在直线段周围绘制一个 1 像素宽的矩形, 或用 Bresenham 线算法选取FragmentDestination。
注意: 详情见 Basic Line Segment Rasterization 和 Bresenham Line Segment Rasterization,参见 Vulkan 1.3 规范。
23.2.5.3. 重心坐标(Barycentric coordinates)
重心坐标是一组 n 个数 bi,定义在包含点 p 的凸多边形(顶点为 vi,位于帧缓冲区空间)。 每个 bi 取值范围为 0 到 1,表示点距离顶点 vi 的接近度。 它们的和恒为 1:
∑ (bi) = 1
这些坐标唯一确定多边形内(或边界上)任意点 p:
p = ∑ (bi × pi)
对于三角形(3 顶点多边形),点 p 的重心坐标可如下计算:
Apolygon = A(v1, v2, v3) b1 = A(p, b2, b3) ÷ Apolygon b2 = A(b1, p, b3) ÷ Apolygon b3 = A(b1, b2, p) ÷ Apolygon
其中 A(点集) 表示由这些顶点组成的多边形的面积。
对于超过 3 顶点的多边形,具体算法依实现而定。一种可行实现是将多边形三角剖分,然后根据点所在三角形计算重心坐标。
23.2.5.4. 多边形光栅化(Polygon Rasterization)
当多边形朝向投影方向时,称为正面(front-facing); 否则为背面(back-facing)。
参数:
返回: RasterizationPoint 列表。
-
令 rasterizationPoints 为一个空列表。
-
令 v(i) 为裁剪后多边形第 i 个顶点(从1开始,共 n 个顶点)的帧缓冲区坐标。
注意: 此处用“多边形”而非“三角形”,因为 § 23.2.4 图元裁剪 可能引入额外顶点, 但应用无法察觉。
-
判断多边形是否为正面,依据其在帧缓冲区坐标中的 area 符号:
area = 0.5 × ((v1.x × vn.y − vn.x × v1.y) + ∑ (vi+1.x × vi.y − vi.x × vi+1.y))
-
在帧缓冲区空间内,确定多边形内的片元(fragments)集合——即将进行每片元操作的位置。 此过程称为“点采样”(point sampling)。 具体逻辑依 descriptor.
multisample
:- 关闭多重采样(disabled)
-
片元与像素中心关联。即所有帧缓冲区坐标 C 满足 fract(C) = vector2(0.5, 0.5) 且位于多边形内均包含。 若像素中心位于边界,是否包含未定义。
注意: 这与光栅化器的精度有关。
- 开启多重采样(enabled)
-
每个像素包含 descriptor.
multisample
.count
个实现自定义的位置。 这些位置有顺序,且全帧缓冲区所有像素一致,每个样本对应多重采样帧缓冲区的一个片元。光栅化器会生成每像素命中的位置掩码,即“sample-mask”,并作为内建变量提供给片元着色器。
-
对每个生成的 FragmentDestination 类型片元:
-
令 rp 为新的 RasterizationPoint 对象
-
计算 b,即该片元的§ 23.2.5.3 重心坐标,并赋值给 rp.barycentricCoordinates。
-
令 di 为 vi 的深度值。
-
将 rp.depth 设为 ∑ (bi × di)
-
将 rp 加入 rasterizationPoints。
-
-
返回 rasterizationPoints。
23.2.6. 片元处理(Fragment Processing)
片元处理阶段是渲染管线的可编程阶段, 用于计算将要写入渲染目标的片元数据(通常为颜色)。
该阶段为每个RasterizationPoint生成一个片元(Fragment):
-
destination:参见FragmentDestination。
-
frontFacing:若片元位于图元正面,则为 true。
-
coverageMask:多重采样覆盖掩码,见 § 23.2.11 样本掩码。
-
depth:在视口坐标中的深度,即
[[viewport]]
的minDepth
和maxDepth
之间。 -
colors:每个
colorAttachments
目标的颜色值列表。 -
depthPassed :若片元通过
depthCompare
操作则为 true。 -
stencilPassed :若片元通过模板
compare
操作则为 true。
参数:
-
rp:由 § 23.2.5 光栅化 生成的 RasterizationPoint。
-
descriptor:类型为
GPURenderPipelineDescriptor
的描述符。 -
state:当前 RenderState。
返回: Fragment 或
null
。
-
令 fragmentDesc = descriptor.
fragment
。 -
令 depthStencilDesc = descriptor.
depthStencil
。 -
令 fragment 为新的 Fragment 对象。
-
设 fragment.destination = rp.destination。
-
设 fragment.frontFacing = rp.frontFacing。
-
设 fragment.coverageMask = rp.coverageMask。
-
如果着色器未输出
frag_depth
内建变量:-
设 fragment.depthPassed = compare fragment(fragment.destination, fragment.depth, "depth", state.
[[depthStencilAttachment]]
, depthStencilDesc?.depthCompare
)。
-
-
设 stencilState = depthStencilDesc?.
stencilFront
(若 rp.frontFacing 为 true),否则为 depthStencilDesc?.stencilBack
。 -
设 fragment.stencilPassed = compare fragment(fragment.destination, state.
[[stencilReference]]
, "stencil", state.[[depthStencilAttachment]]
, stencilState?.compare
)。 -
如果 fragmentDesc 不为
null
:-
若 fragment.depthPassed 为
false
,且着色器入口未输出frag_depth
内建变量,也未写入任何storage 绑定,则以下步骤可被跳过。 -
设置着色器输入内建变量。对每个入口点的非复合参数,若有 内建变量注解,按下表赋值:
position
-
vec4<f32>
(rp.destination.position, rp.depth, rp.perspectiveDivisor) front_facing
-
rp.frontFacing
sample_index
sample_mask
-
rp.coverageMask
-
对片元阶段的每个用户指定着色器输入:
-
令 value 为插值后的片元输入,基于 rp.barycentricCoordinates、 rp.primitiveVertices 以及输入上的插值限定符。
-
将对应片元着色器location输入设为 value。
-
-
调用 fragmentDesc 描述的片元着色器入口点。
-
若片元执行了
discard
,则返回null
。 -
取着色器输出的内建变量:
-
如输出
frag_depth
内建变量 为 value:-
令 vp = state.
[[viewport]]
。 -
设 fragment.depth = clamp(value, vp.
minDepth
, vp.maxDepth
)。 -
设 fragment.depthPassed = compare fragment(fragment.destination, fragment.depth, "depth", state.
[[depthStencilAttachment]]
, depthStencilDesc?.depthCompare
)。
-
-
-
如输出
sample_mask
内建变量为 value:-
设 fragment.coverageMask = fragment.coverageMask ∧ value。
-
否则,处于§ 23.2.8 无色输出(No Color Output)模式,fragment.colors 为空。
-
-
返回 fragment。
参数:
-
destination:FragmentDestination。
-
value:待比较的值。
-
aspect:从 attachment 采样值的aspect。
-
attachment:用于比较的附件(attachment)。
-
compareFunc:要使用的
GPUCompareFunction
,或undefined
。
返回: 若比较通过则为 true
,否则为 false
-
如果 attachment 为
undefined
或没有 aspect,返回true
。 -
如果 compareFunc 为
undefined
或"always"
,返回true
。 -
令 attachmentValue 为 attachment 在 destination 处 aspect 的值。
-
若使用 compareFunc 比较 value 和 attachmentValue 成功,则返回
true
,否则返回false
。
片元的处理会并行进行,所有副作用(如对 GPUBufferBindingType
"storage"
绑定的写入)可无序发生。
23.2.7. 输出合并(Output Merging)
输出合并是渲染管线的固定功能阶段,用于将片元颜色、深度和模板数据写入渲染通道附件。
参数:
-
fragment:由 § 23.2.6 片元处理 生成的 Fragment。
-
pipeline:当前的
GPURenderPipeline
。 -
state:当前 RenderState。
-
令 depthStencilDesc = pipeline.
[[descriptor]]
.depthStencil
。 -
若 pipeline.
[[writesDepth]]
为true
且 fragment.depthPassed 为true
:-
将 state.
[[depthStencilAttachment]]
在 fragment.destination 处的深度 aspect 设为 fragment.depth。
-
-
若 pipeline.
[[writesStencil]]
为 true:-
设 stencilState = depthStencilDesc.
stencilFront
(若 fragment.frontFacing 为true
),否则为 depthStencilDesc.stencilBack
。 -
若 fragment.stencilPassed 为
false
:-
设 stencilOp = stencilState.
failOp
。
否则若 fragment.depthPassed 为
false
:-
设 stencilOp = stencilState.
depthFailOp
。
否则:
-
设 stencilOp = stencilState.
passOp
。
-
-
对 state.
[[depthStencilAttachment]]
在 fragment.destination 处的模板 aspect 按 stencilOp 描述的操作更新值。
-
本阶段的深度输入(如有)会被限制在当前 [[viewport]]
的深度范围内(无论片元着色器是否写入 frag_depth
内建变量)。
参数:
-
fragment:由 § 23.2.6 片元处理 生成的 Fragment。
-
pipeline:当前的
GPURenderPipeline
。 -
state:当前 RenderState。
-
若 fragment.depthPassed 为
false
或 fragment.stencilPassed 为false
,则返回。 -
令 targets = pipeline.
[[descriptor]]
.fragment
.targets
。 -
对 state.
[[colorAttachments]]
中每个 attachment:-
令 color 为 fragment.colors 中与 attachment 对应的值。
-
令 targetDesc 为与 attachment 对应的 targets 条目。
-
将 color 赋值给 attachment 在 fragment.destination 处的值。
-
23.2.8. 无色输出(No Color Output)
在无色输出模式下,管线不会产生任何颜色附件输出。
管线仍会执行光栅化,并根据顶点位置输出生成深度值。深度测试和模板操作依然可用。
23.2.9. Alpha 到覆盖(Alpha to Coverage)
在 alpha-to-coverage 模式下,会根据片元着色器输出 @location(0)
处的 alpha 分量,
生成一个额外的 MSAA 样本的 alpha-to-coverage 掩码。
生成该掩码的算法依平台而异,不同像素可有不同实现。保证:
-
若 alpha ≤ 0.0,结果为 0x0
-
若 alpha ≥ 1.0,结果为 0xFFFFFFFF
-
中间 alpha 值应使掩码中置 1 的位数与 alpha 成比例。部分平台不保证随 alpha 增大,掩码 1 的位数单调递增。
23.2.10. 每样本着色(Per-Sample Shading)
在渲染到多重采样渲染附件时,片元着色器可以按每像素或每样本运行。
如果 sample_index
内建变量 或
sample
插值采样被用且影响着色器输出,片元着色器必须每样本运行一次。
否则可以只对每像素运行一次,并将结果广播到最终样本掩码内的各样本。
使用每样本着色时,样本 N 的颜色输出由 sample_index
== N 时的片元着色器执行结果产生。
23.2.11. 样本掩码(Sample Masking)
像素的最终样本掩码(final sample
mask)计算为:
光栅化掩码(rasterization
mask)
& mask
& 着色器输出掩码(shader-output mask)。
只考虑掩码的低 count
位。
若 最终样本掩码第 N 位为 0,则该样本的所有颜色输出都会被丢弃, 深度测试和模板操作也不会对深度模板附件上相应样本执行。
光栅化掩码(rasterization mask)由光栅化阶段产生, 取决于多边形形状。图形覆盖到的样本在掩码中相应位为 1。
着色器输出掩码(shader-output
mask)为片元着色器输出 "sample_mask" 内建变量 的值。
若片元着色器未输出该内建变量,且 alphaToCoverageEnabled
启用,则 着色器输出掩码为alpha-to-coverage 掩码;
否则默认为 0xFFFFFFFF。
24. 类型定义(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 long ;
GPUSize64Out typedef unsigned long ;
GPUIntegerCoordinateOut typedef unsigned long ;
GPUSize32Out typedef unsigned long ;
GPUFlagsConstant
24.1. 颜色与向量(Colors & Vectors)
dictionary {
GPUColorDict required double r ;required double g ;required double b ;required double a ; };typedef (sequence <double >or GPUColorDict );
GPUColor
注意: double
能精确表示 32 位有符号/无符号整数和单精度浮点数。
r
, 类型为 double-
红色通道值。
g
, 类型为 double-
绿色通道值。
b
, 类型为 double-
蓝色通道值。
a
, 类型为 double-
alpha 通道值。
GPUColor
值 color,根据其类型,语法如下:
-
color.r 指的是
GPUColorDict
.r
或序列的第一个元素(断言该元素存在)。 -
color.g 指的是
GPUColorDict
.g
或序列的第二个元素(断言该元素存在)。 -
color.b 指的是
GPUColorDict
.b
或序列的第三个元素(断言该元素存在)。 -
color.a 指的是
GPUColorDict
.a
或序列的第四个元素(断言该元素存在)。
dictionary {
GPUOrigin2DDict GPUIntegerCoordinate = 0;
x GPUIntegerCoordinate = 0; };
y typedef (sequence <GPUIntegerCoordinate >or GPUOrigin2DDict );
GPUOrigin2D
GPUOrigin2D
值 origin,根据其类型,语法如下:
-
origin.x 指的是
GPUOrigin2DDict
.x
或序列的第一个元素(若不存在则为 0)。 -
origin.y 指的是
GPUOrigin2DDict
.y
或序列的第二个元素(若不存在则为 0)。
参数:
-
origin:待校验的
GPUOrigin2D
。
返回: undefined
内容时间线步骤:
dictionary {
GPUOrigin3DDict GPUIntegerCoordinate = 0;
x GPUIntegerCoordinate = 0;
y GPUIntegerCoordinate = 0; };
z typedef (sequence <GPUIntegerCoordinate >or GPUOrigin3DDict );
GPUOrigin3D
GPUOrigin3D
值 origin,根据其类型,语法如下:
-
origin.x 指的是
GPUOrigin3DDict
.x
或序列的第一个元素(若不存在则为 0)。 -
origin.y 指的是
GPUOrigin3DDict
.y
或序列的第二个元素(若不存在则为 0)。 -
origin.z 指的是
GPUOrigin3DDict
.z
或序列的第三个元素(若不存在则为 0)。
参数:
-
origin:待校验的
GPUOrigin3D
。
返回: undefined
内容时间线步骤:
dictionary {
GPUExtent3DDict required GPUIntegerCoordinate width ;GPUIntegerCoordinate height = 1;GPUIntegerCoordinate depthOrArrayLayers = 1; };typedef (sequence <GPUIntegerCoordinate >or GPUExtent3DDict );
GPUExtent3D
width
, 类型为 GPUIntegerCoordinate-
范围的宽度。
height
, 类型为 GPUIntegerCoordinate,默认值为1
-
范围的高度。
depthOrArrayLayers
, 类型为 GPUIntegerCoordinate,默认值为1
-
范围的深度或包含的数组层数。 如果与
GPUTexture
配合GPUTextureDimension
为"3d"
时定义纹理深度。 若与GPUTexture
配合GPUTextureDimension
为"2d"
时定义数组层数。
GPUExtent3D
值 extent,根据其类型,语法如下:
-
extent.width 指的是
GPUExtent3DDict
.width
或序列的第一个元素(断言该元素存在)。 -
extent.height 指的是
GPUExtent3DDict
.height
或序列的第二个元素(若不存在则为 1)。 -
extent.depthOrArrayLayers 指的是
GPUExtent3DDict
.depthOrArrayLayers
或序列的第三个元素(若不存在则为 1)。
参数:
-
extent:待校验的
GPUExtent3D
。
返回: undefined
内容时间线步骤:
-
如果:
25. 特性索引(Feature Index)
25.1. "core-features-and-limits"
允许使用所有 Core WebGPU 特性和限制。
注意:目前该特性在所有适配器上可用,即使未请求也会自动在所有设备上启用。
25.2. "depth-clip-control"
允许禁用深度裁剪(depth clipping)。
该特性增加了如下可选 API 接口:
-
新的
GPUPrimitiveState
字典成员:
25.3. "depth32float-stencil8"
允许显式创建格式为 "depth32float-stencil8"
的纹理(texture)。
该特性增加了如下可选 API 接口:
25.4. "texture-compression-bc"
允许显式创建 BC 压缩格式(包括 “S3TC”、"RGTC" 和 "BPTC")的纹理。仅支持 2D 纹理。
注意: 支持 "texture-compression-bc"
的适配器并不总是支持 "texture-compression-bc-sliced-3d"
。
若要使用 "texture-compression-bc-sliced-3d"
,
必须显式启用 "texture-compression-bc"
,
因为本特性不会自动启用 BC 格式。
该特性增加了如下可选 API 接口:
-
新的
GPUTextureFormat
枚举值:
25.5. "texture-compression-bc-sliced-3d"
注意: 支持 "texture-compression-bc"
的适配器并不总是支持 "texture-compression-bc-sliced-3d"
。
若要使用 "texture-compression-bc-sliced-3d"
,
必须显式启用 "texture-compression-bc"
,
因为本特性不会自动启用 BC 格式。
该特性未增加任何可选 API 接口。
25.6. "texture-compression-etc2"
允许显式创建 ETC2 压缩格式的纹理。仅支持 2D 纹理。
该特性增加了如下可选 API 接口:
-
新的
GPUTextureFormat
枚举值:
25.7. "texture-compression-astc"
允许显式创建 ASTC 压缩格式的纹理。仅支持 2D 纹理。
该特性增加了如下可选 API 接口:
-
新的
GPUTextureFormat
枚举值:
25.8. "texture-compression-astc-sliced-3d"
注意: 支持 "texture-compression-astc"
的适配器并不总是支持 "texture-compression-astc-sliced-3d"
。
若要使用 "texture-compression-astc-sliced-3d"
,
必须显式启用 "texture-compression-astc"
,
因为本特性不会自动启用 ASTC 格式。
该特性未增加任何可选 API 接口。
25.9. "timestamp-query"
为 GPU 命令缓冲区提供查询时间戳的能力。参见 § 20.4 时间戳查询(Timestamp Query)。
该特性增加了如下可选 API 接口:
-
新的
GPUQueryType
值: -
新的
GPUComputePassDescriptor
成员: -
新的
GPURenderPassDescriptor
成员:
25.10. "indirect-first-instance"
允许在间接绘制参数和
间接 drawIndexed 参数中使用非零的 firstInstance
值。
该特性未增加任何可选 API 接口。
25.11.
"shader-f16"
允许在 WGSL 中使用半精度浮点类型 f16。
该特性增加了如下可选 API 接口:
-
新的 WGSL 扩展:
25.12. "rg11b10ufloat-renderable"
允许格式为 "rg11b10ufloat"
的纹理使用 RENDER_ATTACHMENT
,并允许该格式的纹理进行混合、多重采样和解析。
该特性未增加任何可选 API 接口。
在设备创建时启用 "texture-formats-tier1"
也会启用
"rg11b10ufloat-renderable"
。
25.13. "bgra8unorm-storage"
允许格式为 "bgra8unorm"
的纹理使用 STORAGE_BINDING
用法。
该特性未增加任何可选 API 接口。
25.14. "float32-filterable"
使格式为 "r32float"
、
"rg32float"
和 "rgba32float"
的纹理可滤波(filterable)。
25.15. "float32-blendable"
使格式为 "r32float"
、
"rg32float"
和 "rgba32float"
的纹理可混合(blendable)。
25.16. "clip-distances"
允许在 WGSL 中使用 clip_distances。
该特性增加了如下可选 API 接口:
-
新的 WGSL 扩展:
25.17. "dual-source-blending"
允许在 WGSL 中使用 blend_src,并可同时将两个像素着色器输出
(@blend_src(0)
和 @blend_src(1)
) 作为对单个颜色附件 location 0
的混合操作输入。
该特性增加了如下可选 API 接口:
-
允许使用以下
GPUBlendFactor
: -
新的 WGSL 扩展:
25.18.
"subgroups"
允许 WGSL 中使用 subgroup 和 quad 操作。
该特性未增加可选 API
接口,但只要适配器支持该特性,GPUAdapterInfo
的如下成员会暴露真实值:
-
新的 WGSL 扩展:
25.19. "texture-formats-tier1"
支持如下新的 GPUTextureFormat
可用于 RENDER_ATTACHMENT
、
可混合(blendable)、multisampling
及 STORAGE_BINDING
能力,并支持 "read-only"
和 "write-only"
GPUStorageTextureAccess
:
允许如下 RENDER_ATTACHMENT
、
可混合(blendable)、multisampling
和 resolve
能力用于如下 GPUTextureFormat
:
允许如下 "read-only"
或 "write-only"
GPUStorageTextureAccess
用于如下 GPUTextureFormat
:
在设备创建时启用 "texture-formats-tier2"
也会启用 "texture-formats-tier1"
。
在设备创建时启用 "texture-formats-tier1"
也会启用 "rg11b10ufloat-renderable"
。
25.20. "texture-formats-tier2"
允许如下 "read-write"
GPUStorageTextureAccess
用于如下 GPUTextureFormat
:
在设备创建时启用 "texture-formats-tier2"
也会启用 "texture-formats-tier1"
。
26. 附录(Appendices)
26.1. 纹理格式能力(Texture Format Capabilities)
26.1.1. 普通颜色格式(Plain color formats)
所有支持的普通颜色格式支持用法:
COPY_SRC
、
COPY_DST
、
TEXTURE_BINDING
,
以及维度 "3d"
。
RENDER_ATTACHMENT
和 STORAGE_BINDING
列分别指明对 GPUTextureUsage.RENDER_ATTACHMENT
和 GPUTextureUsage.STORAGE_BINDING
用法的支持情况。
渲染目标像素字节成本(render target pixel byte cost)
和 渲染目标组件对齐(render target component alignment)
用于校验 maxColorAttachmentBytesPerSample
限制。
注意: 这些格式的texel 块内存成本(texel block memory cost) 与其texel 块拷贝占用空间(texel block copy footprint)相同。
26.1.2. 深度-模板格式(Depth-stencil formats)
深度或模板格式(depth-or-stencil format) 指的是任何带有深度和/或模板方面的格式。 组合深度-模板格式(combined depth-stencil format) 是指同时具有深度和模板方面的深度或模板格式。
所有深度或模板格式都支持
COPY_SRC
、
COPY_DST
、
TEXTURE_BINDING
,
以及 RENDER_ATTACHMENT
用法。这些格式都支持多重采样(multisampling)。
但某些拷贝操作对源和目标格式有限制,并且这些格式都不支持 "3d"
纹理维度。
深度纹理不能与 "filtering"
采样器一起使用,但即使使用滤波,始终可以与
"comparison"
采样器一起使用。
格式(Format) |
注意:
texel块内存成本(Bytes)
| 方面(Aspect) | GPUTextureSampleType
| 有效texel拷贝源 | 有效texel拷贝目标 | texel块拷贝占用空间(Bytes) | aspect-specific format |
---|---|---|---|---|---|---|---|
stencil8
| 1 − 4 | stencil | "uint"
| ✓ | 1 | stencil8
| |
depth16unorm
| 2 | depth | "depth" ,
"unfilterable-float"
| ✓ | 2 | depth16unorm
| |
depth24plus
| 4 | depth | "depth" ,
"unfilterable-float"
| ✗ | – | depth24plus
| |
depth24plus-stencil8
| 4 − 8 | depth | "depth" ,
"unfilterable-float"
| ✗ | – | depth24plus
| |
stencil | "uint"
| ✓ | 1 | stencil8
| |||
depth32float
| 4 | depth | "depth" ,
"unfilterable-float"
| ✓ | ✗ | 4 | depth32float
|
depth32float-stencil8
| 5 − 8 | depth | "depth" ,
"unfilterable-float"
| ✓ | ✗ | 4 | depth32float
|
stencil | "uint"
| ✓ | 1 | stencil8
|
24位深度(24-bit depth) 指的是范围为0.0到1.0的24位无符号归一化深度格式,如果暴露出来,其拼写为 "depth24unorm"。
26.1.2.1. 读取和采样深度/模板纹理(Reading and Sampling Depth/Stencil Textures)
可以将一个深度方面(depth-aspect)的 GPUTextureView
绑定到 texture_depth_*
绑定类型,或绑定到其他非深度的2d/cube纹理类型。
模板方面(stencil-aspect)的 GPUTextureView
必须绑定到普通纹理绑定类型。sampleType
在 GPUBindGroupLayout
中必须为 "uint"
。
读取或采样纹理的深度或模板方面时,表现为纹理包含值 (V, X, X, X)
,其中 V 为实际深度或模板值,X 为实现定义的未指定值。
对于深度方面绑定,这些未指定值在 texture_depth_*
类型的绑定下是不可见的。
texture_2d<f32>
类型绑定到 tex
:
textureSample(tex, ...)
将返回vec4<f32>(D, X, X, X)
。textureGather(0, tex, ...)
将返回vec4<f32>(D1, D2, D3, D4)
。textureGather(2, tex, ...)
将返回vec4<f32>(X1, X2, X3, X4)
(完全未指定的值)。
注意:
除非增加类似深度采样器那样更受限的模板采样器类型,否则实现上很难高效“屏蔽”深度/模板读取的驱动差异。
由于这在 WebGL 中不是移植性痛点,因此预计在 WebGPU 中也不会有问题。
实际上,根据硬件不同,可能会得到 (V, V, V, V)
或 (V, 0, 0, 1)
(V
为深度或模板值)。
26.1.2.2. 拷贝深度/模板纹理(Copying Depth/Stencil Textures)
depth32float 格式("depth32float"
和
"depth32float-stencil8"
)的深度方面有受限的范围。
因此,只允许从同格式的其他纹理进行拷贝到此类纹理。
depth24plus 格式("depth24plus"
和
"depth24plus-stencil8"
)的深度方面有不透明的表示(实现为
24位深度 或 "depth32float"
)。
因此,这些格式不允许深度方面texel 拷贝操作。
- 所有这些格式都可以在渲染通道(render pass)中通过片元着色器的
frag_depth
输出写入深度值。 - 带 "depth24plus" 格式的纹理可以被作为着色器纹理读取,并可以写入到纹理(作为渲染通道附件)或 buffer(通过计算着色器中的 storage buffer binding)。
26.1.3. 打包格式(Packed formats)
所有打包纹理格式(packed texture formats)都支持
COPY_SRC
、
COPY_DST
、
以及 TEXTURE_BINDING
用法。
这些格式全部是可过滤(filterable)的。
但这些格式都不是可渲染(renderable)的,也不支持多重采样(multisampling)。
压缩格式(compressed format) 指的是任何块大小大于 1×1 的格式。
注意: 这些格式的texel 块内存成本 与其texel 块拷贝占用空间相同。