1. 引言

WebGPU是什么?

WebGPU与WebGL的对比?

2. 快速体验

参考:Orillusion | 专业WebGPU社区 | WebGPU小白入门(一): 零基础创建第一个WebGPU项目

# Clone the repo
git clone https://github.com/Orillusion/orillusion-webgpu-samples.git # Go inside the folder
cd orillusion-webgpu-samples # Start installing dependencies
npm install #or yarn add # Run project at localhost:3000
npm run dev #or yarn run dev

Chrome 浏览器(版本100+) 中打开localhost:3000,即可看到运行结果:

注意

  • 目前(2022年7月)WebGPU未正式发布,接口代码变更较快

  • WebGPU未正式发布,各个浏览器支持程度不同,本文使用Chrome版本号为:105.0.5153.0(正式版本)canary (64 位),下载地址:开发者专用的 Chrome Canary 版功能 - Google Chrome

部署别人写的代码终究是少了点感觉,接下来将编写一个入手案例

3. Hello Triangle

3.1 环境准备

浏览器:Chrome Canary版,版本号为:105.0.5153.0(正式版本)canary (64 位)

将Chrome开启WebGPU功能:

在地址栏输入 chrome://flags/ 搜索 WebGPU,将WebGPU的功能打开

3.2 基础代码

创建一个HTML文件,设置基础代码,另外,WebGPU是借助HTML中的canvas元素实现的,所以创建一个canvas元素

index.html:

<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Basic Triangle</title>
<style>
html,
body {
margin: 0;
width: 100%;
height: 100%;
background: #000;
color: #fff;
display: flex;
text-align: center;
flex-direction: column;
justify-content: center;
} canvas {
width: 100%;
height: 100%;
}
</style>
</head> <body>
<canvas></canvas>
<script src="./index.js"></script>
</body> </html>

3.3 主要代码

同一目录下创建一个index.js文件,代码内容如下,流程讲解在下一节

index.js:

// initialize webgpu device & config canvas context
async function initWebGPU(canvas) {
if(!navigator.gpu)
throw new Error('Not Support WebGPU')
const adapter = await navigator.gpu.requestAdapter({
powerPreference: 'high-performance'
// powerPreference: 'low-power'
})
if (!adapter)
throw new Error('No Adapter Found')
const device = await adapter.requestDevice()
const context = canvas.getContext('webgpu')
const format = navigator.gpu.getPreferredCanvasFormat ? navigator.gpu.getPreferredCanvasFormat() : context.getPreferredFormat(adapter)
const devicePixelRatio = window.devicePixelRatio || 1
canvas.width = canvas.clientWidth * devicePixelRatio
canvas.height = canvas.clientHeight * devicePixelRatio
const size = {width: canvas.width, height: canvas.height}
context.configure({
// json specific format when key and value are the same
device, format,
// prevent chrome warning
alphaMode: 'opaque'
})
return {device, context, format, size}
} // create a simple pipiline
async function initPipeline(device, format){
const descriptor = {
layout: 'auto',
vertex: {
module: device.createShaderModule({
code: `@vertex
fn main(@builtin(vertex_index) VertexIndex : u32) -> @builtin(position) vec4<f32> {
var pos = array<vec2<f32>, 3>(
vec2<f32>(0.0, 0.5),
vec2<f32>(-0.5, -0.5),
vec2<f32>(0.5, -0.5)
);
return vec4<f32>(pos[VertexIndex], 0.0, 1.0);
}`
}),
entryPoint: 'main'
},
primitive: {
topology: 'triangle-list' // try point-list, line-list, line-strip, triangle-strip?
},
fragment: {
module: device.createShaderModule({
code: `@fragment
fn main() -> @location(0) vec4<f32> {
return vec4<f32>(1.0, 0.0, 0.0, 1.0);
}`
}),
entryPoint: 'main',
targets: [
{
format: format
}
]
}
}
return await device.createRenderPipelineAsync(descriptor)
}
// create & submit device commands
function draw(device, context, pipeline) {
const commandEncoder = device.createCommandEncoder()
const view = context.getCurrentTexture().createView()
const renderPassDescriptor = {
colorAttachments: [
{
view: view,
clearValue: { r: 0, g: 0, b: 0, a: 1.0 },
loadOp: 'clear', // clear/load
storeOp: 'store' // store/discard
}
]
}
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor)
passEncoder.setPipeline(pipeline)
// 3 vertex form a triangle
passEncoder.draw(3)
passEncoder.end()
// webgpu run in a separate process, all the commands will be executed after submit
device.queue.submit([commandEncoder.finish()])
} async function run(){
const canvas = document.querySelector('canvas')
if (!canvas)
throw new Error('No Canvas')
const {device, context, format} = await initWebGPU(canvas)
const pipeline = await initPipeline(device, format)
// start draw
draw(device, context, pipeline) // re-configure context on resize
window.addEventListener('resize', ()=>{
canvas.width = canvas.clientWidth * devicePixelRatio
canvas.height = canvas.clientHeight * devicePixelRatio
// don't need to recall context.configure() after v104
draw(device, context, pipeline)
})
}
run()

