-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRenderer.ts
More file actions
562 lines (548 loc) · 18 KB
/
Renderer.ts
File metadata and controls
562 lines (548 loc) · 18 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
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
import type * as Types from '@app/Types.ts'
import Font from '@app/Font.ts'
import Shaders from '@app/Shaders.ts'
/** Render target texture format. */
const textureFormat: GPUTextureFormat = 'rgba8unorm'
/**
* GPU pipelines and draw commands.
* @description WebGPU draw operations in one place.
*/
export default class Renderer {
/**
* Sets up GPU device and texture.
* @description Adapter, device, render target texture.
* @param width - Texture width in pixels
* @param height - Texture height in pixels
* @returns GpuContext
*/
static async createGpuContext(width: number, height: number): Promise<Types.GpuContext> {
const adapter = await navigator.gpu.requestAdapter()
if (!adapter) {
throw new Error('WebGPU adapter not available')
}
const device = await adapter.requestDevice()
const texture = device.createTexture({
size: { width, height },
format: textureFormat,
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
})
return { device, texture, width, height }
}
/**
* Draws axis and grid segments.
* @description Line pass for axis or grid.
* @param device - GPUDevice
* @param encoder - Command encoder
* @param view - Texture view
* @param segments - Line segments
* @param canvasWidth - Canvas width
* @param canvasHeight - Canvas height
* @param hexColor - Hex color
* @returns void
*/
static drawAxisLines(
device: GPUDevice,
encoder: GPUCommandEncoder,
view: GPUTextureView,
segments: Types.AxisSegment[],
canvasWidth: number,
canvasHeight: number,
hexColor: string
): void {
if (segments.length === 0) {
return
}
const pipeline = Renderer.createLinePipeline(device, Shaders.axisVertex, Shaders.colorFragment)
const axisColor = Renderer.hexToColor(hexColor)
const uniformData = new Float32Array([
canvasWidth,
canvasHeight,
0,
0,
axisColor.r,
axisColor.g,
axisColor.b,
axisColor.a
])
const uniformBuffer = Renderer.makeUniformBuffer(device, uniformData)
const segmentData = new Float32Array(
segments.flatMap((segment) => [segment.x0, segment.y0, segment.x1, segment.y1])
)
const storageBuffer = Renderer.makeStorageBuffer(device, segmentData)
const bindGroup = device.createBindGroup({
layout: pipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: uniformBuffer } },
{ binding: 1, resource: { buffer: storageBuffer } }
]
})
const renderPass = encoder.beginRenderPass({
colorAttachments: [{ view, loadOp: 'load', storeOp: 'store' }]
})
renderPass.setPipeline(pipeline)
renderPass.setBindGroup(0, bindGroup)
renderPass.draw(segments.length * 6)
renderPass.end()
}
/**
* Fills render target background.
* @description Clear or load with color.
* @param encoder - Command encoder
* @param view - Texture view
* @param color - Fill color
* @param load - Load operation
* @returns void
*/
static drawBackground(
encoder: GPUCommandEncoder,
view: GPUTextureView,
color: Types.Color,
load: GPULoadOp = 'clear'
): void {
const renderPass = encoder.beginRenderPass({
colorAttachments: [
{
view,
clearValue: { r: color.r, g: color.g, b: color.b, a: color.a },
loadOp: load,
storeOp: 'store'
}
]
})
renderPass.end()
}
/**
* Draws digit glyphs for axis labels.
* @description SDF digit pass for tick labels.
* @param device - GPUDevice
* @param encoder - Command encoder
* @param view - Texture view
* @param glyphs - Digit glyphs
* @param canvasWidth - Canvas width
* @param canvasHeight - Canvas height
* @param hexColor - Hex color
* @returns void
*/
static drawDigits(
device: GPUDevice,
encoder: GPUCommandEncoder,
view: GPUTextureView,
glyphs: Types.GlyphInstance[],
canvasWidth: number,
canvasHeight: number,
hexColor: string
): void {
if (glyphs.length === 0) {
return
}
const pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
module: device.createShaderModule({ code: Shaders.digitGlyph }),
entryPoint: 'vsMain'
},
fragment: {
module: device.createShaderModule({ code: Shaders.digitGlyph }),
entryPoint: 'fsMain',
targets: [
{
format: textureFormat,
blend: {
color: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha', operation: 'add' },
alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' }
}
}
]
},
primitive: { topology: 'triangle-list' }
})
const digitColor = Renderer.hexToColor(hexColor)
const uniformData = new Float32Array([
canvasWidth,
canvasHeight,
0,
0,
digitColor.r,
digitColor.g,
digitColor.b,
digitColor.a
])
const uniformBuffer = Renderer.makeUniformBuffer(device, uniformData)
const glyphData = new ArrayBuffer(glyphs.length * 32)
const floatView = new Float32Array(glyphData)
const uintView = new Uint32Array(glyphData)
for (let i = 0; i < glyphs.length; i++) {
const glyphItem = glyphs[i] as Types.GlyphInstance
const byteBase = i * 8
floatView[byteBase + 0] = glyphItem.x
floatView[byteBase + 1] = glyphItem.y
floatView[byteBase + 2] = glyphItem.w
floatView[byteBase + 3] = glyphItem.h
uintView[byteBase + 4] = glyphItem.digit
uintView[byteBase + 5] = 0
uintView[byteBase + 6] = 0
uintView[byteBase + 7] = 0
}
const storageBuffer = device.createBuffer({
size: Math.max(glyphData.byteLength, 16),
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
})
device.queue.writeBuffer(storageBuffer, 0, new Uint8Array(glyphData))
const bindGroup = device.createBindGroup({
layout: pipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: uniformBuffer } },
{ binding: 1, resource: { buffer: storageBuffer } }
]
})
const renderPass = encoder.beginRenderPass({
colorAttachments: [{ view, loadOp: 'load', storeOp: 'store' }]
})
renderPass.setPipeline(pipeline)
renderPass.setBindGroup(0, bindGroup)
renderPass.draw(glyphs.length * 6)
renderPass.end()
}
/**
* Draws thick polyline through points.
* @description Line strip with uniform color.
* @param device - GPUDevice
* @param encoder - Command encoder
* @param view - Texture view
* @param points - Data points
* @param uniforms - Line uniforms
* @param hexColor - Hex color
* @param lineWidth - Line width
* @returns void
*/
static drawLines(
device: GPUDevice,
encoder: GPUCommandEncoder,
view: GPUTextureView,
points: Array<{ x: number; y: number }>,
uniforms: Types.LineUniforms,
hexColor: string,
lineWidth: number
): void {
if (points.length < 2) {
return
}
const pipeline = Renderer.createLinePipeline(device, Shaders.lineVertex, Shaders.colorFragment)
const lineColor = Renderer.hexToColor(hexColor)
const updatedUniforms = { ...uniforms, lineWidth, color: lineColor }
const uniformBuffer = Renderer.makeUniformBuffer(
device,
Renderer.buildLineUniformData(updatedUniforms)
)
const pointData = new Float32Array(points.flatMap((point) => [point.x, point.y]))
const storageBuffer = Renderer.makeStorageBuffer(device, pointData)
const bindGroup = device.createBindGroup({
layout: pipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: uniformBuffer } },
{ binding: 1, resource: { buffer: storageBuffer } }
]
})
const segmentCount = points.length - 1
const renderPass = encoder.beginRenderPass({
colorAttachments: [{ view, loadOp: 'load', storeOp: 'store' }]
})
renderPass.setPipeline(pipeline)
renderPass.setBindGroup(0, bindGroup)
renderPass.draw(segmentCount * 6)
renderPass.end()
}
/**
* Draws circle markers at points.
* @description Anti-aliased circles at data points.
* @param device - GPUDevice
* @param encoder - Command encoder
* @param view - Texture view
* @param points - Data points
* @param uniforms - Line uniforms
* @param hexColor - Hex color
* @param markerSize - Marker diameter
* @returns void
*/
static drawMarkers(
device: GPUDevice,
encoder: GPUCommandEncoder,
view: GPUTextureView,
points: Array<{ x: number; y: number }>,
uniforms: Types.LineUniforms,
hexColor: string,
markerSize: number
): void {
if (points.length === 0) {
return
}
const pipeline = Renderer.createLinePipeline(
device,
Shaders.markerVertex,
Shaders.markerFragment
)
const markerColor = Renderer.hexToColor(hexColor)
const updatedUniforms = { ...uniforms, lineWidth: markerSize, color: markerColor }
const uniformBuffer = Renderer.makeUniformBuffer(
device,
Renderer.buildLineUniformData(updatedUniforms)
)
const pointData = new Float32Array(points.flatMap((point) => [point.x, point.y]))
const storageBuffer = Renderer.makeStorageBuffer(device, pointData)
const bindGroup = device.createBindGroup({
layout: pipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: uniformBuffer } },
{ binding: 1, resource: { buffer: storageBuffer } }
]
})
const renderPass = encoder.beginRenderPass({
colorAttachments: [{ view, loadOp: 'load', storeOp: 'store' }]
})
renderPass.setPipeline(pipeline)
renderPass.setBindGroup(0, bindGroup)
renderPass.draw(points.length * 6)
renderPass.end()
}
/**
* Draws text glyphs from font atlas.
* @description Atlas sample and blend per glyph.
* @param device - GPUDevice
* @param encoder - Command encoder
* @param view - Texture view
* @param textGlyphs - Text glyphs
* @param canvasWidth - Canvas width
* @param canvasHeight - Canvas height
* @param hexColor - Hex color
* @returns void
*/
static drawText(
device: GPUDevice,
encoder: GPUCommandEncoder,
view: GPUTextureView,
textGlyphs: Types.TextGlyph[],
canvasWidth: number,
canvasHeight: number,
hexColor: string
): void {
if (textGlyphs.length === 0) {
return
}
const { data: atlasDataRaw, width: atlasWidth, height: atlasHeight } = Font.buildAtlas()
const atlasBuf = new ArrayBuffer(atlasDataRaw.byteLength)
new Uint8Array(atlasBuf).set(atlasDataRaw)
const atlasData = new Uint8Array(atlasBuf)
const atlasTexture = device.createTexture({
size: { width: atlasWidth, height: atlasHeight },
format: 'rgba8unorm',
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST
})
device.queue.writeTexture(
{ texture: atlasTexture },
atlasData,
{ bytesPerRow: atlasWidth * 4 },
{ width: atlasWidth, height: atlasHeight }
)
const atlasSampler = device.createSampler({ minFilter: 'linear', magFilter: 'linear' })
const pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
module: device.createShaderModule({ code: Shaders.textGlyph }),
entryPoint: 'vsMain'
},
fragment: {
module: device.createShaderModule({ code: Shaders.textGlyph }),
entryPoint: 'fsMain',
targets: [
{
format: textureFormat,
blend: {
color: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha', operation: 'add' },
alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' }
}
}
]
},
primitive: { topology: 'triangle-list' }
})
const textColor = Renderer.hexToColor(hexColor)
const uniformData = new Float32Array([
canvasWidth,
canvasHeight,
0,
0,
textColor.r,
textColor.g,
textColor.b,
textColor.a
])
const uniformBuffer = Renderer.makeUniformBuffer(device, uniformData)
const glyphData = new ArrayBuffer(textGlyphs.length * 32)
const floatView = new Float32Array(glyphData)
const uintView = new Uint32Array(glyphData)
for (let i = 0; i < textGlyphs.length; i++) {
const glyphItem = textGlyphs[i] as Types.TextGlyph
const byteBase = i * 8
floatView[byteBase + 0] = glyphItem.x
floatView[byteBase + 1] = glyphItem.y
floatView[byteBase + 2] = glyphItem.w
floatView[byteBase + 3] = glyphItem.h
uintView[byteBase + 4] = glyphItem.charIdx
uintView[byteBase + 5] = Font.charCount
uintView[byteBase + 6] = 0
uintView[byteBase + 7] = 0
}
const storageBuffer = device.createBuffer({
size: Math.max(glyphData.byteLength, 16),
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
})
device.queue.writeBuffer(storageBuffer, 0, new Uint8Array(glyphData))
const bindGroup = device.createBindGroup({
layout: pipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: uniformBuffer } },
{ binding: 1, resource: { buffer: storageBuffer } },
{ binding: 2, resource: atlasTexture.createView() },
{ binding: 3, resource: atlasSampler }
]
})
const renderPass = encoder.beginRenderPass({
colorAttachments: [{ view, loadOp: 'load', storeOp: 'store' }]
})
renderPass.setPipeline(pipeline)
renderPass.setBindGroup(0, bindGroup)
renderPass.draw(textGlyphs.length * 6)
renderPass.end()
}
/**
* Reads pixel data from GPU texture.
* @description Copy out and pack RGBA rows.
* @param ctx - GpuContext
* @returns RGBA pixel data
*/
static async readPixels(ctx: Types.GpuContext): Promise<Uint8Array> {
const { device, texture, width, height } = ctx
const bytesPerRow = Math.ceil((width * 4) / 256) * 256
const readBuffer = device.createBuffer({
size: bytesPerRow * height,
usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
})
const encoder = device.createCommandEncoder()
encoder.copyTextureToBuffer({ texture }, { buffer: readBuffer, bytesPerRow }, { width, height })
device.queue.submit([encoder.finish()])
await readBuffer.mapAsync(GPUMapMode.READ)
const rawData = new Uint8Array(readBuffer.getMappedRange())
const pixels = new Uint8Array(width * height * 4)
for (let rowIndex = 0; rowIndex < height; rowIndex++) {
pixels.set(
rawData.subarray(rowIndex * bytesPerRow, rowIndex * bytesPerRow + width * 4),
rowIndex * width * 4
)
}
readBuffer.unmap()
readBuffer.destroy()
return pixels
}
/**
* Packs LineUniforms into Float32Array.
* @description Float array for uniform buffer.
* @param uniforms - Line uniform values
* @returns Packed float data
*/
private static buildLineUniformData(uniforms: Types.LineUniforms): Float32Array {
return new Float32Array([
uniforms.canvasWidth,
uniforms.canvasHeight,
uniforms.plotLeft,
uniforms.plotTop,
uniforms.plotWidth,
uniforms.plotHeight,
uniforms.dataMinX,
uniforms.dataMaxX,
uniforms.dataMinY,
uniforms.dataMaxY,
uniforms.lineWidth,
0,
uniforms.color.r,
uniforms.color.g,
uniforms.color.b,
uniforms.color.a
])
}
/**
* Builds pipeline with alpha blending.
* @description Line pipeline from vertex and fragment.
* @param device - GPUDevice
* @param vertexSrc - Vertex shader source
* @param fragmentSrc - Fragment shader source
* @returns GPURenderPipeline
*/
private static createLinePipeline(
device: GPUDevice,
vertexSrc: string,
fragmentSrc: string
): GPURenderPipeline {
return device.createRenderPipeline({
layout: 'auto',
vertex: { module: device.createShaderModule({ code: vertexSrc }), entryPoint: 'vsMain' },
fragment: {
module: device.createShaderModule({ code: fragmentSrc }),
entryPoint: 'fsMain',
targets: [
{
format: textureFormat,
blend: {
color: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha', operation: 'add' },
alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' }
}
}
]
},
primitive: { topology: 'triangle-list' }
})
}
/**
* Converts hex string to RGBA.
* @description Parse hex to normalized Color.
* @param hexColor - Hex color string
* @param alpha - Alpha value
* @returns Color
*/
private static hexToColor(hexColor: string, alpha = 1.0): Types.Color {
const hexStripped = hexColor.replace('#', '')
const redValue = parseInt(hexStripped.substring(0, 2), 16) / 255
const greenValue = parseInt(hexStripped.substring(2, 4), 16) / 255
const blueValue = parseInt(hexStripped.substring(4, 6), 16) / 255
return { r: redValue, g: greenValue, b: blueValue, a: alpha }
}
/**
* Allocates and fills storage buffer.
* @description GPU storage buffer from float data.
* @param device - GPUDevice
* @param data - Float data
* @returns GPUBuffer
*/
private static makeStorageBuffer(device: GPUDevice, data: Float32Array): GPUBuffer {
const gpuBuffer = device.createBuffer({
size: Math.max(data.byteLength, 16),
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
})
device.queue.writeBuffer(gpuBuffer, 0, new Float32Array(data))
return gpuBuffer
}
/**
* Allocates and fills uniform buffer.
* @description GPU uniform buffer from float data.
* @param device - GPUDevice
* @param data - Float data
* @returns GPUBuffer
*/
private static makeUniformBuffer(device: GPUDevice, data: Float32Array): GPUBuffer {
const gpuBuffer = device.createBuffer({
size: Math.max(data.byteLength, 16),
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
})
device.queue.writeBuffer(gpuBuffer, 0, new Float32Array(data))
return gpuBuffer
}
}