-
Notifications
You must be signed in to change notification settings - Fork 0
/
glea.js
385 lines (385 loc) · 10.3 KB
/
glea.js
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
/**
* GLea - GL experience audience Library
* @module glea
*/
function convertArray(data, type = WebGLRenderingContext.FLOAT) {
if (type === WebGLRenderingContext.FLOAT) {
return new Float32Array(data);
}
if (type === WebGLRenderingContext.BYTE) {
return new Uint8Array(data);
}
throw Error('type not supported');
}
function shader(code, shaderType) {
return (gl) => {
const sh = gl.createShader(
/frag/.test(shaderType) ? gl.FRAGMENT_SHADER : gl.VERTEX_SHADER
);
if (!sh) {
throw Error('shader type not supported');
}
gl.shaderSource(sh, code);
gl.compileShader(sh);
if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
throw 'Could not compile Shader.\n\n' + gl.getShaderInfoLog(sh);
}
return sh;
};
}
/** Class GLea */
class GLea {
constructor({
canvas,
gl,
contextType = 'webgl',
shaders,
buffers,
devicePixelRatio = 1,
glOptions,
}) {
this.canvas = document.createElement('canvas');
this.canvas = canvas || document.querySelector('canvas');
this.gl = gl;
if (!this.gl && this.canvas) {
if (contextType === 'webgl') {
this.gl =
this.canvas.getContext('webgl', glOptions) ||
this.canvas.getContext('experimental-webgl', glOptions);
}
if (contextType === 'webgl2') {
this.gl = this.canvas.getContext('webgl2', glOptions);
}
if (!this.gl) {
throw Error(`no ${contextType} context available.`);
}
}
const program = this.gl.createProgram();
if (!program) {
throw Error('gl.createProgram failed');
}
this.program = program;
this.buffers = {};
this.shaderFactory = shaders;
this.bufferFactory = buffers;
this.textures = [];
this.devicePixelRatio = devicePixelRatio;
}
/**
* Create a vertex shader
*
* @param code shader code
*/
static vertexShader(code) {
return (gl) => shader(code, 'vert')(gl);
}
/**
* Create a fragment shader
*
* @param {string} code fragment shader code
*/
static fragmentShader(code) {
return (gl) => shader(code, 'frag')(gl);
}
/**
* Create Buffer
*
* @param {number} size buffer size
* @param {number[]} data buffer data
* @param {number} usage usage, by default gl.STATIC_DRAW
* @param {number} type data type, by default gl.FLOAT
* @param {boolean} normalized normalize data, false
* @param {number} stride stride, by default 0
* @param {number} offset offset, by default 0
*/
static buffer(
size,
data,
usage = WebGLRenderingContext.STATIC_DRAW,
type = WebGLRenderingContext.FLOAT,
normalized = false,
stride = 0,
offset = 0
) {
return (name, gl, program) => {
const loc = gl.getAttribLocation(program, name);
gl.enableVertexAttribArray(loc);
// create buffer:
const id = gl.createBuffer();
const bufferData =
data instanceof Array ? convertArray(data, type) : data;
gl.bindBuffer(gl.ARRAY_BUFFER, id);
gl.bufferData(gl.ARRAY_BUFFER, bufferData, usage);
gl.vertexAttribPointer(loc, size, type, normalized, stride, offset);
return {
id,
name,
data: bufferData,
loc,
type,
size,
};
};
}
/**
* init WebGLRenderingContext
* @returns {GLea} glea instance
*/
create() {
const { gl } = this;
const { program } = this;
this.shaderFactory
.map((shaderFunc) => shaderFunc(gl))
.map((shader) => {
gl.attachShader(program, shader);
});
gl.linkProgram(program);
gl.validateProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
const info = gl.getProgramInfoLog(program);
throw 'Could not compile WebGL program. \n\n' + info;
}
this.use();
Object.keys(this.bufferFactory).forEach((name) => {
const bufferFunc = this.bufferFactory[name];
this.buffers[name] = bufferFunc(name, gl, program);
});
this.resize();
return this;
}
/**
* Set active texture
* @param {number} textureIndex texture index in the range [0 .. gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1]
* @param {WebGLTexture} texture webgl texture object
*/
setActiveTexture(textureIndex, texture) {
const { gl } = this;
gl.activeTexture(gl.TEXTURE0 + textureIndex);
gl.bindTexture(gl.TEXTURE_2D, texture);
}
/**
* @typedef GLeaTextureOptions
* @property {string} textureWrapS default: clampToEdge
* @property {string} textureWrapT default: clampToEdge
* @property {string} textureMinFilter default: nearest
* @property {string} textureMagFilter default: nearest
*/
/**
* Create a texture object
*
* @param {number} textureIndex
* @param {GLeaTextureOptions} params configuration options
* @returns texture WebGLTexture object
*/
createTexture(
textureIndex = 0,
params = {
textureWrapS: 'clampToEdge',
textureWrapT: 'clampToEdge',
textureMinFilter: 'nearest',
textureMagFilter: 'nearest',
}
) {
const scream = (str = '') =>
/^[A-Z0-9_]+$/.test(str)
? str
: str.replace(/([A-Z])/g, '_$1').toUpperCase();
const { gl } = this;
const texture = gl.createTexture();
gl.activeTexture(gl.TEXTURE0 + textureIndex);
gl.bindTexture(gl.TEXTURE_2D, texture);
for (let key in params) {
if (params.hasOwnProperty(key)) {
const KEY = scream(key);
const VAL = scream(params[key]);
if (KEY in gl && VAL in gl) {
// @ts-ignore indexing gl by string
gl.texParameteri(gl.TEXTURE_2D, gl[KEY], gl[VAL]);
}
}
}
this.textures.push(texture);
return texture;
}
/**
* Update buffer data
* @param {string} name name
* @param {number} offset default: 0
*/
updateBuffer(name, offset = 0) {
const { gl } = this;
const buffer = this.buffers[name];
gl.bindBuffer(gl.ARRAY_BUFFER, buffer.id);
gl.bufferSubData(gl.ARRAY_BUFFER, offset, buffer.data);
}
/**
* Resize canvas and webgl viewport
*/
resize() {
const { canvas, gl, devicePixelRatio } = this;
if (canvas) {
canvas.width = canvas.clientWidth * devicePixelRatio;
canvas.height = canvas.clientHeight * devicePixelRatio;
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
}
}
/**
* Get canvas width
* @returns {number} canvas width
*/
get width() {
return this.canvas ? this.canvas.width : NaN;
}
/**
* Get canvas height
* @returns {number} canvas height
*/
get height() {
return this.canvas ? this.canvas.height : NaN;
}
/**
* Use program
*/
use() {
this.gl.useProgram(this.program);
return this;
}
/**
* set uniform matrix (mat2, mat3, mat4)
* @param name uniform name
* @param data array of numbers (4 for mat2, 9 for mat3, 16 for mat4)
* @returns location id of the uniform
*/
uniM(name, data) {
const { gl, program } = this;
const loc = gl.getUniformLocation(program, name);
if (data.length === 4) {
gl.uniformMatrix2fv(loc, false, data);
return loc;
}
if (data.length === 9) {
gl.uniformMatrix3fv(loc, false, data);
return loc;
}
if (data.length === 16) {
gl.uniformMatrix4fv(loc, false, data);
return loc;
}
throw Error('unsupported uniform matrix type');
}
/**
* Set uniform float vector
*
* @param {string} name uniform variable name
* @param {number[]} data uniform float vector
*/
uniV(name, data) {
const { gl, program } = this;
const loc = gl.getUniformLocation(program, name);
if (data.length === 2) {
gl.uniform2fv(loc, data);
return loc;
}
if (data.length === 3) {
gl.uniform3fv(loc, data);
return loc;
}
if (data.length === 4) {
gl.uniform4fv(loc, data);
return loc;
}
throw Error('unsupported uniform vector type');
}
/**
* Set uniform int vector
*
* @param {string} name uniform variable name
* @param {number[]} data uniform int vector
*/
uniIV(name, data) {
const { gl, program } = this;
const loc = gl.getUniformLocation(program, name);
if (data.length === 2) {
gl.uniform2iv(loc, data);
return loc;
}
if (data.length === 3) {
gl.uniform3iv(loc, data);
return loc;
}
if (data.length === 4) {
gl.uniform4iv(loc, data);
return loc;
}
throw Error('unsupported uniform vector type');
}
/**
* Set uniform float
*
* @param {string} name uniform variable name
* @param {number} data data
*/
uni(name, data) {
const { gl, program } = this;
const loc = gl.getUniformLocation(program, name);
if (typeof data === 'number') {
gl.uniform1f(loc, data);
}
return loc;
}
/**
* Set uniform int
* @param {string} name uniform variable name
* @param {number} data data
*/
uniI(name, data) {
const { gl, program } = this;
const loc = gl.getUniformLocation(program, name);
if (typeof data === 'number') {
gl.uniform1i(loc, data);
}
}
/**
* Clear screen
*
* @param {number[]} clearColor
*/
clear(clearColor = null) {
const { gl } = this;
if (clearColor) {
gl.clearColor(clearColor[0], clearColor[1], clearColor[2], 1);
}
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
}
/**
* destroys the WebGLRendering context by deleting all textures, buffers and shaders.
* Additionally, it calls loseContext.
* Also the canvas element is removed from the DOM and replaced by a new cloned canvas element
*/
destroy() {
const { gl, program, canvas } = this;
try {
gl.deleteProgram(program);
Object.values(this.buffers).forEach((buffer) => {
gl.deleteBuffer(buffer.id);
});
this.buffers = {};
this.textures.forEach((texture) => {
gl.deleteTexture(texture);
});
this.textures = [];
// @ts-ignore TS doesn't know about getExtension
gl.getExtension('WEBGL_lose_context').loseContext();
const newCanvas = canvas.cloneNode();
if (canvas.parentNode) {
canvas.parentNode.insertBefore(newCanvas, canvas);
canvas.parentNode.removeChild(canvas);
}
this.canvas = newCanvas;
} catch (err) {
console.error(err);
}
}
}
export default GLea;
//# sourceMappingURL=glea.js.map