forked from webgpu/webgpu-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
384 lines (349 loc) · 10.7 KB
/
main.ts
File metadata and controls
384 lines (349 loc) · 10.7 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
import { mat4, vec3 } from 'wgpu-matrix';
import { GUI } from 'dat.gui';
import normalMapWGSL from './normalMap.wgsl';
import { createMeshRenderable } from '../../meshes/mesh';
import { createBoxMeshWithTangents } from '../../meshes/box';
import {
createBindGroupDescriptor,
create3DRenderPipeline,
createTextureFromImage,
} from './utils';
import { quitIfWebGPUNotAvailableOrMissingFeatures } from '../util';
const MAT4X4_BYTES = 64;
enum TextureAtlas {
Spiral,
Toybox,
BrickWall,
}
const canvas = document.querySelector('canvas') as HTMLCanvasElement;
const adapter = await navigator.gpu?.requestAdapter({
featureLevel: 'compatibility',
});
const device = await adapter?.requestDevice();
quitIfWebGPUNotAvailableOrMissingFeatures(adapter, device);
const context = canvas.getContext('webgpu');
const devicePixelRatio = window.devicePixelRatio;
canvas.width = canvas.clientWidth * devicePixelRatio;
canvas.height = canvas.clientHeight * devicePixelRatio;
const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
context.configure({
device,
format: presentationFormat,
});
interface GUISettings {
'Bump Mode':
| 'Albedo Texture'
| 'Normal Texture'
| 'Depth Texture'
| 'Normal Map'
| 'Parallax Scale'
| 'Steep Parallax';
cameraPosX: number;
cameraPosY: number;
cameraPosZ: number;
lightPosX: number;
lightPosY: number;
lightPosZ: number;
lightIntensity: number;
depthScale: number;
depthLayers: number;
Texture: string;
'Reset Light': () => void;
}
const settings: GUISettings = {
'Bump Mode': 'Normal Map',
cameraPosX: 0.0,
cameraPosY: 0.8,
cameraPosZ: -1.4,
lightPosX: 1.7,
lightPosY: 0.7,
lightPosZ: -1.9,
lightIntensity: 5.0,
depthScale: 0.05,
depthLayers: 16,
Texture: 'Spiral',
'Reset Light': () => {
return;
},
};
// Create normal mapping resources and pipeline
const depthTexture = device.createTexture({
size: [canvas.width, canvas.height],
format: 'depth24plus',
usage: GPUTextureUsage.RENDER_ATTACHMENT,
});
const spaceTransformsBuffer = device.createBuffer({
// Buffer holding projection, view, and model matrices plus padding bytes
size: MAT4X4_BYTES * 4,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
const mapInfoBuffer = device.createBuffer({
// Buffer holding mapping type, light uniforms, and depth uniforms
size: Float32Array.BYTES_PER_ELEMENT * 8,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
const mapInfoArray = new ArrayBuffer(mapInfoBuffer.size);
const mapInfoView = new DataView(mapInfoArray, 0, mapInfoArray.byteLength);
// Fetch the image and upload it into a GPUTexture.
let woodAlbedoTexture: GPUTexture;
{
const response = await fetch('../../assets/img/wood_albedo.png');
const imageBitmap = await createImageBitmap(await response.blob());
woodAlbedoTexture = createTextureFromImage(device, imageBitmap);
}
let spiralNormalTexture: GPUTexture;
{
const response = await fetch('../../assets/img/spiral_normal.png');
const imageBitmap = await createImageBitmap(await response.blob());
spiralNormalTexture = createTextureFromImage(device, imageBitmap);
}
let spiralHeightTexture: GPUTexture;
{
const response = await fetch('../../assets/img/spiral_height.png');
const imageBitmap = await createImageBitmap(await response.blob());
spiralHeightTexture = createTextureFromImage(device, imageBitmap);
}
let toyboxNormalTexture: GPUTexture;
{
const response = await fetch('../../assets/img/toybox_normal.png');
const imageBitmap = await createImageBitmap(await response.blob());
toyboxNormalTexture = createTextureFromImage(device, imageBitmap);
}
let toyboxHeightTexture: GPUTexture;
{
const response = await fetch('../../assets/img/toybox_height.png');
const imageBitmap = await createImageBitmap(await response.blob());
toyboxHeightTexture = createTextureFromImage(device, imageBitmap);
}
let brickwallAlbedoTexture: GPUTexture;
{
const response = await fetch('../../assets/img/brickwall_albedo.png');
const imageBitmap = await createImageBitmap(await response.blob());
brickwallAlbedoTexture = createTextureFromImage(device, imageBitmap);
}
let brickwallNormalTexture: GPUTexture;
{
const response = await fetch('../../assets/img/brickwall_normal.png');
const imageBitmap = await createImageBitmap(await response.blob());
brickwallNormalTexture = createTextureFromImage(device, imageBitmap);
}
let brickwallHeightTexture: GPUTexture;
{
const response = await fetch('../../assets/img/brickwall_height.png');
const imageBitmap = await createImageBitmap(await response.blob());
brickwallHeightTexture = createTextureFromImage(device, imageBitmap);
}
// Create a sampler with linear filtering for smooth interpolation.
const sampler = device.createSampler({
magFilter: 'linear',
minFilter: 'linear',
});
const renderPassDescriptor: GPURenderPassDescriptor = {
colorAttachments: [
{
view: undefined, // Assigned later
clearValue: [0, 0, 0, 1],
loadOp: 'clear',
storeOp: 'store',
},
],
depthStencilAttachment: {
view: depthTexture.createView(),
depthClearValue: 1.0,
depthLoadOp: 'clear',
depthStoreOp: 'store',
},
};
const box = createMeshRenderable(
device,
createBoxMeshWithTangents(1.0, 1.0, 1.0)
);
// Uniform bindGroups and bindGroupLayout
const frameBGDescriptor = createBindGroupDescriptor(
[0, 1],
[
GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
GPUShaderStage.FRAGMENT | GPUShaderStage.VERTEX,
],
['buffer', 'buffer'],
[{ type: 'uniform' }, { type: 'uniform' }],
[[{ buffer: spaceTransformsBuffer }, { buffer: mapInfoBuffer }]],
'Frame',
device
);
// Texture bindGroups and bindGroupLayout
const surfaceBGDescriptor = createBindGroupDescriptor(
[0, 1, 2, 3],
[GPUShaderStage.FRAGMENT],
['sampler', 'texture', 'texture', 'texture'],
[
{ type: 'filtering' },
{ sampleType: 'float' },
{ sampleType: 'float' },
{ sampleType: 'float' },
],
// Multiple bindgroups that accord to the layout defined above
[
[
sampler,
woodAlbedoTexture.createView(),
spiralNormalTexture.createView(),
spiralHeightTexture.createView(),
],
[
sampler,
woodAlbedoTexture.createView(),
toyboxNormalTexture.createView(),
toyboxHeightTexture.createView(),
],
[
sampler,
brickwallAlbedoTexture.createView(),
brickwallNormalTexture.createView(),
brickwallHeightTexture.createView(),
],
],
'Surface',
device
);
const aspect = canvas.width / canvas.height;
const projectionMatrix = mat4.perspective((2 * Math.PI) / 5, aspect, 0.1, 10.0);
function getViewMatrix() {
return mat4.lookAt(
[settings.cameraPosX, settings.cameraPosY, settings.cameraPosZ],
[0, 0, 0],
[0, 1, 0]
);
}
function getModelMatrix() {
const modelMatrix = mat4.create();
mat4.identity(modelMatrix);
const now = Date.now() / 1000;
mat4.rotateY(modelMatrix, now * -0.5, modelMatrix);
return modelMatrix;
}
// Change the model mapping type
const getMode = (): number => {
switch (settings['Bump Mode']) {
case 'Albedo Texture':
return 0;
case 'Normal Texture':
return 1;
case 'Depth Texture':
return 2;
case 'Normal Map':
return 3;
case 'Parallax Scale':
return 4;
case 'Steep Parallax':
return 5;
}
};
const texturedCubePipeline = create3DRenderPipeline(
device,
'NormalMappingRender',
[frameBGDescriptor.bindGroupLayout, surfaceBGDescriptor.bindGroupLayout],
normalMapWGSL,
// Position, normal uv tangent bitangent
['float32x3', 'float32x3', 'float32x2', 'float32x3', 'float32x3'],
normalMapWGSL,
presentationFormat,
true
);
let currentSurfaceBindGroup = 0;
const onChangeTexture = () => {
currentSurfaceBindGroup = TextureAtlas[settings.Texture];
};
const gui = new GUI();
gui.add(settings, 'Bump Mode', [
'Albedo Texture',
'Normal Texture',
'Depth Texture',
'Normal Map',
'Parallax Scale',
'Steep Parallax',
]);
gui
.add(settings, 'Texture', ['Spiral', 'Toybox', 'BrickWall'])
.onChange(onChangeTexture);
const lightFolder = gui.addFolder('Light');
const depthFolder = gui.addFolder('Depth');
lightFolder.add(settings, 'Reset Light').onChange(() => {
lightPosXController.setValue(1.7);
lightPosYController.setValue(0.7);
lightPosZController.setValue(-1.9);
lightIntensityController.setValue(5.0);
});
const lightPosXController = lightFolder
.add(settings, 'lightPosX', -5, 5)
.step(0.1);
const lightPosYController = lightFolder
.add(settings, 'lightPosY', -5, 5)
.step(0.1);
const lightPosZController = lightFolder
.add(settings, 'lightPosZ', -5, 5)
.step(0.1);
const lightIntensityController = lightFolder
.add(settings, 'lightIntensity', 0.0, 10)
.step(0.1);
depthFolder.add(settings, 'depthScale', 0.0, 0.1).step(0.01);
depthFolder.add(settings, 'depthLayers', 1, 32).step(1);
function frame() {
// Update spaceTransformsBuffer
const viewMatrix = getViewMatrix();
const worldViewMatrix = mat4.mul(viewMatrix, getModelMatrix());
const worldViewProjMatrix = mat4.mul(projectionMatrix, worldViewMatrix);
const matrices = new Float32Array([
...worldViewProjMatrix,
...worldViewMatrix,
]);
// Update mapInfoBuffer
const lightPosWS = [
settings.lightPosX,
settings.lightPosY,
settings.lightPosZ,
];
const lightPosVS = vec3.transformMat4(lightPosWS, viewMatrix);
const mode = getMode();
device.queue.writeBuffer(
spaceTransformsBuffer,
0,
matrices.buffer,
matrices.byteOffset,
matrices.byteLength
);
// struct MapInfo {
// lightPosVS: vec3f,
// mode: u32,
// lightIntensity: f32,
// depthScale: f32,
// depthLayers: f32,
// }
mapInfoView.setFloat32(0, lightPosVS[0], true);
mapInfoView.setFloat32(4, lightPosVS[1], true);
mapInfoView.setFloat32(8, lightPosVS[2], true);
mapInfoView.setUint32(12, mode, true);
mapInfoView.setFloat32(16, settings.lightIntensity, true);
mapInfoView.setFloat32(20, settings.depthScale, true);
mapInfoView.setFloat32(24, settings.depthLayers, true);
device.queue.writeBuffer(mapInfoBuffer, 0, mapInfoArray);
renderPassDescriptor.colorAttachments[0].view = context
.getCurrentTexture()
.createView();
const commandEncoder = device.createCommandEncoder();
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
// Draw textured Cube
passEncoder.setPipeline(texturedCubePipeline);
passEncoder.setBindGroup(0, frameBGDescriptor.bindGroups[0]);
passEncoder.setBindGroup(
1,
surfaceBGDescriptor.bindGroups[currentSurfaceBindGroup]
);
passEncoder.setVertexBuffer(0, box.vertexBuffer);
passEncoder.setIndexBuffer(box.indexBuffer, 'uint16');
passEncoder.drawIndexed(box.indexCount);
passEncoder.end();
device.queue.submit([commandEncoder.finish()]);
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);