-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCanvasObjects.js
More file actions
1580 lines (1353 loc) · 108 KB
/
CanvasObjects.js
File metadata and controls
1580 lines (1353 loc) · 108 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
//+++++++++++++++++++++++++++
//Author: Thomas Androxman
//Date : Feb/2018
//+++++++++++++++++++++++++++
//Contains: TypeProgressBar, TypeCanvasText, TypeTextLabel, TypeCanvasWebGLpainter, TypeCanvas2Dpainter
//Depends on: BasicLib.js
//Global Functions-----------------------------------------------------------------------------------------------------------------------------------
function InitCanvas(CanvasHandleStr)
{ //Find the canvas element by its HTML ID and adjust the initial size of the canvas pixels to match the size of its box
//Returns a canvas object not a context.
//NOTE:
//With canvas, there are two sets of dimensions a) the box dimensions, b) the pixel dimensions.
//Usually, one or both of height/width are set in CSS and often set as 'inherit', but CSS only affects the box size causing the pixels of the canvas to stretch
//Using the canvasOBJ.width and canvasOBJ.height it is possible to set the pixel dimentions to match the canvax box dimensions
//Note: document.querySelector is considered more powerfull (?) and returns a static collection (at the moment the method was called)
var canvasOBJ = document.getElementById(CanvasHandleStr); if (!canvasOBJ) {return;}
var objStyle = getComputedStyle(canvasOBJ);
var parStyle = getComputedStyle(canvasOBJ.parentElement);
canvasOBJ.width = (objStyle.width == "inherit") ? parseInt(parStyle.clientWidth) : parseInt(objStyle.width);
canvasOBJ.height = (objStyle.height == "inherit") ? parseInt(parStyle.clientHeight): parseInt(objStyle.height);
return canvasOBJ;
}
//===================================================================================================================================================
//Classes / Constructor-functions
//---------------------------------------------------------------------------------------------------------------------------------------------------
//NON KINEMATIC OBJECTS
//NOTE: The following objects interact directly with a 2D canvas context in a static way (they are not expected to have kinematic behaviors relative to a camera)
function TypeProgressBar (fromPoint, toPoint, width, barColor, backColor, outThickness, outColor)
{
var barCoordinates;
var barWidth;
var outlineThickness;
var activeColor;
var backgroundColor;
var outlineColor;
var barVector;
var progress;
var timeStamp;
//PRIVATE methods
var Initialize = function (point0, point1, width, barColor, backColor, outThickness, outColor)
{
barCoordinates = {fromPoint:(point0 instanceof TypeXYZw)? point0 : new TypeXYZw(point0), toPoint:(point1 instanceof TypeXYZw)? point1 : new TypeXYZw(point1)};
barWidth = Number(width);
outlineThickness = (outThickness===void(0))? void(0) : Number(outThickness);
activeColor = (barColor instanceof TypeColor)? barColor : new TypeColor(barColor);
backgroundColor = (backColor instanceof TypeColor)? backColor : new TypeColor(backColor);
outlineColor = (outColor===void(0))? void(0) : (outColor instanceof TypeColor)? outColor : new TypeColor(outColor);
barVector = barCoordinates.toPoint.Minus(barCoordinates.fromPoint);
progress = 0;
timeStamp = 0;
}
//PUBLIC methods
this.GetTimestamp = function () {return timeStamp;}
this.SetProgress = function (newRatio) {progress = ClipValue(newRatio,1,0);}
this.SetTimestamp = function () {timeStamp = Date.now();}
this.Draw = function (ctx)
{
ctx.save();
ctx.lineCap = 'round';
//The background container
if (outlineThickness!==void(0))
{ //The outline
ctx.beginPath();
ctx.moveTo(barCoordinates.fromPoint.x, barCoordinates.fromPoint.y);
ctx.lineWidth = barWidth+outlineThickness*2;
ctx.lineTo(barCoordinates.toPoint.x, barCoordinates.toPoint.y);
ctx.strokeStyle = outlineColor.GetCSScolor();
ctx.stroke();
}
ctx.beginPath();
ctx.moveTo(barCoordinates.fromPoint.x, barCoordinates.fromPoint.y);
ctx.lineWidth = barWidth;
ctx.lineTo(barCoordinates.toPoint.x, barCoordinates.toPoint.y);
ctx.strokeStyle = backgroundColor.GetCSScolor();
ctx.stroke();
//The active bar
var newToPoint = barCoordinates.fromPoint.Plus(barVector.ScaleBy(progress));
ctx.beginPath();
ctx.moveTo(barCoordinates.fromPoint.x, barCoordinates.fromPoint.y);
ctx.lineWidth = barWidth;
ctx.lineTo(newToPoint.x, newToPoint.y);
ctx.strokeStyle = activeColor.GetCSScolor();
ctx.stroke();
ctx.restore();
}
//Initialization
Initialize(fromPoint, toPoint, width, barColor, backColor, outThickness, outColor);
}
//---------------------------------------------------------------------------------------------------------------------------------------------------
function TypeCanvasText (thisText,txtSize,txtFont,atX,atY,txtColor,txtAlign,txtBase,useBack,backColor,padding)
{
this.textStr = thisText;
this.textSize = txtSize;
this.textFont = txtFont;
this.textColor = new TypeColor(txtColor);
this.textOscillator = new TypeOscillator();
this.textAlign = txtAlign;
this.textBaseline = txtBase;
this.useBackground = useBack;
this.backColor = new TypeColor(backColor);
this.backPadding = padding;
this.position = new TypeXYZw(atX,atY);
this.kinematics = new TypeKinematics(atX,atY); //Depracated
//Methods
this.SetDatumPos = function (x,y,z) {this.kinematics.SetDatumPos(x,y,z);}
this.Draw = function (ctx)
{
//Setup the text font
ctx.font = this.textSize+"px "+this.textFont;
ctx.textAlign = this.textAlign;
ctx.textBaseline= this.textBaseline;
//Text rectangle coordinates
var txtLen = ctx.measureText(this.textStr).width;
var textRectangle = [[this.kinematics.GetDatumPos().x,this.kinematics.GetDatumPos().y-1],[]];
if (this.textAlign =="center") textRectangle[0][0] -= txtLen/2; else if (this.textAlign=="right") textRectangle[0][0] -= txtLen;
if (this.textBaseline=="middle") textRectangle[0][1] += this.textSize/2; else if (this.textBaseline=="top") textRectangle[0][1] += this.textSize;
textRectangle[1] = [textRectangle[0][0]+txtLen,textRectangle[0][1]-this.textSize];
//Display the background rounded rectangle
if (this.useBackground == true)
{
ctx.beginPath();
ctx.moveTo (textRectangle[0][0],textRectangle[0][1]+this.backPadding);
ctx.lineTo (textRectangle[1][0],textRectangle[0][1]+this.backPadding);
ctx.arcTo (textRectangle[1][0]+this.backPadding,textRectangle[0][1]+this.backPadding,textRectangle[1][0]+this.backPadding,textRectangle[0][1],this.backPadding);
ctx.lineTo (textRectangle[1][0]+this.backPadding,textRectangle[1][1]);
ctx.arcTo (textRectangle[1][0]+this.backPadding,textRectangle[1][1]-this.backPadding,textRectangle[1][0],textRectangle[1][1]-this.backPadding,this.backPadding);
ctx.lineTo (textRectangle[0][0],textRectangle[1][1]-this.backPadding);
ctx.arcTo (textRectangle[0][0]-this.backPadding,textRectangle[1][1]-this.backPadding,textRectangle[0][0]-this.backPadding,textRectangle[1][1],this.backPadding);
ctx.lineTo (textRectangle[0][0]-this.backPadding,textRectangle[0][1]);
ctx.arcTo (textRectangle[0][0]-this.backPadding,textRectangle[0][1]+this.backPadding,textRectangle[0][0],textRectangle[0][1]+this.backPadding,this.backPadding);
ctx.closePath();
ctx.fillStyle = this.backColor.GetCSScolor();
ctx.fill();
}
//Display the text
ctx.fillStyle = GetCSScolor([this.textColor.GetR(),this.textColor.GetG(),this.textColor.GetB(),this.textColor.GetAlpha()*this.textOscillator.GetState()]);
ctx.fillText(this.textStr, this.kinematics.GetDatumPos().x, this.kinematics.GetDatumPos().y);
}
}
//---------------------------------------------------------------------------------------------------------------------------------------------------
//KINEMATIC OBJECTS
//NOTE: These objects are expected to be part of a scene in a kinematic environment and are drawn via the TypeCanvas2dPainter or TypeWebGlPainter objects
function TypeTextLabel (thisText,txtSize,txtFont,pos,txtColor,txtHorAlign,txtVerAlign,backColor,padding,isRounded)
{ //This is a text object with background fill (a label) that is used within a scene responding to a camera and kinematics
var textObj;
var textObjProp;
var textOscillator;
var backFillObj;
var backFillObjProp;
var backPadding;
var Initialize = function (thisText,txtSize,txtFont,plane,txtColor,txtHorAlign,txtVerAlign,backColor,padding,isRounded)
{
//Note: plane could be a TypeXYZw (a point) or a TypePlane
//Note: the text size is in world coordinates
//Note: padding is in world units
//Argument gate
if (isRounded===void(0)) {isRounded=true;}
if (!IsString(thisText)) {thisText='';}
if (!(plane instanceof TypePlane) && !(plane instanceof TypeXYZw)) {plane = new TypeXYZw(plane);} //Try to interpret it as a point first
if (plane instanceof TypeXYZw) {plane = new TypePlane(plane,new TypeXYZw(plane.x+1,plane.y,plane.z),new TypeXYZw(plane.x,plane.y+1,plane.z));}
if (isNaN(txtSize)) {txtSize = 0.2;}
if (!IsString(txtHorAlign) || (txtHorAlign!='left' && txtHorAlign!='right' && txtHorAlign!='center')) {txtHorAlign = 'left';}
if (!IsString(txtVerAlign) || (txtVerAlign!='bottom' && txtVerAlign!='middle' && txtVerAlign!='top')) {txtVerAlign = 'bottom';}
if (backColor && !(backColor instanceof TypeColor)) {backColor = new TypeColor(backColor);}
textObj = new TypeText(thisText); textObj.SetPlane(plane);
textObjProp = new TypeTextProperties(textObj,txtFont,txtSize,txtHorAlign,txtVerAlign,txtColor); //targetTxt,fnt,sze,alU,alV,clr,outline,outlnProp
textOscillator = new TypeOscillator();
if (!backColor) {return;} //If the text has no background fill then nothing else to do
else {backPadding = (isNaN(padding))? 0 : padding;}
//The background fill for the text (the rectangle dimensions and orientation doesn't matter at the moment)
var textFillBox = new TypeCurve(); //The text box rectangle outline
textFillBox.AddRectangle([0,0],[1,0],[0,1],backPadding); //The corner radius is as much as the padding
backFillObj = new TypeSurface();
backFillObj.name = 'TextLabel fill';
backFillObj.AddFillFromPlanarBoundary(textFillBox);
backFillObjProp = new TypeSurfaceProperties(backFillObj);
backFillObjProp.SetMaterial(new TypeLegacyMaterial()).SetColor(backColor);
backFillObjProp.SetEdgeProperties(new TypeCurveProperties(textFillBox,void(0),0)); //Note: typeCurveProperties args (targetCrv,crvColor, crvThickness, crvDashPattern)
UpdateFillBox(); //Fits the dimensions of the fill box to the length of the text string
}
var ChangeText = function (newText) {textObj.SetText(newText); UpdateFillBox();}
var ChangeTextColor = function (newColor) {textObjProp.SetColor(newColor);}
var UpdateFillBox = function ()
{ //This method will resize the fill box to the dimensions of the text string assuming the font is monospace
if (!backFillObj) {return;} //If the text has no background fill, there is nothing to do
var textDim = new TypeXYZw(textObj.GetText().length*txtSize*0.6,txtSize); //assume text is monospace
var offsetVec = new TypeXYZw();
var alignment = textObjProp.GetAlignment();
var boundCurve = backFillObj.GetBoundaryCurves()[0];
if (alignment.horizontal=='center') {offsetVec = offsetVec.Minus(textObj.GetPlane().GetUnitU().ScaleBy(textDim.x/2 + backPadding));}
if (alignment.horizontal=='right') {offsetVec = offsetVec.Minus(textObj.GetPlane().GetUnitU().ScaleBy(textDim.x + backPadding));}
if (alignment.horizontal=='left') {offsetVec = offsetVec.Minus(textObj.GetPlane().GetUnitU().ScaleBy(backPadding));}
if (alignment.vertical =='middle') {offsetVec = offsetVec.Minus(textObj.GetPlane().GetUnitV().ScaleBy(textDim.y/2 + backPadding*0.5));}
if (alignment.vertical =='top') {offsetVec = offsetVec.Minus(textObj.GetPlane().GetUnitV().ScaleBy(textDim.y + backPadding));}
if (alignment.vertical =='bottom') {offsetVec = offsetVec.Minus(textObj.GetPlane().GetUnitV().ScaleBy(backPadding*0.5));}
var pointLL = textObj.GetPlane().GetA().Plus(offsetVec);
var pointLR = pointLL.Plus(textObj.GetPlane().GetUnitU().ScaleBy(textDim.x+backPadding*2));
var pointTL = pointLL.Plus(textObj.GetPlane().GetUnitV().ScaleBy(textDim.y+backPadding*2));
//Explicitly set each coordinate in order to preserve the 'w' value
boundCurve.GetVertex(0).SetX(pointLL.x).SetY(pointLL.y).SetZ(pointLL.z);
boundCurve.GetVertex(1).SetX(pointLR.x).SetY(pointLR.y).SetZ(pointLR.z);
boundCurve.GetVertex(2).SetX(pointTL.x).SetY(pointTL.y).SetZ(pointTL.z);
}
//Public methods
this.GetOscillator = function () {return textOscillator;}
this.GetTextObject = function () {return textObj;}
this.GetTextString = function () {return textObj.GetText();}
this.GetTextProperties = function () {return textObjProp;}
this.GetTextColor = function () {return textObjProp.GetColor();}
this.GetFillColor = function () {return backFillObjProp.GetColor();}
this.GetTextFill = function () {return backFillObj;}
this.GetFillProperties = function () {return backFillObjProp;}
this.SetText = function (newText) {ChangeText(newText);}
this.SetTextColor = function (newColor) {ChangeTextColor(newColor);}
this.UpdateFill = function () {UpdateFillBox();}
//Initialization
Initialize(thisText,txtSize,txtFont,pos,txtColor,txtHorAlign,txtVerAlign,backColor,padding,isRounded);
}
//---------------------------------------------------------------------------------------------------------------------------------------------------
//CANVAS PAINTER OBJECTS (these are the main interfaces for rendering a scene to canvas2D or WebGL)
//---------------------------------------------------------------------------------------------------------------------------------------------------
function TypeCanvasWebGLpainter (scene,canvasIdString,vertexShaderPath,fragmentShaderPath)
{ //This object takes a scene and draws it on the given canvas via WebGL
//This object is permanently linked to a scene because it keeps track of OpenGL buffers for the scene objects and textures
//Note: A canvas element can only have one context (either 2d, or webgl). You cannot switch contexts midway.
//Note: With webGL (for any change) everything on screen is cleared and then redrawn from scratch for each frame
//PRIVATE properties ------------------
var sourceScene; //The TypeScene object to read geometry from
var targetCanvas; //The target HTML canvas object to output the geometry
var currentCamera;
var glSceneObjects = []; //Holds information (buffer handles etc) for each scene object
var glSceneTextures = []; //Holds information (buffer handles etc) for each texture
var glTrivialTextureBfr; //A gl buffer object. Something to point the texture-unit to when no textures are needed
var lastModified; //An object that holds GLobject and GLtexture array universal modifaction dates
var webGL; //The canvas context object
var glShaderProgram; //The compiled shader program
var glShaderVar; //Holds the IDs of all shader variables. Used to communicate with the shaders
//Note: It is possible for both isReady and isFailed to be false -> when something is still loading
var isReady = false; //initialization flag
var isFailed = false; //initialization flag
const appearanceMask =
{
showFullColor:1,
showWireframe:2,
seeThruWireframe:4,
showEdges:8,
respondsToLight:16
};
//-------------------------------------
//PRIVATE methods ---------------------
//-------------------------------------
var SetFailed = function () {isReady=false; isFailed=true;}
var SetReady = function () {isReady=true; isFailed=false;}
var Initialize = function (sScene, canvasStr, vShaderPath, fShaderPath)
{
//Argument checks
var foundCanvas = InitCanvas(canvasStr);
if (!foundCanvas) {Say('WARNING (TypeCanvasWebGLpainter) Did not find canvas element:<'+canvasStr+'> in the document',-1); SetFailed(); return;}
if (!(sScene instanceof TypeScene)) {Say('WARNING (TypeCanvasWebGLpainter) Did not receive a valid scene object',-1); SetFailed(); return;}
//Initialize properties
sourceScene = sScene;
targetCanvas = foundCanvas;
currentCamera = sourceScene.GetCamera(); //A camera is guaranteed to exist
lastModified = {glObjects:0,glTextures:0,draw:0};
//Note: allowable contexts ['webgl','experimental-webgl','webgl2']
//Note: alloweable attributes ['alpha','depth','stencil','antialias','premultipliedAlpha','preserveDrawingBuffer','failIfMajorPerformanceCaveat']
//Create a canvas context (basically select which engine will be driving the canvas)
var contextType = 'webgl'; //This painter object only deals with webGL (a 2D canvas would be a separate painter object)
webGL = targetCanvas.getContext(contextType); if (!webGL) {webGL = targetCanvas.getContext('experimental-webgl');}
if (!webGL) {Say('WARNING (TypeCanvasWebGLpainter) Could not initialize <'+contextType+'> context',-1); SetFailed(); return;}
//Note: A frame buffer is that which contains the display pixel colors
//Note: depth buffer - without a depth buffer things are displayed by order of drawing them (A further away object drawn later will display over a closer object)
//Note: Images typically have 0,0 at TopLeft. WebGL assumes 0,0 at bottom left unless pixelStorei is used to flip the Y axis
//Setup some initial webGL states (webGL is a state machine)
webGL.enable(webGL.DEPTH_TEST); //things are now drawn based on depth regardless of the order they were drawn
webGL.enable(webGL.BLEND); //this option enables transparency/blending effects
webGL.blendFunc(webGL.SRC_ALPHA, webGL.ONE_MINUS_SRC_ALPHA); //blend function when source is not premultiplied alpha
webGL.clearColor(1.0, 1.0, 1.0, 1.0); //Clear screen
webGL.pixelStorei(webGL.UNPACK_FLIP_Y_WEBGL, true); //Set once globally to always flip the Y axis of images (see note above).
//Note: Line width is depracated. The WebGL specification now defines that gl.lineWidth() does not change the line width anymore.
//Note: webGL will initialize webGL.viewport to the dimensions of the 'foundCanvas'
//It is important that the camera aspect ratio matches the viewport's
currentCamera.SetViewport(foundCanvas.width,foundCanvas.height);
//Setup a trivial texture using a single pixel
glTrivialTextureBfr = webGL.createTexture();
webGL.bindTexture(webGL.TEXTURE_2D, glTrivialTextureBfr);
webGL.texImage2D(webGL.TEXTURE_2D, 0, webGL.RGBA, 1, 1, 0, webGL.RGBA, webGL.UNSIGNED_BYTE, new Uint8Array([0, 255, 0, 255]) );
//Note: Arguments for--> void gl.texImage2D(target, level, internalformat, width, height, border, format, type, ArrayBufferView? pixels);
//Note: Alternate --> void gl.texImage2D(target, level, internalformat, format, type, HTMLImageElement? pixels);
//Import the shader files
var vertexShaderFile = new TypeFile ( (!IsString(vShaderPath))? 'WebglVertexShader.glsl' : vShaderPath);
var fragmentShaderFile = new TypeFile ( (!IsString(fShaderPath))? 'WebglFragmentShader.glsl' : fShaderPath);
InstallShaders (vertexShaderFile,fragmentShaderFile); //Compile the shader program using the two shader files
//Note: webGL.getAttribLocation will be used to access the attribute variables of the shader
//Note: webGL.getUniformLocation will be used to access the uniform variables of the shader
}
var InstallShaders = function (vertFile, fragFile)
{ //Helper function for Initialize()
//This method acts directly on the glShaderProgram parameter
//Reads the shader source code into gl shader objects and then compiles them and links them into shader program
//Note: setTimeout accepts arguments in the form of (function, intervalTime, param1, param2, param3, ....). The params are passed to the function as arguments
if (vertFile.IsStillLoading() || fragFile.IsStillLoading()) {setTimeout(InstallShaders,100,vertFile, fragFile); return;}
if (vertFile.IsFailed()) {Say('WARNING (InstallShaders) Failed to load the vertex shader file <'+vertFile.GetFilePath()+'>',-1);return;}
if (fragFile.IsFailed()) {Say('WARNING (InstallShaders) Failed to load the fragment shader file <'+fragFile.GetFilePath()+'>',-1);return;}
var glVertexShader = ReadShader (webGL.VERTEX_SHADER,vertFile.GetDataAsText()); if (isFailed) {return;}
var glFragmentShader = ReadShader (webGL.FRAGMENT_SHADER,fragFile.GetDataAsText()); if (isFailed) {return;}
glShaderProgram = webGL.createProgram(); //Create an empty webGL shader program object
webGL.attachShader(glShaderProgram, glVertexShader); //attach the vertex shader
webGL.attachShader(glShaderProgram, glFragmentShader); //attach the fragment shader
webGL.linkProgram(glShaderProgram);
//Note: webGL.getAttachedShaders(glShaderProgram); would return an Array of glShader objects attached to it
//Note: feeding each glShader object to webGL.getShaderSource(shader); will return the source code for that
//Note: The shader source text is retained inside the glShaderProgram object
//Error check
if (!webGL.getProgramParameter(glShaderProgram, webGL.LINK_STATUS))
{ //getProgramParameter returns a boolean for LINK_STATUS
Say('WARNING (InstallShaders) Link error '+webGL.getProgramInfoLog(glShaderProgram),-1);
webGL.deleteProgram(glShaderProgram);
glShaderProgram = void(0);
SetFailed ();
return;
}
webGL.useProgram(glShaderProgram);
ConnectToShaderVariables();
SetReady(); Say ('NOTE: (InstallShaders) Shader program installed with no errors',-1);
}
var ReadShader = function (shaderType, shaderText)
{ //Helper function for InstallShaders-->Initialize
//Transfer the shader text data into a WebGL shader object.
var glShader = webGL.createShader (shaderType); //create an empty shader object in the webGL
webGL.shaderSource(glShader, shaderText); //Load the shader text data into the glShader object
webGL.compileShader(glShader);
//Error check
if (!webGL.getShaderParameter(glShader, webGL.COMPILE_STATUS))
{ //getShaderParameter returns a boolean for COMPILE_STATUS
Say('WARNING (ReadShader) Compile error with <'+( (shaderType==webGL.VERTEX_SHADER)? 'Vertex shader' : 'Fragment shader' )+'> '+webGL.getShaderInfoLog(glShader),-1);
webGL.deleteShader(glShader);
SetFailed ();
return;
}
return glShader;
}
var ConnectToShaderVariables = function ()
{ //Helper function for InstallShaders--Initialize
//These variables are expected (otherwise things break)
//Note: glsl will not connect variables which did not seem to be used in the code during compile
glShaderVar =
{
//Uniforms (common to both shaders)
appearanceFlags: webGL.getUniformLocation(glShaderProgram, 'appearanceFlags'), //int
//Uniforms (vertexShader)
projViewModelMatrix:webGL.getUniformLocation(glShaderProgram, 'projViewModelMatrix'), //mat4
normalsMatrix: webGL.getUniformLocation(glShaderProgram, 'normalsMatrix'), //mat4
defaultColor: webGL.getUniformLocation(glShaderProgram, 'defaultColor'), //vec4
lightColor: webGL.getUniformLocation(glShaderProgram, 'lightColor'), //vec4
lightPosition: webGL.getUniformLocation(glShaderProgram, 'lightPosition'), //vec3
lightIntensity: webGL.getUniformLocation(glShaderProgram, 'lightIntensity'), //float
//Attributes (vertexShader)
vertexCoord: webGL.getAttribLocation(glShaderProgram, 'vertexCoord'), //vec3
vertexColor: webGL.getAttribLocation(glShaderProgram, 'vertexColor'), //vec4
vertexNormal: webGL.getAttribLocation(glShaderProgram, 'vertexNormal'), //vec3
vertexUVcoord: webGL.getAttribLocation(glShaderProgram, 'vertexUVcoord'), //vec2
vertexTexUnit: webGL.getAttribLocation(glShaderProgram, 'vertexTexUnit'), //flat
//Uniforms (fragmentShader)
useTextures: webGL.getUniformLocation(glShaderProgram, 'useTextures'), //bool
wireframeColor: webGL.getUniformLocation(glShaderProgram, 'wireframeColor'), //vec4
ambientColor: webGL.getUniformLocation(glShaderProgram, 'ambientColor'), //vec4
ambientIntensity: webGL.getUniformLocation(glShaderProgram, 'ambientIntensity'), //float
textureUnit: webGL.getUniformLocation(glShaderProgram, 'textureUnit') //sampler2D (GLint) array. This gets the ID of the first element
};
}
var GenerateApearanceFlagsInt = function (ObjAppearance)
{ //Creates an integer whose bits are treated as booleans for various appearance options
//Note this is done because space is limited at the shader level (booleans take unnecessary space)
//bit-0: mask(1) Full color / monochrome
//bit-1: mask(2) Surface wireframe on/off
//bit-2: mask(4) Surface seethru wireframe on/off
//bit-3: mask(8) Surface edges on/off
//bit-4: mask(16) Responds to light
var sceneAppearance = sourceScene.GetDefaultAppearance();
var result = 0;
//Note: To set a bit perform a bitwise OR with the mask
//Note: To unset a bit perform a bitwise AND with the NOT mask
//Note: To test for a bit perform a bitwise AND with the mask
var showFullColor = ObjAppearance.GetShowFullColor(); if ( showFullColor===void(0)) {showFullColor = sceneAppearance.GetShowFullColor();}
var showWireframe = ObjAppearance.GetShowWireframe(); if ( showWireframe===void(0)) {showWireframe = sceneAppearance.GetShowWireframe();}
var seeThruWireframe = ObjAppearance.GetSeeThruWireframe(); if (seeThruWireframe===void(0)) {seeThruWireframe = sceneAppearance.GetSeeThruWireframe();}
var showEdges = ObjAppearance.GetShowEdges(); if ( showEdges===void(0)) {showEdges = sceneAppearance.GetShowEdges();}
var respondsToLight = ObjAppearance.GetRespondsToLight(); if ( respondsToLight===void(0)) {respondsToLight = sceneAppearance.GetRespondsToLight();}
if (showFullColor) {result |= appearanceMask.showFullColor;} else {result &= ~appearanceMask.showFullColor;}
if (showWireframe) {result |= appearanceMask.showWireframe;} else {result &= ~appearanceMask.showWireframe;}
if (seeThruWireframe) {result |= appearanceMask.seeThruWireframe;} else {result &= ~appearanceMask.seeThruWireframe;}
if (showEdges) {result |= appearanceMask.showEdges;} else {result &= ~appearanceMask.showEdges;}
if (respondsToLight) {result |= appearanceMask.respondsToLight;} else {result &= ~appearanceMask.respondsToLight;}
return result;
}
var SetupShaderVarsForLights = function ()
{
//Will handle the ambient light and only one scene light in this version (this should change in the future)
let currentCam = sourceScene.GetCamera();
let oneSceneLight = sourceScene.GetLight(0); if (!oneSceneLight.GetIsActive()) {return;}
let lightPos = oneSceneLight.GetPosition().GetCopy();
if (oneSceneLight.GetIsRelativeToCam())
{
let camZ = currentCam.GetEyePos().Minus(currentCam.GetTargetPos());
let lightPosZ = camZ.ResizeTo(lightPos.z);
let lightPosY = currentCam.GetUpDirection().AsOrthoTo(camZ).ResizeTo(lightPos.y);
let lightPosX = camZ.CrossProduct(currentCam.GetUpDirection()).ResizeTo(lightPos.x);
lightPos = lightPosX.Plus(lightPosY).Plus(lightPosZ).Plus(currentCam.GetEyePos());
}
webGL.uniform3fv (glShaderVar.lightPosition, new Float32Array(lightPos.GetAsArray(3)) ); //Sending a vec3
webGL.uniform4fv (glShaderVar.lightColor, new Float32Array(oneSceneLight.GetColor().GetArrRGB()) ); //Use 4fv because we are dealing with a float vec4 in form of an array
webGL.uniform1f (glShaderVar.lightIntensity, oneSceneLight.GetIntensity()); //Use 1f because we are dealing with a single float
webGL.uniform4fv (glShaderVar.ambientColor, new Float32Array(sourceScene.GetAmbientLight().color.GetArrRGB()) ); //Sending a vec4
webGL.uniform1f (glShaderVar.ambientIntensity, sourceScene.GetAmbientLight().intensity); //Sending a float
}
//INTERMEDIATE step methods. (prepare the data from sceneObject geometry) -------------------
//-------------------------------------------------------------------------------------------
var MakeGLsceneObject = function (scnObj)
{ //This function creates and returns a new object (to eventually be stored in the GLsceneObjects array)
var parentSceneObj = scnObj.GetParent(); //Find if this scnObj is the child of something else
var parentGLobj = (parentSceneObj!==void(0))? glSceneObjects[ sourceScene.GetSceneObject(parentSceneObj,true) ] : void(0);
resultObj =
{
sceneObj:scnObj, //holds the corresponding geometry object from the target scene's objects[] array
parentGLsceneObj:parentGLobj, //holds the parent GL object from the glSceneObjects[] array
lastModified:Date.now(),
srfVertBuffer:void(0),
srfIndexBuffer:void(0), //Which indexes from the vertex buffer to use to draw the triangles of the mesh
srfNormBuffer:void(0),
srfUvBuffer:void(0),
srfColorBuffer:void(0),
srfTextureUnitBuffer:void(0), //Holds indexes from the srfTextureArr[], which itself holds indexes from the glSceneTextures array
srfTexturesLog:[], //Holds indexes of the glSceneTextures array (glSceneTextures is synchronous to sceneTextures). The textures used by an object is a subset of all the textures in the scene
crvPolylineVertBuffer:void(0),
crvPolylineColorBuffer:void(0),
crvLinepileVertBuffer:void(0),
crvLinepileColorBuffer:void(0)
};
//Note: srfTextureUnitBuffer is a Vertex-to-textureUnit relationship buffer (associates each vertex with a number from 0-8; up to 8 texture units)
//Note: srfTexturesArr holds references to GLtexture objects (from the glSceneTextures array) used in this particular scene object
return Object.seal(resultObj); //Sealed objects do not allow properties to be added later
}
var MakeGLtextureObject = function (sceneTextureObj)
{ //This function returns an object for the glSceneTextures array
resultObj =
{
sceneTxtr:sceneTextureObj,
lastModified:Date.now(),
txtrBuffer:webGL.createTexture()
};
return Object.seal(resultObj); //Sealed objects do not allow properties to be added later
}
var GenerateBuffers = function ()
{ //Generates buffers for the entire scene
//These are techinically called VBOs
//Has anything changed in the entire scene ?
if (sourceScene.GetAnyLookLastModified()<=GetAnyLookLastModified()) {return;} //Nothing to do
//Generate texture buffers
if (sourceScene.GetTexturesLastModified()>lastModified.glTextures) {GenerateTextureBuffers();}
//Generate scene object buffers
if (sourceScene.GetObjectsLastModified()>lastModified.glObjects) {GenerateObjectBuffers();}
//Note: A Vertex Buffer Object (VBO) is a memory buffer in the high speed memory of your video card designed to hold information about vertices.
//for example we could have two VBOs, one that describes the coordinates of our vertices and another that describes the color associated with each vertex.
//VBOs can also store information such as normals, texcoords, indicies, etc.
//Note: In WebGL 2.0 there are also Vertex Array Objects.
//A Vertex Array Object (VAO) is an object which contains one or more Vertex Buffer Objects and is designed to store the information for a complete rendered object.
//So in this case all the buffers used to render a single 'sceneObject' would be in a single VAO
}
var GenerateObjectBuffers = function ()
{ //Helper function for GenerateBuffers (buffers for the sceneObjects)
var sceneObjectCount = sourceScene.GetObjectCount();
for (let i=0;i<sceneObjectCount;i++)
{ //Walk through each sceneObject
let oneGLobject;
let oneSceneObject = sourceScene.GetSceneObject(i); //This is a TypeSceneObject object
//Preliminary checks -------------------------------------
//Handle a missmatch, probably due to a deleted sceneObject causing the glSceneObjects array to be out of sync
if (glSceneObjects[i] && glSceneObjects[i].sceneObj != oneSceneObject) {ResetCrvGLbuffers(glSceneObjects[i]); ResetSrfGLbuffers(glSceneObjects[i]); glSceneObjects[i]=void(0);}
if (glSceneObjects[i] && oneSceneObject.GetLastModified()<=glSceneObjects[i].lastModified) {continue;} //No update needed for this specific scene object
if (glSceneObjects[i]) {oneGLobject = glSceneObjects[i];} //if reached here, scene object has been updated. Buffers need to reload
else {oneGLobject = MakeGLsceneObject(oneSceneObject); glSceneObjects[i]=oneGLobject;} //Wrap the scene object into a new GLsceneObject
//--------------------------------------------------------
//Define temporary 1D arrays (that will disapear once this method is done) for the current scene object, which will be used later to fill the buffers.
//Note: A sceneObject may contain pieces that are either surface objects or curve objects. Each sceneObject needs buffers for both surfaces and curves
//Note: This surfaceArrays portion uses an index array and will proceed through gl.drawElements
let surfaceArrays =
{
sourceSceneObj : oneSceneObject,
vertexArrIdxBookmark : 0, //Bookmark indicating the index of the vertex array that represents the 'zero' index of the current surface.
vertexArr1D : [],
indexArr1D : [],
normalsArr1D : [],
UVarr1D : [],
colorArr1D : [],
textureUnitsArr1D : [], //per vertex indexes from the texturesLog
texturesLog : [], //The subset of scene textures used by this sceneObject
useDefaultMat : true //ignore colorArr1D if non of the surfaces had a custom material assigned; or the ones that did was only for texture
};
//Note: About the vertexArrIdxBookmark -->
//--> Inside a sceneObject there are pieces (surfaces or curves)
//--> the vertices of all surface pieces will pile on a single GL vertex buffer, but they are represented autonomously inside the sceneObject (their vertex arrays start from zero)
//--> a running bookmark is needed that marks which index of the GL vertex buffer pile is the 'zero' index of the current piece (surface) object
//Note: This curveArrays portion does *not* use an index array and will pass through gl.drawArrays linearly
let curveArrays =
{
sourceSceneObj : oneSceneObject,
polylineVertexArr1D : [],
polylineColorArr1D : [],
linepileVertexArr1D : [],
linepileColorArr1D : [],
useDefaultMat : true //ignore colorArr1D if non of the curve objects had a custom material assigned
};
//Loop through all the pieces of the current sceneObject to generate flat array data
//Note: surfaceArrays and curveArrays started empty and will get filled with data from scratch in the for-loop below
let pieceCount = oneSceneObject.GetPieceCount();
for (let j=0;j<pieceCount;j++)
{ //Walk though each piece
let onePiece = oneSceneObject.GetPiece(j); //This could be a surface or a curve
let onePieceProperties = oneSceneObject.GetPropertiesForPiece(j,true); //either a TypeSurfaceProperties or a TypeCurveProperties
if (onePieceProperties && !onePieceProperties.GetIsVisible()) {continue;} //If the object is declared as non-visible, skip it.
if (onePiece instanceof TypeSurface) {PrepareSurfaceArrays(surfaceArrays, onePiece, onePieceProperties);}
else if (onePiece instanceof TypeCurve) {PrepareCurveArrays(curveArrays, onePiece, onePieceProperties);}
}
//Transfer the generated array data (from the for-loop above) into the webGL buffers.
//Note: Non-visible pieces did not add their data to the temporary surface or curve arrays
TransferSceneObjectSrfToWebGL (oneGLobject, surfaceArrays); //The surfaces of the sceneObject
TransferSceneObjectCrvToWebGL (oneGLobject, curveArrays); //The curves of the sceneObject
}
}
var PrepareCurveArrays = function (curveArrays, thisCurve, crvProperties)
{ //Helper function for GenerateObjectBuffers-->GenerateBuffers
//Tranfer curve data from the sceneObject to 1D curve arrays (depending on curve type)
//Note: This is an intermediate step before passing data into webGL buffers
let crvColor = (crvProperties)? crvProperties.GetColor() : void(0);
if (crvColor) {curveArrays.useDefaultMat=false;} //crvProperties!=void(0) means this curve has custom color and thus at least one curve in the sceneObject has custom color
//Note: crvColor could be void(0) and have to fall back to thisCurve default material which could be void(0) and have to fall back to the scene default material
if (!crvColor) {crvColor=(curveArrays.sourceSceneObj.GetDefaultMaterial())? curveArrays.sourceSceneObj.GetDefaultMaterial().GetColor() : void(0);}
if (!crvColor) {crvColor=sourceScene.GetDefaultMaterial().GetColor();} //This guaranteed to exist
let crvType = thisCurve.GetType();
if (crvType == 'Polyline') {TransferPolylineToArr1D(curveArrays, thisCurve, crvColor);}
else if (crvType == 'Line') {TransferLinepileToArr1D(curveArrays, thisCurve, crvColor);}
else if (crvType == 'Interpolated'
|| crvType == 'Ngon') {TransferComputedCrvToArr1D (curveArrays, thisCurve, crvColor);}
else {Say('WARNING (PrepareCurveArrays) Curve type <'+crvType+' is not currently supported.',-1);}
}
var TransferPolylineToArr1D = function (curveArrays, thisCurve, crvColor)
{ //Helper function for PrepareCurveArrays-->GenerateObjectBuffers-->GenerateBuffers
let vertCount = thisCurve.GetVertexCount(); if (vertCount==0) {return;}
for (let i=0;i<vertCount;i++)
{ //Walk through each vertex
let oneVertex = thisCurve.GetVertex(i); //a TypeXYZw object
curveArrays.polylineVertexArr1D.push(oneVertex.x, oneVertex.y, oneVertex.z, oneVertex.w); //Add vertex
curveArrays.polylineColorArr1D.push(crvColor.GetR(), crvColor.GetG(), crvColor.GetB(), crvColor.GetAlpha()); //Add color
}
//Polyline termination
//Note: A sceneObject can have multiple polyline pieces. Once these pieces pile up in a buffer we can no longer tell where one begins and another ends
//Note: Adding an invalid point (NaN,NaN,NaN) will cause the webGL draw function to not draw that segment (leaving a gap)
curveArrays.polylineVertexArr1D.push(NaN,NaN,NaN,NaN); //Termination point
curveArrays.polylineColorArr1D.push(NaN,NaN,NaN,NaN); //Color for the termination point
}
var TransferLinepileToArr1D = function (curveArrays, thisCurve, crvColor)
{ //Helper function for PrepareCurveArrays-->GenerateObjectBuffers-->GenerateBuffers
let vertCount = thisCurve.GetVertexCount(); if (vertCount==0) {return;}
for (let i=0;i<vertCount;i++)
{ //Walk through each vertex
let oneVertex = thisCurve.GetVertex(i); //a TypeXYZw object
curveArrays.linepileVertexArr1D.push(oneVertex.x, oneVertex.y, oneVertex.z, oneVertex.w); //Add vertex
curveArrays.linepileColorArr1D.push(crvColor.GetR(), crvColor.GetG(), crvColor.GetB(), crvColor.GetAlpha()); //Add color
}
//Linepiles do not need termination. Two linepiles combined is still a linepile
}
var TransferComputedCrvToArr1D = function (curveArrays, thisCurve, crvColor)
{ //Helper function for PrepareCurveArrays-->GenerateObjectBuffers-->GenerateBuffers
//Treat the interpolated curve a polyline approximation
let computedPolyline = thisCurve.GetComputedVertArr(); //returns an array of TypeXYZw
let vertCount = computedPolyline.length;
for (let i=0;i<vertCount;i++)
{ //Walk through each vertex
let oneVertex = computedPolyline[i];
curveArrays.polylineVertexArr1D.push(oneVertex.x, oneVertex.y, oneVertex.z, oneVertex.w); //Add vertex
curveArrays.polylineColorArr1D.push(crvColor.GetR(), crvColor.GetG(), crvColor.GetB(), crvColor.GetAlpha()); //Add color
}
//Polyline termination
curveArrays.polylineVertexArr1D.push(NaN,NaN,NaN,NaN); //Termination point
curveArrays.polylineColorArr1D.push(NaN,NaN,NaN,NaN); //Color for the termination point
}
var PrepareSurfaceArrays = function (surfaceArrays, thisSurface, srfProperties)
{ //Helper function for GenerateObjectBuffers-->GenerateBuffers
//Determine the current material (fall back to the scene default if necessary)
//Note: There is a difference between surface properties and a material (surface properties contains a material, but also contains normals and UVs)
let currentSrfProperties = (srfProperties)? srfProperties : new TypeSurfaceProperties (thisSurface);
let currentSrfMaterial = currentSrfProperties.GetMaterial(); //Look for a material at the local properties level
if (currentSrfMaterial && !currentSrfMaterial.GetTexture()) {surfaceArrays.useDefaultMat=false;} //this surface has custom color (we have a material without a texture), so a color array will be used in the entire scene object
if (!currentSrfMaterial) {currentSrfMaterial = surfaceArrays.sourceSceneObj.GetDefaultMaterial();} //Fall back to the sceneObject
if (!currentSrfMaterial) {currentSrfMaterial = sourceScene.GetDefaultMaterial();} //Fall back to the scene. At this point a material is guaranteed
//Determine the texture unit for the texture used in this surface
//Note: Will be computing texture units on the fly (one surface at a time)
//Note: A texture unit is an index of the textureLog which contains an index of the sceneTextures array
//Note: A texture unit will later be linked to a buffer object in the glTexturesArray (which is synchronized with the scene textures array)
let currentSrfTextureObj = currentSrfMaterial.GetTexture();
let currentSrfSceneTextureIdx = sourceScene.GetTexture(currentSrfTextureObj,true); //returns the index of the current surface's texture within the main scene's texture array (or void if not found).
let currentTextureUnit = (currentSrfSceneTextureIdx!==void(0))? surfaceArrays.texturesLog.indexOf(currentSrfSceneTextureIdx) : void(0); //Try to find the current scene's texture index within texturesLog.
//Note: there is a difference between no (void) texture unit and non-found (-1)
if (currentTextureUnit<0) {surfaceArrays.texturesLog.push(currentSrfSceneTextureIdx); currentTextureUnit = surfaceArrays.texturesLog.length-1;} //If not found, then add it.
else if (currentTextureUnit===void(0)) {currentTextureUnit=-1;} //A value of -1 signals the shader not to use texture on that vertex
//Note: Normals and textureUVs are guaranteed to exist as objects (even if their arrays are empty [])
let currentSrfNormals = currentSrfProperties.GetNormals(); if (currentSrfNormals.GetNormalsCount()<thisSurface.GetVertexCount()) {currentSrfNormals.GenerateNormals();}
let currentSrfUVs = currentSrfProperties.GetTextureUVs();
let currentColor = currentSrfMaterial.GetColor();
//Loop through the vertices of the current surface
let vertCount = thisSurface.GetVertexCount();
for (let i=0;i<vertCount;i++)
{ //Walk through each vertex
let oneVertex = thisSurface.GetVertex(i);
let oneNormal = currentSrfNormals.GetNormalAtVertex(i);
let oneTextureUV = currentSrfUVs.GetUVatVertex(i); if (!oneTextureUV) {oneTextureUV = {x:NaN,y:NaN}; }
//Add data to the arrays synchronously
surfaceArrays.vertexArr1D.push(oneVertex.x, oneVertex.y, oneVertex.z, surfaceArrays.vertexArrIdxBookmark + i); //Pass the vertex index on the w component to be available to the shader for effects
surfaceArrays.normalsArr1D.push(oneNormal.x, oneNormal.y, oneNormal.z); //The normals array
surfaceArrays.UVarr1D.push(oneTextureUV.x, oneTextureUV.y); //The UVs array only has x,y coordinates
surfaceArrays.colorArr1D.push(currentColor.GetR(), currentColor.GetG(), currentColor.GetB(), currentColor.GetAlpha()); //The colors array is of type R,G,B,A
surfaceArrays.textureUnitsArr1D.push(currentTextureUnit); //The texture unit array
}
//Handle the index array
let meshSize = thisSurface.GetMeshSize();
for (let i=0;i<meshSize;i++)
{ //Walk through the surface mesh (which contains vertex indexes)
//Note: The zero vertex of thisSurface is the vertexArrIdxBookmark vertex in vertexArr1D
let oneIndex = surfaceArrays.vertexArrIdxBookmark + thisSurface.GetMeshValue(i); //Each mesh value is an index of a vertex in the vertex array
surfaceArrays.indexArr1D.push(oneIndex); //The index array (contains indegers)
}
//Update the vertex bookmark
//Note: vertexArr1D is a flat array. One vertex takes three indexes. This bookmark counts the actual vertices within vertexArr1D
surfaceArrays.vertexArrIdxBookmark += vertCount; //No need to multiply by three
}
//FINAL step methods. (interact with webGL) -------------------------------------------------
//-------------------------------------------------------------------------------------------
var GenerateTextureBuffers = function ()
{ //Helper function for GenerateBuffers
//Goes through all scene textures and updates the buffers if necessary
var sceneTextureCount = sourceScene.GetTextureCount();
for (let i=0;i<sceneTextureCount;i++)
{
let oneGLtextureObject;
let oneSceneTxtr = sourceScene.GetTexture(i); //This is a TypeImage object
//Preliminary checks
if (glSceneTextures[i] && oneSceneTxtr.GetLastModified()<=glSceneTextures[i].lastModified) {continue;} //No update needed for this specific texture buffer
if (glSceneTextures[i]) {oneGLtextureObject=glSceneTextures[i];} //SceneTexture has been updated. Buffer needs to reload
else {oneGLtextureObject = MakeGLtextureObject(oneSceneTxtr); glSceneTextures[i]=oneGLtextureObject;} //Wrap the scene texture into a new GL texture object
//Note: Transferring data to an existing buffer will override the old data in the buffer (no need to delete)
TransferImageToWebGL (oneGLtextureObject);
}
}
var TransferImageToWebGL = function (glTextureObject)
{ //Helper function for GenerateTextureBuffers-->GenerateBuffers
//This method loads the sceneTexture into the webGL buffer asynchronously
if (glTextureObject.sceneTxtr.IsStillLoading()) {setTimeout(TransferImageToWebGL,500); return;}
if (glTextureObject.sceneTxtr.IsFailed()) {return;}
webGL.bindTexture(webGL.TEXTURE_2D, glTextureObject.txtrBuffer); //Make this particular texture buffer 'current' in webGL
//Note: Arguments for gl.texImage2D(gl.TEXTURE_2D, level(=0), internalFormat(=gl.RGBA), srcFormat(=gl.RGBA), srcType(=gl.UNSIGNED_BYTE), HTMLimageObject);
webGL.texImage2D(webGL.TEXTURE_2D, 0, webGL.RGBA, webGL.RGBA, webGL.UNSIGNED_BYTE,glTextureObject.sceneTxtr.GetImageObj()); //Load the data into the buffer
//Note: You can not generate a mipmap for a non-power-of-2 texture in WebGL1.0
//Note: mipmaps is the practice of generating (internally) multiple sizes of the same texture and using them depending on magnification (to avoid zooming artifacts)
//Treat the current texture binding as non power of two texture
webGL.texParameteri(webGL.TEXTURE_2D, webGL.TEXTURE_MAG_FILTER, webGL.LINEAR);
webGL.texParameteri(webGL.TEXTURE_2D, webGL.TEXTURE_MIN_FILTER, webGL.LINEAR);
webGL.texParameteri(webGL.TEXTURE_2D, webGL.TEXTURE_WRAP_S, webGL.CLAMP_TO_EDGE);
webGL.texParameteri(webGL.TEXTURE_2D, webGL.TEXTURE_WRAP_T, webGL.CLAMP_TO_EDGE);
glTextureObject.lastModified = Date.now(); //for the texture buffer itself
lastModified.glTextures = Date.now(); //for the texture array
}
var TransferSceneObjectCrvToWebGL = function (sceneObjectGLbuffers, crvArrays)
{ //Helper function for GenerateObjectBuffers-->GenerateBuffers
TranferSceneObjectPolylinesToWebGL (sceneObjectGLbuffers, crvArrays);
TranferSceneObjectLinepilesToWebGL (sceneObjectGLbuffers, crvArrays);
}
var TranferSceneObjectPolylinesToWebGL = function (sceneObjectGLbuffers, crvArrays)
{ //Helper function for TransferSceneObjectCrvToWebGL-->GenerateObjectBuffers-->GenerateBuffers
let polylineVertCount = crvArrays.polylineVertexArr1D.length/4;
if (polylineVertCount==0) {EmptyDataFromGLbuffer (sceneObjectGLbuffers, 'crvPolylineVertBuffer'); return;}
//Transfer the POLYLINE vertices
if (sceneObjectGLbuffers.parentGLsceneObj!==void(0)) {sceneObjectGLbuffers.crvPolylineVertBuffer = sceneObjectGLbuffers.parentGLsceneObj.crvPolylineVertBuffer; }
else {LoadDataToGLbuffer (sceneObjectGLbuffers, 'crvPolylineVertBuffer', webGL.ARRAY_BUFFER, new Float32Array(crvArrays.polylineVertexArr1D), polylineVertCount, 4); }
//Transfer the POLYLINE colors
if (crvArrays.useDefaultMat==false) {LoadDataToGLbuffer (sceneObjectGLbuffers, 'crvPolylineColorBuffer', webGL.ARRAY_BUFFER, new Float32Array(crvArrays.polylineColorArr1D), polylineVertCount, 4);}
else {EmptyDataFromGLbuffer (sceneObjectGLbuffers, 'crvPolylineColorBuffer'); }
}
var TranferSceneObjectLinepilesToWebGL = function (sceneObjectGLbuffers, crvArrays)
{ //Helper function for TransferSceneObjectCrvToWebGL-->GenerateObjectBuffers-->GenerateBuffers
let linepileVertCount = crvArrays.linepileVertexArr1D.length/4;
if (linepileVertCount==0) {EmptyDataFromGLbuffer (sceneObjectGLbuffers, 'crvLinepileVertBuffer'); return;}
//Transfer the LINEPILE vertices
if (sceneObjectGLbuffers.parentGLsceneObj!==void(0)) {sceneObjectGLbuffers.crvLinepileVertBuffer = sceneObjectGLbuffers.parentGLsceneObj.crvLinepileVertBuffer; }
else {LoadDataToGLbuffer (sceneObjectGLbuffers, 'crvLinepileVertBuffer', webGL.ARRAY_BUFFER, new Float32Array(crvArrays.linepileVertexArr1D), linepileVertCount, 4); }
//Transfer the LINEPILE colors
if (crvArrays.useDefaultMat==false) {LoadDataToGLbuffer (sceneObjectGLbuffers, 'crvLinepileColorBuffer', webGL.ARRAY_BUFFER, new Float32Array(crvArrays.linepileColorArr1D), linepileVertCount, 4);}
else {EmptyDataFromGLbuffer (sceneObjectGLbuffers, 'crvLinepileColorBuffer'); }
}
var TransferSceneObjectSrfToWebGL = function (sceneObjectGLbuffers, srfArrays)
{ //Helper function for GenerateObjectBuffers-->GenerateBuffers
let vertCount = srfArrays.vertexArr1D.length/4;
if (vertCount==0) {ResetSrfGLbuffers(sceneObjectGLbuffers); return;} //There are no surfaces in this sceneObject
if (srfArrays.indexArr1D.length==0) {Say('WARNING: (TransferSceneObjectSrfToWebGL) A surface had no index array',-1); return;} //A surface will not draw without an index array
//Note: If a buffer already exists and we call webGL.bufferData on it a second time, the old data is deleted by webGL
//Note: Float32Array and Uint16Array are Javascript typed-array objects
//Transfer the vertex and index arrays
if (sceneObjectGLbuffers.parentGLsceneObj!==void(0))
{ //If this is a child object re-use the parent vertex buffer data (no need to make new memory for it)
sceneObjectGLbuffers.srfVertBuffer = sceneObjectGLbuffers.parentGLsceneObj.srfVertBuffer;
sceneObjectGLbuffers.srfIndexBuffer = sceneObjectGLbuffers.parentGLsceneObj.srfIndexBuffer;
}
else
{ //This is not a child object. New buffer memory is needed
LoadDataToGLbuffer (sceneObjectGLbuffers, 'srfVertBuffer', webGL.ARRAY_BUFFER, new Float32Array(srfArrays.vertexArr1D), vertCount, 4); //Transfer the surface vertices
LoadDataToGLbuffer (sceneObjectGLbuffers, 'srfIndexBuffer', webGL.ELEMENT_ARRAY_BUFFER, new Uint16Array(srfArrays.indexArr1D), srfArrays.indexArr1D.length, 1); //Transfer the index array
}
//Transfer the normals
LoadDataToGLbuffer (sceneObjectGLbuffers, 'srfNormBuffer', webGL.ARRAY_BUFFER, new Float32Array(srfArrays.normalsArr1D), vertCount, 3); //Transfer the normals
//Transfer the colors
if (srfArrays.useDefaultMat==false) { LoadDataToGLbuffer (sceneObjectGLbuffers, 'srfColorBuffer', webGL.ARRAY_BUFFER, new Float32Array(srfArrays.colorArr1D), vertCount, 4); }
else {EmptyDataFromGLbuffer (sceneObjectGLbuffers, 'srfColorBuffer');}
//Transfer the UVs and texture units (only if textures are being used at all by this scene object)
if (srfArrays.texturesLog.length>0)
{
LoadDataToGLbuffer (sceneObjectGLbuffers, 'srfUvBuffer', webGL.ARRAY_BUFFER, new Float32Array(srfArrays.UVarr1D), vertCount, 2); //The UVs
LoadDataToGLbuffer (sceneObjectGLbuffers, 'srfTextureUnitBuffer', webGL.ARRAY_BUFFER, new Uint16Array(srfArrays.textureUnitsArr1D), vertCount, 1); //The texture units
}
else
{ //Things changed. Delete the buffer object if it exists
EmptyDataFromGLbuffer (sceneObjectGLbuffers, 'srfUvBuffer');
EmptyDataFromGLbuffer (sceneObjectGLbuffers, 'srfTextureUnitBuffer');
}
//Transfer the texture log
sceneObjectGLbuffers.srfTexturesLog = srfArrays.texturesLog;
}
var LoadDataToGLbuffer = function (thisGLsceneObject, thisProperty, thisBufferType, thisTypedArray, unitCount, arrUnitSize)
{ //Helper function for the Transfer-to-webGL functions
//Note: Buffer types are webGL.ARRAY_BUFFER, webGL.ELEMENTS_BUFFER
//Note: Float32Array and Uint16Array are Javascript typed-array objects
//Note: in webGL (or OpenGL) buffers are just arrays in memory (this memory could be anywhere, GPU or CPU, decided by the system, the browser etc)
//Note: once you create a buffer (an array of data in memory) you can link it to a built-in webGL portal by using a "bind" function
//Note: For example for webGL to read vertex data you need to bind/link your buffer (with the data you loaded to it) to the gl.ARRAY_BUFFER dock using the gl.bindBuffer method
//Note: You can continuously dock and undock your buffers from webGL
//Note: If a buffer already exists and we call webGL.bufferData on it a second time, the old data is deleted by webGL
if (thisGLsceneObject[thisProperty]===void(0)) {thisGLsceneObject[thisProperty] = {obj:webGL.createBuffer(), length:unitCount, unitSize:arrUnitSize};} //Create the buffer object
webGL.bindBuffer(thisBufferType, thisGLsceneObject[thisProperty].obj); //Dock it to thisBufferType
webGL.bufferData(thisBufferType, thisTypedArray, webGL.STATIC_DRAW); //Send data to thisBufferType (which is directed to our buffer object)
thisGLsceneObject.lastModified = lastModified.glObjects = Date.now(); //Buffer has been modified
}
var EmptyDataFromGLbuffer = function (thisGLsceneObject, thisProperty)
{
if (thisGLsceneObject[thisProperty]===void(0)) {return;}
webGL.deleteBuffer(thisGLsceneObject[thisProperty].obj);
thisGLsceneObject[thisProperty]=void(0);
thisGLsceneObject.lastModified = lastModified.glObjects = Date.now(); //Buffer has been modified
}
var ResetCrvGLbuffers = function (sceneObjectGLbuffers)
{
EmptyDataFromGLbuffer (sceneObjectGLbuffers, 'crvPolylineVertBuffer');
EmptyDataFromGLbuffer (sceneObjectGLbuffers, 'crvPolylineColorBuffer');
EmptyDataFromGLbuffer (sceneObjectGLbuffers, 'crvLinepileVertBuffer');
EmptyDataFromGLbuffer (sceneObjectGLbuffers, 'crvLinepileColorBuffer');
}
var ResetSrfGLbuffers = function (sceneObjectGLbuffers)
{
EmptyDataFromGLbuffer (sceneObjectGLbuffers, 'srfVertBuffer');
EmptyDataFromGLbuffer (sceneObjectGLbuffers, 'srfIndexBuffer');
EmptyDataFromGLbuffer (sceneObjectGLbuffers, 'srfNormBuffer');
EmptyDataFromGLbuffer (sceneObjectGLbuffers, 'srfUvBuffer');
EmptyDataFromGLbuffer (sceneObjectGLbuffers, 'srfColorBuffer');
EmptyDataFromGLbuffer (sceneObjectGLbuffers, 'srfTextureUnitBuffer');
if (sceneObjectGLbuffers.srfTexturesLog.length>0) {sceneObjectGLbuffers.srfTexturesLog=[];}
}
var DrawPolylines = function (currentGLsceneObj, sceneDefaultAppearance, currentObjAppearance)
{ //Helper function for the main Draw()
if (!currentGLsceneObj.crvPolylineVertBuffer) {return;} //Nothing to do
let defaultCrvColor = currentObjAppearance.GetCurveColor(); if (defaultCrvColor===void(0)) {defaultCrvColor = sceneDefaultAppearance.GetCurveColor();}
let shaderDefaultColor = (currentGLsceneObj.crvPolylineColorBuffer)? [-1,0,0,1] : defaultCrvColor.GetArrRGB(); //if there is a color buffer no default color is needed
webGL.uniform4fv (glShaderVar.defaultColor, new Float32Array(shaderDefaultColor)); //passing a float vec4
ConnectShaderAttributeToBuffer (currentGLsceneObj.crvPolylineVertBuffer, glShaderVar.vertexCoord, webGL.FLOAT, false, 0, 0);
ConnectShaderAttributeToBuffer (currentGLsceneObj.crvPolylineColorBuffer, glShaderVar.vertexColor, webGL.FLOAT, false, 0, 0);
//Note: DrawArrays is a DrawElements with linear indices (0, 1, 2, 3, ...)
webGL.bindBuffer (webGL.ARRAY_BUFFER, currentGLsceneObj.crvPolylineVertBuffer.obj );
webGL.drawArrays (webGL.LINE_STRIP, 0, currentGLsceneObj.crvPolylineVertBuffer.length);
}
var DrawLinepiles = function (currentGLsceneObj, sceneDefaultAppearance, currentObjAppearance)
{ //Helper function for the main Draw()
if (!currentGLsceneObj.crvLinepileVertBuffer) {return;} //Nothing to do
let defaultCrvColor = currentObjAppearance.GetCurveColor(); if (!defaultCrvColor) {defaultCrvColor = sceneDefaultAppearance.GetCurveColor();}
let shaderDefaultColor = (currentGLsceneObj.crvLinepileColorBuffer)? [-1,0,0,1] : defaultCrvColor.GetArrRGB(); //if there is a color buffer no default color is needed
webGL.uniform4fv (glShaderVar.defaultColor, new Float32Array(shaderDefaultColor)); //passing a float vec4
ConnectShaderAttributeToBuffer (currentGLsceneObj.crvLinepileVertBuffer, glShaderVar.vertexCoord, webGL.FLOAT, false, 0, 0);
ConnectShaderAttributeToBuffer (currentGLsceneObj.crvLinepileColorBuffer, glShaderVar.vertexColor, webGL.FLOAT, false, 0, 0);
webGL.bindBuffer (webGL.ARRAY_BUFFER, currentGLsceneObj.crvLinepileVertBuffer.obj );
webGL.drawArrays (webGL.LINES, 0, currentGLsceneObj.crvLinepileVertBuffer.length);
}
var DrawSurfaceEdges = function (currentGLsceneObj, sceneDefaultAppearance, currentObjAppearance, appearanceFlags)
{
//... to do ...
}
var DrawSurfaces = function (currentGLsceneObj ,sceneDefaultAppearance, currentObjAppearance, objTextureCount, appearanceFlags)
{ //Helper function for Draw()
if (!currentGLsceneObj.srfIndexBuffer) {return;} //Nothing to do
let monochromeColor = new TypeColor(1.0,1.0,1.0,1.0,1.0);
let showInFullColor = (appearanceFlags & appearanceMask.showFullColor) ? true : false;
let defaultSrfColor = (!showInFullColor)? monochromeColor : currentObjAppearance.GetColor(); if (defaultSrfColor===void(0)) {defaultSrfColor = sceneDefaultAppearance.GetColor();}
let shaderDefaultColor = (currentGLsceneObj.srfColorBuffer)? [-1,0,0,1] : defaultSrfColor.GetArrRGB(); //if there is a color buffer no default color is needed
webGL.uniform4fv (glShaderVar.defaultColor, new Float32Array(shaderDefaultColor)); //passing data to the shader variable (float vec4 defaultColor)
//Note: There is no glPolygonMode in webGL. Wireframes must be shown manually
//Assign texture buffers to texture units
for (let j=0; j<objTextureCount; j++)
{
webGL.activeTexture(webGL.TEXTURE0 + j); //Select a texture unit (webgl 1.0 guarantees at least 8)
webGL.bindTexture(webGL.TEXTURE_2D, glSceneTextures[ currentGLsceneObj.srfTexturesLog[j] ].txtrBuffer ); //Dock our texture buffer to webGL.TEXTURE_2D to become unit webGL.TEXTURE0 + j
}
//Tell the shader attributes how to get data to draw surfaces
//Note: Attributes are the variables in the shaders that automatically zip through the buffer data one by one during a draw call
//Note: The attributes are connected ONLY if the buffer actually exists (has data)
ConnectShaderAttributeToBuffer (currentGLsceneObj.srfVertBuffer, glShaderVar.vertexCoord, webGL.FLOAT, false, 0, 0);
ConnectShaderAttributeToBuffer (currentGLsceneObj.srfNormBuffer, glShaderVar.vertexNormal, webGL.FLOAT, false, 0, 0);
ConnectShaderAttributeToBuffer (currentGLsceneObj.srfColorBuffer, glShaderVar.vertexColor, webGL.FLOAT, false, 0, 0);
ConnectShaderAttributeToBuffer (currentGLsceneObj.srfUvBuffer, glShaderVar.vertexUVcoord, webGL.FLOAT, false, 0, 0);
ConnectShaderAttributeToBuffer (currentGLsceneObj.srfTextureUnitBuffer, glShaderVar.vertexTexUnit, webGL.SHORT, false, 0, 0);
//Draw the surface using the elements array
webGL.bindBuffer (webGL.ELEMENT_ARRAY_BUFFER, currentGLsceneObj.srfIndexBuffer.obj );
webGL.drawElements (webGL.TRIANGLES, currentGLsceneObj.srfIndexBuffer.length, webGL.UNSIGNED_SHORT, 0);
//CleanUp
webGL.disableVertexAttribArray(glShaderVar.vertexNormal); //disconnect this shader variable
webGL.disableVertexAttribArray(glShaderVar.vertexColor); //disconnect this shader variable
webGL.disableVertexAttribArray(glShaderVar.vertexUVcoord); //disconnect this shader variable
webGL.disableVertexAttribArray(glShaderVar.vertexTexUnit); //disconnect this shader variable
}
var ConnectShaderAttributeToBuffer = function (thisBuffer, thisAttribLocation, dataType, doNormalize, stride, offset)
{ //Helper function for the DRAW functions
if (thisBuffer===void(0) || thisAttribLocation<0) {return;}
if (doNormalize===void(0)) {doNormalize = false;}
if (stride===void(0)) {stride = 0;}
if (offset===void(0)) {offset = 0;}
//Note: glEnableVertexAttribArray enables the generic vertex attribute array specified by index.
//Note: By default, all client-side capabilities are disabled, including all generic vertex attribute arrays.
//Note: If enabled, the values in the generic vertex attribute array will be accessed and used for rendering when calls are made to glDrawArrays or glDrawElements.
webGL.bindBuffer(webGL.ARRAY_BUFFER, thisBuffer.obj);
webGL.enableVertexAttribArray(thisAttribLocation);
webGL.vertexAttribPointer(thisAttribLocation, thisBuffer.unitSize, dataType, doNormalize, stride, offset);
}
var GetAnyLookLastModified = function () { return (lastModified.glObjects>=lastModified.glTextures) ? lastModified.glObjects : lastModified.glTextures; }
//-------------------------------------
//PUBLIC methods ----------------------
//-------------------------------------
this.IsLoaded = function () {return isReady;}
this.IsFailed = function () {return isFailed;}
this.IsStillLoading = function () {return !(isReady || isFailed);}
this.OperateCamera = function (theMouseState)
{ //This menthod controls viewport behavior (should move this functionality to the camera operator object in the future)
if (!(theMouseState instanceof Object
&& theMouseState.hasOwnProperty('delta')
&& theMouseState.hasOwnProperty('buttonState')
&& theMouseState.hasOwnProperty('specialKeys') )) {Say('WARNING: (OperateCamera) Did not receive a proper mouseState object',-1); return;}
//Note: Expected layout for theMouseState.buttonState
//bit-0: (1) Left button
//bit-1: (2) Right button
//bit-2: (4) Middle button
//bit-3: (8) 4th button (typically, "Browser Back" button)
//bit-4: (16) 5th button (typically, "Browser Forward" button)