generated from gnikoloff/frontend-boilerplate
/
index.ts
400 lines (338 loc) · 10.5 KB
/
index.ts
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
import {
PerspectiveCamera,
GeometryUtils,
CameraController,
SceneObject,
} from '../../lib/hwoa-rang-gpu'
import { testForWebGPUSupport } from '../shared/test-for-webgpu-support'
import VERTEX_SHADER from './shader.vert.wglsl'
import FRAGMENT_SHADER from './shader.frag.wglsl'
import '../index.css'
const SAMPLE_COUNT = 4
testForWebGPUSupport()
class RenderNode extends SceneObject {
device: GPUDevice = null
indexBuffer: GPUBuffer = null
indices: Uint16Array | Uint32Array = null
transformUniformBuffer: GPUBuffer = null
transformUniformBindGroup: GPUBindGroup = null
materialUniformBuffer: GPUBuffer = null
materialUniformBindGroup: GPUBindGroup = null
geoBuffers: Array<GPUBuffer> = []
constructor(device, pipeline, geometry) {
super()
this.device = device
const { vertices, uv, normal, indices } = geometry
const vertexBuffer = device.createBuffer({
size: vertices.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
mappedAtCreation: true,
})
new Float32Array(vertexBuffer.getMappedRange()).set(vertices)
vertexBuffer.unmap()
const normalBuffer = device.createBuffer({
size: normal.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
mappedAtCreation: true,
})
new Float32Array(normalBuffer.getMappedRange()).set(normal)
normalBuffer.unmap()
const uvBuffer = device.createBuffer({
size: uv.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
mappedAtCreation: true,
})
new Float32Array(uvBuffer.getMappedRange()).set(uv)
uvBuffer.unmap()
const indexBuffer = device.createBuffer({
size: indices.byteLength,
usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST,
mappedAtCreation: true,
})
if (indices instanceof Uint16Array) {
new Uint16Array(indexBuffer.getMappedRange()).set(indices)
} else {
new Uint32Array(indexBuffer.getMappedRange()).set(indices)
}
indexBuffer.unmap()
this.geoBuffers = [vertexBuffer, normalBuffer, uvBuffer]
this.indexBuffer = indexBuffer
this.indices = indices
this.transformUniformBuffer = device.createBuffer({
size: 16 * Float32Array.BYTES_PER_ELEMENT,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
})
this.transformUniformBindGroup = device.createBindGroup({
layout: pipeline.getBindGroupLayout(1),
entries: [
{
binding: 0,
resource: {
buffer: this.transformUniformBuffer,
},
},
],
})
this.materialUniformBuffer = device.createBuffer({
size: 3 * Float32Array.BYTES_PER_ELEMENT,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
})
const r = Math.random() * 0.35 + 0.65
const g = Math.random() * 0.35 + 0.65
const b = Math.random() * 0.35 + 0.65
device.queue.writeBuffer(
this.materialUniformBuffer,
0,
new Float32Array([r, g, b]),
)
this.materialUniformBindGroup = device.createBindGroup({
layout: pipeline.getBindGroupLayout(2),
entries: [
{
binding: 0,
resource: {
buffer: this.materialUniformBuffer,
},
},
],
})
}
render = (renderPass) => {
this.geoBuffers.forEach((buffer, i) => {
renderPass.setVertexBuffer(i, buffer)
})
renderPass.setIndexBuffer(
this.indexBuffer,
this.indices instanceof Uint16Array ? 'uint16' : 'uint32',
)
this.device.queue.writeBuffer(
this.transformUniformBuffer,
0,
this.worldMatrix as ArrayBuffer,
)
renderPass.setBindGroup(1, this.transformUniformBindGroup)
renderPass.setBindGroup(2, this.materialUniformBindGroup)
renderPass.drawIndexed(this.indices.length)
}
}
;(async () => {
const canvas = document.getElementById('gpu-c') as HTMLCanvasElement
canvas.width = innerWidth * devicePixelRatio
canvas.height = innerHeight * devicePixelRatio
canvas.style.setProperty('width', `${innerWidth}px`)
canvas.style.setProperty('height', `${innerHeight}px`)
const adapter = await navigator.gpu?.requestAdapter()
const device = await adapter?.requestDevice()
const context = canvas.getContext('webgpu')
const presentationFormat = context.getPreferredFormat(adapter)
const primitiveType = 'triangle-list'
context.configure({
device,
format: presentationFormat,
})
const pipeline = device.createRenderPipeline({
vertex: {
module: device.createShaderModule({
code: VERTEX_SHADER,
}),
entryPoint: 'main',
buffers: [
{
arrayStride: 3 * Float32Array.BYTES_PER_ELEMENT,
attributes: [
{
shaderLocation: 0,
format: 'float32x3',
offset: 0,
},
],
},
{
arrayStride: 3 * Float32Array.BYTES_PER_ELEMENT,
attributes: [
{
shaderLocation: 1,
format: 'float32x3',
offset: 0,
},
],
},
{
arrayStride: 2 * Float32Array.BYTES_PER_ELEMENT,
attributes: [
{
shaderLocation: 2,
format: 'float32x2',
offset: 0,
},
],
},
],
},
fragment: {
module: device.createShaderModule({
code: FRAGMENT_SHADER,
}),
entryPoint: 'main',
targets: [
{
format: presentationFormat,
},
],
},
primitive: {
topology: primitiveType,
stripIndexFormat: undefined,
// cullMode: 'back',
},
multisample: {
count: SAMPLE_COUNT,
},
depthStencil: {
format: 'depth24plus',
depthWriteEnabled: true,
depthCompare: 'less',
},
})
const sphereGeometry = GeometryUtils.createSphere({ radius: 1 })
const sunNodeOrbit = new SceneObject()
const sunNode = new RenderNode(device, pipeline, sphereGeometry)
sunNode.setParent(sunNodeOrbit)
const earthOrbitNode = new SceneObject()
earthOrbitNode.setParent(sunNodeOrbit)
const earthNode = new RenderNode(device, pipeline, sphereGeometry)
earthNode.setParent(earthOrbitNode)
const moonOrbitNode = new SceneObject()
moonOrbitNode.setParent(earthOrbitNode)
const moonNode = new RenderNode(device, pipeline, sphereGeometry)
moonNode.setParent(moonOrbitNode)
const moonSatelliteOrbitNode = new SceneObject()
moonSatelliteOrbitNode.setParent(moonOrbitNode)
const moonSatelliteNode = new RenderNode(device, pipeline, sphereGeometry)
moonSatelliteNode.setParent(moonSatelliteOrbitNode)
const satellite0OrbitNode = new SceneObject()
satellite0OrbitNode.setParent(sunNodeOrbit)
const satellite0Node = new RenderNode(device, pipeline, sphereGeometry)
satellite0Node.setParent(satellite0OrbitNode)
const satellite1OrbitNode = new SceneObject()
satellite1OrbitNode.setParent(satellite0OrbitNode)
const satellite1Node = new RenderNode(device, pipeline, sphereGeometry)
satellite1Node.setParent(satellite1OrbitNode)
const cameraUniformBuffer = device.createBuffer({
size: 16 * 2 * Float32Array.BYTES_PER_ELEMENT,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
})
const cameraUniformBindGroup = device.createBindGroup({
layout: pipeline.getBindGroupLayout(0),
entries: [
{
binding: 0,
resource: {
buffer: cameraUniformBuffer,
},
},
],
})
const perspCamera = new PerspectiveCamera(
(45 * Math.PI) / 180,
canvas.width / canvas.height,
0.1,
500,
)
perspCamera.setPosition({ x: 0, y: -30, z: 42 })
perspCamera.lookAt([0, 0, 0])
perspCamera.updateProjectionMatrix()
perspCamera.updateViewMatrix()
new CameraController(perspCamera)
const textureDepth = device.createTexture({
size: [canvas.width, canvas.height, 1],
format: 'depth24plus',
sampleCount: SAMPLE_COUNT,
usage: GPUTextureUsage.RENDER_ATTACHMENT,
})
const renderTexture = device.createTexture({
size: [canvas.width, canvas.height],
sampleCount: SAMPLE_COUNT,
format: presentationFormat,
usage: GPUTextureUsage.RENDER_ATTACHMENT,
})
let textureView = renderTexture.createView()
// let textureView
requestAnimationFrame(drawFrame)
function drawFrame(ts) {
requestAnimationFrame(drawFrame)
ts /= 1000
const commandEncoder = device.createCommandEncoder()
const renderPass = commandEncoder.beginRenderPass({
colorAttachments: [
{
view: textureView,
resolveTarget: context.getCurrentTexture().createView(),
loadValue: [0.1, 0.1, 0.1, 1.0],
storeOp: 'store',
},
],
depthStencilAttachment: {
view: textureDepth.createView(),
depthLoadValue: 1,
depthStoreOp: 'store',
stencilLoadValue: 0,
stencilStoreOp: 'store',
},
})
device.queue.writeBuffer(
cameraUniformBuffer,
0,
perspCamera.projectionMatrix as ArrayBuffer,
)
device.queue.writeBuffer(
cameraUniformBuffer,
16 * Float32Array.BYTES_PER_ELEMENT,
perspCamera.viewMatrix as ArrayBuffer,
)
renderPass.setBindGroup(0, cameraUniformBindGroup)
renderPass.setPipeline(pipeline)
sunNodeOrbit
.setPosition({ x: Math.sin(ts) * 4, y: Math.cos(ts) * 4 })
.setRotation({ z: ts })
.updateModelMatrix()
sunNode.updateModelMatrix()
earthOrbitNode
.setPosition({ x: 14 })
.setRotation({ z: ts * 2 })
.updateModelMatrix()
const earthScale = Math.sin(ts) * 1 + 1.5
earthNode
.setScale({
x: earthScale,
y: earthScale,
z: earthScale,
})
.updateModelMatrix()
moonOrbitNode
.setPosition({ x: 8 })
.setRotation({ z: ts * 4 })
.updateModelMatrix()
moonNode.setScale({ x: 0.8, y: 0.8, z: 0.8 }).updateModelMatrix()
moonSatelliteOrbitNode
.setPosition({ x: 2.5 })
.setScale({ x: 0.3, y: 0.3, z: 0.3 })
.updateModelMatrix()
satellite0OrbitNode
.setPosition({ x: -14 })
.setRotation({ z: ts * -3 })
.updateModelMatrix()
satellite0Node.setScale({ x: 0.3, y: 0.3, z: 0.3 }).updateModelMatrix()
satellite1OrbitNode.setPosition({ x: 5 }).updateModelMatrix()
sunNodeOrbit.updateWorldMatrix()
sunNode.render(renderPass)
earthNode.render(renderPass)
moonNode.render(renderPass)
moonSatelliteNode.render(renderPass)
satellite0Node.render(renderPass)
satellite1Node.render(renderPass)
renderPass.endPass()
device.queue.submit([commandEncoder.finish()])
}
})()
//