运行代码(笔者这里使用VS Code和Live Server插件),使用Chrome打开,顺利的话即可看到三角形:

4. 运行流程

5. 参考资料

[1]WebGPU 到底是什么? - 知乎 (zhihu.com)

[2]WebGPU学习系列目录 - Wonder-YYC - 博客园 (cnblogs.com)

[3]WebGPU性能测试分析 - Wonder-YYC - 博客园 (cnblogs.com)

[4]WebGL 与 WebGPU 比对 前奏 - 四季留歌 - 博客园 (cnblogs.com)

[5]WebGPU (orillusion.com)

[6]orillusion-webgpu-samples/basicTriangle.ts at main · Orillusion/orillusion-webgpu-samples (github.com)

[7]Orillusion | 专业WebGPU社区 | WebGPU小白入门(一): 零基础创建第一个WebGPU项目

[8]WebGPU小白入门(二):绘制简单三角形——1.认识渲染流程_哔哩哔哩_bilibili

WebGPU 01之Hello Triangle的更多相关文章

  1. OpenGL 学习笔记 01 环境配置

    以下教程仅适用于Mac下的Xcode编程环境!其他的我也不会搞. 推荐教程:opengl-tutorial  本项目Github网址       OpenGL太可怕了...必需得把学的记下来,不然绝壁 ...

  2. 1043 - Triangle Partitioning(数学)

    1043 - Triangle Partitioning   PDF (English) Statistics Forum Time Limit: 0.5 second(s) Memory Limit ...

  3. C博客01——分支,顺序结构

    C博客01--分支,顺序结构 1. 本章学习总结 1.1 思维导图 请以思维导图总结本周的学习内容. 1.2 本章学习体会及代码量体会 1.2.1 学习体会 对于C语言课程的理解,我有点吃力,不是说老 ...

  4. Category Theory: 01 One Structured Family of Structures

    Category Theory: 01 One Structured Family of Structures 这次看来要放弃了.看了大概三分之一.似乎不能够让注意力集中了.先更新吧. 群的定义 \( ...

  5. Triangle leetcode java

    题目: Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjace ...

  6. 一个由正则表达式引发的血案 vs2017使用rdlc实现批量打印 vs2017使用rdlc [asp.net core 源码分析] 01 - Session SignalR sql for xml path用法 MemCahe C# 操作Excel图形——绘制、读取、隐藏、删除图形 IOC,DIP,DI,IoC容器

    1. 血案由来 近期我在为Lazada卖家中心做一个自助注册的项目,其中的shop name校验规则较为复杂,要求:1. 英文字母大小写2. 数字3. 越南文4. 一些特殊字符,如“&”,“- ...

  7. WebGPU学习(五): 现代图形API技术要点和WebGPU支持情况调研

    大家好,本文整理了现代图形API的技术要点,重点研究了并行和GPU Driven Render Pipeline相关的知识点,调查了WebGPU的相关支持情况. 另外,本文对实时光线追踪也进行了简要的 ...

  8. WebGPU学习(六):学习“rotatingCube”示例

    大家好,本文学习Chrome->webgpu-samplers->rotatingCube示例. 上一篇博文: WebGPU学习(五): 现代图形API技术要点和WebGPU支持情况调研 ...

  9. [译]Vulkan教程(01)入门

    [译]Vulkan教程(01)入门 接下来我将翻译(https://vulkan-tutorial.com)上的Vulkan教程.这可能是我学习Vulkan的最好方式,但不是最理想的方式. 我会用“d ...

  10. WebGPU学习(九):学习“fractalCube”示例

    大家好,本文学习Chrome->webgpu-samplers->fractalCube示例. 上一篇博文: WebGPU学习(八):学习"texturedCube"示 ...

随机推荐

  1. go操作Kfaka

    目录 1. Kafka介绍 1.1.1. Kafka是什么 1.1.2. Kafka的特点 1.1.3. 常用的场景 1.1.4. Kafka中包含以下基础概念 1.1.5. 消息 1.1.6. 消息 ...

  2. 基于训练和推理场景下的MindStudio高精度对比

    摘要:MindStudio提供精度比对功能,支持Vector比对能力. 本文分享自华为云社区<[MindStudio训练营第一季]MindStudio 高精度对比随笔>,作者:Tianyi ...

  3. 小技巧 EntityFrameworkCore 实现 CodeFirst 通过模型生成数据库表时自动携带模型及字段注释信息

    今天分享自己在项目中用到的一个小技巧,就是使用 EntityFrameworkCore 时我们在通过代码去 Update-Database 生成数据库时如何自动将代码模型上的注释和字段上的注释携带到数 ...

  4. jmeter 之 JSON 断言

    1.JSON 断言所在位置:断言->JSON 断言 2.JSON断言中的字段解析 Assert JSON Path exists:json 表达式,判断所字段是否存在,存在则为True, 否则为 ...

  5. JavaScript:立即执行函数

    想象一下,如果我希望某个代码块,只执行一次,就不再执行,应该怎么办? 代码块肯定是用函数来表示,执行肯定是调用函数,但是确保只执行一次,该怎么办? 我们为什么可以多次调用函数,因为函数名指向了函数的内 ...

  6. JavaScript:箭头函数:作为参数进行传参

    之前已经说过,JS的函数,也是对象,而函数名是一个变量,是可以进行传参的,也即函数是可以被传参的. 只要是函数,都可以被传参,但是箭头函数的语法更为灵活,所以更方便进行传参. 如上图所示,fun1是一 ...

  7. 【环境搭建】RocketMQ集群搭建

    前置条件及效果图 条件: 两台服务器,个人是两台腾讯云服务器(其中嫖的朋友一个): 版本: rocketmq-version:4.4.0 rocketmq-console(mq控制台) Java:1. ...

  8. 2022年7月12,第四组,周鹏,被算法折磨的一天【哭】【哭】【哭】【puls哭】

    今天学习了JS的几种循环语法,说实话,前几天的简单让我大意了,没有闪,很成功的被搞崩了! 一杯水,一根烟,一个算法边写边骂是一天. 多少次,我满怀期待的以为它会出现想要的结果, 但现实的残酷狠狠的折磨 ...

  9. [数据结构]广度优先搜索算法(Breadth-First-Search,BFS)

    广度优先搜索的概念 广度优先搜索(BFS)类似于二叉树的层序遍历算法,它的基本思想是:首先访问起始顶点v,然后由v出发,依次访问v的各个未被访问过的邻接顶点w1,w2,w3-.wn,然后再依次访问w1 ...

  10. KMP 与 Z 函数

    \(\text{By DaiRuiChen007}\) 一.KMP 算法 I. 问题描述 在文本串 \(S\) 中找到模式串 \(T\) 的所有出现,其中 \(|S|=n,|T|=m\) II. 前置 ...