-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
p5.RendererGL.js
2437 lines (2207 loc) · 76.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 GeometryBuilder from './GeometryBuilder';
import libtess from 'libtess'; // Fixed with exporting module from libtess
import Renderer from '../core/p5.Renderer';
const STROKE_CAP_ENUM = {};
const STROKE_JOIN_ENUM = {};
let lineDefs = '';
const defineStrokeCapEnum = function (key, val) {
lineDefs += `#define STROKE_CAP_${key} ${val}\n`;
STROKE_CAP_ENUM[constants[key]] = val;
};
const defineStrokeJoinEnum = function (key, val) {
lineDefs += `#define STROKE_JOIN_${key} ${val}\n`;
STROKE_JOIN_ENUM[constants[key]] = val;
};
// Define constants in line shaders for each type of cap/join, and also record
// the values in JS objects
defineStrokeCapEnum('ROUND', 0);
defineStrokeCapEnum('PROJECT', 1);
defineStrokeCapEnum('SQUARE', 2);
defineStrokeJoinEnum('ROUND', 0);
defineStrokeJoinEnum('MITER', 1);
defineStrokeJoinEnum('BEVEL', 2);
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 sphereMappingFrag from './shaders/sphereMapping.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 pointVert from './shaders/point.vert';
import pointFrag from './shaders/point.frag';
import imageLightVert from './shaders/imageLight.vert';
import imageLightDiffusedFrag from './shaders/imageLightDiffused.frag';
import imageLightSpecularFrag from './shaders/imageLightSpecular.frag';
const defaultShaders = {
normalVert,
normalFrag,
basicFrag,
sphereMappingFrag,
lightVert:
lightingShader +
lightVert,
lightTextureFrag,
phongVert,
phongFrag:
lightingShader +
phongFrag,
fontVert,
fontFrag,
lineVert:
lineDefs + lineVert,
lineFrag:
lineDefs + lineFrag,
pointVert,
pointFrag,
imageLightVert,
imageLightDiffusedFrag,
imageLightSpecularFrag
};
let sphereMapping = defaultShaders.sphereMappingFrag;
for (const key in defaultShaders) {
defaultShaders[key] = webgl2CompatibilityShader + defaultShaders[key];
}
import filterGrayFrag from './shaders/filters/gray.frag';
import filterErodeFrag from './shaders/filters/erode.frag';
import filterDilateFrag from './shaders/filters/dilate.frag';
import filterBlurFrag from './shaders/filters/blur.frag';
import filterPosterizeFrag from './shaders/filters/posterize.frag';
import filterOpaqueFrag from './shaders/filters/opaque.frag';
import filterInvertFrag from './shaders/filters/invert.frag';
import filterThresholdFrag from './shaders/filters/threshold.frag';
import filterShaderVert from './shaders/filters/default.vert';
const filterShaderFrags = {
[constants.GRAY]: filterGrayFrag,
[constants.ERODE]: filterErodeFrag,
[constants.DILATE]: filterDilateFrag,
[constants.BLUR]: filterBlurFrag,
[constants.POSTERIZE]: filterPosterizeFrag,
[constants.OPAQUE]: filterOpaqueFrag,
[constants.INVERT]: filterInvertFrag,
[constants.THRESHOLD]: filterThresholdFrag
};
/**
* @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 true
*
* 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 true
*
* 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.
*
* version - either 1 or 2, to specify which WebGL version to ask for. By
* default, WebGL 2 will be requested. If WebGL2 is not available, it will
* fall back to WebGL 1. You can check what version is used with by looking at
* the global `webglVersion` property.
*
* @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)) {
p5._friendlyError(
'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.states.curCamera) {
this._renderer.states.curCamera._renderer = this._renderer;
}
};
/**
* @private
* @param {Uint8Array|Float32Array|undefined} pixels An existing pixels array to reuse if the size is the same
* @param {WebGLRenderingContext} gl The WebGL context
* @param {WebGLFramebuffer|null} framebuffer The Framebuffer to read
* @param {Number} x The x coordiante to read, premultiplied by pixel density
* @param {Number} y The y coordiante to read, premultiplied by pixel density
* @param {Number} width The width in pixels to be read (factoring in pixel density)
* @param {Number} height The height in pixels to be read (factoring in pixel density)
* @param {GLEnum} format Either RGB or RGBA depending on how many channels to read
* @param {GLEnum} type The datatype of each channel, e.g. UNSIGNED_BYTE or FLOAT
* @param {Number|undefined} flipY If provided, the total height with which to flip the y axis about
* @returns {Uint8Array|Float32Array} pixels A pixels array with the current state of the
* WebGL context read into it
*/
export function readPixelsWebGL(
pixels,
gl,
framebuffer,
x,
y,
width,
height,
format,
type,
flipY
) {
// Record the currently bound framebuffer so we can go back to it after, and
// bind the framebuffer we want to read from
const prevFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
const channels = format === gl.RGBA ? 4 : 3;
// Make a pixels buffer if it doesn't already exist
const len = width * height * channels;
const TypedArrayClass = type === gl.UNSIGNED_BYTE ? Uint8Array : Float32Array;
if (!(pixels instanceof TypedArrayClass) || pixels.length !== len) {
pixels = new TypedArrayClass(len);
}
gl.readPixels(
x,
flipY ? (flipY - y - height) : y,
width,
height,
format,
type,
pixels
);
// Re-bind whatever was previously bound
gl.bindFramebuffer(gl.FRAMEBUFFER, prevFramebuffer);
if (flipY) {
// WebGL pixels are inverted compared to 2D pixels, so we have to flip
// the resulting rows. Adapted from https://stackoverflow.com/a/41973289
const halfHeight = Math.floor(height / 2);
const tmpRow = new TypedArrayClass(width * channels);
for (let y = 0; y < halfHeight; y++) {
const topOffset = y * width * 4;
const bottomOffset = (height - y - 1) * width * 4;
tmpRow.set(pixels.subarray(topOffset, topOffset + width * 4));
pixels.copyWithin(topOffset, bottomOffset, bottomOffset + width * 4);
pixels.set(tmpRow, bottomOffset);
}
}
return pixels;
}
/**
* @private
* @param {WebGLRenderingContext} gl The WebGL context
* @param {WebGLFramebuffer|null} framebuffer The Framebuffer to read
* @param {Number} x The x coordinate to read, premultiplied by pixel density
* @param {Number} y The y coordinate to read, premultiplied by pixel density
* @param {GLEnum} format Either RGB or RGBA depending on how many channels to read
* @param {GLEnum} type The datatype of each channel, e.g. UNSIGNED_BYTE or FLOAT
* @param {Number|undefined} flipY If provided, the total height with which to flip the y axis about
* @returns {Number[]} pixels The channel data for the pixel at that location
*/
export function readPixelWebGL(
gl,
framebuffer,
x,
y,
format,
type,
flipY
) {
// Record the currently bound framebuffer so we can go back to it after, and
// bind the framebuffer we want to read from
const prevFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
const channels = format === gl.RGBA ? 4 : 3;
const TypedArrayClass = type === gl.UNSIGNED_BYTE ? Uint8Array : Float32Array;
const pixels = new TypedArrayClass(channels);
gl.readPixels(
x, flipY ? (flipY - y - 1) : y, 1, 1,
format, type,
pixels
);
// Re-bind whatever was previously bound
gl.bindFramebuffer(gl.FRAMEBUFFER, prevFramebuffer);
return Array.from(pixels);
}
/**
* 3D graphics class
* @private
* @class p5.RendererGL
* @extends p5.Renderer
* @todo extend class to include public method for offscreen
* rendering (FBO).
*/
p5.RendererGL = class RendererGL extends Renderer {
constructor(elt, pInst, isMainCanvas, attr) {
super(elt, pInst, isMainCanvas);
this.elt = elt;
this.canvas = elt;
this._setAttributeDefaults(pInst);
this._initContext();
this.isP3D = true; //lets us know we're in 3d mode
// When constructing a new p5.Geometry, this will represent the builder
this.geometryBuilder = undefined;
// 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.drawingContext = this.drawingContext;
if (isMainCanvas) {
// for pixel method sharing with pimage
this._pInst._curElement = this;
this._pInst.canvas = this.canvas;
} else {
// hide if offscreen buffer by default
this.canvas.style.display = 'none';
}
// Push/pop state
this.states.uModelMatrix = new p5.Matrix();
this.states.uViewMatrix = new p5.Matrix();
this.states.uMVMatrix = new p5.Matrix();
this.states.uPMatrix = new p5.Matrix();
this.states.uNMatrix = new p5.Matrix('mat3');
this.states.curMatrix = new p5.Matrix('mat3');
this.states.curCamera = new p5.Camera(this);
this.states.enableLighting = false;
this.states.ambientLightColors = [];
this.states.specularColors = [1, 1, 1];
this.states.directionalLightDirections = [];
this.states.directionalLightDiffuseColors = [];
this.states.directionalLightSpecularColors = [];
this.states.pointLightPositions = [];
this.states.pointLightDiffuseColors = [];
this.states.pointLightSpecularColors = [];
this.states.spotLightPositions = [];
this.states.spotLightDirections = [];
this.states.spotLightDiffuseColors = [];
this.states.spotLightSpecularColors = [];
this.states.spotLightAngle = [];
this.states.spotLightConc = [];
this.states.activeImageLight = null;
this.states.curFillColor = [1, 1, 1, 1];
this.states.curAmbientColor = [1, 1, 1, 1];
this.states.curSpecularColor = [0, 0, 0, 0];
this.states.curEmissiveColor = [0, 0, 0, 0];
this.states.curStrokeColor = [0, 0, 0, 1];
this.states.curBlendMode = constants.BLEND;
this.states._hasSetAmbient = false;
this.states._useSpecularMaterial = false;
this.states._useEmissiveMaterial = false;
this.states._useNormalMaterial = false;
this.states._useShininess = 1;
this.states._useMetalness = 0;
this.states.tint = [255, 255, 255, 255];
this.states.constantAttenuation = 1;
this.states.linearAttenuation = 0;
this.states.quadraticAttenuation = 0;
this.states._currentNormal = new p5.Vector(0, 0, 1);
this.states.drawMode = constants.FILL;
this.states._tex = null;
// erasing
this._isErasing = false;
// clipping
this._clipDepths = [];
this._isClipApplied = false;
this._stencilTestOn = false;
this.mixedAmbientLight = [];
this.mixedSpecularColor = [];
// p5.framebuffer for this are calculated in getDiffusedTexture function
this.diffusedTextures = new Map();
// p5.framebuffer for this are calculated in getSpecularTexture function
this.specularTextures = new Map();
this.preEraseBlend = undefined;
this._cachedBlendMode = undefined;
this._cachedFillStyle = [1, 1, 1, 1];
this._cachedStrokeStyle = [0, 0, 0, 1];
if (this.webglVersion === constants.WEBGL2) {
this.blendExt = this.GL;
} else {
this.blendExt = this.GL.getExtension('EXT_blend_minmax');
}
this._isBlending = false;
this._useLineColor = false;
this._useVertexColor = false;
this.registerEnabled = new Set();
// Camera
this.states.curCamera._computeCameraDefaultSettings();
this.states.curCamera._setDefaultCamera();
// FilterCamera
this.filterCamera = new p5.Camera(this);
this.filterCamera._computeCameraDefaultSettings();
this.filterCamera._setDefaultCamera();
// Information about the previous frame's touch object
// for executing orbitControl()
this.prevTouches = [];
// Velocity variable for use with orbitControl()
this.zoomVelocity = 0;
this.rotateVelocity = new p5.Vector(0, 0);
this.moveVelocity = new p5.Vector(0, 0);
// Flags for recording the state of zooming, rotation and moving
this.executeZoom = false;
this.executeRotateAndMove = false;
this._drawingFilter = false;
this._drawingImage = false;
this.states.specularShader = undefined;
this.sphereMapping = undefined;
this.states.diffusedShader = undefined;
this._defaultLightShader = undefined;
this._defaultImmediateModeShader = undefined;
this._defaultNormalShader = undefined;
this._defaultColorShader = undefined;
this._defaultPointShader = undefined;
this.states.userFillShader = undefined;
this.states.userStrokeShader = undefined;
this.states.userPointShader = undefined;
this.states.userImageShader = undefined;
this._useUserVertexProperties = undefined;
// Default drawing is done in Retained Mode
// Geometry and Material hashes stored here
this.retainedMode = {
geometry: {},
buffers: {
stroke: [
new p5.RenderBuffer(4, 'lineVertexColors', 'lineColorBuffer', 'aVertexColor', this),
new p5.RenderBuffer(3, 'lineVertices', 'lineVerticesBuffer', 'aPosition', this),
new p5.RenderBuffer(3, 'lineTangentsIn', 'lineTangentsInBuffer', 'aTangentIn', this),
new p5.RenderBuffer(3, 'lineTangentsOut', 'lineTangentsOutBuffer', 'aTangentOut', this),
new p5.RenderBuffer(1, 'lineSides', 'lineSidesBuffer', 'aSide', this)
],
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)
],
user:[]
}
};
// Immediate Mode
// Geometry and Material hashes stored here
this.immediateMode = {
geometry: new p5.Geometry(),
shapeMode: constants.TRIANGLE_FAN,
contourIndices: [],
_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(4, 'lineVertexColors', 'lineColorBuffer', 'aVertexColor', this),
new p5.RenderBuffer(3, 'lineVertices', 'lineVerticesBuffer', 'aPosition', this),
new p5.RenderBuffer(3, 'lineTangentsIn', 'lineTangentsInBuffer', 'aTangentIn', this),
new p5.RenderBuffer(3, 'lineTangentsOut', 'lineTangentsOutBuffer', 'aTangentOut', this),
new p5.RenderBuffer(1, 'lineSides', 'lineSidesBuffer', 'aSide', this)
],
point: this.GL.createBuffer(),
user:[]
}
};
this.pointSize = 5.0; //default point size
this.curStrokeWeight = 1;
this.curStrokeCap = constants.ROUND;
this.curStrokeJoin = constants.ROUND;
// map of texture sources to textures created in this gl context via this.getTexture(src)
this.textures = new Map();
// set of framebuffers in use
this.framebuffers = new Set();
// stack of active framebuffers
this.activeFramebuffers = [];
// for post processing step
this.states.filterShader = undefined;
this.filterLayer = undefined;
this.filterLayerTemp = undefined;
this.defaultFilterShaders = {};
this.textureMode = constants.IMAGE;
// default wrap settings
this.textureWrapX = constants.CLAMP;
this.textureWrapY = constants.CLAMP;
this.states._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;
// Used to distinguish between user calls to vertex() and internal calls
this.isProcessingVertices = false;
this._tessy = this._initTessy();
this.fontInfos = {};
this._curShader = undefined;
}
/**
* Starts creating a new p5.Geometry. Subsequent shapes drawn will be added
* to the geometry and then returned when
* <a href="#/p5/endGeometry">endGeometry()</a> is called. One can also use
* <a href="#/p5/buildGeometry">buildGeometry()</a> to pass a function that
* draws shapes.
*
* If you need to draw complex shapes every frame which don't change over time,
* combining them upfront with `beginGeometry()` and `endGeometry()` and then
* drawing that will run faster than repeatedly drawing the individual pieces.
*/
beginGeometry() {
if (this.geometryBuilder) {
throw new Error('It looks like `beginGeometry()` is being called while another p5.Geometry is already being build.');
}
this.geometryBuilder = new GeometryBuilder(this);
this.geometryBuilder.prevFillColor = [...this.states.curFillColor];
this.states.curFillColor = [-1, -1, -1, -1];
}
/**
* Finishes creating a new <a href="#/p5.Geometry">p5.Geometry</a> that was
* started using <a href="#/p5/beginGeometry">beginGeometry()</a>. One can also
* use <a href="#/p5/buildGeometry">buildGeometry()</a> to pass a function that
* draws shapes.
*
* @returns {p5.Geometry} The model that was built.
*/
endGeometry() {
if (!this.geometryBuilder) {
throw new Error('Make sure you call beginGeometry() before endGeometry()!');
}
const geometry = this.geometryBuilder.finish();
this.states.curFillColor = this.geometryBuilder.prevFillColor;
this.geometryBuilder = undefined;
return geometry;
}
/**
* Creates a new <a href="#/p5.Geometry">p5.Geometry</a> that contains all
* the shapes drawn in a provided callback function. The returned combined shape
* can then be drawn all at once using <a href="#/p5/model">model()</a>.
*
* If you need to draw complex shapes every frame which don't change over time,
* combining them with `buildGeometry()` once and then drawing that will run
* faster than repeatedly drawing the individual pieces.
*
* One can also draw shapes directly between
* <a href="#/p5/beginGeometry">beginGeometry()</a> and
* <a href="#/p5/endGeometry">endGeometry()</a> instead of using a callback
* function.
* @param {Function} callback A function that draws shapes.
* @returns {p5.Geometry} The model that was built from the callback function.
*/
buildGeometry(callback) {
this.beginGeometry();
callback();
return this.endGeometry();
}
//////////////////////////////////////////////
// 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;
}
_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
);
}
}
_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 = p5.prototype._maxAllowedPixelDimensions;
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 };
}
//This is helper function to reset the context anytime the attributes
//are changed with setAttributes()
_resetContext(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._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);
}
}
_update() {
// reset model view and apply initial camera transform
// (containing only look at info; no projection).
this.states.uModelMatrix.reset();
this.states.uViewMatrix.set(this.states.curCamera.cameraMatrix);
// reset light data for new frame.
this.states.ambientLightColors.length = 0;
this.states.specularColors = [1, 1, 1];
this.states.directionalLightDirections.length = 0;
this.states.directionalLightDiffuseColors.length = 0;
this.states.directionalLightSpecularColors.length = 0;
this.states.pointLightPositions.length = 0;
this.states.pointLightDiffuseColors.length = 0;
this.states.pointLightSpecularColors.length = 0;
this.states.spotLightPositions.length = 0;
this.states.spotLightDirections.length = 0;
this.states.spotLightDiffuseColors.length = 0;
this.states.spotLightSpecularColors.length = 0;
this.states.spotLightAngle.length = 0;
this.states.spotLightConc.length = 0;
this.states._enableLighting = false;
//reset tint value for new frame
this.states.tint = [255, 255, 255, 255];
//Clear depth every frame
this.GL.clearStencil(0);
this.GL.clear(this.GL.DEPTH_BUFFER_BIT | this.GL.STENCIL_BUFFER_BIT);
this.GL.disable(this.GL.STENCIL_TEST);
}
/**
* [background description]
*/
background(...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.clear(_r, _g, _b, _a);
}
// Combines the model and view matrices to get the uMVMatrix
// This method will be reusable wherever you need to update the combined matrix.
calculateCombinedMatrix() {
const modelMatrix = this.states.uModelMatrix;
const viewMatrix = this.states.uViewMatrix;
return modelMatrix.copy().mult(viewMatrix);
}
//////////////////////////////////////////////
// COLOR
//////////////////////////////////////////////
/**
* Basic fill material for geometry with a given color
* @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
*/
fill(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.states.curFillColor = color._array;
this.states.drawMode = constants.FILL;
this.states._useNormalMaterial = false;
this.states._tex = null;
}
/**
* Basic stroke material for geometry with a given color
* @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);
* }