-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathwebgpu.html
More file actions
387 lines (337 loc) · 10.9 KB
/
webgpu.html
File metadata and controls
387 lines (337 loc) · 10.9 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0" />
<title>Stats-GL - WebGPU Demo</title>
<link rel="help" href="/llms.txt" type="text/plain" title="LLM Instructions">
<style>
body {
margin: 0;
overflow: hidden;
background: #000;
font-family: system-ui, -apple-system, sans-serif;
}
canvas {
width: 100vw;
height: 100vh;
}
.code-overlay {
position: absolute;
bottom: 0;
left: 0;
padding: 14px;
background-color: #1e1e1ef8;
color: #d4d4d4;
overflow: auto;
margin: 0;
font-family: 'Courier New', Courier, monospace;
@media screen and (max-width: 608px) {
display: none;
}
}
.nav-tabs {
display: flex;
gap: 1px;
margin-top: -14px;
position: absolute;
right: 0;
margin-bottom: 14px;
font-family: system-ui, -apple-system, sans-serif;
}
.nav-tab {
background: #1e1e1ef8;
color: #d4d4d4;
padding: 4px 8px;
text-decoration: none;
font-size: 12px;
transition: background-color 0.2s;
}
.nav-tab:hover {
background: #3d3d3d;
}
.nav-tab.active {
background: #3d3d3d;
}
pre {
margin: 0;
}
.keyword {
color: #569cd6;
}
.comment {
color: #6a9955;
}
.string {
color: #ce9178;
}
::selection {
background: #264f78;
}
#footer {
position: absolute;
bottom: 0;
right: 0;
color: #fff;
font-size: 14px;
padding: 14px;
text-align: right;
background-color: #1e1e1ef8;
}
#footer a {
color: #fff;
font-weight: bold;
text-decoration: none;
}
#twitter {
position: absolute;
bottom: 0;
right: 0;
}
#footer svg {
fill: #fff;
width: 14px;
height: 14px;
border: 0;
}
.error-message {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #ff6b6b;
font-size: 18px;
text-align: center;
padding: 20px;
background: rgba(0, 0, 0, 0.8);
border-radius: 8px;
}
</style>
</head>
<body>
<canvas id="gpucanvas"></canvas>
<div class="code-overlay">
<div class="nav-tabs">
<a href="/" class="nav-tab">Three.js</a>
<a href="/webgl.html" class="nav-tab">WebGL</a>
<a href="/webgpu.html" class="nav-tab active">WebGPU</a>
<a href="/worker.html" class="nav-tab">Worker</a>
<a href="/worker_tsl.html" class="nav-tab">Worker TSL</a>
</div>
<pre>
<span class="comment">// Native WebGPU example</span>
<span class="keyword">import</span> Stats <span class="keyword">from</span> <span class="string">'stats-gl'</span>
<span class="keyword">const</span> stats = <span class="keyword">new</span> Stats({ trackGPU: true });
<span class="keyword">await</span> stats.init(device);
document.body.appendChild(stats.dom);
<span class="keyword">function</span> render() {
<span class="keyword">const</span> encoder = device.createCommandEncoder();
stats.begin();
<span class="keyword">const</span> pass = encoder.beginRenderPass({
colorAttachments: [...],
timestampWrites: stats.getTimestampWrites()
});
<span class="comment">// draw calls</span>
pass.end();
stats.end(encoder);
device.queue.submit([encoder.finish()]);
stats.update();
requestAnimationFrame(render);
}</pre>
</div>
<div id="footer">
Made with love ❤️ by
<a
href="https://twitter.com/onirenaud"
target="_blank"
>@onirenaud</a
>
-
<a
href="https://twitter.com/utsuboco"
target="_blank"
>@utsuboco</a
>
</div>
<script type="module">
import Stats from './dist/main.js';
// import Stats from './lib/main.ts';
async function main() {
const canvas = document.querySelector('#gpucanvas');
// Check WebGPU support
if (!navigator.gpu) {
document.body.innerHTML = '<div class="error-message">WebGPU is not supported in this browser.<br>Try Chrome 113+ or Edge 113+.</div>';
return;
}
// Request adapter with timestamp-query feature
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) {
document.body.innerHTML = '<div class="error-message">Failed to get WebGPU adapter.</div>';
return;
}
// Check timestamp-query support
const hasTimestampQuery = adapter.features.has('timestamp-query');
const requiredFeatures = hasTimestampQuery ? ['timestamp-query'] : [];
const device = await adapter.requestDevice({
requiredFeatures
});
if (!hasTimestampQuery) {
console.warn('Stats-GL: timestamp-query not supported, GPU timing will not be available');
}
// Configure canvas
const context = canvas.getContext('webgpu');
const format = navigator.gpu.getPreferredCanvasFormat();
context.configure({
device,
format,
alphaMode: 'opaque'
});
// Initialize stats with native WebGPU device
const stats = new Stats({ trackGPU: true, trackHz: true });
await stats.init(device);
document.body.appendChild(stats.dom);
// Create shader module
const shaderModule = device.createShaderModule({
code: `
struct Uniforms {
rotation: f32,
aspect: f32,
}
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
struct VertexOutput {
@builtin(position) position: vec4f,
@location(0) uv: vec2f,
}
@vertex
fn vertexMain(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput {
// Triangle vertices
var positions = array<vec2f, 3>(
vec2f(0.0, 1.0), // top
vec2f(-0.866, -0.5), // bottom left
vec2f(0.866, -0.5) // bottom right
);
var uvs = array<vec2f, 3>(
vec2f(0.5, 0.0), // top
vec2f(0.0, 1.0), // bottom left
vec2f(1.0, 1.0) // bottom right
);
let pos = positions[vertexIndex];
let uv = uvs[vertexIndex];
// Apply rotation and aspect ratio
let scale = min(1.0, uniforms.aspect) * 0.5;
let c = cos(uniforms.rotation);
let s = sin(uniforms.rotation);
let rotated = vec2f(
pos.x * c - pos.y * s,
pos.x * s + pos.y * c
) * scale;
var output: VertexOutput;
output.position = vec4f(rotated.x / uniforms.aspect, rotated.y, 0.0, 1.0);
output.uv = uv;
return output;
}
@fragment
fn fragmentMain(@location(0) uv: vec2f) -> @location(0) vec4f {
// Create RGB from UV coordinates
return vec4f(uv.x, uv.y, 1.0 - (uv.x + uv.y) * 0.5, 1.0);
}
`
});
// Create uniform buffer
const uniformBuffer = device.createBuffer({
size: 8, // 2 floats
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
});
// Create bind group layout and pipeline layout
const bindGroupLayout = device.createBindGroupLayout({
entries: [{
binding: 0,
visibility: GPUShaderStage.VERTEX,
buffer: { type: 'uniform' }
}]
});
const pipelineLayout = device.createPipelineLayout({
bindGroupLayouts: [bindGroupLayout]
});
// Create render pipeline
const pipeline = device.createRenderPipeline({
layout: pipelineLayout,
vertex: {
module: shaderModule,
entryPoint: 'vertexMain'
},
fragment: {
module: shaderModule,
entryPoint: 'fragmentMain',
targets: [{ format }]
},
primitive: {
topology: 'triangle-list'
}
});
// Create bind group
const bindGroup = device.createBindGroup({
layout: bindGroupLayout,
entries: [{
binding: 0,
resource: { buffer: uniformBuffer }
}]
});
// Animation variables
let rotation = 0;
let lastTime = 0;
function render(currentTime = 0) {
// Update rotation
const deltaTime = (currentTime - lastTime) * 0.001;
lastTime = currentTime;
rotation += deltaTime;
// Resize canvas to match display size with devicePixelRatio
const dpr = window.devicePixelRatio || 1;
const displayWidth = Math.floor(canvas.clientWidth * dpr);
const displayHeight = Math.floor(canvas.clientHeight * dpr);
if (canvas.width !== displayWidth || canvas.height !== displayHeight) {
canvas.width = displayWidth;
canvas.height = displayHeight;
}
const aspect = displayWidth / displayHeight;
// Update uniforms
const uniformData = new Float32Array([rotation, aspect]);
device.queue.writeBuffer(uniformBuffer, 0, uniformData);
// Create command encoder
const encoder = device.createCommandEncoder();
// Begin CPU timing
stats.begin();
// Begin render pass with timestampWrites for GPU timing
const pass = encoder.beginRenderPass({
colorAttachments: [{
view: context.getCurrentTexture().createView(),
loadOp: 'clear',
storeOp: 'store',
clearValue: { r: 0.1, g: 0.1, b: 0.1, a: 1.0 }
}],
timestampWrites: stats.getTimestampWrites()
});
pass.setPipeline(pipeline);
pass.setBindGroup(0, bindGroup);
pass.draw(3);
pass.end();
// End timing and resolve GPU timestamps
stats.end(encoder);
// Submit commands
device.queue.submit([encoder.finish()]);
// Update stats display
stats.update();
requestAnimationFrame(render);
}
// Start animation
render();
}
main().catch(err => {
console.error('WebGPU initialization failed:', err);
document.body.innerHTML = `<div class="error-message">WebGPU initialization failed:<br>${err.message}</div>`;
});
</script>
</body>
</html>