Google codelab WebGPU入门教程源码<3> - 绘制网格(源码)

对应的教程文章: https://codelabs.developers.google.com/your-first-webgpu-app?hl=zh-cn#4

对应的源码执行效果: 

对应的教程源码: 

此处源码和教程本身提供的部分代码可能存在一点差异。

class Color4 {

	r: number;
	g: number;
	b: number;
	a: number;

	constructor(pr = 1.0, pg = 1.0, pb = 1.0, pa = 1.0) {
		this.r = pr;
		this.g = pg;
		this.b = pb;
		this.a = pa;
	}
}

export class WGPURColorGrid {
	private mRVertices: Float32Array = null;
	private mRPipeline: any | null = null;
	private mVtxBuffer: any | null = null;
	private mCanvasFormat: any | null = null;
	private mWGPUDevice: any | null = null;
	private mWGPUContext: any | null = null;
	private mUniformBindGroup: any | null = null;
	private mGridSize = 32;
	constructor() {}
	initialize(): void {

		const canvas = document.createElement("canvas");
		canvas.width = 512;
		canvas.height = 512;
		document.body.appendChild(canvas);
		this.initWebGPU(canvas).then(() => {
			console.log("webgpu initialization finish ...");

			this.clearWGPUCanvas();
		});
		document.onmousedown = (evt):void => {
			this.clearWGPUCanvas( new Color4( Math.random(), Math.random(), Math.random()) );
		}
	}
	private createUniform(device: any, pipeline: any): void {
		// Create a uniform buffer that describes the grid.
		const uniformArray = new Float32Array([this.mGridSize, this.mGridSize]);
		const uniformBuffer = device.createBuffer({
			label: "Grid Uniforms",
			size: uniformArray.byteLength,
			usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
		});
		device.queue.writeBuffer(uniformBuffer, 0, uniformArray);

		this.mUniformBindGroup = device.createBindGroup({
			label: "Cell renderer bind group",
			layout: pipeline.getBindGroupLayout(0),
			entries: [{
				binding: 0,
				resource: { buffer: uniformBuffer }
			}],
		});
	}
	private createRectGeometryData(device: any, pass: any): void {

		let vertices = this.mRVertices;
		let vertexBuffer = this.mVtxBuffer;
		let cellPipeline = this.mRPipeline;
		if(!cellPipeline) {
			let hsize = 0.8;
			vertices = new Float32Array([
			//   X,    Y,
				-hsize, -hsize, // Triangle 1 (Blue)
				 hsize, -hsize,
				 hsize,  hsize,

				-hsize, -hsize, // Triangle 2 (Red)
				 hsize,  hsize,
				-hsize,  hsize,
			]);

			vertexBuffer = device.createBuffer({
				label: "Cell vertices",
				size: vertices.byteLength,
				usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
			});
			device.queue.writeBuffer(vertexBuffer, /*bufferOffset=*/0, vertices);
			const vertexBufferLayout = {
				arrayStride: 8,
				attributes: [{
					format: "float32x2",
					offset: 0,
					shaderLocation: 0, // Position, see vertex shader
				}],
			};
			const shaderCodes = `
			struct VertexInput {
				@location(0) pos: vec2f,
				@builtin(instance_index) instance: u32,
			};

			struct VertexOutput {
				@builtin(position) pos: vec4f,
				@location(0) cell: vec2f,
			};

			@group(0) @binding(0) var<uniform> grid: vec2f;

			@vertex
			fn vertexMain(input: VertexInput) -> VertexOutput  {
				let i = f32(input.instance);
				let cell = vec2f(i % grid.x, floor(i / grid.x));
				let cellOffset = cell / grid * 2;
				let gridPos = (input.pos + 1) / grid - 1 + cellOffset;

				var output: VertexOutput;
				output.pos = vec4f(gridPos, 0, 1);
				output.cell = cell;
				return output;
			}

			@fragment
			fn fragmentMain(input: VertexOutput) -> @location(0) vec4f {
				let c = input.cell/grid;
				return vec4f(c, 1.0 - c.x, 1);
			}
			`;
			const cellShaderModule = device.createShaderModule({
				label: "Cell shader",
				code: shaderCodes
				});
			cellPipeline = device.createRenderPipeline({
				label: "Cell pipeline",
				layout: "auto",
				vertex: {
					module: cellShaderModule,
					entryPoint: "vertexMain",
					buffers: [vertexBufferLayout]
				},
				fragment: {
					module: cellShaderModule,
					entryPoint: "fragmentMain",
					targets: [{
						format: this.mCanvasFormat
					}]
				},
			});
			this.mRVertices = vertices;
			this.mVtxBuffer = vertexBuffer;
			this.mRPipeline = cellPipeline;

			this.createUniform(device, cellPipeline);
		}
		pass.setPipeline(cellPipeline);
		pass.setVertexBuffer(0, vertexBuffer);
		pass.setBindGroup(0, this.mUniformBindGroup);
		pass.draw(vertices.length / 2, this.mGridSize * this.mGridSize);
	}

