-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathp5.RendererGL.js
More file actions
2078 lines (1897 loc) · 62.1 KB
/
p5.RendererGL.js
File metadata and controls
2078 lines (1897 loc) · 62.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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as constants from '../core/constants';
import {
getWebGLShaderAttributes,
getWebGLUniformMetadata,
populateGLSLHooks,
readPixelsWebGL,
readPixelWebGL,
setWebGLTextureParams,
setWebGLUniformValue,
checkWebGLCapabilities
} from './utils';
import { Renderer3D } from '../core/p5.Renderer3D';
import { getStrokeDefs } from './enums';
import { Shader } from './p5.Shader';
import { MipmapTexture } from './p5.Texture';
import { Framebuffer } from './p5.Framebuffer';
import { RGB, RGBA } from '../color/creating_reading';
import { Image } from '../image/p5.Image';
import { glslBackend } from './strands_glslBackend';
import { TypeInfoFromGLSLName } from '../strands/ir_types.js';
import { getShaderHookTypes } from './shaderHookUtils';
import filterBaseVert from "./shaders/filters/base.vert";
import lightingShader from "./shaders/lighting.glsl";
import webgl2CompatibilityShader from "./shaders/webgl2Compatibility.glsl";
import normalVert from "./shaders/normal.vert";
import normalFrag from "./shaders/normal.frag";
import basicFrag from "./shaders/basic.frag";
import lightVert from "./shaders/light.vert";
import lightTextureFrag from "./shaders/light_texture.frag";
import phongVert from "./shaders/phong.vert";
import phongFrag from "./shaders/phong.frag";
import fontVert from "./shaders/font.vert";
import fontFrag from "./shaders/font.frag";
import lineVert from "./shaders/line.vert";
import lineFrag from "./shaders/line.frag";
import imageLightVert from "./shaders/imageLight.vert";
import imageLightDiffusedFrag from "./shaders/imageLightDiffused.frag";
import imageLightSpecularFrag from "./shaders/imageLightSpecular.frag";
import filterBaseFrag from "./shaders/filters/base.frag";
const { lineDefs } = getStrokeDefs((n, v) => `#define ${n} ${v}\n`);
const defaultShaders = {
normalVert,
normalFrag,
basicFrag,
lightVert: lightingShader + lightVert,
lightTextureFrag,
phongVert,
phongFrag: lightingShader + phongFrag,
fontVert,
fontFrag,
lineVert: lineDefs + lineVert,
lineFrag: lineDefs + lineFrag,
imageLightVert,
imageLightDiffusedFrag,
imageLightSpecularFrag,
filterBaseVert,
filterBaseFrag,
};
for (const key in defaultShaders) {
defaultShaders[key] = webgl2CompatibilityShader + defaultShaders[key];
}
/**
* 3D graphics class
* @private
* @class p5.RendererGL
* @extends p5.Renderer
* @todo extend class to include public method for offscreen
* rendering (FBO).
*/
class RendererGL extends Renderer3D {
constructor(pInst, w, h, isMainCanvas, elt) {
super(pInst, w, h, isMainCanvas, elt);
if (this.webglVersion === constants.WEBGL2) {
this.blendExt = this.GL;
} else {
this.blendExt = this.GL.getExtension("EXT_blend_minmax");
}
this._userEnabledStencil = false;
// Store original methods for internal use
this._internalEnable = this.drawingContext.enable;
this._internalDisable = this.drawingContext.disable;
// Override WebGL enable function
this.drawingContext.enable = (key) => {
if (key === this.drawingContext.STENCIL_TEST) {
if (!this._clipping) {
this._userEnabledStencil = true;
}
}
return this._internalEnable.call(this.drawingContext, key);
};
// Override WebGL disable function
this.drawingContext.disable = (key) => {
if (key === this.drawingContext.STENCIL_TEST) {
this._userEnabledStencil = false;
}
return this._internalDisable.call(this.drawingContext, key);
};
this._cachedBlendMode = undefined;
this.strandsBackend = glslBackend;
}
setupContext() {
this._setAttributeDefaults(this._pInst);
this._initContext();
// This redundant property is useful in reminding you that you are
// interacting with WebGLRenderingContext, still worth considering future removal
this.GL = this.drawingContext;
}
//////////////////////////////////////////////
// Rendering
//////////////////////////////////////////////
/**
* @private sets blending in gl context to curBlendMode
* @param {Number[]} color [description]
* @return {Number[]} Normalized numbers array
*/
_applyBlendMode () {
if (this._cachedBlendMode === this.states.curBlendMode) {
return;
}
const gl = this.GL;
switch (this.states.curBlendMode) {
case constants.BLEND:
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
break;
case constants.ADD:
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.ONE, gl.ONE);
break;
case constants.REMOVE:
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_ALPHA);
break;
case constants.MULTIPLY:
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA);
break;
case constants.SCREEN:
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_COLOR);
break;
case constants.EXCLUSION:
gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
gl.blendFuncSeparate(
gl.ONE_MINUS_DST_COLOR,
gl.ONE_MINUS_SRC_COLOR,
gl.ONE,
gl.ONE
);
break;
case constants.REPLACE:
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.ONE, gl.ZERO);
break;
case constants.SUBTRACT:
gl.blendEquationSeparate(gl.FUNC_REVERSE_SUBTRACT, gl.FUNC_ADD);
gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
break;
case constants.DARKEST:
if (this.blendExt) {
gl.blendEquationSeparate(
this.blendExt.MIN || this.blendExt.MIN_EXT,
gl.FUNC_ADD
);
gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE);
} else {
console.warn(
'blendMode(DARKEST) does not work in your browser in WEBGL mode.'
);
}
break;
case constants.LIGHTEST:
if (this.blendExt) {
gl.blendEquationSeparate(
this.blendExt.MAX || this.blendExt.MAX_EXT,
gl.FUNC_ADD
);
gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE);
} else {
console.warn(
'blendMode(LIGHTEST) does not work in your browser in WEBGL mode.'
);
}
break;
default:
console.error(
'Oops! Somehow Renderer3D set curBlendMode to an unsupported mode.'
);
break;
}
this._cachedBlendMode = this.states.curBlendMode;
}
_shaderOptions() {
return undefined;
}
_useShader(shader) {
const gl = this.GL;
gl.useProgram(shader._glProgram);
}
/**
* Once all buffers have been bound, this checks to see if there are any
* remaining active attributes, likely left over from previous renders,
* and disables them so that they don't affect rendering.
* @private
*/
_disableRemainingAttributes(shader) {
for (const location of this.registerEnabled.values()) {
if (
!Object.keys(shader.attributes).some(
key => shader.attributes[key].location === location
)
) {
this.GL.disableVertexAttribArray(location);
this.registerEnabled.delete(location);
}
}
}
_drawBuffers(geometry, { mode = constants.TRIANGLES, count }) {
const gl = this.GL;
const glBuffers = this.geometryBufferCache.getCached(geometry);
if (!glBuffers) return;
if (this._curShader.shaderType === 'stroke'){
if (count === 1) {
gl.drawArrays(gl.TRIANGLES, 0, geometry.lineVertices.length / 3);
} else {
try {
gl.drawArraysInstanced(
gl.TRIANGLES,
0,
geometry.lineVertices.length / 3,
count
);
} catch (e) {
console.log(
"🌸 p5.js says: Instancing is only supported in WebGL2 mode"
);
}
}
} else if (this._curShader.shaderType === 'text') {
// Text rendering uses a fixed quad geometry with 6 indices
this._bindBuffer(glBuffers.indexBuffer, gl.ELEMENT_ARRAY_BUFFER);
gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
} else if (glBuffers.indexBuffer) {
this._bindBuffer(glBuffers.indexBuffer, gl.ELEMENT_ARRAY_BUFFER);
// If this model is using a Uint32Array we need to ensure the
// OES_element_index_uint WebGL extension is enabled.
if (
this._pInst.webglVersion !== constants.WEBGL2 &&
glBuffers.indexBufferType === gl.UNSIGNED_INT
) {
if (!gl.getExtension("OES_element_index_uint")) {
throw new Error(
"Unable to render a 3d model with > 65535 triangles. Your web browser does not support the WebGL Extension OES_element_index_uint."
);
}
}
if (count === 1) {
gl.drawElements(
gl.TRIANGLES,
geometry.faces.length * 3,
glBuffers.indexBufferType,
0
);
} else {
try {
gl.drawElementsInstanced(
gl.TRIANGLES,
geometry.faces.length * 3,
glBuffers.indexBufferType,
0,
count
);
} catch (e) {
console.log(
"🌸 p5.js says: Instancing is only supported in WebGL2 mode"
);
}
}
} else {
const glMode = mode === constants.TRIANGLES ? gl.TRIANGLES : gl.TRIANGLE_STRIP;
if (count === 1) {
gl.drawArrays(glMode, 0, geometry.vertices.length);
} else {
try {
gl.drawArraysInstanced(glMode, 0, geometry.vertices.length, count);
} catch (e) {
console.log(
"🌸 p5.js says: Instancing is only supported in WebGL2 mode"
);
}
}
}
}
//////////////////////////////////////////////
// Text
//////////////////////////////////////////////
_beforeDrawText() {
this.GL.pixelStorei(this.GL.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
}
_afterDrawText() {
this.GL.pixelStorei(this.GL.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
}
//////////////////////////////////////////////
// Setting
//////////////////////////////////////////////
_setAttributeDefaults(pInst) {
// See issue #3850, safer to enable AA in Safari
const applyAA = navigator.userAgent.toLowerCase().includes("safari");
const defaults = {
alpha: true,
depth: true,
stencil: true,
antialias: applyAA,
premultipliedAlpha: true,
preserveDrawingBuffer: true,
perPixelLighting: true,
version: 2,
};
if (pInst._glAttributes === null) {
pInst._glAttributes = defaults;
} else {
pInst._glAttributes = Object.assign(defaults, pInst._glAttributes);
}
return;
}
_setAttributes(key, value) {
if (typeof this._pInst._glAttributes === "undefined") {
console.log(
"You are trying to use setAttributes on a p5.Graphics object " +
"that does not use a WEBGL renderer."
);
return;
}
let unchanged = true;
if (typeof value !== "undefined") {
//first time modifying the attributes
if (this._pInst._glAttributes === null) {
this._pInst._glAttributes = {};
}
if (this._pInst._glAttributes[key] !== value) {
//changing value of previously altered attribute
this._pInst._glAttributes[key] = value;
unchanged = false;
}
//setting all attributes with some change
} else if (key instanceof Object) {
if (this._pInst._glAttributes !== key) {
this._pInst._glAttributes = key;
unchanged = false;
}
}
//@todo_FES
if (!this.isP3D || unchanged) {
return;
}
if (!this._pInst._setupDone) {
if (this.geometryBufferCache.numCached() > 0) {
p5._friendlyError(
"Sorry, Could not set the attributes, you need to call setAttributes() " +
"before calling the other drawing methods in setup()"
);
return;
}
}
this._resetContext(null, null, RendererGL);
if (this.states.curCamera) {
this.states.curCamera._renderer = this._renderer;
}
}
_initContext() {
if (this._pInst._glAttributes?.version !== 1) {
// Unless WebGL1 is explicitly asked for, try to create a WebGL2 context
this.drawingContext = this.canvas.getContext(
"webgl2",
this._pInst._glAttributes
);
}
this.webglVersion = this.drawingContext
? constants.WEBGL2
: constants.WEBGL;
// If this is the main canvas, make sure the global `webglVersion` is set
this._pInst.webglVersion = this.webglVersion;
if (!this.drawingContext) {
// If we were unable to create a WebGL2 context (either because it was
// disabled via `setAttributes({ version: 1 })` or because the device
// doesn't support it), fall back to a WebGL1 context
this.drawingContext =
this.canvas.getContext("webgl", this._pInst._glAttributes) ||
this.canvas.getContext("experimental-webgl", this._pInst._glAttributes);
}
if (this.drawingContext === null) {
throw new Error("Error creating webgl context");
} else {
const gl = this.drawingContext;
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
// Make sure all images are loaded into the canvas premultiplied so that
// they match the way we render colors. This will make framebuffer textures
// be encoded the same way as textures from everything else.
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
this._viewport = this.drawingContext.getParameter(
this.drawingContext.VIEWPORT
);
}
}
_updateSize() {}
_getMaxTextureSize() {
const gl = this.drawingContext;
return gl.getParameter(gl.MAX_TEXTURE_SIZE);
}
_adjustDimensions(width, height) {
if (!this._maxTextureSize) {
this._maxTextureSize = this._getMaxTextureSize();
}
let maxTextureSize = this._maxTextureSize;
let maxAllowedPixelDimensions = Math.floor(
maxTextureSize / this._pixelDensity
);
let adjustedWidth = Math.min(width, maxAllowedPixelDimensions);
let adjustedHeight = Math.min(height, maxAllowedPixelDimensions);
if (adjustedWidth !== width || adjustedHeight !== height) {
console.warn(
"Warning: The requested width/height exceeds hardware limits. " +
`Adjusting dimensions to width: ${adjustedWidth}, height: ${adjustedHeight}.`
);
}
return { adjustedWidth, adjustedHeight };
}
_resetBuffersBeforeDraw() {
this.GL.clearStencil(0);
this.GL.clear(this.GL.DEPTH_BUFFER_BIT | this.GL.STENCIL_BUFFER_BIT);
if (!this._userEnabledStencil) {
this._internalDisable.call(this.GL, this.GL.STENCIL_TEST);
}
}
_applyClip() {
const gl = this.GL;
gl.clearStencil(0);
gl.clear(gl.STENCIL_BUFFER_BIT);
this._internalEnable.call(gl, gl.STENCIL_TEST);
this._stencilTestOn = true;
gl.stencilFunc(
gl.ALWAYS, // the test
1, // reference value
0xff // mask
);
gl.stencilOp(
gl.KEEP, // what to do if the stencil test fails
gl.KEEP, // what to do if the depth test fails
gl.REPLACE // what to do if both tests pass
);
gl.disable(gl.DEPTH_TEST);
}
_unapplyClip() {
const gl = this.GL;
gl.stencilOp(
gl.KEEP, // what to do if the stencil test fails
gl.KEEP, // what to do if the depth test fails
gl.KEEP // what to do if both tests pass
);
gl.stencilFunc(
this._clipInvert ? gl.EQUAL : gl.NOTEQUAL, // the test
0, // reference value
0xff // mask
);
gl.enable(gl.DEPTH_TEST);
}
_clearClipBuffer() {
this.GL.clearStencil(1);
this.GL.clear(this.GL.STENCIL_BUFFER_BIT);
if (!this._userEnabledStencil) {
this._internalDisable.call(this.GL, this.GL.STENCIL_TEST);
}
}
// x,y are canvas-relative (pre-scaled by _pixelDensity)
_getPixel(x, y) {
const gl = this.GL;
return readPixelWebGL(
gl,
null,
x,
y,
gl.RGBA,
gl.UNSIGNED_BYTE,
this._pInst.height * this._pInst.pixelDensity()
);
}
/**
* Loads the pixels data for this canvas into the pixels[] attribute.
* Note that updatePixels() and set() do not work.
* Any pixel manipulation must be done directly to the pixels[] array.
*
* @private
*/
loadPixels() {
//@todo_FES
if (this._pInst._glAttributes.preserveDrawingBuffer !== true) {
console.log(
"loadPixels only works in WebGL when preserveDrawingBuffer " +
"is true."
);
return;
}
const pd = this._pixelDensity;
const gl = this.GL;
this.pixels = readPixelsWebGL(
this.pixels,
gl,
null,
0,
0,
this.width * pd,
this.height * pd,
gl.RGBA,
gl.UNSIGNED_BYTE,
this.height * pd
);
}
updatePixels() {
const fbo = this._getTempFramebuffer();
fbo.pixels = this.pixels;
fbo.updatePixels();
this.push();
this.resetMatrix();
this.clear();
this.states.setValue("imageMode", constants.CORNER);
this.image(
fbo,
0,
0,
fbo.width,
fbo.height,
-fbo.width / 2,
-fbo.height / 2,
fbo.width,
fbo.height
);
this.pop();
this.GL.clearDepth(1);
this.GL.clear(this.GL.DEPTH_BUFFER_BIT);
}
zClipRange() {
return [-1, 1];
}
defaultNearScale() {
return 0.1;
}
defaultFarScale() {
return 10;
}
viewport(w, h) {
this._viewport = [0, 0, w, h];
this.GL.viewport(0, 0, w, h);
}
_updateViewport() {
this._origViewport = {
width: this.GL.drawingBufferWidth,
height: this.GL.drawingBufferHeight,
};
this.viewport(this._origViewport.width, this._origViewport.height);
}
_createPixelsArray() {
this.pixels = new Uint8Array(
this.GL.drawingBufferWidth * this.GL.drawingBufferHeight * 4
);
}
/**
* clears color and depth buffers
* with r,g,b,a
* @private
* @param {Number} r normalized red val.
* @param {Number} g normalized green val.
* @param {Number} b normalized blue val.
* @param {Number} a normalized alpha val.
*/
clear(...args) {
const _r = args[0] || 0;
const _g = args[1] || 0;
const _b = args[2] || 0;
let _a = args[3] || 0;
const activeFramebuffer = this.activeFramebuffer();
if (
activeFramebuffer &&
activeFramebuffer.format === constants.UNSIGNED_BYTE &&
!activeFramebuffer.antialias &&
_a === 0
) {
// Drivers on Intel Macs check for 0,0,0,0 exactly when drawing to a
// framebuffer and ignore the command if it's the only drawing command to
// the framebuffer. To work around it, we can set the alpha to a value so
// low that it still rounds down to 0, but that circumvents the buggy
// check in the driver.
_a = 1e-10;
}
this.GL.clearColor(_r * _a, _g * _a, _b * _a, _a);
this.GL.clearDepth(1);
this.GL.clear(this.GL.COLOR_BUFFER_BIT | this.GL.DEPTH_BUFFER_BIT);
}
/**
* Resets all depth information so that nothing previously drawn will
* occlude anything subsequently drawn.
*/
clearDepth(depth = 1) {
this.GL.clearDepth(depth);
this.GL.clear(this.GL.DEPTH_BUFFER_BIT);
}
_applyStencilTestIfClipping() {
const drawTarget = this.drawTarget();
if (drawTarget._isClipApplied !== this._stencilTestOn) {
if (drawTarget._isClipApplied) {
this._internalEnable.call(this.GL, this.GL.STENCIL_TEST);
this._stencilTestOn = true;
} else {
if (!this._userEnabledStencil) {
this._internalDisable.call(this.GL, this.GL.STENCIL_TEST);
}
this._stencilTestOn = false;
}
}
}
//////////////////////////////////////////////
// SHADER
//////////////////////////////////////////////
/*
* shaders are created and cached on a per-renderer basis,
* on the grounds that each renderer will have its own gl context
* and the shader must be valid in that context.
*/
baseMaterialShader() {
if (!this._pInst._glAttributes.perPixelLighting) {
throw new Error(
"The material shader does not support hooks without perPixelLighting. Try turning it back on."
);
}
return super.baseMaterialShader();
}
_getLightShader() {
if (!this._defaultLightShader) {
if (this._pInst._glAttributes.perPixelLighting) {
this._defaultLightShader = new Shader(
this,
this._webGL2CompatibilityPrefix("vert", "highp") +
defaultShaders.phongVert,
this._webGL2CompatibilityPrefix("frag", "highp") +
defaultShaders.phongFrag,
{
vertex: {
"void beforeVertex": "() {}",
"Vertex getObjectInputs": "(Vertex inputs) { return inputs; }",
"Vertex getWorldInputs": "(Vertex inputs) { return inputs; }",
"Vertex getCameraInputs": "(Vertex inputs) { return inputs; }",
"void afterVertex": "() {}",
},
fragment: {
"void beforeFragment": "() {}",
"Inputs getPixelInputs": "(Inputs inputs) { return inputs; }",
"vec4 combineColors": `(ColorComponents components) {
vec4 color = vec4(0.);
color.rgb += components.diffuse * components.baseColor;
color.rgb += components.ambient * components.ambientColor;
color.rgb += components.specular * components.specularColor;
color.rgb += components.emissive;
color.a = components.opacity;
return color;
}`,
"vec4 getFinalColor": "(vec4 color) { return color; }",
"void afterFragment": "() {}",
},
}
);
} else {
this._defaultLightShader = new Shader(
this,
this._webGL2CompatibilityPrefix("vert", "highp") +
defaultShaders.lightVert,
this._webGL2CompatibilityPrefix("frag", "highp") +
defaultShaders.lightTextureFrag
);
}
}
return this._defaultLightShader;
}
_getNormalShader() {
if (!this._defaultNormalShader) {
this._defaultNormalShader = new Shader(
this,
this._webGL2CompatibilityPrefix("vert", "highp") +
defaultShaders.normalVert,
this._webGL2CompatibilityPrefix("frag", "highp") +
defaultShaders.normalFrag,
{
vertex: {
"void beforeVertex": "() {}",
"Vertex getObjectInputs": "(Vertex inputs) { return inputs; }",
"Vertex getWorldInputs": "(Vertex inputs) { return inputs; }",
"Vertex getCameraInputs": "(Vertex inputs) { return inputs; }",
"void afterVertex": "() {}",
},
fragment: {
"void beforeFragment": "() {}",
"vec4 getFinalColor": "(vec4 color) { return color; }",
"void afterFragment": "() {}",
},
}
);
}
return this._defaultNormalShader;
}
_getColorShader() {
if (!this._defaultColorShader) {
this._defaultColorShader = new Shader(
this,
this._webGL2CompatibilityPrefix("vert", "highp") +
defaultShaders.normalVert,
this._webGL2CompatibilityPrefix("frag", "highp") +
defaultShaders.basicFrag,
{
vertex: {
"void beforeVertex": "() {}",
"Vertex getObjectInputs": "(Vertex inputs) { return inputs; }",
"Vertex getWorldInputs": "(Vertex inputs) { return inputs; }",
"Vertex getCameraInputs": "(Vertex inputs) { return inputs; }",
"void afterVertex": "() {}",
},
fragment: {
"void beforeFragment": "() {}",
"vec4 getFinalColor": "(vec4 color) { return color; }",
"void afterFragment": "() {}",
},
}
);
}
return this._defaultColorShader;
}
_getLineShader() {
if (!this._defaultLineShader) {
this._defaultLineShader = new Shader(
this,
this._webGL2CompatibilityPrefix("vert", "highp") +
defaultShaders.lineVert,
this._webGL2CompatibilityPrefix("frag", "highp") +
defaultShaders.lineFrag,
{
vertex: {
"void beforeVertex": "() {}",
"StrokeVertex getObjectInputs":
"(StrokeVertex inputs) { return inputs; }",
"StrokeVertex getWorldInputs":
"(StrokeVertex inputs) { return inputs; }",
"StrokeVertex getCameraInputs":
"(StrokeVertex inputs) { return inputs; }",
"void afterVertex": "() {}",
},
fragment: {
"void beforeFragment": "() {}",
"Inputs getPixelInputs": "(Inputs inputs) { return inputs; }",
"vec4 getFinalColor": "(vec4 color) { return color; }",
"bool shouldDiscard": "(bool outside) { return outside; }",
"void afterFragment": "() {}",
},
}
);
}
return this._defaultLineShader;
}
_getFontShader() {
if (!this._defaultFontShader) {
if (this.webglVersion === constants.WEBGL) {
this.GL.getExtension("OES_standard_derivatives");
}
this._defaultFontShader = new Shader(
this,
this._webGL2CompatibilityPrefix("vert", "highp") +
defaultShaders.fontVert,
this._webGL2CompatibilityPrefix("frag", "highp") +
defaultShaders.fontFrag
);
}
return this._defaultFontShader;
}
baseFilterShader() {
if (!this._baseFilterShader) {
this._baseFilterShader = new Shader(
this,
this._webGL2CompatibilityPrefix("vert", "highp") +
defaultShaders.filterBaseVert,
this._webGL2CompatibilityPrefix("frag", "highp") +
defaultShaders.filterBaseFrag,
{
vertex: {},
fragment: {
"vec4 getColor": `(FilterInputs inputs, in sampler2D canvasContent) {
return getTexture(canvasContent, inputs.texCoord);
}`,
},
hookAliases: {
'getColor': ['filterColor'],
},
}
);
}
return this._baseFilterShader;
}
_webGL2CompatibilityPrefix(shaderType, floatPrecision) {
let code = "";
if (this.webglVersion === constants.WEBGL2) {
code += "#version 300 es\n#define WEBGL2\n";
}
if (shaderType === "vert") {
code += "#define VERTEX_SHADER\n";
} else if (shaderType === "frag") {
code += "#define FRAGMENT_SHADER\n";
}
if (floatPrecision) {
code += `precision ${floatPrecision} float;\n`;
}
return code;
}
/*
* WebGL-specific implementation of imageLight shader creation
*/
_createImageLightShader(type) {
if (type === 'diffused') {
return new Shader(
this,
this._webGL2CompatibilityPrefix("vert", "highp") +
defaultShaders.imageLightVert,
this._webGL2CompatibilityPrefix("frag", "highp") +
defaultShaders.imageLightDiffusedFrag
);
} else if (type === 'specular') {
return new Shader(
this,
this._webGL2CompatibilityPrefix("vert", "highp") +
defaultShaders.imageLightVert,
this._webGL2CompatibilityPrefix("frag", "highp") +
defaultShaders.imageLightSpecularFrag
);
}
throw new Error(`Unknown imageLight shader type: ${type}`);
}
/*
* WebGL-specific implementation of mipmap texture creation
*/
_createMipmapTexture(levels) {
return new MipmapTexture(this, levels, {});
}
/*
* Prepare array to collect ImageData levels for WebGL
*/
_prepareMipmapData(size, mipLevels) {
return { levels: [], size, mipLevels };
}
/*
* Accumulate ImageData from framebuffer for WebGL
*/
_accumulateMipLevel(framebuffer, mipmapData, mipLevel, width, height) {
const imageData = framebuffer.get().drawingContext.getImageData(0, 0, width, height);
mipmapData.levels.push(imageData);
}
/*
* Create final MipmapTexture from collected ImageData for WebGL
*/
_finalizeMipmapTexture(mipmapData) {
return new MipmapTexture(this, mipmapData.levels, {
minFilter: constants.LINEAR_MIPMAP,
magFilter: constants.LINEAR,
});
}
createMipmapTextureHandle({ levels, format, dataType, width, height }) {
const gl = this.GL;
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
// Determine GL format and data type
const glFormat = gl.RGBA;
const glDataType = gl.UNSIGNED_BYTE;
for (let level = 0; level < levels.length; level++) {
gl.texImage2D(
gl.TEXTURE_2D,
level,
glFormat,
glFormat,
glDataType,
levels[level]
);
}
// Set mipmap-appropriate filtering
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
gl.bindTexture(gl.TEXTURE_2D, null);
return { texture, glFormat, glDataType };
}
/* Binds a buffer to the drawing context
* when passed more than two arguments it also updates or initializes
* the data associated with the buffer
*/
_bindBuffer(buffer, target, values, type, usage) {
const gl = this.GL;
if (!target) target = gl.ARRAY_BUFFER;
gl.bindBuffer(target, buffer);
if (values !== undefined) {
const data = this._normalizeBufferData(values, type);
gl.bufferData(target, data, usage || gl.STATIC_DRAW);
}
}
_prepareBuffer(renderBuffer, geometry, shader) {
const attributes = shader.attributes;
const gl = this.GL;
const glBuffers = this._getOrMakeCachedBuffers(geometry);
// loop through each of the buffer definitions
const attr = attributes[renderBuffer.attr];
if (!attr) {
return;
}