-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
417 lines (366 loc) · 15.3 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>WebGPU Life</title>
</head>
<body>
<canvas width="512" height="512"></canvas>
<script type="module">
// Your WebGPU code will begin here!
const GRID_SIZE = 32;
const UPDATE_INTERVAL = 200;
const WORKGROUP_SIZE = 8;
let step = 0;
function updateGrid() {
// encoder is an interface that records gpu commands
// needs to be re-initialed each frame
const encoder = device.createCommandEncoder();
// compute pass runs before render pass so that the render pass can immediately
// use the latest results from the compute pass.
const computePass = encoder.beginComputePass();
computePass.setPipeline(simulationPipeline);
computePass.setBindGroup(0, bindGroups[step % 2]);
// instead of drawing like in render pass, we dispatch the work to the compute
// shader while defining how many workgroups you want to execute on each axis.
// this number corresponds to the @workgroup_size in the shader code
const workgroupCount = Math.ceil(GRID_SIZE / WORKGROUP_SIZE);
computePass.dispatchWorkgroups(workgroupCount, workgroupCount);
computePass.end();
// step is incremented after compute pass so that the output buffer becomes
// the input buffer between compute and render passes.
step++;
// All render passes start with a `beginRenderPass()` call.
// It defines the textures that receive output of a command.
// begin recording commands
const pass = encoder.beginRenderPass({
colorAttachments: [{
// defining "where" (which view) the rendered output must go to
view: context.getCurrentTexture().createView(),
// what to do when render pass starts
loadOp: "clear",
// set clear value
clearValue: [0, 0, 0.4, 1.0],
// what to do when render pass ends
storeOp: "store"
}]
})
// set which pipeline should be used
pass.setPipeline(cellPipeline)
// bind grid size uniform
pass.setBindGroup(0, bindGroups[step & 1]);
console.log(step)
// set the buffer that contains the vertices
pass.setVertexBuffer(0, vertexBuffer) // 0 for the index of the element in vertexBuffer
// draw triangle for n vertices
pass.draw(vertices.length / 2, GRID_SIZE * GRID_SIZE)
// stop recording commands
pass.end()
// // create a command buffer
// const commandBuffer = encoder.finish();
// // submit the command buffer to the gpu device's queue
// device.queue.submit([commandBuffer]);
// // commandBuffer is now useless, so instead, this is often done:
device.queue.submit([encoder.finish()])
}
// check if webgpu is supported
if (!navigator.gpu) {
throw new Error("WebGPU not supported on this browser!")
}
// check if gpu is available
const adapter = await navigator.gpu.requestAdapter()
if (!adapter) {
throw new Error("No appropriate GPU found.")
}
// request a gpu
const device = await adapter.requestDevice();
// Error logging (check https://toji.dev/webgpu-best-practices/error-handling)
// This example is pulled directly from the spec.
device.pushErrorScope('validation');
device.popErrorScope().then((error) => {
if (error) {
// There was an error creating the sampler, so discard it.
sampler = null;
console.error(`An error occured while creating sampler: ${error.message}`);
}
});
// get canvas element and get webgpu context
const canvas = document.querySelector("canvas");
const context = canvas.getContext("webgpu");
// returns optimal texture format
const canvasFormat = navigator.gpu.getPreferredCanvasFormat();
// context returned by canvas must be configured
context.configure({device, format: canvasFormat});
const vertices = new Float32Array([
// X, Y,
-0.8, -0.8, // Triangle 1 (Blue)
0.8, -0.8,
0.8, 0.8,
-0.8, -0.8, // Triangle 2 (Red)
0.8, 0.8,
-0.8, 0.8,
]);
// create a gpu buffer for the vertices
const vertexBuffer = device.createBuffer({
// optional label for each buffer
label: "Cell vertices",
// bytes of memory to be allocated
size: vertices.byteLength,
// bitwise flags to be passed for usage of buffer
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST
});
// copy data into device buffer memory
device.queue.writeBuffer(vertexBuffer, 0, vertices);
// create a uniform buffer for the grid
const uniformArray = new Float32Array([GRID_SIZE, GRID_SIZE]);
const uniformBuffer = device.createBuffer({
label: "Grid Uniforms",
size: uniformArray.byteLength,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
});
device.queue.writeBuffer(uniformBuffer, 0, uniformArray);
// create a storage buffer to store dynamically sized arrays
const cellStateArray = new Uint32Array(GRID_SIZE * GRID_SIZE);
const cellStateBuffer = [
device.createBuffer({
label: "Cell State A Storage",
size: cellStateArray.byteLength,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
}),
device.createBuffer({
label: "Cell State B Storage",
size: cellStateArray.byteLength,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
})
];
for (let i = 0; i < cellStateArray.length; i += 3) {
cellStateArray[i] = Math.random() <= 0.5 ? 0 : 1;
}
device.queue.writeBuffer(cellStateBuffer[0], 0, cellStateArray);
// define the vertex layout
const vertexBufferLayout = {
// bytes in an element (float32x2 => 32*2 = 8 * (4 * 2) )
arrayStride: 4 * 2,
// info regarding each element (here, a vertex)
attributes: [
{
// for available formats check GPUVertexFormat
format: "float32x2",
// bytes to skip in the element to get to the attribute
offset: 0,
// pointer to location of variable in shader (between 0 and 15)
shaderLocation: 0
}
]
}
// shaders
const cellShaderModule = device.createShaderModule({
label: "Cell Shader",
code: `
// shader code
// WSGL runs shader functions in parallel, meaning vertices are processed non-sequentially.
// Each vertex shader functions receives a single vertex (from the buffer) as an argument,
// and produces the output for a single vertex.
// using structs to pass data from vertex shader to fragment shader
struct VtxIn{
@location(0) vtxPos: vec2f,
@builtin(instance_index) instance: u32
};
struct VtxOut{
@builtin(position) vtxPos: vec4f,
@location(0) cell: vec2f
};
// an alternate method when shader and fragment code is not in the same place
struct FragIn{
@location(0) cell: vec2f
};
// declaring grid uniform
@group(0) @binding(0) var<uniform> grid: vec2f;
@group(0) @binding(1) var<storage> cellState: array<u32>;
// The type of a function (declared by 'fn') is defined by the attribute before it.
// for vertex shader, it is '@vertex', and this function MUST return the position of the
// transformed vertex by setting the built-in attribute 'position' to the final value.
// The vertex shader is responsible for transforming the world coordinates to clip space,
// and passes them to the rasterizer, which is responsible for finding the pixels within
// the transformed triangle in the clip space. However, the pixels have not yet been colored.
@vertex
fn vertexMain(vtxData: VtxIn) ->
VtxOut {
let i = f32(vtxData.instance);
let cell = vec2f(i % grid.y, floor(i / grid.x));
let state = f32(cellState[vtxData.instance]);
let cellOffset = (cell / grid) * 2;
let gridPos = ((vtxData.vtxPos * state + 1) / grid) - 1 + cellOffset;
var output: VtxOut;
output.vtxPos = vec4f(gridPos, 0, 1);
output.cell = cell;
return output;
}
// The fragment shader is responsible for coloring each pixel that the rasterizer picks.
// The fragment shader returns the color the pixel should be colored
@fragment
fn fragmentMain(vtxData: VtxOut) -> @location(0) vec4f {
var c = vtxData.cell / grid;
return vec4f(c, 1-c.x, 1);
}
`
})
// compute shader
const computeShaderModule = device.createShaderModule({
label: "Game of Life Simulation c-shader",
code: `
@group(0) @binding(0) var<uniform> grid: vec2f;
// compute shaders do not have any standard output, hence the output must be captured
// through in a texture or buffer. Ping-Pong method can be used in this case.
// var<storage> is a read-only bufer
@group(0) @binding(1) var<storage> cellStateIn: array<u32>;
// var<storage, read_write> allows both read and write
@group(0) @binding(2) var<storage, read_write> cellStateOut: array<u32>;
// cell-mapping function to translate (x,y) into n;
fn cellIndex(cell: vec2u) -> u32 {
return (cell.y % u32(grid.y)) * u32(grid.x) + (cell.x % u32(grid.x));
}
// get value in cell
fn cellActive(x: u32, y: u32) -> u32{
return cellStateIn[cellIndex(vec2(x, y))];
}
@compute
@workgroup_size(${WORKGROUP_SIZE}, ${WORKGROUP_SIZE})
fn computeMain(@builtin(global_invocation_id) cell: vec3u){
// determine how many neighboring cells are active
let activeNeighbors = cellActive(cell.x+1, cell.y+1) +
cellActive(cell.x+1, cell.y) +
cellActive(cell.x+1, cell.y-1) +
cellActive(cell.x, cell.y-1) +
cellActive(cell.x-1, cell.y-1) +
cellActive(cell.x-1, cell.y) +
cellActive(cell.x-1, cell.y+1) +
cellActive(cell.x, cell.y+1);
// // accessing x and y attributes using cell.xy is same as vec2(cell.x, cell.y), which is known as coordinate sizzling
// if(cellStateIn[cellIndex(cell.xy)] == 1){
// cellStateOut[cellIndex(cell.xy)] = 0;
// } else {
// cellStateOut[cellIndex(cell.xy)] = 1;
// }
let i = cellIndex(cell.xy);
switch activeNeighbors {
case 2: { // cell with 2 neighbors exactly stay active
cellStateOut[i] = cellStateIn[i];
}
case 3: { // cell with 3 neighbors exactly become active
cellStateOut[i] = 1;
}
default: { // else, they become inactive
cellStateOut[i] = 0;
}
}
}
`
})
// bind group layout must be manually defined (instead "auto") when multiple pipelines are being used
// and they share a bind group
const bindGroupLayout = device.createBindGroupLayout({
label: "Cell Bind Group Layout",
entries: [{
// the binding attribute corresponds to the @binding() value in the shader code
binding: 0,
visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT | GPUShaderStage.COMPUTE,
buffer: {} // Grid uniform buffer
}, {
binding: 1,
visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT | GPUShaderStage.COMPUTE,
buffer: {type: "read-only-storage"}
}, {
binding: 2,
visibility: GPUShaderStage.COMPUTE,
buffer: {type: "storage"}
}]
})
// to bind the uniform buffer to the shader
const bindGroups = [
device.createBindGroup({
label: "Cell renderer bind group A",
// '0' corresponds to the @group(0) in the shader
layout: bindGroupLayout,
entries: [
{
// '0' corresponds to the @binding(0) in the shader
binding: 0,
// where the actual resource (buffer) is located
resource: {buffer: uniformBuffer}
},
{
binding: 1,
resource: {buffer: cellStateBuffer[0]}
},
{
binding: 2,
resource: {buffer: cellStateBuffer[1]}
}
]
}),
device.createBindGroup({
label: "Cell renderer bind group B",
// '0' corresponds to the @group(0) in the shader
layout: bindGroupLayout,
entries: [
{
// '0' corresponds to the @binding(0) in the shader
binding: 0,
// where the actual resource (buffer) is located
resource: {buffer: uniformBuffer}
},
{
binding: 1,
resource: {buffer: cellStateBuffer[1]}
},
{
binding: 2,
resource: {buffer: cellStateBuffer[0]}
}
]
})
]
// defining the pipeline layout
const pipelineLayout = device.createPipelineLayout({
label: "Cell Pipeline Layout",
// the order of bind group layouts correspond to the @group() in the shader code
bindGroupLayouts: [bindGroupLayout]
});
// render pipeline
const cellPipeline = device.createRenderPipeline({
label: "Cell pipeline",
// what types of input the pipeline needs
layout: pipelineLayout,
// vertex stage definition
vertex: {
// where shader code is defined
module: cellShaderModule,
// name of function that should be run first
entryPoint: "vertexMain",
// how data is packed into your buffers
buffers: [vertexBufferLayout]
},
fragment: {
module: cellShaderModule,
entryPoint: "fragmentMain",
// details of the output format
targets: [{
// must match textures given in colorAttachments
format: canvasFormat
}]
}
});
// create the compute pipeline
const simulationPipeline = device.createComputePipeline({
label: "Simulation Pipeline",
layout: pipelineLayout,
compute: {
module: computeShaderModule,
entryPoint: "computeMain"
}
});
setInterval(updateGrid, UPDATE_INTERVAL);
</script>
</body>
</html>