	private clearWGPUCanvas(clearColor: Color4 = null): void {

		clearColor = clearColor ? clearColor : new Color4(0.05, 0.05, 0.1);
		const device = this.mWGPUDevice;
		const context = this.mWGPUContext;
		const rpassParam = {
			colorAttachments: [
				{
					clearValue: clearColor,
					// clearValue: [0.3,0.7,0.5,1.0], // yes
					view: context.getCurrentTexture().createView(),
					loadOp: "clear",
					storeOp: "store"
				}
			]
		};

		const encoder = device.createCommandEncoder();
		const pass = encoder.beginRenderPass( rpassParam );


		this.createRectGeometryData(device, pass);
		pass.end();
		const commandBuffer = encoder.finish();
		device.queue.submit([commandBuffer]);
	}
	private async initWebGPU(canvas: HTMLCanvasElement) {

		const gpu = (navigator as any).gpu;
		if (gpu) {
			console.log("WebGPU supported on this browser.");

			const adapter = await gpu.requestAdapter();
			if (adapter) {
				console.log("Appropriate GPUAdapter found.");
				const device = await adapter.requestDevice();
				if (device) {
					this.mWGPUDevice = device;
					console.log("Appropriate GPUDevice found.");
					const context = canvas.getContext("webgpu") as any;
					const canvasFormat = gpu.getPreferredCanvasFormat();
					this.mWGPUContext = context;
					this.mCanvasFormat = canvasFormat;
					console.log("canvasFormat: ", canvasFormat);
					context.configure({
						device: device,
						format: canvasFormat,
						alphaMode: "premultiplied"
					});
				} else {
					throw new Error("No appropriate GPUDevice found.");
				}
			} else {
				throw new Error("No appropriate GPUAdapter found.");
			}
		} else {
			throw new Error("WebGPU not supported on this browser.");
		}
	}
	run(): void {}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/166646.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【实用技巧】更改ArduinoIDE默认库文件位置,解放系统盘,将Arduino15中的库文件移动到其他磁盘

本文主要介绍更改Arduino IDE &#xff08;含2.0以上版本&#xff09;默认库文件位置的方法。 原创文章&#xff0c;转载请注明出处&#xff1a; 【实用技巧】更改ArduinoIDE默认库文件位置&#xff0c;解放C盘&#xff0c;将Arduino15中的库文件移动到其他磁盘-CSDN博客文章浏…

基于RK3588的8k多屏异显安卓智能网络机顶盒

采用RK3588芯片方案的8K网络机顶盒&#xff0c;搭载纯净的安卓12操作系统&#xff0c;支持Ubuntu和Debian系统容拓展。主要面向外贸市场。此款机顶盒自带两个HDMI输出接口&#xff0c;一个HDMI输入接口&#xff0c;内置双频WiFi6无线模块&#xff0c;支持千兆以太网和USB接口。…

SPASS-曲线估计

基本概念 曲线估计&#xff08;曲线拟合、曲线回归&#xff09;则是研究两变量间非线性关系的一种方法&#xff0c;选定一种用方程表达的曲线&#xff0c;使得实际数据与理论数据之间的差异尽可能地小。如果曲线选择得好&#xff0c;那么可以揭示因变量与自变量的内在关系&…

java拼图小游戏

第一步是创建项目 项目名自拟 第二部创建个包名 来规范class 然后是创建类 创建一个代码类 和一个运行类 代码如下&#xff1a; package heima;import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import jav…

Flutter笔记:缩放手势

Flutter笔记 缩放手势 作者&#xff1a;李俊才 &#xff08;jcLee95&#xff09;&#xff1a;https://blog.csdn.net/qq_28550263 邮箱 &#xff1a;291148484163.com 本文地址&#xff1a;https://blog.csdn.net/qq_28550263/article/details/134485138 目 录 1. 概述2. 缩放手…

数据结构【DS】图的应用

图的连通性问题 最少边数 最多边数 无向图非连通 &#x1d48e;&#x1d7ce; &#x1d48e;&#x1d48f;−&#x1d7d0;∗(&#x1d48f;−&#x1d7cf;)/&#x1d7d0; 无向图连通 &#x1d48e;&#x1d48f;−&#x1d7cf; &#x1d48e;&#x1d48f;∗(&#…

网络割接用VRRP替换HSRP

如图3-11所示&#xff0c;C6500作为核心层设备上行连接出口路由器NE40E-X3&#xff0c;下行连接接入层设备CE6800。C6500上配置HSRP实现冗余备份网关&#xff0c;同时在二层网络部署MSTP破除环路。 总体思路 HSRP为CISCO私有协议&#xff0c;CE系列交换机&#xff08;以CE1280…

【算法挨揍日记】day26——53. 最大子数组和、918. 环形子数组的最大和

53. 最大子数组和 53. 最大子数组和 题目描述&#xff1a; 给你一个整数数组 nums &#xff0c;请你找出一个具有最大和的连续子数组&#xff08;子数组最少包含一个元素&#xff09;&#xff0c;返回其最大和。 子数组 是数组中的一个连续部分。 解题思路&#xff1a; 状态…

quinn源码解析:QUIC数据包是如何发送的

quinn源码解析&#xff1a;QUIC数据包是如何发送的 简介QUIC协议中的概念endpoint&#xff08;端点&#xff09;connection&#xff08;连接&#xff09;Stream&#xff08;流&#xff09;Frame (帧) 发包过程解析SendStream::write_allConnectionDriverEndpointDriver 简介 q…

【Java】线程池源码解析

目录 一、线程池介绍 1.1、什么是线程池 1.2、线程池的工作原理 二、Executor框架接口 2.1、JDK提供的原生线程池 2.2、类关系 三、线程池核心源码分析 3.1、关键属性 3.2、状态控制 3.3、线程池状态的跃迁 3.4、execute方法源码分析 3.5、addWorker方法源码分析 3…

第五篇 《随机点名答题系统》——抽点答题详解(类抽奖系统、在线答题系统、线上答题系统、在线点名系统、线上点名系统、在线考试系统、线上考试系统)

目录 1.功能需求 2.界面设计 3.流程设计 4.关键代码 随机点名答题系统&#xff08;类抽奖系统、在线答题系统、线上答题系统、在线点名系统、线上点名系统、在线考试系统、线上考试系统&#xff09;&#xff0c;是基于php&#xff08;8.2.11&#xff09;&#xff0c;Java…

【汇编】[bx+idata]的寻址方式、SI和DI寄存器

文章目录 前言一、[bxidata]寻址方式1.1 [bxidata]的含义1.2 示例代码 二、SI和DI寄存器2.1 SI和DI寄存器是什么&#xff1f;2.2 [bxsi]和[bxdi]方式寻址2.3 [bxsiidata]和[bxdiidata] 总结 前言 在汇编语言中&#xff0c;寻址方式是指指令如何定位内存中的数据。BX寄存器与偏…

C#,数值计算——插值和外推,Laplace_interp的计算方法与源程序

1 文本格式 using System; namespace Legalsoft.Truffer { /// <summary> /// Object for interpolating missing data in a matrix by solving Laplaces /// equation.Call constructor once, then solve one or more times /// </summary> …

7 Redis的PipeLine

PipeLine的作用是批量执行命令 redis的性能瓶颈基本上是网络 import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.…

应用开发平台集成表单设计器系列之3——整体集成思路及表单设计器功能深度了解

背景 平台需要实现自定义表单功能&#xff0c;作为低代码开发的一部分&#xff0c;通过技术预研和技术选型&#xff0c;选择form-create和form-create-designer这两个组件进行集成作为实现方案。通过深入了解和技术验证&#xff0c;确认了组件的功能能满足需求&#xff0c;具备…

迪克森电荷泵

迪克森电荷泵&#xff08;Dickson Charge Pump&#xff09;是一种电压倍增器电路&#xff0c;可以将低电压升高到较高电压&#xff0c;相对于其他电压升压电路&#xff0c;迪克森电荷泵具有较高的效率和较简单的电路结构。该电路的基本原理是通过电容和开关来实现电荷的积累和转…

数据结构 堆

手写堆&#xff0c;而非stl中的堆 如何手写一个堆&#xff1f; //将数组建成堆 <O(n) for (int i n / 2;i;i--) //从n/2开始down down(i); 从n/2元素开始down&#xff0c;最下面一层元素的个数是n/2&#xff0c;其余上面的元素的个数是n/2&#xff0c;从最下面一层到最高层…

《数字图像处理-OpenCV/Python》连载(44)图像的投影变换

《数字图像处理-OpenCV/Python》连载&#xff08;44&#xff09;图像的投影变换 本书京东优惠购书链接&#xff1a;https://item.jd.com/14098452.html 本书CSDN独家连载专栏&#xff1a;https://blog.csdn.net/youcans/category_12418787.html 第 6 章 图像的几何变换 几何变…

Open AI开发者大会:AI“科技春晚”

ChatGPT的亮相即将满一年之时&#xff0c;OpenAI举行了自己的首次开发者大会。OpenAI首席执行官Sam Altman宣布推出最新的大模型GPT-4 Turbo。正如“Turbo”一词的中文含义“涡轮增压器”一样&#xff0c;本次发布会上&#xff0c;OpenAI的这款最新大模型在长文本、知识库、多模…

V100 GPU服务器安装GPU驱动教程

大家好,我是爱编程的喵喵。双985硕士毕业,现担任全栈工程师一职,热衷于将数据思维应用到工作与生活中。从事机器学习以及相关的前后端开发工作。曾在阿里云、科大讯飞、CCF等比赛获得多次Top名次。现为CSDN博客专家、人工智能领域优质创作者。喜欢通过博客创作的方式对所学的…
最新文章