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. 关于Window中右键新建菜单的设置

    在日常工作中,有时候需要根据自己的需要对Windows桌面右键新建菜单进行自定义,自定义的方法如下: 1.在Window中输入Win+R调出运行命令框 2.输入regedit,打开注册表 3.如果想要 ...

  2. 06.python闭包

    python闭包 什么样的函数是 闭包函数 ? 满足以下条件: 闭:外层函数嵌套了一个内层函数. 包:内层函数调用外层函数命名空间内的名字. 举例如下: def out_func(): # 外层函数 ...

  3. flask博客项目之tinymce图片上传

    查看当前的博客发表情况 截图一张立马粘贴进来 点击发表,显示数据太长 不断撤退回到刚刚页面 删除大图,换成小图,上传方式 点击发表可以成功发表 数据库中查看,是把图片生成这种编码后字符串方式存储的了, ...

  4. NOIP-2022游寄

    NOIP-2022游寄 Day 1 虽然没有上次去南京CSP-S那么激动,但还是有点小开心的,毕竟能水掉两天课.Phigros重度沉迷患者,推了4个小时的分.坐右前方那哥们好卷,在车上写图论-- JS ...

  5. 【转载】SQL SERVER 将多行数据合并成一行

    昨天遇到一个SQL Server的问题:需要写一个储存过程来处理几个表中的数据,最后问题出在我想将一个表的一个列的多行内容拼接成一行 比如表中有两列数据 : ep_classes  ep_name A ...

  6. 我曾经用“UC震惊部”震碎了很多人的三观

    Hi,欢迎大家在有空的时候做客[江涛学编程],这里是2023年的第9篇原创文章,今天写的这篇是当事人对昨天上热搜的统一回复. 我没有曾经跨过山河大海,我也没有曾经穿越人山人海,但我曾经用"U ...

  7. 网盘不限速下载器,全速下载,快过SVIP

    一.软件简介 该软件利用作者开通的SVIP下载文件到服务器,然后由服务器传送给客户端实现不限速下载,所有功能(下载文件夹.批量下载)基本都免费开放了,现在每天每个用户拥有免费的20G的流量可以使用,已 ...

  8. 请务必注意精度不一样,就不相等(float 与double)

    即使两个小数显示的值是一样的,但是类型不一要样,精度不一样实际上是不一样的 就比如下面这段代码: #include <iostream> #include <cstring> ...

  9. Quartz.Net 官方教程 Tutorial 3/3

    Schedule 相关属性设置 扩展属性方式 var host = Host.CreateDefaultBuilder() .ConfigureServices(services => { se ...

  10. 基于APIView写接口

    一.视图层代码 """ 基于APIView实现接口的编写 用的是同一个模型表 路由也没变 这次做了解耦合 写了序列化类 与视图类分开了 """ ...