forked from gpujs/gpu.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkernel.js
More file actions
641 lines (585 loc) · 19.1 KB
/
kernel.js
File metadata and controls
641 lines (585 loc) · 19.1 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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
const { WebGLKernel } = require('../web-gl/kernel');
const { WebGL2FunctionNode } = require('./function-node');
const { FunctionBuilder } = require('../function-builder');
const { utils } = require('../../utils');
const { fragmentShader } = require('./fragment-shader');
const { vertexShader } = require('./vertex-shader');
const { lookupKernelValueType } = require('./kernel-value-maps');
let isSupported = null;
/**
*
* @type {HTMLCanvasElement|OffscreenCanvas}
*/
let testCanvas = null;
/**
*
* @type {WebGLRenderingContext}
*/
let testContext = null;
let testExtensions = null;
/**
*
* @type {IKernelFeatures}
*/
let features = null;
/**
* @extends WebGLKernel
*/
class WebGL2Kernel extends WebGLKernel {
static get isSupported() {
if (isSupported !== null) {
return isSupported;
}
this.setupFeatureChecks();
isSupported = this.isContextMatch(testContext);
return isSupported;
}
static setupFeatureChecks() {
if (typeof document !== 'undefined') {
testCanvas = document.createElement('canvas');
} else if (typeof OffscreenCanvas !== 'undefined') {
testCanvas = new OffscreenCanvas(0, 0);
}
if (!testCanvas) return;
testContext = testCanvas.getContext('webgl2');
if (!testContext || !testContext.getExtension) return;
testExtensions = {
EXT_color_buffer_float: testContext.getExtension('EXT_color_buffer_float'),
OES_texture_float_linear: testContext.getExtension('OES_texture_float_linear'),
};
features = this.getFeatures();
}
static isContextMatch(context) {
// from global
if (typeof WebGL2RenderingContext !== 'undefined') {
return context instanceof WebGL2RenderingContext;
}
return false;
}
/**
*
* @return {IKernelFeatures}
*/
static getFeatures() {
const gl = this.testContext;
return Object.freeze({
isFloatRead: this.getIsFloatRead(),
isIntegerDivisionAccurate: this.getIsIntegerDivisionAccurate(),
isSpeedTacticSupported: this.getIsSpeedTacticSupported(),
kernelMap: true,
isTextureFloat: true,
isDrawBuffers: true,
channelCount: this.getChannelCount(),
maxTextureSize: this.getMaxTextureSize(),
lowIntPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT),
lowFloatPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT),
mediumIntPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_INT),
mediumFloatPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT),
highIntPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_INT),
highFloatPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT),
});
}
static getIsTextureFloat() {
return true;
}
static getChannelCount() {
return testContext.getParameter(testContext.MAX_DRAW_BUFFERS);
}
static getMaxTextureSize() {
return testContext.getParameter(testContext.MAX_TEXTURE_SIZE);
}
static lookupKernelValueType(type, dynamic, precision, value) {
return lookupKernelValueType(type, dynamic, precision, value);
}
static get testCanvas() {
return testCanvas;
}
static get testContext() {
return testContext;
}
/**
*
* @returns {{isFloatRead: Boolean, isIntegerDivisionAccurate: Boolean, kernelMap: Boolean, isTextureFloat: Boolean}}
*/
static get features() {
return features;
}
static get fragmentShader() {
return fragmentShader;
}
static get vertexShader() {
return vertexShader;
}
/**
*
* @return {WebGLRenderingContext|WebGL2RenderingContext}
*/
initContext() {
const settings = {
alpha: false,
depth: false,
antialias: false
};
return this.canvas.getContext('webgl2', settings);
}
initExtensions() {
this.extensions = {
EXT_color_buffer_float: this.context.getExtension('EXT_color_buffer_float'),
OES_texture_float_linear: this.context.getExtension('OES_texture_float_linear'),
};
}
/**
* @desc Validate settings related to Kernel, such as dimensions size, and auto output support.
* @param {IArguments} args
*/
validateSettings(args) {
if (!this.validate) {
this.texSize = utils.getKernelTextureSize({
optimizeFloatMemory: this.optimizeFloatMemory,
precision: this.precision,
}, this.output);
return;
}
const { features } = this.constructor;
if (this.precision === 'single' && !features.isFloatRead) {
throw new Error('Float texture outputs are not supported');
} else if (!this.graphical && this.precision === null) {
this.precision = features.isFloatRead ? 'single' : 'unsigned';
}
if (this.fixIntegerDivisionAccuracy === null) {
this.fixIntegerDivisionAccuracy = !features.isIntegerDivisionAccurate;
} else if (this.fixIntegerDivisionAccuracy && features.isIntegerDivisionAccurate) {
this.fixIntegerDivisionAccuracy = false;
}
this.checkOutput();
if (!this.output || this.output.length === 0) {
if (args.length !== 1) {
throw new Error('Auto output only supported for kernels with only one input');
}
const argType = utils.getVariableType(args[0], this.strictIntegers);
switch (argType) {
case 'Array':
this.output = utils.getDimensions(argType);
break;
case 'NumberTexture':
case 'MemoryOptimizedNumberTexture':
case 'ArrayTexture(1)':
case 'ArrayTexture(2)':
case 'ArrayTexture(3)':
case 'ArrayTexture(4)':
this.output = args[0].output;
break;
default:
throw new Error('Auto output not supported for input type: ' + argType);
}
}
if (this.graphical) {
if (this.output.length !== 2) {
throw new Error('Output must have 2 dimensions on graphical mode');
}
if (this.precision === 'single') {
console.warn('Cannot use graphical mode and single precision at the same time');
this.precision = 'unsigned';
}
this.texSize = utils.clone(this.output);
return;
} else if (!this.graphical && this.precision === null && features.isTextureFloat) {
this.precision = 'single';
}
this.texSize = utils.getKernelTextureSize({
optimizeFloatMemory: this.optimizeFloatMemory,
precision: this.precision,
}, this.output);
this.checkTextureSize();
}
translateSource() {
const functionBuilder = FunctionBuilder.fromKernel(this, WebGL2FunctionNode, {
fixIntegerDivisionAccuracy: this.fixIntegerDivisionAccuracy
});
this.translatedSource = functionBuilder.getPrototypeString('kernel');
this.setupReturnTypes(functionBuilder);
}
drawBuffers() {
this.context.drawBuffers(this.drawBuffersMap);
}
getTextureFormat() {
const { context: gl } = this;
switch (this.getInternalFormat()) {
case gl.R32F:
return gl.RED;
case gl.RG32F:
return gl.RG;
case gl.RGBA32F:
return gl.RGBA;
case gl.RGBA:
return gl.RGBA;
default:
throw new Error('Unknown internal format');
}
}
getInternalFormat() {
const { context: gl } = this;
if (this.precision === 'single') {
if (this.pipeline) {
switch (this.returnType) {
case 'Number':
case 'Float':
case 'Integer':
if (this.optimizeFloatMemory) {
return gl.RGBA32F;
} else {
return gl.R32F;
}
case 'Array(2)':
return gl.RG32F;
case 'Array(3)': // there is _no_ 3 channel format which is guaranteed to be color-renderable
case 'Array(4)':
return gl.RGBA32F;
default:
throw new Error('Unhandled return type');
}
}
return gl.RGBA32F;
}
return gl.RGBA;
}
_setupOutputTexture() {
const gl = this.context;
if (this.texture) {
// here we inherit from an already existing kernel, so go ahead and just bind textures to the framebuffer
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0);
return;
}
gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
const texture = gl.createTexture();
const texSize = this.texSize;
gl.activeTexture(gl.TEXTURE0 + this.constantTextureCount + this.argumentTextureCount);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
const format = this.getInternalFormat();
if (this.precision === 'single') {
gl.texStorage2D(gl.TEXTURE_2D, 1, format, texSize[0], texSize[1]);
} else {
gl.texImage2D(gl.TEXTURE_2D, 0, format, texSize[0], texSize[1], 0, format, gl.UNSIGNED_BYTE, null);
}
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
this.texture = new this.TextureConstructor({
texture,
size: texSize,
dimensions: this.threadDim,
output: this.output,
context: this.context,
internalFormat: this.getInternalFormat(),
textureFormat: this.getTextureFormat(),
kernel: this,
});
}
_setupSubOutputTextures() {
const gl = this.context;
if (this.mappedTextures) {
// here we inherit from an already existing kernel, so go ahead and just bind textures to the framebuffer
for (let i = 0; i < this.subKernels.length; i++) {
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i + 1, gl.TEXTURE_2D, this.mappedTextures[i].texture, 0);
}
return;
}
const texSize = this.texSize;
this.drawBuffersMap = [gl.COLOR_ATTACHMENT0];
this.mappedTextures = [];
for (let i = 0; i < this.subKernels.length; i++) {
const texture = this.createTexture();
this.drawBuffersMap.push(gl.COLOR_ATTACHMENT0 + i + 1);
gl.activeTexture(gl.TEXTURE0 + this.constantTextureCount + this.argumentTextureCount + i);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
// TODO: upgrade this
const format = this.getInternalFormat();
if (this.precision === 'single') {
gl.texStorage2D(gl.TEXTURE_2D, 1, format, texSize[0], texSize[1]);
// gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, texSize[0], texSize[1], 0, gl.RGBA, gl.FLOAT, null);
} else {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texSize[0], texSize[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
}
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i + 1, gl.TEXTURE_2D, texture, 0);
this.mappedTextures.push(new this.TextureConstructor({
texture,
size: texSize,
dimensions: this.threadDim,
output: this.output,
context: this.context,
internalFormat: this.getInternalFormat(),
textureFormat: this.getTextureFormat(),
kernel: this,
}));
}
}
/**
*
* @desc Get the header string for the program.
* This returns an empty string if no sub-kernels are defined.
*
* @returns {String} result
*/
_getHeaderString() {
return '';
}
/**
* @desc Get texture coordinate string for the program
* @returns {String} result
*/
_getTextureCoordinate() {
const subKernels = this.subKernels;
const variablePrecision = this.getVariablePrecisionString(this.texSize, this.tactic);
if (subKernels === null || subKernels.length < 1) {
return `in ${ variablePrecision } vec2 vTexCoord;\n`;
} else {
return `out ${ variablePrecision } vec2 vTexCoord;\n`;
}
}
/**
* @desc Generate transpiled glsl Strings for user-defined parameters sent to a kernel
* @param {Array} args - The actual parameters sent to the Kernel
* @returns {String} result
*/
_getMainArgumentsString(args) {
const result = [];
const argumentNames = this.argumentNames;
for (let i = 0; i < argumentNames.length; i++) {
result.push(this.kernelArguments[i].getSource(args[i]));
}
return result.join('');
}
/**
* @desc Get Kernel program string (in *glsl*) for a kernel.
* @returns {String} result
*/
getKernelString() {
const result = [this.getKernelResultDeclaration()];
const subKernels = this.subKernels;
if (subKernels !== null) {
result.push(
'layout(location = 0) out vec4 data0'
);
switch (this.returnType) {
case 'Number':
case 'Float':
case 'Integer':
for (let i = 0; i < subKernels.length; i++) {
const subKernel = subKernels[i];
result.push(
subKernel.returnType === 'Integer' ?
`int subKernelResult_${ subKernel.name } = 0` :
`float subKernelResult_${ subKernel.name } = 0.0`,
`layout(location = ${ i + 1 }) out vec4 data${ i + 1 }`
);
}
break;
case 'Array(2)':
for (let i = 0; i < subKernels.length; i++) {
result.push(
`vec2 subKernelResult_${ subKernels[i].name }`,
`layout(location = ${ i + 1 }) out vec4 data${ i + 1 }`
);
}
break;
case 'Array(3)':
for (let i = 0; i < subKernels.length; i++) {
result.push(
`vec3 subKernelResult_${ subKernels[i].name }`,
`layout(location = ${ i + 1 }) out vec4 data${ i + 1 }`
);
}
break;
case 'Array(4)':
for (let i = 0; i < subKernels.length; i++) {
result.push(
`vec4 subKernelResult_${ subKernels[i].name }`,
`layout(location = ${ i + 1 }) out vec4 data${ i + 1 }`
);
}
break;
}
} else {
result.push(
'out vec4 data0'
);
}
return utils.linesToString(result) + this.translatedSource;
}
getMainResultGraphical() {
return utils.linesToString([
' threadId = indexTo3D(index, uOutputDim)',
' kernel()',
' data0 = actualColor',
]);
}
getMainResultPackedPixels() {
switch (this.returnType) {
case 'LiteralInteger':
case 'Number':
case 'Integer':
case 'Float':
return this.getMainResultKernelPackedPixels() +
this.getMainResultSubKernelPackedPixels();
default:
throw new Error(`packed output only usable with Numbers, "${this.returnType}" specified`);
}
}
/**
* @return {String}
*/
getMainResultKernelPackedPixels() {
return utils.linesToString([
' threadId = indexTo3D(index, uOutputDim)',
' kernel()',
` data0 = ${this.useLegacyEncoder ? 'legacyEncode32' : 'encode32'}(kernelResult)`
]);
}
/**
* @return {String}
*/
getMainResultSubKernelPackedPixels() {
const result = [];
if (!this.subKernels) return '';
for (let i = 0; i < this.subKernels.length; i++) {
const subKernel = this.subKernels[i];
if (subKernel.returnType === 'Integer') {
result.push(
` data${i + 1} = ${this.useLegacyEncoder ? 'legacyEncode32' : 'encode32'}(float(subKernelResult_${this.subKernels[i].name}))`
);
} else {
result.push(
` data${i + 1} = ${this.useLegacyEncoder ? 'legacyEncode32' : 'encode32'}(subKernelResult_${this.subKernels[i].name})`
);
}
}
return utils.linesToString(result);
}
getMainResultKernelMemoryOptimizedFloats(result, channel) {
result.push(
' threadId = indexTo3D(index, uOutputDim)',
' kernel()',
` data0.${channel} = kernelResult`
);
}
getMainResultSubKernelMemoryOptimizedFloats(result, channel) {
if (!this.subKernels) return result;
for (let i = 0; i < this.subKernels.length; i++) {
const subKernel = this.subKernels[i];
if (subKernel.returnType === 'Integer') {
result.push(
` data${i + 1}.${channel} = float(subKernelResult_${subKernel.name})`
);
} else {
result.push(
` data${i + 1}.${channel} = subKernelResult_${subKernel.name}`
);
}
}
}
getMainResultKernelNumberTexture() {
return [
' threadId = indexTo3D(index, uOutputDim)',
' kernel()',
' data0[0] = kernelResult',
];
}
getMainResultSubKernelNumberTexture() {
const result = [];
if (!this.subKernels) return result;
for (let i = 0; i < this.subKernels.length; ++i) {
const subKernel = this.subKernels[i];
if (subKernel.returnType === 'Integer') {
result.push(
` data${i + 1}[0] = float(subKernelResult_${subKernel.name})`
);
} else {
result.push(
` data${i + 1}[0] = subKernelResult_${subKernel.name}`
);
}
}
return result;
}
getMainResultKernelArray2Texture() {
return [
' threadId = indexTo3D(index, uOutputDim)',
' kernel()',
' data0[0] = kernelResult[0]',
' data0[1] = kernelResult[1]',
];
}
getMainResultSubKernelArray2Texture() {
const result = [];
if (!this.subKernels) return result;
for (let i = 0; i < this.subKernels.length; ++i) {
const subKernel = this.subKernels[i];
result.push(
` data${i + 1}[0] = subKernelResult_${subKernel.name}[0]`,
` data${i + 1}[1] = subKernelResult_${subKernel.name}[1]`
);
}
return result;
}
getMainResultKernelArray3Texture() {
return [
' threadId = indexTo3D(index, uOutputDim)',
' kernel()',
' data0[0] = kernelResult[0]',
' data0[1] = kernelResult[1]',
' data0[2] = kernelResult[2]',
];
}
getMainResultSubKernelArray3Texture() {
const result = [];
if (!this.subKernels) return result;
for (let i = 0; i < this.subKernels.length; ++i) {
const subKernel = this.subKernels[i];
result.push(
` data${i + 1}[0] = subKernelResult_${subKernel.name}[0]`,
` data${i + 1}[1] = subKernelResult_${subKernel.name}[1]`,
` data${i + 1}[2] = subKernelResult_${subKernel.name}[2]`
);
}
return result;
}
getMainResultKernelArray4Texture() {
return [
' threadId = indexTo3D(index, uOutputDim)',
' kernel()',
' data0 = kernelResult',
];
}
getMainResultSubKernelArray4Texture() {
const result = [];
if (!this.subKernels) return result;
for (let i = 0; i < this.subKernels.length; ++i) {
result.push(
` data${i + 1} = subKernelResult_${this.subKernels[i].name}`
);
}
return result;
}
destroyExtensions() {
this.extensions.EXT_color_buffer_float = null;
this.extensions.OES_texture_float_linear = null;
}
/**
* @return {IKernelJSON}
*/
toJSON() {
const json = super.toJSON();
json.functionNodes = FunctionBuilder.fromKernel(this, WebGL2FunctionNode).toJSON();
json.settings.threadDim = this.threadDim;
return json;
}
}
module.exports = {
WebGL2Kernel
};