-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
p5.RendererGL.js
executable file
·1533 lines (1366 loc) · 43.8 KB
/
p5.RendererGL.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
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 p5 from '../core/main';
import * as constants from '../core/constants';
import libtess from 'libtess';
import './p5.Shader';
import './p5.Camera';
import '../core/p5.Renderer';
import './p5.Matrix';
import { readFileSync } from 'fs';
import { join } from 'path';
const lightingShader = readFileSync(
join(__dirname, '/shaders/lighting.glsl'),
'utf-8'
);
const defaultShaders = {
immediateVert: readFileSync(
join(__dirname, '/shaders/immediate.vert'),
'utf-8'
),
vertexColorVert: readFileSync(
join(__dirname, '/shaders/vertexColor.vert'),
'utf-8'
),
vertexColorFrag: readFileSync(
join(__dirname, '/shaders/vertexColor.frag'),
'utf-8'
),
normalVert: readFileSync(join(__dirname, '/shaders/normal.vert'), 'utf-8'),
normalFrag: readFileSync(join(__dirname, '/shaders/normal.frag'), 'utf-8'),
basicFrag: readFileSync(join(__dirname, '/shaders/basic.frag'), 'utf-8'),
lightVert:
lightingShader +
readFileSync(join(__dirname, '/shaders/light.vert'), 'utf-8'),
lightTextureFrag: readFileSync(
join(__dirname, '/shaders/light_texture.frag'),
'utf-8'
),
phongVert: readFileSync(join(__dirname, '/shaders/phong.vert'), 'utf-8'),
phongFrag:
lightingShader +
readFileSync(join(__dirname, '/shaders/phong.frag'), 'utf-8'),
fontVert: readFileSync(join(__dirname, '/shaders/font.vert'), 'utf-8'),
fontFrag: readFileSync(join(__dirname, '/shaders/font.frag'), 'utf-8'),
lineVert: readFileSync(join(__dirname, '/shaders/line.vert'), 'utf-8'),
lineFrag: readFileSync(join(__dirname, '/shaders/line.frag'), 'utf-8'),
pointVert: readFileSync(join(__dirname, '/shaders/point.vert'), 'utf-8'),
pointFrag: readFileSync(join(__dirname, '/shaders/point.frag'), 'utf-8')
};
/**
* 3D graphics class
* @private
* @class p5.RendererGL
* @constructor
* @extends p5.Renderer
* @todo extend class to include public method for offscreen
* rendering (FBO).
*/
p5.RendererGL = function(elt, pInst, isMainCanvas, attr) {
p5.Renderer.call(this, elt, pInst, isMainCanvas);
this._setAttributeDefaults(pInst);
this._initContext();
this.isP3D = true; //lets us know we're in 3d mode
// This redundant property is useful in reminding you that you are
// interacting with WebGLRenderingContext, still worth considering future removal
this.GL = this.drawingContext;
this._pInst._setProperty('drawingContext', this.drawingContext);
// erasing
this._isErasing = false;
// lights
this._enableLighting = false;
this.ambientLightColors = [];
this.specularColors = [1, 1, 1];
this.directionalLightDirections = [];
this.directionalLightDiffuseColors = [];
this.directionalLightSpecularColors = [];
this.pointLightPositions = [];
this.pointLightDiffuseColors = [];
this.pointLightSpecularColors = [];
this.spotLightPositions = [];
this.spotLightDirections = [];
this.spotLightDiffuseColors = [];
this.spotLightSpecularColors = [];
this.spotLightAngle = [];
this.spotLightConc = [];
this.drawMode = constants.FILL;
this.curFillColor = this._cachedFillStyle = [1, 1, 1, 1];
this.curAmbientColor = this._cachedFillStyle = [0, 0, 0, 0];
this.curSpecularColor = this._cachedFillStyle = [0, 0, 0, 0];
this.curEmissiveColor = this._cachedFillStyle = [0, 0, 0, 0];
this.curStrokeColor = this._cachedStrokeStyle = [0, 0, 0, 1];
this.curBlendMode = constants.BLEND;
this._cachedBlendMode = undefined;
this.blendExt = this.GL.getExtension('EXT_blend_minmax');
this._isBlending = false;
this._useSpecularMaterial = false;
this._useEmissiveMaterial = false;
this._useNormalMaterial = false;
this._useShininess = 1;
this._tint = [255, 255, 255, 255];
// lightFalloff variables
this.constantAttenuation = 1;
this.linearAttenuation = 0;
this.quadraticAttenuation = 0;
/**
* model view, projection, & normal
* matrices
*/
this.uMVMatrix = new p5.Matrix();
this.uPMatrix = new p5.Matrix();
this.uNMatrix = new p5.Matrix('mat3');
// Current vertex normal
this._currentNormal = new p5.Vector(0, 0, 1);
// Camera
this._curCamera = new p5.Camera(this);
this._curCamera._computeCameraDefaultSettings();
this._curCamera._setDefaultCamera();
this._defaultLightShader = undefined;
this._defaultImmediateModeShader = undefined;
this._defaultNormalShader = undefined;
this._defaultColorShader = undefined;
this._defaultPointShader = undefined;
this.userFillShader = undefined;
this.userStrokeShader = undefined;
this.userPointShader = undefined;
// Default drawing is done in Retained Mode
// Geometry and Material hashes stored here
this.retainedMode = {
geometry: {},
buffers: {
stroke: [
new p5.RenderBuffer(3, 'lineVertices', 'lineVertexBuffer', 'aPosition', this, this._flatten),
new p5.RenderBuffer(4, 'lineNormals', 'lineNormalBuffer', 'aDirection', this, this._flatten)
],
fill: [
new p5.RenderBuffer(3, 'vertices', 'vertexBuffer', 'aPosition', this, this._vToNArray),
new p5.RenderBuffer(3, 'vertexNormals', 'normalBuffer', 'aNormal', this, this._vToNArray),
new p5.RenderBuffer(4, 'vertexColors', 'colorBuffer', 'aVertexColor', this),
new p5.RenderBuffer(3, 'vertexAmbients', 'ambientBuffer', 'aAmbientColor', this),
//new BufferDef(3, 'vertexSpeculars', 'specularBuffer', 'aSpecularColor'),
new p5.RenderBuffer(2, 'uvs', 'uvBuffer', 'aTexCoord', this, this._flatten)
],
text: [
new p5.RenderBuffer(3, 'vertices', 'vertexBuffer', 'aPosition',this, this._vToNArray),
new p5.RenderBuffer(2, 'uvs', 'uvBuffer', 'aTexCoord', this, this._flatten)
]
}
};
// Immediate Mode
// Geometry and Material hashes stored here
this.immediateMode = {
geometry: new p5.Geometry(),
shapeMode: constants.TRIANGLE_FAN,
_bezierVertex: [],
_quadraticVertex: [],
_curveVertex: [],
buffers: {
fill: [
new p5.RenderBuffer(3, 'vertices', 'vertexBuffer', 'aPosition', this, this._vToNArray),
new p5.RenderBuffer(3, 'vertexNormals', 'normalBuffer', 'aNormal', this, this._vToNArray),
new p5.RenderBuffer(4, 'vertexColors', 'colorBuffer', 'aVertexColor', this),
new p5.RenderBuffer(3, 'vertexAmbients', 'ambientBuffer', 'aAmbientColor', this),
new p5.RenderBuffer(2, 'uvs', 'uvBuffer', 'aTexCoord', this, this._flatten)
],
stroke: [
new p5.RenderBuffer(3, 'lineVertices', 'lineVertexBuffer', 'aPosition', this, this._flatten),
new p5.RenderBuffer(4, 'lineNormals', 'lineNormalBuffer', 'aDirection', this, this._flatten)
],
point: this.GL.createBuffer()
}
};
this.pointSize = 5.0; //default point size
this.curStrokeWeight = 1;
// array of textures created in this gl context via this.getTexture(src)
this.textures = [];
this.textureMode = constants.IMAGE;
// default wrap settings
this.textureWrapX = constants.CLAMP;
this.textureWrapY = constants.CLAMP;
this._tex = null;
this._curveTightness = 6;
// lookUpTable for coefficients needed to be calculated for bezierVertex, same are used for curveVertex
this._lookUpTableBezier = [];
// lookUpTable for coefficients needed to be calculated for quadraticVertex
this._lookUpTableQuadratic = [];
// current curveDetail in the Bezier lookUpTable
this._lutBezierDetail = 0;
// current curveDetail in the Quadratic lookUpTable
this._lutQuadraticDetail = 0;
this._tessy = this._initTessy();
this.fontInfos = {};
this._curShader = undefined;
return this;
};
p5.RendererGL.prototype = Object.create(p5.Renderer.prototype);
//////////////////////////////////////////////
// Setting
//////////////////////////////////////////////
p5.RendererGL.prototype._setAttributeDefaults = function(pInst) {
// See issue #3850, safer to enable AA in Safari
const applyAA = navigator.userAgent.toLowerCase().includes('safari');
const defaults = {
alpha: false,
depth: true,
stencil: true,
antialias: applyAA,
premultipliedAlpha: false,
preserveDrawingBuffer: true,
perPixelLighting: true
};
if (pInst._glAttributes === null) {
pInst._glAttributes = defaults;
} else {
pInst._glAttributes = Object.assign(defaults, pInst._glAttributes);
}
return;
};
p5.RendererGL.prototype._initContext = function() {
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);
this._viewport = this.drawingContext.getParameter(
this.drawingContext.VIEWPORT
);
}
};
//This is helper function to reset the context anytime the attributes
//are changed with setAttributes()
p5.RendererGL.prototype._resetContext = function(options, callback) {
const w = this.width;
const h = this.height;
const defaultId = this.canvas.id;
const isPGraphics = this._pInst instanceof p5.Graphics;
if (isPGraphics) {
const pg = this._pInst;
pg.canvas.parentNode.removeChild(pg.canvas);
pg.canvas = document.createElement('canvas');
const node = pg._pInst._userNode || document.body;
node.appendChild(pg.canvas);
p5.Element.call(pg, pg.canvas, pg._pInst);
pg.width = w;
pg.height = h;
} else {
let c = this.canvas;
if (c) {
c.parentNode.removeChild(c);
}
c = document.createElement('canvas');
c.id = defaultId;
if (this._pInst._userNode) {
this._pInst._userNode.appendChild(c);
} else {
document.body.appendChild(c);
}
this._pInst.canvas = c;
this.canvas = c;
}
const renderer = new p5.RendererGL(
this._pInst.canvas,
this._pInst,
!isPGraphics
);
this._pInst._setProperty('_renderer', renderer);
renderer.resize(w, h);
renderer._applyDefaults();
if (!isPGraphics) {
this._pInst._elements.push(renderer);
}
if (typeof callback === 'function') {
//setTimeout with 0 forces the task to the back of the queue, this ensures that
//we finish switching out the renderer
setTimeout(() => {
callback.apply(window._renderer, options);
}, 0);
}
};
/**
* @module Rendering
* @submodule Rendering
* @for p5
*/
/**
* Set attributes for the WebGL Drawing context.
* This is a way of adjusting how the WebGL
* renderer works to fine-tune the display and performance.
*
* Note that this will reinitialize the drawing context
* if called after the WebGL canvas is made.
*
* If an object is passed as the parameter, all attributes
* not declared in the object will be set to defaults.
*
* The available attributes are:
* <br>
* alpha - indicates if the canvas contains an alpha buffer
* default is false
*
* depth - indicates whether the drawing buffer has a depth buffer
* of at least 16 bits - default is true
*
* stencil - indicates whether the drawing buffer has a stencil buffer
* of at least 8 bits
*
* antialias - indicates whether or not to perform anti-aliasing
* default is false (true in Safari)
*
* premultipliedAlpha - indicates that the page compositor will assume
* the drawing buffer contains colors with pre-multiplied alpha
* default is false
*
* preserveDrawingBuffer - if true the buffers will not be cleared and
* and will preserve their values until cleared or overwritten by author
* (note that p5 clears automatically on draw loop)
* default is true
*
* perPixelLighting - if true, per-pixel lighting will be used in the
* lighting shader otherwise per-vertex lighting is used.
* default is true.
*
* @method setAttributes
* @for p5
* @param {String} key Name of attribute
* @param {Boolean} value New value of named attribute
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(255);
* push();
* rotateZ(frameCount * 0.02);
* rotateX(frameCount * 0.02);
* rotateY(frameCount * 0.02);
* fill(0, 0, 0);
* box(50);
* pop();
* }
* </code>
* </div>
* <br>
* Now with the antialias attribute set to true.
* <br>
* <div>
* <code>
* function setup() {
* setAttributes('antialias', true);
* createCanvas(100, 100, WEBGL);
* }
*
* function draw() {
* background(255);
* push();
* rotateZ(frameCount * 0.02);
* rotateX(frameCount * 0.02);
* rotateY(frameCount * 0.02);
* fill(0, 0, 0);
* box(50);
* pop();
* }
* </code>
* </div>
*
* <div>
* <code>
* // press the mouse button to disable perPixelLighting
* function setup() {
* createCanvas(100, 100, WEBGL);
* noStroke();
* fill(255);
* }
*
* let lights = [
* { c: '#f00', t: 1.12, p: 1.91, r: 0.2 },
* { c: '#0f0', t: 1.21, p: 1.31, r: 0.2 },
* { c: '#00f', t: 1.37, p: 1.57, r: 0.2 },
* { c: '#ff0', t: 1.12, p: 1.91, r: 0.7 },
* { c: '#0ff', t: 1.21, p: 1.31, r: 0.7 },
* { c: '#f0f', t: 1.37, p: 1.57, r: 0.7 }
* ];
*
* function draw() {
* let t = millis() / 1000 + 1000;
* background(0);
* directionalLight(color('#222'), 1, 1, 1);
*
* for (let i = 0; i < lights.length; i++) {
* let light = lights[i];
* pointLight(
* color(light.c),
* p5.Vector.fromAngles(t * light.t, t * light.p, width * light.r)
* );
* }
*
* specularMaterial(255);
* sphere(width * 0.1);
*
* rotateX(t * 0.77);
* rotateY(t * 0.83);
* rotateZ(t * 0.91);
* torus(width * 0.3, width * 0.07, 24, 10);
* }
*
* function mousePressed() {
* setAttributes('perPixelLighting', false);
* noStroke();
* fill(255);
* }
* function mouseReleased() {
* setAttributes('perPixelLighting', true);
* noStroke();
* fill(255);
* }
* </code>
* </div>
*
* @alt a rotating cube with smoother edges
*/
/**
* @method setAttributes
* @for p5
* @param {Object} obj object with key-value pairs
*/
p5.prototype.setAttributes = function(key, value) {
if (typeof this._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._glAttributes === null) {
this._glAttributes = {};
}
if (this._glAttributes[key] !== value) {
//changing value of previously altered attribute
this._glAttributes[key] = value;
unchanged = false;
}
//setting all attributes with some change
} else if (key instanceof Object) {
if (this._glAttributes !== key) {
this._glAttributes = key;
unchanged = false;
}
}
//@todo_FES
if (!this._renderer.isP3D || unchanged) {
return;
}
if (!this._setupDone) {
for (const x in this._renderer.retainedMode.geometry) {
if (this._renderer.retainedMode.geometry.hasOwnProperty(x)) {
console.error(
'Sorry, Could not set the attributes, you need to call setAttributes() ' +
'before calling the other drawing methods in setup()'
);
return;
}
}
}
this.push();
this._renderer._resetContext();
this.pop();
if (this._renderer._curCamera) {
this._renderer._curCamera._renderer = this._renderer;
}
};
/**
* @class p5.RendererGL
*/
p5.RendererGL.prototype._update = function() {
// reset model view and apply initial camera transform
// (containing only look at info; no projection).
this.uMVMatrix.set(
this._curCamera.cameraMatrix.mat4[0],
this._curCamera.cameraMatrix.mat4[1],
this._curCamera.cameraMatrix.mat4[2],
this._curCamera.cameraMatrix.mat4[3],
this._curCamera.cameraMatrix.mat4[4],
this._curCamera.cameraMatrix.mat4[5],
this._curCamera.cameraMatrix.mat4[6],
this._curCamera.cameraMatrix.mat4[7],
this._curCamera.cameraMatrix.mat4[8],
this._curCamera.cameraMatrix.mat4[9],
this._curCamera.cameraMatrix.mat4[10],
this._curCamera.cameraMatrix.mat4[11],
this._curCamera.cameraMatrix.mat4[12],
this._curCamera.cameraMatrix.mat4[13],
this._curCamera.cameraMatrix.mat4[14],
this._curCamera.cameraMatrix.mat4[15]
);
// reset light data for new frame.
this.ambientLightColors.length = 0;
this.specularColors = [1, 1, 1];
this.directionalLightDirections.length = 0;
this.directionalLightDiffuseColors.length = 0;
this.directionalLightSpecularColors.length = 0;
this.pointLightPositions.length = 0;
this.pointLightDiffuseColors.length = 0;
this.pointLightSpecularColors.length = 0;
this.spotLightPositions.length = 0;
this.spotLightDirections.length = 0;
this.spotLightDiffuseColors.length = 0;
this.spotLightSpecularColors.length = 0;
this.spotLightAngle.length = 0;
this.spotLightConc.length = 0;
this._enableLighting = false;
//reset tint value for new frame
this._tint = [255, 255, 255, 255];
//Clear depth every frame
this.GL.clear(this.GL.DEPTH_BUFFER_BIT);
};
/**
* [background description]
*/
p5.RendererGL.prototype.background = function(...args) {
const _col = this._pInst.color(...args);
const _r = _col.levels[0] / 255;
const _g = _col.levels[1] / 255;
const _b = _col.levels[2] / 255;
const _a = _col.levels[3] / 255;
this.GL.clearColor(_r, _g, _b, _a);
this.GL.clear(this.GL.COLOR_BUFFER_BIT);
};
//////////////////////////////////////////////
// COLOR
//////////////////////////////////////////////
/**
* Basic fill material for geometry with a given color
* @method fill
* @class p5.RendererGL
* @param {Number|Number[]|String|p5.Color} v1 gray value,
* red or hue value (depending on the current color mode),
* or color Array, or CSS color string
* @param {Number} [v2] green or saturation value
* @param {Number} [v3] blue or brightness value
* @param {Number} [a] opacity
* @chainable
* @example
* <div>
* <code>
* function setup() {
* createCanvas(200, 200, WEBGL);
* }
*
* function draw() {
* background(0);
* noStroke();
* fill(100, 100, 240);
* rotateX(frameCount * 0.01);
* rotateY(frameCount * 0.01);
* box(75, 75, 75);
* }
* </code>
* </div>
*
* @alt
* black canvas with purple cube spinning
*/
p5.RendererGL.prototype.fill = function(v1, v2, v3, a) {
//see material.js for more info on color blending in webgl
const color = p5.prototype.color.apply(this._pInst, arguments);
this.curFillColor = color._array;
this.drawMode = constants.FILL;
this._useNormalMaterial = false;
this._tex = null;
};
/**
* Basic stroke material for geometry with a given color
* @method stroke
* @param {Number|Number[]|String|p5.Color} v1 gray value,
* red or hue value (depending on the current color mode),
* or color Array, or CSS color string
* @param {Number} [v2] green or saturation value
* @param {Number} [v3] blue or brightness value
* @param {Number} [a] opacity
* @example
* <div>
* <code>
* function setup() {
* createCanvas(200, 200, WEBGL);
* }
*
* function draw() {
* background(0);
* stroke(240, 150, 150);
* fill(100, 100, 240);
* rotateX(frameCount * 0.01);
* rotateY(frameCount * 0.01);
* box(75, 75, 75);
* }
* </code>
* </div>
*
* @alt
* black canvas with purple cube with pink outline spinning
*/
p5.RendererGL.prototype.stroke = function(r, g, b, a) {
//@todo allow transparency in stroking currently doesn't have
//any impact and causes problems with specularMaterial
arguments[3] = 255;
const color = p5.prototype.color.apply(this._pInst, arguments);
this.curStrokeColor = color._array;
};
p5.RendererGL.prototype.strokeCap = function(cap) {
// @TODO : to be implemented
console.error('Sorry, strokeCap() is not yet implemented in WEBGL mode');
};
p5.RendererGL.prototype.strokeJoin = function(join) {
// @TODO : to be implemented
// https://processing.org/reference/strokeJoin_.html
console.error('Sorry, strokeJoin() is not yet implemented in WEBGL mode');
};
p5.RendererGL.prototype.filter = function(filterType) {
// filter can be achieved using custom shaders.
// https://github.com/aferriss/p5jsShaderExamples
// https://itp-xstory.github.io/p5js-shaders/#/
console.error('filter() does not work in WEBGL mode');
};
p5.RendererGL.prototype.blendMode = function(mode) {
if (
mode === constants.DARKEST ||
mode === constants.LIGHTEST ||
mode === constants.ADD ||
mode === constants.BLEND ||
mode === constants.SUBTRACT ||
mode === constants.SCREEN ||
mode === constants.EXCLUSION ||
mode === constants.REPLACE ||
mode === constants.MULTIPLY ||
mode === constants.REMOVE
)
this.curBlendMode = mode;
else if (
mode === constants.BURN ||
mode === constants.OVERLAY ||
mode === constants.HARD_LIGHT ||
mode === constants.SOFT_LIGHT ||
mode === constants.DODGE
) {
console.warn(
'BURN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, and DODGE only work for blendMode in 2D mode.'
);
}
};
p5.RendererGL.prototype.erase = function(opacityFill, opacityStroke) {
if (!this._isErasing) {
this._applyBlendMode(constants.REMOVE);
this._isErasing = true;
this._cachedFillStyle = this.curFillColor.slice();
this.curFillColor = [1, 1, 1, opacityFill / 255];
this._cachedStrokeStyle = this.curStrokeColor.slice();
this.curStrokeColor = [1, 1, 1, opacityStroke / 255];
}
};
p5.RendererGL.prototype.noErase = function() {
if (this._isErasing) {
this._isErasing = false;
this.curFillColor = this._cachedFillStyle.slice();
this.curStrokeColor = this._cachedStrokeStyle.slice();
this.blendMode(this._cachedBlendMode);
}
};
/**
* Change weight of stroke
* @method strokeWeight
* @param {Number} stroke weight to be used for drawing
* @example
* <div>
* <code>
* function setup() {
* createCanvas(200, 400, WEBGL);
* setAttributes('antialias', true);
* }
*
* function draw() {
* background(0);
* noStroke();
* translate(0, -100, 0);
* stroke(240, 150, 150);
* fill(100, 100, 240);
* push();
* strokeWeight(8);
* rotateX(frameCount * 0.01);
* rotateY(frameCount * 0.01);
* sphere(75);
* pop();
* push();
* translate(0, 200, 0);
* strokeWeight(1);
* rotateX(frameCount * 0.01);
* rotateY(frameCount * 0.01);
* sphere(75);
* pop();
* }
* </code>
* </div>
*
* @alt
* black canvas with two purple rotating spheres with pink
* outlines the sphere on top has much heavier outlines,
*/
p5.RendererGL.prototype.strokeWeight = function(w) {
if (this.curStrokeWeight !== w) {
this.pointSize = w;
this.curStrokeWeight = w;
}
};
// x,y are canvas-relative (pre-scaled by _pixelDensity)
p5.RendererGL.prototype._getPixel = function(x, y) {
let imageData, index;
imageData = new Uint8Array(4);
this.drawingContext.readPixels(
x, y, 1, 1,
this.drawingContext.RGBA, this.drawingContext.UNSIGNED_BYTE,
imageData
);
index = 0;
return [
imageData[index + 0],
imageData[index + 1],
imageData[index + 2],
imageData[index + 3]
];
};
/**
* 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
* @method loadPixels
*/
p5.RendererGL.prototype.loadPixels = function() {
const pixelsState = this._pixelsState;
//@todo_FES
if (this._pInst._glAttributes.preserveDrawingBuffer !== true) {
console.log(
'loadPixels only works in WebGL when preserveDrawingBuffer ' + 'is true.'
);
return;
}
//if there isn't a renderer-level temporary pixels buffer
//make a new one
let pixels = pixelsState.pixels;
const len = this.GL.drawingBufferWidth * this.GL.drawingBufferHeight * 4;
if (!(pixels instanceof Uint8Array) || pixels.length !== len) {
pixels = new Uint8Array(len);
this._pixelsState._setProperty('pixels', pixels);
}
const pd = this._pInst._pixelDensity;
this.GL.readPixels(
0, 0, this.width * pd, this.height * pd,
this.GL.RGBA, this.GL.UNSIGNED_BYTE,
pixels
);
};
//////////////////////////////////////////////
// HASH | for geometry
//////////////////////////////////////////////
p5.RendererGL.prototype.geometryInHash = function(gId) {
return this.retainedMode.geometry[gId] !== undefined;
};
/**
* [resize description]
* @private
* @param {Number} w [description]
* @param {Number} h [description]
*/
p5.RendererGL.prototype.resize = function(w, h) {
p5.Renderer.prototype.resize.call(this, w, h);
this.GL.viewport(
0,
0,
this.GL.drawingBufferWidth,
this.GL.drawingBufferHeight
);
this._viewport = this.GL.getParameter(this.GL.VIEWPORT);
this._curCamera._resize();
//resize pixels buffer
const pixelsState = this._pixelsState;
if (typeof pixelsState.pixels !== 'undefined') {
pixelsState._setProperty(
'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.
*/
p5.RendererGL.prototype.clear = function(...args) {
const _r = args[0] || 0;
const _g = args[1] || 0;
const _b = args[2] || 0;
const _a = args[3] || 0;
this.GL.clearColor(_r, _g, _b, _a);
this.GL.clearDepth(1);
this.GL.clear(this.GL.COLOR_BUFFER_BIT | this.GL.DEPTH_BUFFER_BIT);
};
p5.RendererGL.prototype.applyMatrix = function(a, b, c, d, e, f) {
if (arguments.length === 16) {
p5.Matrix.prototype.apply.apply(this.uMVMatrix, arguments);
} else {
this.uMVMatrix.apply([
a, b, 0, 0,
c, d, 0, 0,
0, 0, 1, 0,
e, f, 0, 1
]);
}
};
/**
* [translate description]
* @private
* @param {Number} x [description]
* @param {Number} y [description]
* @param {Number} z [description]
* @chainable
* @todo implement handle for components or vector as args
*/
p5.RendererGL.prototype.translate = function(x, y, z) {
if (x instanceof p5.Vector) {
z = x.z;
y = x.y;
x = x.x;
}
this.uMVMatrix.translate([x, y, z]);
return this;
};
/**
* Scales the Model View Matrix by a vector
* @private
* @param {Number | p5.Vector | Array} x [description]
* @param {Number} [y] y-axis scalar
* @param {Number} [z] z-axis scalar
* @chainable
*/
p5.RendererGL.prototype.scale = function(x, y, z) {
this.uMVMatrix.scale(x, y, z);
return this;
};
p5.RendererGL.prototype.rotate = function(rad, axis) {
if (typeof axis === 'undefined') {
return this.rotateZ(rad);
}
p5.Matrix.prototype.rotate.apply(this.uMVMatrix, arguments);
return this;
};
p5.RendererGL.prototype.rotateX = function(rad) {
this.rotate(rad, 1, 0, 0);
return this;
};
p5.RendererGL.prototype.rotateY = function(rad) {
this.rotate(rad, 0, 1, 0);
return this;
};
p5.RendererGL.prototype.rotateZ = function(rad) {
this.rotate(rad, 0, 0, 1);
return this;
};
p5.RendererGL.prototype.push = function() {
// get the base renderer style
const style = p5.Renderer.prototype.push.apply(this);
// add webgl-specific style properties
const properties = style.properties;
properties.uMVMatrix = this.uMVMatrix.copy();
properties.uPMatrix = this.uPMatrix.copy();
properties._curCamera = this._curCamera;
// make a copy of the current camera for the push state
// this preserves any references stored using 'createCamera'
this._curCamera = this._curCamera.copy();
properties.ambientLightColors = this.ambientLightColors.slice();
properties.specularColors = this.specularColors.slice();
properties.directionalLightDirections =
this.directionalLightDirections.slice();
properties.directionalLightDiffuseColors =
this.directionalLightDiffuseColors.slice();
properties.directionalLightSpecularColors =
this.directionalLightSpecularColors.slice();
properties.pointLightPositions = this.pointLightPositions.slice();
properties.pointLightDiffuseColors = this.pointLightDiffuseColors.slice();
properties.pointLightSpecularColors = this.pointLightSpecularColors.slice();
properties.spotLightPositions = this.spotLightPositions.slice();