-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathp5.Renderer3D.js
More file actions
1996 lines (1760 loc) · 60.5 KB
/
p5.Renderer3D.js
File metadata and controls
1996 lines (1760 loc) · 60.5 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 { Graphics } from "../core/p5.Graphics";
import { Renderer } from './p5.Renderer';
import GeometryBuilder from "../webgl/GeometryBuilder";
import { Matrix } from "../math/p5.Matrix";
import { Camera } from "../webgl/p5.Camera";
import { Vector } from "../math/p5.Vector";
import { ShapeBuilder } from "../webgl/ShapeBuilder";
import { GeometryBufferCache } from "../webgl/GeometryBufferCache";
import { filterParamDefaults } from "../image/const";
import { PrimitiveToVerticesConverter } from "../shape/custom_shapes";
import { Color } from "../color/p5.Color";
import { Element } from "../dom/p5.Element";
import { Framebuffer } from "../webgl/p5.Framebuffer";
import { DataArray } from "../webgl/p5.DataArray";
import { textCoreConstants } from "../type/textCore";
import { RenderBuffer } from "../webgl/p5.RenderBuffer";
import { Image } from "../image/p5.Image";
import { Texture } from "../webgl/p5.Texture";
import { makeFilterShader } from "../core/filterShaders";
import { getStrokeDefs } from "../webgl/enums";
const { STROKE_CAP_ENUM, STROKE_JOIN_ENUM } = getStrokeDefs(()=>"");
export class Renderer3D extends Renderer {
constructor(pInst, w, h, isMainCanvas, elt) {
super(pInst, w, h, isMainCanvas);
// Create new canvas
this.canvas = this.elt = elt || document.createElement("canvas");
this.contextReady = this.setupContext();
if (this._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";
}
this.elt.id = "defaultCanvas0";
this.elt.classList.add("p5Canvas");
// Set and return p5.Element
this.wrappedElt = new Element(this.elt, this._pInst);
// Extend renderer with methods of p5.Element with getters
for (const p of Object.getOwnPropertyNames(Element.prototype)) {
if (p !== 'constructor' && p[0] !== '_') {
Object.defineProperty(this, p, {
get() {
return this.wrappedElt[p];
}
})
}
}
const dimensions = this._adjustDimensions(w, h);
w = dimensions.adjustedWidth;
h = dimensions.adjustedHeight;
this.width = w;
this.height = h;
// Set canvas size
this.elt.width = w * this._pixelDensity;
this.elt.height = h * this._pixelDensity;
this.elt.style.width = `${w}px`;
this.elt.style.height = `${h}px`;
this._updateViewport();
// Attach canvas element to DOM
if (this._pInst._userNode) {
// user input node case
this._pInst._userNode.appendChild(this.elt);
} else {
//create main element
if (document.getElementsByTagName("main").length === 0) {
let m = document.createElement("main");
document.body.appendChild(m);
}
//append canvas to main
document.getElementsByTagName("main")[0].appendChild(this.elt);
}
this.isP3D = true; //lets us know we're in 3d mode
// When constructing a new Geometry, this will represent the builder
this.geometryBuilder = undefined;
// Push/pop state
this.states.uModelMatrix = new Matrix(4);
this.states.uViewMatrix = new Matrix(4);
this.states.uPMatrix = new Matrix(4);
this.mainCamera = new Camera(this);
if (!this.states.curCamera) {
this.states.curCamera = this.mainCamera;
}
this.states.uPMatrix.set(this.states.curCamera.projMatrix);
this.states.uViewMatrix.set(this.states.curCamera.cameraMatrix);
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 Vector(0, 0, 1);
this.states.drawMode = constants.FILL;
this.states._tex = null;
this.states.textureMode = constants.IMAGE;
this.states.textureWrapX = constants.CLAMP;
this.states.textureWrapY = constants.CLAMP;
// erasing
this._isErasing = false;
// simple lines
this._simpleLines = 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._cachedFillStyle = [1, 1, 1, 1];
this._cachedStrokeStyle = [0, 0, 0, 1];
this._isBlending = false;
this._useLineColor = false;
this._useVertexColor = false;
this.registerEnabled = new Set();
// Camera
this.mainCamera._computeCameraDefaultSettings();
this.mainCamera._setDefaultCamera();
// FilterCamera
this.filterCamera = new 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 Vector(0, 0);
this.moveVelocity = new 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.specularShader = undefined;
this.sphereMapping = undefined;
this.diffusedShader = undefined;
this._baseFilterShader = undefined;
this._defaultLightShader = undefined;
this._defaultImmediateModeShader = undefined;
this._defaultNormalShader = undefined;
this._defaultColorShader = undefined;
this.states.userFillShader = undefined;
this.states.userStrokeShader = undefined;
this.states.userImageShader = undefined;
this.states.curveDetail = 1 / 4;
// Used by beginShape/endShape functions to construct a p5.Geometry
this.shapeBuilder = new ShapeBuilder(this);
this.geometryBufferCache = new GeometryBufferCache(this);
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.fontInfos = {};
this._curShader = undefined;
this.drawShapeCount = 1;
this.scratchMat3 = new Matrix(3);
// Whether or not to remove degenerate faces from geometry. This is usually
// set to false for performance.
this._validateFaces = false;
this.buffers = {
fill: [
new RenderBuffer(
3,
"vertices",
"vertexBuffer",
"aPosition",
this,
this._vToNArray
),
new RenderBuffer(
3,
"vertexNormals",
"normalBuffer",
"aNormal",
this,
this._vToNArray
),
new RenderBuffer(
4,
"vertexColors",
"colorBuffer",
"aVertexColor",
this
).default((geometry) => geometry.vertices.flatMap(() => [-1, -1, -1, -1])),
new RenderBuffer(
3,
"vertexAmbients",
"ambientBuffer",
"aAmbientColor",
this
),
new RenderBuffer(2, "uvs", "uvBuffer", "aTexCoord", this, (arr) =>
arr.flat()
),
],
stroke: [
new RenderBuffer(
4,
"lineVertexColors",
"lineColorBuffer",
"aVertexColor",
this
).default((geometry) => geometry.lineVertices.flatMap(() => [-1, -1, -1, -1])),
new RenderBuffer(
3,
"lineVertices",
"lineVerticesBuffer",
"aPosition",
this
),
new RenderBuffer(
3,
"lineTangentsIn",
"lineTangentsInBuffer",
"aTangentIn",
this
),
new RenderBuffer(
3,
"lineTangentsOut",
"lineTangentsOutBuffer",
"aTangentOut",
this
),
new RenderBuffer(1, "lineSides", "lineSidesBuffer", "aSide", this),
],
text: [
new RenderBuffer(
3,
"vertices",
"vertexBuffer",
"aPosition",
this,
this._vToNArray
),
new RenderBuffer(2, "uvs", "uvBuffer", "aTexCoord", this, (arr) =>
arr.flat()
),
],
user: [],
};
}
//This is helper function to reset the context anytime the attributes
//are changed with setAttributes()
async _resetContext(options, callback, ctor = Renderer3D) {
const w = this.width;
const h = this.height;
const defaultId = this.canvas.id;
const isPGraphics = this._pInst instanceof Graphics;
// Preserve existing position and styles before recreation
const prevStyle = {
position: this.canvas.style.position,
top: this.canvas.style.top,
left: this.canvas.style.left,
};
if (isPGraphics) {
// Handle PGraphics: remove and recreate the canvas
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);
Element.call(pg, pg.canvas, pg._pInst);
// Restore previous width and height
pg.width = w;
pg.height = h;
} else {
// Handle main canvas: remove and recreate it
let c = this.canvas;
if (c) {
c.parentNode.removeChild(c);
}
c = document.createElement("canvas");
c.id = defaultId;
// Attach the new canvas to the correct parent node
if (this._pInst._userNode) {
this._pInst._userNode.appendChild(c);
} else {
document.body.appendChild(c);
}
this._pInst.canvas = c;
this.canvas = c;
// Restore the saved position
this.canvas.style.position = prevStyle.position;
this.canvas.style.top = prevStyle.top;
this.canvas.style.left = prevStyle.left;
}
const renderer = new ctor(
this._pInst,
w,
h,
!isPGraphics,
this._pInst.canvas
);
this._pInst._renderer = renderer;
renderer._applyDefaults();
if (renderer.contextReady) {
await renderer.contextReady
}
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);
}
}
remove() {
this.wrappedElt.remove();
this.wrappedElt = null;
this.canvas = null;
this.elt = null;
}
//////////////////////////////////////////////
// Geometry Building
//////////////////////////////////////////////
/**
* 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.
* @private
*/
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.fillColor;
this.fill(new Color([-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.
* @private
*
* @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();
if (this.geometryBuilder.prevFillColor) {
this.fill(this.geometryBuilder.prevFillColor);
} else {
this.noFill();
}
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();
}
//////////////////////////////////////////////
// Shape drawing
//////////////////////////////////////////////
beginShape(...args) {
super.beginShape(...args);
// TODO remove when shape refactor is complete
// this.shapeBuilder.beginShape(...args);
}
curveDetail(d) {
if (d === undefined) {
return this.states.curveDetail;
} else {
this.states.setValue("curveDetail", d);
}
}
drawShape(shape) {
const visitor = new PrimitiveToVerticesConverter({
curveDetail: this.states.curveDetail,
});
shape.accept(visitor);
this.shapeBuilder.constructFromContours(shape, visitor.contours);
if (this.geometryBuilder) {
this.geometryBuilder.addImmediate(
this.shapeBuilder.geometry,
this.shapeBuilder.shapeMode,
{ validateFaces: this._validateFaces }
);
} else if (this.states.fillColor || this.states.strokeColor) {
this._drawGeometry(this.shapeBuilder.geometry, {
mode: this.shapeBuilder.shapeMode,
count: this.drawShapeCount
});
}
this.drawShapeCount = 1;
}
endShape(mode, count) {
this.drawShapeCount = count;
super.endShape(mode, count);
}
vertexProperty(...args) {
this.currentShape.vertexProperty(...args);
}
normal(xorv, y, z) {
if (xorv instanceof Vector) {
this.states.setValue("_currentNormal", xorv);
} else {
this.states.setValue("_currentNormal", new Vector(xorv, y, z));
}
this.updateShapeVertexProperties();
}
model(model, count = 1) {
if (model.vertices.length > 0) {
if (this.geometryBuilder) {
this.geometryBuilder.addRetained(model);
} else {
if (!this.geometryInHash(model.gid)) {
model._edgesToVertices();
this._getOrMakeCachedBuffers(model);
}
this._drawGeometry(model, { count });
}
}
}
_getOrMakeCachedBuffers(geometry) {
return this.geometryBufferCache.ensureCached(geometry);
}
//////////////////////////////////////////////
// Rendering
//////////////////////////////////////////////
_drawGeometry(geometry, { mode = constants.TRIANGLES, count = 1 } = {}) {
for (const propName in geometry.userVertexProperties) {
const prop = geometry.userVertexProperties[propName];
this.buffers.user.push(
new RenderBuffer(
prop.getDataSize(),
prop.getSrcName(),
prop.getDstName(),
prop.getName(),
this
)
);
}
if (
this.states.fillColor &&
geometry.vertices.length >= 3 &&
![constants.LINES, constants.POINTS].includes(mode)
) {
this._drawFills(geometry, { mode, count });
}
if (this.states.strokeColor && geometry.lineVertices.length >= 1) {
this._drawStrokes(geometry, { count });
}
this.buffers.user = [];
}
_drawFills(geometry, { count, mode } = {}) {
this._useVertexColor = geometry.vertexColors.length > 0 &&
!geometry.vertexColors.isDefault;
const shader =
!this._drawingFilter && this.states.userFillShader
? this.states.userFillShader
: this._getFillShader();
shader.bindShader('fill');
this._setGlobalUniforms(shader);
this._setFillUniforms(shader);
shader.bindTextures();
for (const buff of this.buffers.fill) {
buff._prepareBuffer(geometry, shader);
}
this._prepareUserAttributes(geometry, shader);
this._disableRemainingAttributes(shader);
this._applyColorBlend(
this.states.curFillColor,
geometry.hasFillTransparency()
);
this._drawBuffers(geometry, { mode, count });
shader.unbindShader();
}
_drawStrokes(geometry, { count } = {}) {
this._useLineColor = geometry.vertexStrokeColors.length > 0;
const shader = this._getStrokeShader();
shader.bindShader('stroke');
this._setGlobalUniforms(shader);
this._setStrokeUniforms(shader);
shader.bindTextures();
for (const buff of this.buffers.stroke) {
buff._prepareBuffer(geometry, shader);
}
this._prepareUserAttributes(geometry, shader);
this._disableRemainingAttributes(shader);
this._applyColorBlend(
this.states.curStrokeColor,
geometry.hasStrokeTransparency()
);
this._drawBuffers(geometry, {count})
shader.unbindShader();
}
_prepareUserAttributes(geometry, shader) {
for (const buff of this.buffers.user) {
if (!this._pInst.constructor.disableFriendleErrors) {
// Check for the right data size
const prop = geometry.userVertexProperties[buff.attr];
if (prop) {
const adjustedLength = prop.getSrcArray().length / prop.getDataSize();
if (adjustedLength > geometry.vertices.length) {
this._pInst.constructor._friendlyError(
`One of the geometries has a custom vertex property '${prop.getName()}' with more values than vertices. This is probably caused by directly using the Geometry.vertexProperty() method.`,
"vertexProperty()"
);
} else if (adjustedLength < geometry.vertices.length) {
this._pInst.constructor._friendlyError(
`One of the geometries has a custom vertex property '${prop.getName()}' with fewer values than vertices. This is probably caused by directly using the Geometry.vertexProperty() method.`,
"vertexProperty()"
);
}
}
}
buff._prepareBuffer(geometry, shader);
}
}
_drawGeometryScaled(model, scaleX, scaleY, scaleZ) {
let originalModelMatrix = this.states.uModelMatrix;
this.states.setValue("uModelMatrix", this.states.uModelMatrix.clone());
try {
this.states.uModelMatrix.scale(scaleX, scaleY, scaleZ);
if (this.geometryBuilder) {
this.geometryBuilder.addRetained(model);
} else {
this._drawGeometry(model);
}
} finally {
this.states.setValue("uModelMatrix", originalModelMatrix);
}
}
_update() {
// reset model view and apply initial camera transform
// (containing only look at info; no projection).
this.states.setValue("uModelMatrix", this.states.uModelMatrix.clone());
this.states.uModelMatrix.reset();
this.states.setValue("uViewMatrix", this.states.uViewMatrix.clone());
this.states.uViewMatrix.set(this.states.curCamera.cameraMatrix);
// reset light data for new frame.
this.states.setValue("ambientLightColors", []);
this.states.setValue("specularColors", [1, 1, 1]);
this.states.setValue("directionalLightDirections", []);
this.states.setValue("directionalLightDiffuseColors", []);
this.states.setValue("directionalLightSpecularColors", []);
this.states.setValue("pointLightPositions", []);
this.states.setValue("pointLightDiffuseColors", []);
this.states.setValue("pointLightSpecularColors", []);
this.states.setValue("spotLightPositions", []);
this.states.setValue("spotLightDirections", []);
this.states.setValue("spotLightDiffuseColors", []);
this.states.setValue("spotLightSpecularColors", []);
this.states.setValue("spotLightAngle", []);
this.states.setValue("spotLightConc", []);
this.states.setValue("enableLighting", false);
//reset tint value for new frame
this.states.setValue("tint", [255, 255, 255, 255]);
//Clear depth every frame
this._resetBuffersBeforeDraw()
}
background(...args) {
const a0 = args[0];
const isImageLike =
a0 != null &&
typeof a0 === 'object' &&
typeof a0.width === 'number' &&
typeof a0.height === 'number' &&
(a0.canvas != null || a0.elt != null);
// WEBGL / 3D: support background(image-like)
if (isImageLike) {
this._pInst.clear();
this._pInst.push();
this._pInst.resetMatrix();
this._pInst.imageMode(constants.CENTER);
this._pInst.image(a0, 0, 0, this._pInst.width, this._pInst.height);
this._pInst.pop();
return;
}
// Default: background(color)
const _col = this._pInst.color(...args);
this.clear(..._col._getRGBA());
}
//////////////////////////////////////////////
// Positioning
//////////////////////////////////////////////
get uModelMatrix() {
return this.states.uModelMatrix;
}
get uViewMatrix() {
return this.states.uViewMatrix;
}
get uPMatrix() {
return this.states.uPMatrix;
}
get uMVMatrix() {
const m = this.uModelMatrix.copy();
m.mult(this.uViewMatrix);
return m;
}
/**
* Get a matrix from world-space to screen-space
*/
getWorldToScreenMatrix() {
const modelMatrix = this.states.uModelMatrix;
const viewMatrix = this.states.uViewMatrix;
const projectionMatrix = this.states.uPMatrix;
const projectedToScreenMatrix = new Matrix(4);
projectedToScreenMatrix.scale(this.width, this.height, 1);
projectedToScreenMatrix.translate([0.5, 0.5, 0.5]);
projectedToScreenMatrix.scale(0.5, -0.5, 0.5);
const modelViewMatrix = modelMatrix.copy().mult(viewMatrix);
const modelViewProjectionMatrix = modelViewMatrix.mult(projectionMatrix);
const worldToScreenMatrix = modelViewProjectionMatrix
.mult(projectedToScreenMatrix);
return worldToScreenMatrix;
}
//////////////////////////////////////////////
// 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
* 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);
* }
*
* @alt
* black canvas with purple cube spinning
*/
fill(...args) {
super.fill(...args);
//see material.js for more info on color blending in webgl
// const color = fn.color.apply(this._pInst, arguments);
const color = this.states.fillColor;
this.states.setValue('curFillColor', color._array);
this.states.setValue('drawMode', constants.FILL);
this.states.setValue('_useNormalMaterial', false);
this.states.setValue('_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
* 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);
* }
*
* @alt
* black canvas with purple cube with pink outline spinning
*/
stroke(...args) {
super.stroke(...args);
// const color = fn.color.apply(this._pInst, arguments);
this.states.setValue('curStrokeColor', this.states.strokeColor._array);
}
getCommonVertexProperties() {
return {
...super.getCommonVertexProperties(),
stroke: this.states.strokeColor,
fill: this.states.fillColor,
normal: this.states._currentNormal,
};
}
getSupportedIndividualVertexProperties() {
return {
textureCoordinates: true,
};
}
strokeCap(cap) {
this.curStrokeCap = cap;
}
strokeJoin(join) {
this.curStrokeJoin = join;
}
getFilterLayer() {
if (!this.filterLayer) {
this.filterLayer = new Framebuffer(this);
}
return this.filterLayer;
}
getFilterLayerTemp() {
if (!this.filterLayerTemp) {
this.filterLayerTemp = new Framebuffer(this);
}
return this.filterLayerTemp;
}
matchSize(fboToMatch, target) {
if (
fboToMatch.width !== target.width ||
fboToMatch.height !== target.height
) {
fboToMatch.resize(target.width, target.height);
}
if (fboToMatch.pixelDensity() !== target.pixelDensity()) {
fboToMatch.pixelDensity(target.pixelDensity());
}
}
filter(...args) {
let fbo = this.getFilterLayer();
// use internal shader for filter constants BLUR, INVERT, etc
let filterParameter = undefined;
let operation = undefined;
if (typeof args[0] === 'string') {
operation = args[0];
let useDefaultParam =
operation in filterParamDefaults && args[1] === undefined;
filterParameter = useDefaultParam
? filterParamDefaults[operation]
: args[1];
// Create and store shader for constants once on initial filter call.
// Need to store multiple in case user calls different filters,
// eg. filter(BLUR) then filter(GRAY)
if (!(operation in this.defaultFilterShaders)) {
this.defaultFilterShaders[operation] = this._makeFilterShader(fbo.renderer, operation);
}
this.states.setValue(
'filterShader',
this.defaultFilterShaders[operation]
);
}
// use custom user-supplied shader
else {
this.states.setValue('filterShader', args[0]);
}
// Setting the target to the framebuffer when applying a filter to a framebuffer.
const target = this.activeFramebuffer() || this;
// Resize the framebuffer 'fbo' and adjust its pixel density if it doesn't match the target.
this.matchSize(fbo, target);
fbo.draw(() => this.clear()); // prevent undesirable feedback effects accumulating secretly.
let texelSize = [
1 / (target.width * target.pixelDensity()),
1 / (target.height * target.pixelDensity()),
];
// apply blur shader with multiple passes.
if (operation === constants.BLUR) {
// Treating 'tmp' as a framebuffer.
const tmp = this.getFilterLayerTemp();
// Resize the framebuffer 'tmp' and adjust its pixel density if it doesn't match the target.
this.matchSize(tmp, target);
// setup
this.push();
this.states.setValue('strokeColor', null);
this.blendMode(constants.BLEND);
// draw main to temp buffer
this.shader(this.states.filterShader);
this.states.filterShader.setUniform('texelSize', texelSize);
this.states.filterShader.setUniform('canvasSize', [
target.width,
target.height,
]);
this.states.filterShader.setUniform(
'radius',
Math.max(1, filterParameter)
);
// Horiz pass: draw `target` to `tmp`
tmp.draw(() => {
this.states.filterShader.setUniform('direction', [1, 0]);
this.states.filterShader.setUniform('tex0', target);
this.clear();
this.shader(this.states.filterShader);
this.noLights();
this.plane(target.width, target.height);
});
// Vert pass: draw `tmp` to `fbo`
fbo.draw(() => {
this.states.filterShader.setUniform('direction', [0, 1]);
this.states.filterShader.setUniform('tex0', tmp);
this.clear();
this.shader(this.states.filterShader);
this.noLights();
this.plane(target.width, target.height);
});