forked from gpujs/gpu.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgpu.js
More file actions
446 lines (400 loc) · 11.4 KB
/
gpu.js
File metadata and controls
446 lines (400 loc) · 11.4 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
const gpuMock = require('gpu-mock.js');
const {
utils
} = require('./utils');
const {
CPUKernel
} = require('./backend/cpu/kernel');
const {
HeadlessGLKernel
} = require('./backend/headless-gl/kernel');
const {
WebGL2Kernel
} = require('./backend/web-gl2/kernel');
const {
WebGLKernel
} = require('./backend/web-gl/kernel');
const {
kernelRunShortcut
} = require('./kernel-run-shortcut');
/**
* @type {Kernel[]}
*/
const kernelOrder = [HeadlessGLKernel, WebGL2Kernel, WebGLKernel];
/**
*
* @type {string[]}
*/
const kernelTypes = ['gpu', 'cpu'];
const internalKernels = {
'headlessgl': HeadlessGLKernel,
'webgl2': WebGL2Kernel,
'webgl': WebGLKernel,
};
/**
* The GPU.js library class which manages the GPU context for the creating kernels
*/
class GPU {
static get isGPUSupported() {
return kernelOrder.some(Kernel => Kernel.isSupported);
}
/**
*
* @returns {boolean}
*/
static get isKernelMapSupported() {
return kernelOrder.some(Kernel => Kernel.isSupported && Kernel.features.kernelMap);
}
/**
* @desc TRUE is platform supports OffscreenCanvas
*/
static get isOffscreenCanvasSupported() {
return (typeof Worker !== 'undefined' && typeof OffscreenCanvas !== 'undefined') || typeof importScripts !== 'undefined';
}
/**
* @desc TRUE if platform supports WebGL
*/
static get isWebGLSupported() {
return WebGLKernel.isSupported;
}
/**
* @desc TRUE if platform supports WebGL2
*/
static get isWebGL2Supported() {
return WebGL2Kernel.isSupported;
}
/**
* @desc TRUE if platform supports HeadlessGL
*/
static get isHeadlessGLSupported() {
return HeadlessGLKernel.isSupported;
}
/**
*
* @desc TRUE if platform supports Canvas
*/
static get isCanvasSupported() {
return typeof HTMLCanvasElement !== 'undefined';
}
/**
* @desc TRUE if platform supports HTMLImageArray}
*/
static get isGPUHTMLImageArraySupported() {
return WebGL2Kernel.isSupported;
}
/**
* @desc TRUE if platform supports FloatOutput}
* @returns {boolean}
*/
static get isFloatOutputSupported() {
return kernelOrder.some(Kernel => Kernel.isSupported && Kernel.features.isFloatRead && Kernel.features.isTextureFloat);
}
/**
* Creates an instance of GPU.
* @param {IGPUSettings} [settings] - Settings to set mode, and other properties
*/
constructor(settings) {
settings = settings || {};
this.canvas = settings.canvas || null;
this.context = settings.context || null;
this.mode = settings.mode;
if (this.mode === 'dev') return;
this.Kernel = null;
this.kernels = [];
this.functions = [];
this.nativeFunctions = [];
// add functions from settings
if (settings.functions) {
for (let i = 0; i < settings.functions.length; i++) {
this.addFunction(settings.functions[i]);
}
}
// add native functions from settings
if (settings.nativeFunctions) {
for (const p in settings.nativeFunctions) {
this.addNativeFunction(p, settings.nativeFunctions[p]);
}
}
this.chooseKernel();
}
/**
* Choose kernel type and save on .Kernel property of GPU
*/
chooseKernel() {
if (this.Kernel) return;
let Kernel = null;
if (this.context) {
for (let i = 0; i < kernelOrder.length; i++) {
const ExternalKernel = kernelOrder[i];
if (ExternalKernel.isContextMatch(this.context)) {
Kernel = ExternalKernel;
break;
}
}
if (Kernel === null) {
throw new Error('unknown Context');
}
} else if (this.mode) {
if (this.mode in internalKernels) {
if (internalKernels[this.mode].isSupported) {
Kernel = internalKernels[this.mode];
}
} else if (this.mode === 'gpu') {
for (let i = 0; i < kernelOrder.length; i++) {
if (kernelOrder[i].isSupported) {
Kernel = kernelOrder[i];
break;
}
}
} else if (this.mode === 'cpu') {
Kernel = CPUKernel;
}
if (!Kernel) {
throw new Error(`A requested mode of "${this.mode}" and is not supported`);
}
} else {
for (let i = 0; i < kernelOrder.length; i++) {
if (kernelOrder[i].isSupported) {
Kernel = kernelOrder[i];
break;
}
}
if (!Kernel) {
Kernel = CPUKernel;
}
}
if (!this.mode) {
this.mode = Kernel.mode;
}
this.Kernel = Kernel;
}
/**
* @desc This creates a callable function object to call the kernel function with the argument parameter set
* @param {Function|String|object} source - The calling to perform the conversion
* @param {Object} [settings] - The parameter configuration object
* @returns {Kernel} callable function to run
*/
createKernel(source, settings) {
if (typeof source === 'undefined') {
throw new Error('Missing source parameter');
}
if (typeof source !== 'object' && !utils.isFunction(source) && typeof source !== 'string') {
throw new Error('source parameter not a function');
}
if (this.mode === 'dev') {
return gpuMock(source, settings);
}
source = typeof source === 'function' ? source.toString() : source;
const mergedSettings = Object.assign({
context: this.context,
canvas: this.canvas,
functions: this.functions,
nativeFunctions: this.nativeFunctions
}, settings || {});
const kernel = kernelRunShortcut(new this.Kernel(source, mergedSettings));
//if canvas didn't come from this, propagate from kernel
if (!this.canvas) {
this.canvas = kernel.canvas;
}
//if context didn't come from this, propagate from kernel
if (!this.context) {
this.context = kernel.context;
}
this.kernels.push(kernel);
return kernel;
}
/**
*
* Create a super kernel which executes sub kernels
* and saves their output to be used with the next sub kernel.
* This can be useful if we want to save the output on one kernel,
* and then use it as an input to another kernel. *Machine Learning*
*
* @param {Object|Array} subKernels - Sub kernels for this kernel
* @param {Function} rootKernel - Root kernel
*
* @returns {Function} callable kernel function
*
* @example
* const megaKernel = gpu.createKernelMap({
* addResult: function add(a, b) {
* return a[this.thread.x] + b[this.thread.x];
* },
* multiplyResult: function multiply(a, b) {
* return a[this.thread.x] * b[this.thread.x];
* },
* }, function(a, b, c) {
* return multiply(add(a, b), c);
* });
*
* megaKernel(a, b, c);
*
* Note: You can also define subKernels as an array of functions.
* > [add, multiply]
*
*/
createKernelMap() {
let fn;
let settings;
if (typeof arguments[arguments.length - 2] === 'function') {
fn = arguments[arguments.length - 2];
settings = arguments[arguments.length - 1];
} else {
fn = arguments[arguments.length - 1];
}
if (!this.Kernel.isSupported || !this.Kernel.features.kernelMap) {
if (this.mode && kernelTypes.indexOf(this.mode) < 0) {
throw new Error(`kernelMap not supported on ${this.Kernel.name}`);
}
}
const kernel = this.createKernel(fn, settings);
if (Array.isArray(arguments[0])) {
const functions = arguments[0];
for (let i = 0; i < functions.length; i++) {
const source = functions[i].toString();
const name = utils.getFunctionNameFromString(source);
kernel.addSubKernel({
name,
source,
property: i,
});
}
} else {
const functions = arguments[0];
for (let p in functions) {
if (!functions.hasOwnProperty(p)) continue;
const source = functions[p].toString();
const name = utils.getFunctionNameFromString(source);
kernel.addSubKernel({
name: name || p,
source,
property: p,
});
}
}
return kernel;
}
/**
*
* Combine different kernels into one super Kernel,
* useful to perform multiple operations inside one
* kernel without the penalty of data transfer between
* cpu and gpu.
*
* The number of kernel functions sent to this method can be variable.
* You can send in one, two, etc.
*
* @param {Function} subKernels - Kernel function(s) to combine.
* @param {Function} rootKernel - Root kernel to combine kernels into
*
* @example
* combineKernels(add, multiply, function(a,b,c){
* return add(multiply(a,b), c)
* })
*
* @returns {Function} Callable kernel function
*
*/
combineKernels() {
const lastKernel = arguments[arguments.length - 2];
const combinedKernel = arguments[arguments.length - 1];
if (this.mode === 'cpu') return combinedKernel;
const canvas = arguments[0].canvas;
let context = arguments[0].context;
for (let i = 0; i < arguments.length - 1; i++) {
arguments[i]
.setCanvas(canvas)
.setContext(context)
.setPipeline(true);
}
//TODO: needs moved to kernel
return function() {
combinedKernel.apply(null, arguments);
const texSize = lastKernel.texSize;
const gl = lastKernel.context;
const threadDim = lastKernel.threadDim;
let result;
if (lastKernel.floatOutput) {
const w = texSize[0];
const h = Math.ceil(texSize[1] / 4);
result = new Float32Array(w * h * 4);
gl.readPixels(0, 0, w, h, gl.RGBA, gl.FLOAT, result);
} else {
const bytes = new Uint8Array(texSize[0] * texSize[1] * 4);
gl.readPixels(0, 0, texSize[0], texSize[1], gl.RGBA, gl.UNSIGNED_BYTE, bytes);
result = new Float32Array(bytes.buffer);
}
result = result.subarray(0, threadDim[0] * threadDim[1] * threadDim[2]);
if (lastKernel.output.length === 1) {
return result;
} else if (lastKernel.output.length === 2) {
return utils.splitArray(result, lastKernel.output[0]);
} else if (lastKernel.output.length === 3) {
const cube = utils.splitArray(result, lastKernel.output[0] * lastKernel.output[1]);
return cube.map(function(x) {
return utils.splitArray(x, lastKernel.output[0]);
});
}
};
}
/**
* @desc Adds additional functions, that the kernel may call.
* @param {Function|String} source - Javascript function to convert
* @param {IFunctionSettings} [settings]
* @returns {GPU} returns itself
*/
addFunction(source, settings) {
settings = settings || {};
if (typeof source !== 'string' && typeof source !== 'function') throw new Error('source not a string or function');
const sourceString = typeof source === 'string' ? source : source.toString();
let argumentTypes = [];
if (typeof settings.argumentTypes === 'object') {
argumentTypes = utils.getArgumentNamesFromString(sourceString)
.map(name => settings.argumentTypes[name]) || [];
} else {
argumentTypes = settings.argumentTypes || [];
}
this.functions.push({
source: sourceString,
argumentTypes,
returnType: settings.returnType
});
return this;
}
/**
* @desc Adds additional native functions, that the kernel may call.
* @param {String} name - native function name, used for reverse lookup
* @param {String} source - the native function implementation, as it would be defined in it's entirety
* @param {object} [settings]
* @returns {GPU} returns itself
*/
addNativeFunction(name, source, settings) {
if (this.kernels.length > 0) {
throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');
}
this.nativeFunctions.push({
name,
source,
settings
});
return this;
}
/**
* @desc Destroys all memory associated with gpu.js & the webGl if we created it
*/
destroy() {
// perform on next run loop - for some reason we dont get lose context events
// if webGl is created and destroyed in the same run loop.
setTimeout(() => {
for (let i = 0; i < this.kernels.length; i++) {
this.kernels[i].destroy(true); // remove canvas if exists
}
this.kernels[0].kernel.constructor.destroyContext(this.context);
}, 0);
}
}
module.exports = {
GPU,
kernelOrder,
kernelTypes
};