-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBasicLib.js
More file actions
3859 lines (3339 loc) · 236 KB
/
BasicLib.js
File metadata and controls
3859 lines (3339 loc) · 236 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
//+++++++++++++++++++++++++++
//This Library has:
// Global Func: IsArray, IsString, XOR, ArrCompare, GetCSScolor, PaddedNumber, GetPathComponents, GetArrRGB, Say, InitCanvas, ClipValue
// Class/Objects: TypeKinematics, TypeColor, TypeOscillator, TypeSlider, TypeXYZw, TypeBoundingBox, TypeCentroid, TypePlane, TypeTmatrix, TypeCamera2D(depracated),
// TypeCamera, TypeCameraOperator, TypeText, TypeCurve, TypeSurface, TypeSurfaceNormals, TypeSurfaceTextureCoord, TypeLegacyMaterial,
// TypeSceneObjectAppearance, TypeSurfaceProperties, TypeCurveProperties, TypeTextProperties, TypePointLight, TypeSceneObject, TypeScene, TypeFile, TypeImage, TypeOBJFileLoader
//NOTE: This library is kept *theoretical* and fundamental; building blocks for other libraries. (Does not contain HTML specific functions (canvas etc), or WebGL specific.)
//+++++++++++++++++++++++++++
//===================================================================================================================================================
//Global Constants-----------------------------------------------------------------------------------------------------------------------------------
var epsilon = 0.001;
const degToRad = 0.017453292519943295769236907684886127134428718885417;
const radToDeg = 57.295779513082320876798154814105170332405472466564;
const pi = 3.1415926535897932384626433832795028841971693993751;
const primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997];
//===================================================================================================================================================
//Global variables-----------------------------------------------------------------------------------------------------------------------------------
var sysTimeStamp = Date.now(); //In milliseconds
var sessionTimer = 0;
var deltaT = 0.01;
//---------------------------------------------------------------------------------------------------------------------------------------------------
//===================================================================================================================================================
//Global Functions-----------------------------------------------------------------------------------------------------------------------------------
function IsArray (thisThing) {return Array.isArray(thisThing);}
function IsString (thisThing) {return (typeof thisThing == 'string' || (thisThing instanceof String));}
function GetCSScolor (ColorArr)
{ //Convert a regular array of values to a CSS color string
if (ColorArr instanceof TypeXYZw) {ColorArr = ColorArr.GetAsArray();}
if (!IsArray(ColorArr) || ColorArr.length<3) {return "rgb(0,0,0)"; }
else if (ColorArr.length>=4) {return "rgba("+Number(ColorArr[0])+","+Number(ColorArr[1])+","+Number(ColorArr[2])+","+Number(ColorArr[3])+")";}
else {return "rgb(" +Number(ColorArr[0])+","+Number(ColorArr[1])+","+Number(ColorArr[2])+")";}
}
function XOR (a,b) {return (a==true)? !b : b;}
function GetArrRGB (CSScolorStr)
{ //Convert a CSS color string to an array of numerical values
var result = CSScolorStr.match(/\d+/g); //RegExp /..../ It contains operant \d (find digit), contains + (find all digits, not just one), ends with the g modifier (find all matches rather than stopping after the first match)
var count = result.length;
for (var i=0;i<count;i++) result[i]=Number(result[i]);
return result;
}
function ArrCompare(arr1,arr2)
{ //Compare two arrays value by value
if (!IsArray(arr1) || !IsArray(arr2)) return false;
var count = arr1.length;
if (count!=arr2.length) {return false;}
for (var i=0;i<count;i++) {if (arr1[i]!=arr2[i]) return false;}
return true;
}
function Say (userSays,elementID)
{ //Print a message; either to a specificly supplied ID of an HTML element, or to the console
var defaultElementID = "PrintOut"; if (elementID === void(0)) {elementID = defaultElementID;} //PrintOut is Default HTML element (by convention)
var OutputHTMLelement = document.getElementById(elementID); //document.getElementById always expects a string (so numbers will return null)
if (!IsString(userSays)) {userSays = String(userSays);}
//Printing to the document
if (OutputHTMLelement!==null) {OutputHTMLelement.innerHTML = userSays; return;}
//Printing to the console
console.log (userSays);
}
function ClipValue (x,max,min)
{ //Constrain x within min, max
//Note: x==NaN or x===Nan do not work as expected. Number.isNaN(x) is idial and instanteneous
//Note: Number(x) is extremely fast for actual numbers (infinitescimal performance hit)
//Note: isNaN(x) is relatively expensive
if (min===void(0)) {min=0;}
if (max===void(0)) {max=min+1;}
if (min>max) {let t=max; max=min; min=t;}
if (x<min) {x=min;} else if (x>max) {x=max;}
return x;
}
function ClipValue2 (x,max,min)
{ //clean and constrain x within min, max
//Note: x==NaN or x===Nan do not work as expected. Number.isNaN(x) is idial and instanteneous
//Note: Number(x) is extremely fast for actual numbers (infinitescimal performance hit)
//Note: isNaN(x) is relatively expensive
x = Number(x); max = Number(max); min = Number(min);
if (Number.isNaN(min)) {min=0;} if (Number.isNaN(max)) {max=min+1;} if (min>max) {let t=max; max=min; min=t;}
if (x<min || Number.isNaN(x)) {x=min;} else if (x>max) {x=max;}
return x;
}
function PaddedNumber (num,totalDigits,padding)
{ //Returns the number as a string and adds zeros at the front if the number itself has less digits
var zeros = '';
var posNum = Math.abs(num);
var sign = (num<0)? '-' : '';
var numDigitCount = (posNum<1)? 1 : Math.floor(Math.log10(posNum))+1;
var zerosCount = totalDigits-numDigitCount
if (padding===void(0)) {padding = '0';}
if (Number.isNaN(zerosCount) || zerosCount<=0) {return num;} //Nothing to do
for (let i=0; i<zerosCount; i++) {zeros += padding;}
return sign+zeros+posNum;
}
function GetPathComponents (customPath)
{ //Splits the path into a root substring and a filename substring (default path is where the calling HTML file located)
var path = (customPath===void(0))? location.href : customPath; //location.href returns the full path to the calling HTML file
var lastSlashIdx = path.lastIndexOf('/');
return {rootDir:path.substring(0,lastSlashIdx+1), fileName:path.substring(lastSlashIdx+1)};
}
//===================================================================================================================================================
//Classes / Constructor-functions
//---------------------------------------------------------------------------------------------------------------------------------------------------
/*function TypeClassName (arguments)
{ //Description:
//PRIVATE properties
//PRIVATE methods
var Initialize = function (arguments) {}
//PUBLIC methods
//Initialization
Initialize(arguments);
}*/
//---------------------------------------------------------------------------------------------------------------------------------------------------
function TypeSlider (trvLength,T,asSpring)
{ //This object slides numerically from stowed to a deployed state within a range (it doesn't draw anything). If elastic, it will remain active until it comes to a rest.
var isElastic; //Slider behaves as a spring
var deploy; //boolean (command)
var condition; //Silder state --> 0:stowed, 1:deployed and resting, 0.5:in motion
var travel; //Total length if slider (or length of spring when deployed and at rest)
var deflection; //How compressed it is (distance from deployed state)
var kCoef; //Spring coefficient
var bCoef; //Drag coefficient
var currPos; //active location
var posRatio; //percent to full travel
var initVel, velocity, minAccel, minVel;
//Methods ---------------------
var Initialize = function (travelLength,period,elastic)
{
isElastic = (elastic)? true : false;
deploy = false;
condition = 0;
travel = travelLength;
deflection = travel;
kCoef = (elastic==false)? 0 : Math.pow((2*pi)/period,2); // T = 2*pi*sqrt(m/k) --> k = ((2*pi)/T)^2
bCoef = Math.sqrt(kCoef)*0.8;
currPos = 0; //from 0 to 'travel'
posRatio = 0; //from 0 to 1
initVel = travelLength/period;
velocity = (elastic==true)? 0 : initVel;
minVel = 0.015 * initVel;
minAccel = kCoef * Math.abs(0.002*travel);
}
var CalculateState = function ()
{
if ((deploy==false && condition==0) || (deploy==true && condition==1)) return;
if (isElastic==true && deploy==true) CalculateStateAsSpring(); else CalculateStateAsSimple();
posRatio = currPos/travel;
}
var CalculateStateAsSpring = function ()
{ //Note: deltaT is a global var
//before deltaT
deflection = travel - currPos;
var drag = bCoef * velocity; //dampening-deceleration: F = bCoef * vel
var accAt0 = kCoef * deflection - drag; //accelation
if (Math.abs(accAt0)<minAccel && Math.abs(velocity)<minVel) {condition=1;velocity=0; currPos=travel; return;} else {condition=0.5;}
//after deltaT
currPos = (currPos==0)? accAt0 * deltaT * deltaT /2 : currPos + (velocity * deltaT);
velocity += (accAt0 * deltaT); //new velocity
}
var CalculateStateAsSimple = function ()
{
var deltaX, speed;
if (deploy == false) speed = -velocity; else speed = velocity;
deltaX = speed * deltaT;
currPos += deltaX;
if (currPos>travel) {currPos=travel; condition=1;} else if (currPos<0) {currPos=0; condition=0;} else {condition=0.5;}
}
this.SetDeploy = function (toThis)
{
if(deploy==toThis) return; else deploy=toThis; //proceed only if different
if(deploy==false || (deploy==true && isElastic==false)) {velocity=initVel;} else {velocity=0;}
}
this.IsActive = function () {return (condition>0 || deploy==true)? true : false;}
this.IsInMotion = function () {return condition==0.5;}
this.IsStowed = function () {return condition==0;}
this.IsExtended = function () {return condition==1;}
this.UpdateState = function () {CalculateState(); return posRatio;}
this.GetDeploy = function () {return deploy;}
this.GetState = function () {return posRatio;}
this.GetPosition = function () {return currPos;}
this.GetDeflection = function () {return deflection;}
this.GetCondition = function () {return condition;}
this.GetMaxTravel = function () {return travel;}
this.toString = function () {return '[object TypeSlider]\nCurrentPos='+posRatio+', Condition='+condition+', Deployed='+deploy+', Elastic='+isElastic+']\n';}
Initialize(trvLength,T,asSpring);
}
//---------------------------------------------------------------------------------------------------------------------------------------------------
function TypeOscillator (periodOrAny,repeat,waveShift,startAtTime)
{ //Varies from 0 to 1. This object is essentially a little piston (cosine function) used as heartbeat for oscilating movements or behaviors (such as color fades, etc)
//var timeStamp = sessionTimer;
//Private properties ----------------
var period; //time (ticks) for a cycle to complete
var maxCycles; //Note: 1 cycle means start-state and end-state are the same. 0.5 cycle is a fade. (Infinity: repeat forever, 0:deactivate oscillator, 1: one cycle only, n: so many cycles)
var offset; //shift the waveform left or right essentially changing its starting state
var timer = 0;
var state; //the state of the oscilator wave (from 0 to 1; this is the output value
var cycleCount = 0; //how many cycles have currently been completed
var isActive; //Is the oscillator running or has it passed its maxCycles
//Private methods -------------------
var CalculateState = function ()
{
if (isActive==false) {return;} //Save same CPU time
cycleCount = (timer+deltaT)/period;
if ( cycleCount>maxCycles) {timer=maxCycles*period; cycleCount=maxCycles; isActive=false;} //if next tick will cross over the MaxCycles, oscillator should end in a precise state
//var dt = (sessionTimer-timeStamp)/100; timeStamp=sessionTimer;
var angleTheta = (2*Math.PI) * ((timer+offset)/period); //In radians. Full period is 2*pi radians
state = (1+Math.cos(angleTheta))/2; //cosine goes from -1 to 1 --> 1+cos goes from 0 to 2 --> so you divide by 2 to get a 0-1 oscillation
//Uptick
if (maxCycles!=0) timer += deltaT; else isActive=false; //When MaxCycles=0 the state is calculated exactly one time at the beginning during initialization
}
//Public methods ---------------------
this.GetTimer = function () {return timer;}
this.GetPeriod = function () {return period;}
this.GetMaxCycles = function () {return maxCycles;}
this.GetOffset = function () {return offset;}
this.GetCounter = function () {return cycleCount;}
this.GetState = function () {CalculateState(); return state; }
this.GetIsActive = function () {return isActive;}
this.Restart = function () {timer=0; isActive=true; CalculateState(); return this;}
this.Stop = function (state) {isActive = false; return this;}
this.SetEqualTo = function (other) {this.Set(other); return this;}
this.Set = function (X,r,o,t)
{
if (X instanceof TypeOscillator) { period = X.GetPeriod(); maxCycles = X.GetMaxCycles(); offset = X.GetOffset(); timer = X.GetTimer(); state = X.GetState(); isActive = X.GetIsActive(); return; }
if (IsArray(X)) { t = X[3]; o = X[2]; r = X[1]; X = X[0]; }
timer = isNaN(t)? 0 : Number(t);
period = isNaN(X)? 2 : Number(X);
maxCycles = isNaN(r)? 0 : Number(r);
offset = isNaN(o)? 0 : ((Number(o)*10)%(period*10))/10; //ensure offset is always less than the period (the 10 thing is for precision purposes)
isActive = true;
CalculateState();
return this;
}
this.toString = function () {return '[Object TypeOscillator] (period:'+period+', MaxCycles:'+maxCycles+', Offset:'+offset+', Timer ticks:'+timer+', STATE:'+state+')\n';}
//Initialization
this.Set(periodOrAny,repeat,waveShift,startAtTime);
}
//---------------------------------------------------------------------------------------------------------------------------------------------------
function TypeColor (userX,userG,userB,userA,clipTo,scaleTo)
{ //Color object
//PRIVATE properties --------------------------------
var MaxRange; //if it is 1 then the values are all percentages (floats)
var R,G,B,A; //These values all hold floating numbers (not integers) maintaining accuracy internally (especially for RGB - HSL conversions)
//For the alpha value: 1=opaque, 0=transparent
//PRIVATE methods -----------------------------------
var ConvertRGBtoHSL = function ()
{
var percentR, percentG, percentB, min, max, resultH, resultS, resultL;
if (MaxRange>1) {percentR=R/MaxRange;percentG=G/MaxRange;percentB=B/MaxRange;} else {percentR=R;percentG=G;percentB=B;}
min=percentR;
max=percentR;
if (percentG<min) min=percentG;
if (percentG>max) max=percentG;
if (percentB<min) min=percentB;
if (percentB>max) max=percentB;
resultL = 100*(min+max)/2;
if (resultL<=50) {resultS=100*(max-min)/(max+min);} else {resultS=100*(max-min)/(2.0-max-min);}
if (percentR==max) {resultH=(percentG-percentB)/(max-min);}
else if (percentG==max) {resultH=2.0+(percentB-percentR)/(max-min);}
else {resultH=4.0+(percentR-percentG)/(max-min);}
resultH=resultH*60; if (resultH<0) resultH+=360;
return [resultH,resultS,resultL];
}
//PUBLIC methods ------------------------------------
this.MultiplyWith = function (scalar) {return new TypeColor(R*scalar,G*scalar,B*scalar,A,MaxRange);}
this.GetArrRGB = function (isRaw,norm) {var ratio = (norm)? 1/MaxRange : 1; return (isRaw==true || MaxRange==1)? [R*ratio,G*ratio,B*ratio,A*ratio] : [Math.round(R*ratio),Math.round(G*ratio),Math.round(B*ratio),A];}
this.GetStrRGB = function (isRaw) {var ratio = 255/MaxRange; return (isRaw==true)? "rgb(" +R+","+G+","+B+")" : "rgb(" +Math.round(R*ratio)+","+Math.round(G*ratio)+","+Math.round(B*ratio)+")";}
this.GetCSScolor = function (isRaw) {var ratio = 255/MaxRange; return (isRaw==true)? "rgba(" +R+","+G+","+B+","+A+")" : "rgba(" +Math.round(R*ratio)+","+Math.round(G*ratio)+","+Math.round(B*ratio)+","+A+")";}
this.GetR = function (isRaw) {return (isRaw==true || MaxRange==1)? R : Math.round(R);}
this.GetG = function (isRaw) {return (isRaw==true || MaxRange==1)? G : Math.round(G);}
this.GetB = function (isRaw) {return (isRaw==true || MaxRange==1)? B : Math.round(B);}
this.GetA = function () {return A;} //1=opaque, 0=transparent
this.GetAlpha = function () {return A;} //Synonym to GetA()
this.GetMaxRange = function () {return MaxRange;}
this.GetArrHSL = function () {return ConvertRGBtoHSL();}
this.GetCSScolorHSL = function () {var arrHSL = this.GetArrHSL(); return "hsl("+arrHSL[0]+","+arrHSL[1]+"%,"+arrHSL[2]+"%)";}
this.GetCopy = function () {return new TypeColor(R,G,B,A,MaxRange);}
this.SetAsPercent = function (isPercent)
{ //Defaults to true if nothing given
if (isPercent===void(0) || isPercent) {this.SetMaxRange(1,true);}
else if (!isPercent && MaxRange==1) {this.SetMaxRange(255,true);}
}
this.SetMaxRange = function (newRange, resize)
{ //Expects that 'newRange' is a number and 'resize' is a boolean
//'resize' means that setting the MaxRange will propoertionally adjust the R,G,B values (otherwise the values are merely clipped or stay the same)
if (isNaN(newRange) || newRange<0 || newRange==MaxRange) {return;}
resize = (resize || resize===void(0))? true: false; if (!resize || MaxRange===void(0)) {MaxRange = newRange; return;}
let ratio = newRange / MaxRange;
R *= ratio;
G *= ratio;
B *= ratio;
MaxRange = newRange;
}
this.SetR = function (newR) {R=ClipValue(newR,MaxRange); return this;}
this.SetG = function (newG) {G=ClipValue(newG,MaxRange); return this;}
this.SetB = function (newB) {B=ClipValue(newB,MaxRange); return this;}
this.SetA = function (newA) {A=ClipValue(newA,1); return this;} //if newA is NaN this will default to 0=transparent
this.SetColor = function (X,newG,newB,newA,clip,scaleTo)
{
//Note: if clip resieves a boolean it is interpreted as 1 and is the equivalent of 'isPercent'
//Note: if scaleTo is missing it is set equal to clip (no scaling)
if (X instanceof TypeColor) {R=X.GetR(true); G=X.GetG(true); B=X.GetB(true); A=X.GetAlpha(); MaxRange=X.GetMaxRange(); return;}
var temp=X;
if (IsString(temp) && isNaN(temp)) {temp=temp.match(/[+-]?\d+(\.\d+)?/g);} //In case it is literally a string -->"RGBA(R,G,B,A)" such as coming from a CSS object
if (IsArray(temp)) {X=temp[0]; newG=temp[1]; newB=temp[2]; newA=temp[3]; clip=temp[4]; scaleTo=temp[5]; } //Distributes the array into the other arguments
if (clip && scaleTo===void(0)) {scaleTo = clip;}
if ( isNaN(clip) || clip<0 ) { clip = 255;} //defaults to the standard 255 range
if (isNaN(scaleTo) || scaleTo<0) {scaleTo = 255;} //defaults to the standard 255 range
MaxRange = clip;
this.SetR(X);
this.SetG(newG);
this.SetB(newB);
this.SetA((newA===void(0))? 1:newA); //if not given, default to 1=opaque
this.SetMaxRange(scaleTo,true);
}
this.SetEqualTo = function (otherColor) {this.SetColor (otherColor);}
this.TransitionTo = function (otherColor,percent)
{
otherColor = (otherColor instanceof TypeColor)? otherColor : new TypeColor(otherColor);
percent = ClipValue(percent);
let ratio = otherColor.GetMaxRange / MaxRange;
return new TypeColor ( R*ratio+(otherColor.GetR(true)-R)*percent, G*ratio+(otherColor.GetG(true)-G)*percent, B*ratio+(otherColor.GetB(true)-B)*percent, A*ratio+(otherColor.GetAlpha()-A)*percent, MaxRange );
}
this.IsEqualTo = function (otherColor)
{
otherColor = (otherColor instanceof TypeColor)? otherColor : new TypeColor(otherColor);
if (R==otherColor.GetR(true) && G==otherColor.GetG(true) && B==otherColor.GetB(true) && A==otherColor.GetAlpha() && MaxRange==otherColor.GetMaxRange()) return true;
return false;
}
this.toString = function () {return this.GetCSScolor();}
//Initialize
this.SetColor(userX,userG,userB,userA,clipTo,scaleTo);
}
//---------------------------------------------------------------------------------------------------------------------------------------------------
function TypeKinematics(x,y,z)
{
//Note: This object generally serves as a property inside other objects
//It is suited to handle things that have a center point (center of mass) by which they can translate or rotate
//PRIVATE Properties -------------------------------
var mass = 1; //in Kg
var elasticity = 1; //from 0-1 for collision energy transfer
var friction = 0; //from 0-1
var datumPos = new TypeXYZw(x,y,z); //Center of grapvity (useful mainly during rotations about this point). This is not meant to be changed constantly to track an object.
var translationVel = new TypeXYZw(); //units per second
var rotationVel = new TypeXYZw(0,0,1,0); //A unit vector indicating the spin axis (normal to the plane of rotation) with a 'w' value indicating the magnitude (angular velocity)
var tMatrix = new TypeTmatrix(); //Position rotation and translation transformations to act on datumPos.
var tMatrixHistory = [];
var angleCounter; //
//Note: The tMatrix is the bottom line. It is what should be used to transform any point to its final state.
//Note: Rotation velocity is a vector that uses the 'w' to store the angular speed. (this way 'w' can be set to zero without loosing the rotation plane)
//Note: tMatrix only rotates about the world axis, the datumPos is needed to transfer the rotation to other locales.
//Note: if only translations are applied, datum position is irrelevant
//Note: a relative rotation, involves: a) translating by a minus datum amount, b) rotating, c) translating by a plus datum amount
//Private methods
var ClearTranslationRotation = function () {tMatrix.SetIdentity(); translationVel.SetEqualTo(0,0,0,1); rotationVel.SetEqualTo(0,0,1,0);}
//PUBLIC Methods-----------------------------------
this.Update = function (isLiveUpdate)
{ //This applies the rotation and translation velocities to the tMatrix
var translDelta = translationVel.ScaleBy(deltaT); //deltaT is a global variable
var rotDeltaTh = rotationVel.w*deltaT; //rotDelta = (speed rad/sec) * (dt sec)
var currDatumPos = tMatrix.MultiplyWith(datumPos);
//Rotation is always about the datum
if (angleCounter!==void(0)) {angleCounter += rotDeltaTh;}
if (isLiveUpdate!==false && rotDeltaTh!=0)
{
tMatrix.SetTranslate(-currDatumPos.x, -currDatumPos.y, -currDatumPos.z);
tMatrix.SetRotate3D(rotationVel,rotDeltaTh);
tMatrix.SetTranslate(currDatumPos.x+translDelta.x, currDatumPos.y+translDelta.y, currDatumPos.z+translDelta.z);
return tMatrix;
}
if (isLiveUpdate!==false && rotDeltaTh==0)
{
tMatrix.SetTranslate(translDelta.x, translDelta.y, translDelta.z);
return tMatrix;
}
if (isLiveUpdate===false && rotDeltaTh!=0)
{
let tempMatrix = tMatrix.Translate(-currDatumPos.x, -currDatumPos.y, -currDatumPos.z);
tempMatrix = tempMatrix.Rotate3D(rotationVel,rotDeltaTh);
tempMatrix = tempMatrix.Translate(currDatumPos.x+translDelta.x, currDatumPos.y+translDelta.y, currDatumPos.z+translDelta.z);
return tempMatrix;
}
return tMatrix.Translate(translDelta.x, translDelta.y, translDelta.z);
}
//---------
this.HasRotation = function () {return (rotationVel.w==0)? false:true;}
this.HasTranslation = function () {return !translationVel.IsZero();}
this.GetMass = function () {return mass;}
this.GetElasticity = function () {return elasticity;}
this.GetFriction = function () {return friction;}
this.GetDatumPos = function () {return datumPos;}
this.GetAngleCounter = function () {return angleCounter;}
this.GetTranslationVel = function () {return translationVel;}
this.GetRotationVel = function () {return rotationVel;}
this.GetTmatrix = function () {return tMatrix;}
this.GetSavedTmatrix = function (i) {return tMatrixHistory[i];}
this.GetPos = function () {return tMatrix.MultiplyWith(datumPos);}
this.GetFuturePos = function () {return this.Update(false).MultiplyWith(datumPos);}
this.SavedTmatrixPop = function () {return tMatrixHistory.pop();}
//---------
this.SetMass = function (m) {m = Number(m); if (m<0 || m==NaN) {m=0;} mass=m;} //Cannot be negative
this.SetElasticity = function (el) {elasticity = ClipValue(el);} //Checks range to 0-1
this.SetFriction = function (fr) {friction = ClipValue(fr);} //Checks range to 0-1
this.SetDatumPos = function (x,y,z) {if (x instanceof TypeXYZw) {datumPos=x;} else {datumPos.SetEqualTo(x,y,z);} }
this.SetTranslationVel = function (x,y,z) {if (x instanceof TypeXYZw) {translationVel=x} else {translationVel.SetEqualTo(x,y,z);} }
this.SetRotationVel = function (x,y,z,w){if (x instanceof TypeXYZw) {rotationVel=x} else {rotationVel.SetEqualTo(x,y,z,w);}}
this.SetTmatrix = function (tm) {if (tm instanceof TypeTmatrix) {tMatrix=tm} else {tMatrix.SetEqualTo(tm);} }
this.SetSavedTmatrix = function (i,tm) {if (tm instanceof TypeTmatrix) {tMatrixHistory[i]=tm} else {tMatrixHistory[i] = new TypeTmatrix(tm);} }
this.SaveTmatrixPush = function (tm) {if (tm instanceof TypeTmatrix) {tMatrixHistory.push(tm)} else {tMatrixHistory.push(new TypeTmatrix(tm));} }
this.StartAngleCounter = function () {angleCounter = 0;}
this.ClearAngleCounter = function () {angleCounter = void(0);}
this.Reset = function () {ClearTranslationRotation();}
this.ResetTmatrix = function () {tMatrix.SetIdentity();}
this.DeleteTmatrixHist = function () {tMatrixHistory=[];}
//---------
this.ApplyTo = function (point) {if (point instanceof TypeXYZw) {return tMatrix.MultiplyWith(point);} } //Apply the tMatrix to any point. (ignores local datum)
this.toString = function ()
{
var result = '[Object TypeKinematics]';
return result;
}
}
//---------------------------------------------------------------------------------------------------------------------------------------------------
function TypeXYZw (X,Y,Z,W)
{
//Note: This is a 3D vector with w serving as a storage and does not contaminate the vector algebra calculations
//Note: In some applications w serves as a scalar (the projection matrix of a camera will affect the w value)
//Note: w defaults to 1.0 to fascilitate vectors serving as vertices sent for rendering (such as openGL)
//PRIVATE properties
var epsilon = 0.0001; //tolerance for coplanar/colinear tests
//PUBLIC properties
//Note: These properties were left public for the benefit of uncomplicated access
//Note: On the downside, client functions could assign all kinds of garbage here. Normally these would be strongly typed (like in C++)
//Note: These properties are not really empty. They are initialized to X,Y,Z,W at the bottom of this class with the SetEqualTo function
this.x;
this.y;
this.z;
this.w; //The w component is NOT included in any of the calculations
//PUBLIC methods -- the following methods are non destructive (return a new vector or point)
//Note: dotProduct definition (A*B) -> LenA*LenB*cos(theta)
this.DotProduct = function (v) {return (v instanceof TypeXYZw)?(v.x*this.x + v.y*this.y + v.z*this.z):NaN;} //Note: The Tmatrix object has it's own internal dot product that includes the w
this.CrossProduct = function (v) {return (v instanceof TypeXYZw)? new TypeXYZw(this.y*v.z - this.z*v.y, this.z*v.x - this.x*v.z, this.x*v.y - this.y*v.x):void(0);}
this.MutualOrtho = function (v) {return this.CrossProduct(v);} //Synonym for cross product. Returns a vector mutualy orthogonal to 'this' and 'v'
this.Minus = function (v) {return (v instanceof TypeXYZw)? new TypeXYZw(this.x-v.x,this.y-v.y,this.z-v.z,1):void(0);} //a - b is a vector from b->a (ba),
this.Plus = function (v) {return (v instanceof TypeXYZw)? new TypeXYZw(this.x+v.x,this.y+v.y,this.z+v.z,1):void(0);}
this.Length = function () {return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z);}
this.ScaleBy = function (scalar) {return new TypeXYZw (this.x*scalar,this.y*scalar,this.z*scalar);}
this.ResizeTo = function (newLength) {var currLen = this.Length(); return (currLen>0)? this.ScaleBy(newLength/currLen) : this;}
this.AngleXY = function () {return Math.atan2(this.y,this.x);} //angle in radians (atan2 handles correct quadrants)}
this.AngleYZ = function () {return Math.atan2(this.z,this.y);}
this.AngleXZ = function () {return Math.atan2(this.z,this.x);}
this.AngleTO = function (v) {return (v instanceof TypeXYZw)? Math.acos(this.DotProduct(v)/(this.Length()*v.Length())):NaN;}
this.ProjectONTOvec = function (v) {return (v instanceof TypeXYZw)? v.ScaleBy(v.DotProduct(this)/v.DotProduct(v)):void(0);} //V * (LenThis*cos(theta) / LenV)
this.ProjectONTOpln = function (a, b, c) {if (!(a instanceof TypeXYZw && b instanceof TypeXYZw && c instanceof TypeXYZw)) {return;}
var p0 = this.Minus(a); //source point relative to 'a'
var normal = b.Minus(a).CrossProduct(c.Minus(a)); //a vector perpendicular to ab and ac
var shadow = p0.ProjectONTOvec(normal); //the shadow of p0 onto the normal vector
return p0.Minus(shadow).Plus(a);} //the other shadow of p0 to the plane shifted by 'a' is the result
this.ExtendRayToPln = function (r,a,nrm,cl){if (!(r instanceof TypeXYZw && a instanceof TypeXYZw && nrm instanceof TypeXYZw)) {return;} //'cl' is a boolean for culling
var rayVec = r.Minus(this); //assume 'this' is the ray origin which is to be extended along r
var numer = nrm.DotProduct(a.Minus(this)); //assume 'a' is the origin of the plane. Norm can be un-normalized (it's scale factor cancels out)
var denum = nrm.DotProduct(rayVec); if (denum==0 || cl==true && denum>0 && numer>0) {return;} //assume 'cl' is for culling.
var coef = numer/denum; if(coef<0) {return;} //Negative coef means plane is behind ray.
return this.Plus(rayVec.ScaleBy(coef));} //if a hit, returns the hit point
this.TestRayToRect = function (r,a,b,c,cl){if (!(a instanceof TypeXYZw && b instanceof TypeXYZw && c instanceof TypeXYZw)) {return;}
var ab = b.Minus(a), ac = c.Minus(a).AsOrthoTo(ab), norm = ab.CrossProduct(ac); //assume 'c' is any point on the rectangle's top side
var pln = this.ExtendRayToPln(r,a,norm,cl); if (!pln) {return;} pln = pln.Minus(a); //make pln relative to 'a'
var abU = ab.DotProduct(pln) / ab.DotProduct(ab); //LenA*LenB*cos(theta)/LenA^2 = LenB*cos(theta)/LenA
var acV = ac.DotProduct(pln) / ac.DotProduct(ac);
return (abU>=0 && acV>=0 && abU<=1 && acV<=1)? new TypeXYZw(abU,acV,0) : void(0);} //returns rectangle coordinates of where the ray hit
this.ExtendRayToLne = function (r,a,b,st) {var d1 = r.Minus(this); //Direction vec of line 1 (ray). Skew lines: https://en.wikipedia.org/wiki/Skew_lines
var d2 = b.Minus(a); //Direction vec of line 2 (segment ab)
var norm = d1.CrossProduct(d2), n1 = d1.CrossProduct(norm);
var t2 = this.Minus(a).DotProduct(n1) / d2.DotProduct(n1); if (st && (t2<0 || t2>1)) {return;} // st is boolean for 'strict' (the closest pt must be strictly in segment ab)
return a.Plus(d2.ScaleBy(t2));} //returns a point along ab that is closest to the ray.
this.CircumCenter = function (a,b) {var v1 = b.Minus(a);
var v2 = this.Minus(a);
var norm = v1.CrossProduct(v2);
var numer = v2.ScaleBy(v1.DotProduct(v1)).Minus(v1.ScaleBy(v2.DotProduct(v2))).CrossProduct(norm);
var denum = 2*norm.DotProduct(norm);
return (Math.abs(denum)>epsilon)? a.Plus(numer.ScaleBy(1/denum)):void(0);} //returns the center of a circle containing all three points
this.AsOrthoTo = function (v) {return (v instanceof TypeXYZw)? this.Minus(this.ProjectONTOvec(v)):void(0);}
this.RotAboutX = function (angle) {return new TypeXYZw (this.x, Math.cos(angle)*this.y-Math.sin(angle)*this.z, Math.sin(angle)*this.y+Math.cos(angle)*this.z);}
this.RotAboutY = function (angle) {return new TypeXYZw (Math.cos(angle)*this.z-Math.sin(angle)*this.x, this.y, Math.sin(angle)*this.z+Math.cos(angle)*this.x);}
this.RotAboutZ = function (angle) {return new TypeXYZw (Math.cos(angle)*this.x-Math.sin(angle)*this.y, Math.sin(angle)*this.x+Math.cos(angle)*this.y, this.z);}
this.RotThruPoint = function (pt,angle) {return (pt instanceof TypeXYZw)? this.ScaleBy(Math.cos(angle)).Plus(pt.ScaleBy(Math.sin(angle))):void(0);} //Assume 'this' as U axis and 'pt' as V axis (even if not ortho to U) of an ellipse
this.RotAboutAxis = function (axis,angle){if (!(axis instanceof TypeXYZw)) {return;}
var relOrigin = this.ProjectONTOvec(axis);
var relX = this.Minus(relOrigin);
var relY = axis.CrossProduct(this).ResizeTo(relX.Length());
relX = relX.ScaleBy( Math.cos(angle));
relY = relY.ScaleBy( Math.sin(angle));
return relX.Plus(relY).Plus(relOrigin);}
this.IsCoplanar = function (a, b, c) {var normal = b.Minus(a).CrossProduct(c.Minus(a)).ResizeTo(1); //Resizing to 1 is slower, but produces more robust results
var orthoTest = this.Minus(a).ResizeTo(1).DotProduct(normal); //Resizing this.Minus(a) to 1, in case it is far away, for reliable results
return Math.abs(orthoTest)<epsilon;} //Any ortho to the norm is coplanar. Dot product of orthogonal vectors is zero
this.IsCollinear = function (a, b) {return b.Minus(a).IsScalarOf(this.Minus(a));} //a and b are points in space defining a line. Check if 'this' point is on that line
this.IsScalarOf = function (v) {return (Math.abs(this.x*v.y-this.y*v.x)<epsilon && Math.abs(this.x*v.z-this.z*v.x)<epsilon && Math.abs(this.y*v.z-this.z*v.y)<epsilon)? true : false;} //vectors are scalars of each other
this.IsRightOf = function (a, b, n) {var ab = b.Minus(a); var ac = this.Minus(a); if (ab.IsScalarOf(ac)) {return void(0);} //assume n is the plane normal
var crossP = ab.CrossProduct(ac); return (crossP.DotProduct(n) > epsilon)? true : false;}
this.IsOrtho = function (v) {return this.DotProduct(v) < epsilon ? true : false;}
this.IsZero = function () {return (Math.abs(this.x)<epsilon && Math.abs(this.y)<epsilon && Math.abs(this.z)<epsilon)? true : false;} //Does not account for 'w'
this.IsEqual = function (v) {return (v instanceof TypeXYZw)? (Math.abs(this.x-v.x)<epsilon && Math.abs(this.y-v.y)<epsilon && Math.abs(this.z-v.z)<epsilon) : false;}
this.IsNaN = function () {return isNaN(this.x) || isNaN(this.y) || isNaN(this.z) || isNaN(this.w);}
this.ReflectAbout = function (v) {return this.ProjectONTOvec(v).Plus(this.AsOrthoTo(v).ScaleBy(-1));}
this.Homogeneous = function () {return this.ScaleBy(1/this.w);}
this.GetMax = function () {return Math.max(this.x,this.y,this.z);}
this.GetMin = function () {return Math.min(this.x,this.y,this.z);}
this.Get = function (idx) {return (idx==0)? this.x : (idx==1)? this.y : (idx==2)? this.z : (idx==3)? this.w : void(0);}
this.GetCopy = function (dim) {return new TypeXYZw(this.x,((dim===void(0) || dim>1)? this.y : 0),((dim===void(0) || dim>2)? this.z : 0),((dim===void(0) || dim>3)? this.w : 1));}
this.GetAsArray = function (dim) {return (dim==2)? [this.x,this.y] : (dim==3)? [this.x,this.y,this.z] : [this.x,this.y,this.z,this.w];}
this.GetTolerance = function () {return epsilon;}
this.toString = function () {return '[Object TypeXYZw]->('+this.x+','+this.y+','+this.z+','+this.w+')';}
//This methods are destructive
this.SetTolerance = function (newE) {epsilon = (isNaN(newE))? epsilon : Number(newE); return this;}
this.SetInt = function (dim) {if (dim===void(0)){dim=4;} if (dim>0) {this.x = Math.floor(this.x);} if (dim>1) {this.y = Math.floor(this.y);} if (dim>2) {this.z = Math.floor(this.z);} if (dim>3) {this.w = Math.floor(this.w);}}
this.SetMax = function (v) {if (!(v instanceof TypeXYZw)) {return this;} if (v.x>this.x) {this.x = v.x;} if (v.y>this.y) {this.y = v.y;} if (v.z>this.z) {this.z = v.z;} return this;}
this.SetMin = function (v) {if (!(v instanceof TypeXYZw)) {return this;} if (v.x<this.x) {this.x = v.x;} if (v.y<this.y) {this.y = v.y;} if (v.z<this.z) {this.z = v.z;} return this;}
this.SetX = function (newX) {this.x = Number(newX); return this;}
this.SetY = function (newY) {this.y = Number(newY); return this;}
this.SetZ = function (newZ) {this.z = Number(newZ); return this;}
this.SetW = function (newW) {this.w = newW; return this;} //w is not as strict since it doesn't participate in vector algebra (other than Homogeneous() )
this.Set = function (v,dim){if (dim===void(0)){dim=4;} if (dim>0) {this.x=v.x;} if (dim>1) {this.y=v.y;} if (dim>2) {this.z=v.z;} if (dim>3) {this.w=v.w;}}
this.SetEqualTo = function (any,y,z,w)
{
if (any instanceof TypeXYZw) {this.x=any.x; this.y=any.y; this.z=any.z; this.w=any.w; return;}
if (IsArray(any)) { w = any[3]; z = any[2]; y = any[1]; any = any[0]; } //If any of the array indexes are out of range the assignment is void(0)
//Note: NaN is allowed as a value
this.SetX( (any===void(0))? 0 : any );
this.SetY( ( y===void(0))? 0 : y );
this.SetZ( ( z===void(0))? 0 : z );
this.SetW( ( w===void(0))? 1 : w );
}
//Initialization
this.SetEqualTo (X,Y,Z,W);
}
//---------------------------------------------------------------------------------------------------------------------------------------------------
function TypeBoundingBox ()
{ //A world aligned bounding box
//Privte properties
var min; //A TypeXYZw point
var max; //A TypeXYZw point
//Public methods
this.GetMin = function () {return (min)? min.GetCopy() : void(0);}
this.GetMax = function () {return (max)? max.GetCopy() : void(0);}
this.GetDim = function () {return (min && max)? max.Minus(min) : void(0);}
this.Reset = function () {min = max = void(0);}
this.Update = function (newPoint)
{
//Note: Can receive another boundingBox object
let auxPoint;
if ( newPoint instanceof TypeBoundingBox) {auxPoint = newPoint.GetMax(); newPoint = newPoint.GetMin();}
if (!(newPoint instanceof TypeXYZw)) {return;}
if (!min || !max) {min = newPoint.GetCopy(); max = (auxPoint)? auxPoint.GetCopy() : newPoint.GetCopy(); return this;} //Trivial case
min.SetMin(newPoint); if (auxPoint) {min.SetMin(auxPoint);}
max.SetMax(newPoint); if (auxPoint) {max.SetMax(auxPoint);}
return this;
}
this.toString = function ()
{
var result = '[Object TypeBoundingBox]';
result += 'Min point: '+min+'\n';
result += 'Max point: '+max+'\n';
return result;
}
}
//---------------------------------------------------------------------------------------------------------------------------------------------------
function TypeCentroid ()
{
//Privte properties
var position; //A TypeXYZw point
var weight; //The number of points that contributed to the position so far
//Public methods
this.GetPosition = function () {return position;}
this.GetWeight = function () {return weight;}
this.Reset = function () {position = weight = void(0);}
this.Update = function (newPoint)
{
//Note: Can receive another centroid object
let otherWeight = 1;
if ( newPoint instanceof TypeCentroid) {otherWeight = newPoint.GetWeight(); newPoint = newPoint.GetPosition();}
if (!(newPoint instanceof TypeXYZw)) {return;}
if (!position) {position = newPoint.GetCopy(); weight = otherWeight; return this;} //Trivial case
//Note: The idea is that if each vertex represents a unit weight then
// --> we balance the moment of all previous weights against a single one on a beam
// --> So that if x+y = beamLength, x*cummWeight = y * weight --> delta = weight / (cumWeight+weight)
let delta = newPoint.Minus(position).ScaleBy(otherWeight/(weight+otherWeight));
position = position.Plus (delta);
weight += otherWeight;
return this;
}
this.toString = function ()
{
var result = '[Object TypeCentroid]\n';
result += 'Position: '+position+'\n';
result += 'Weight : '+Weight;
return result;
}
}
//---------------------------------------------------------------------------------------------------------------------------------------------------
function TypePlane (p1,p2,p3)
{ //An object that represents a plane and can perform planarity tests
//A planarity check would either return true, or cause the object to 'burst' by turning it's values to NaN (if such a command is sent)
//Every planarity check updates a bounding rectangle (the minimum rectangle in UV coordinates that can envelop all the hits thus far)
//The origin of the bounding rectangle is point 'a' (while points 'b' and 'c' are used to form the UV coordinate system)
//Private properties
var a,b,c; //Three TypeXYZw points to define a plane
var vecU,vecV; //Vectors defining a UV coordinate system
var normal; //The plane normal vector
var boundingUV; //The bounding rectangle of all tested points in UV coordinates
//Private methods
var Initialize = function (p1,p2,p3)
{
if (!isNaN(p1)) { a = new TypeXYZw(0,0,p1); b = new TypeXYZw(1,0,p1); c = new TypeXYZw(0,1,p1);} //when p1 is a numeric value interpret it as zDepth
else if (p1 instanceof TypePlane) { a = p1.GetA(); b = p1.GetB(); c = p1.GetC(); } //when p1 is another plane
else
{
a = (IsArray(p1))? new TypeXYZw(p1) : (p1 instanceof TypeXYZw)? p1 : void(0);
b = (IsArray(p2))? new TypeXYZw(p2) : (p2 instanceof TypeXYZw)? p2 : void(0);
c = (IsArray(p3))? new TypeXYZw(p3) : (p3 instanceof TypeXYZw)? p3 : void(0);
if (b && b.IsEqual(a)) {b = void(0);}
if (c && b && a && c.IsCollinear(a,b)) {c = void(0);}
}
vecU = (a && b)? b.Minus(a).ResizeTo(1) : void(0);
vecV = (vecU && c)? c.Minus(a).AsOrthoTo(vecU).ResizeTo(1) : void(0);
normal = (vecU && vecV)? vecU.CrossProduct(vecV) : void(0);
boundingUV = new TypeBoundingBox();
boundingUV.Update(ComputeUVcoordinates(a));
boundingUV.Update(ComputeUVcoordinates(b));
boundingUV.Update(ComputeUVcoordinates(c));
}
var ComputeUVcoordinates = function (point)
{ //Receives a previously checked coplanar 'point'
//Returns a TypeXYZw containing the UV coordinates of the 'point' (the 'z' dimention will always be 0)
//Note: Assume vecU and vecV have been made orthogonal to each other during their initialization
//Note: Assume vecU and vecV have been checked to be non-zero (a, or b, or c were checked to be non-stacked)
if (!vecU) {return;} //A single vecU is essentially a 1D scenario
//Note: coordU and coordV are scalars and vecU,vecV are unit vectors
//Note: DotProduct definition: LenA*LenB*cos(theta).
//Note: The formula vecU.DotProduct(vecAP)/vecU.DotProduct(vecU) is equivalent to LenA*LenB*cos(theta) / LenA^2 = LenB*cos(theta) / LenA --> gives the shadow of B relative to the length of A
//Note: Therefore the length of the shadow of 'vecAP' relative to vecU would be --> vecU.DotProduct(vecAP)/vecU.DotProduct(vecU), but since vecU is a unit vector (length 1) the denominator is unnecessary
var vecAP = point.Minus(a); //Vector from origin 'a' to 'point'
var coordU = vecU.DotProduct(vecAP);
var coordV = (vecV)? vecV.DotProduct(vecAP) : 0;
return new TypeXYZw(coordU,coordV);
}
var SetFailed = function () {a = b = c = NaN; vecU = vecV = normal = void(0); boundingUV.Reset();} //This is the 'burst' command
//Public methods
this.IsProper = function () {return (a && b && c)? true:false;} //A 'proper' plane has all three points defined
this.IsStarted = function () {return (a || b || c)? true:false;} //If there is at least on point the plane is considered 'started'
this.IsEmpty = function () {return (a===void(0) && b===void(0) && c===void(0))? true:false;}
this.IsNaN = function () {return (Number.isNaN(a) || Number.isNaN(b) || Number.isNaN(c))? true:false;}
this.IsFailed = function () {return this.IsNaN();}
this.GetA = function () {return a;}
this.GetB = function () {return b;}
this.GetC = function () {return c;}
this.GetUnitU = function () {return (vecU)? vecU.GetCopy() : void(0);}
this.GetUnitV = function () {return (vecV)? vecV.GetCopy() : void(0);}
this.GetNormal = function () {return normal;}
this.GetBoundUVrec = function () {return boundingUV;} //This is a TypeBoundingBox containing UV min and max points (in UV coordinates)
this.GetBoundUVdim = function () {return boundingUV.GetDim();} //This is a TypeXYZw representing the widht and height of the bounding rectangle (in UV coordinates)
this.GetUVcoord = function (point)
{ //Returns a point in plane UV coordinates
//Note: This is not considerred an official check and it has no effect on the bounding box
//Argument gate
if (point===void(0)) {return;}
if (!(point instanceof TypeXYZw)) {point = new TypeXYZw(point);}
if (!point.IsCoplanar(a,b,c)) {return;}
return ComputeUVcoordinates(point);
}
this.GetBoundMin = function ()
{ //Return a point in world coordinates representing the minimum edge of the bounding rectangle
//A bounding rectangle represents the area within which all the hits (Has() checks) have occured thus far
if (!vecU) {return;}
var minUV = boundingUV.GetMin(); //UV coordinates of the min point
var deltaU = vecU.ScaleBy(minUV.x); //minUV.x represents the U coordinate (as if it was minUV.U)
var deltaV = (vecV)? vecV.ScaleBy(minUV.y) : 0;
return a.Plus(deltaU).Plus(deltaV); //'a' is considered the origin of the UV coordinates on this plane
}
this.GetBoundMax = function ()
{ //Return a point in world coordinates representing the minimum edge of the bounding rectangle
//A bounding rectangle represents the area within which all the hits (Has() checks) have occured thus far
if (!vecU) {return;}
var maxUV = boundingUV.GetMax(); //UV coordinates of the max point
var deltaU = vecU.ScaleBy(maxUV.x); //maxUV.x represents the U coordinate (as if it was maxUV.U)
var deltaV = (vecV)? vecV.ScaleBy(maxUV.y) : 0;
return a.Plus(deltaU).Plus(deltaV); //'a' is considered the origin of the UV coordinates on this plane
}
this.GetZdepth = function ()
{ //The Z value of the points in the plane in the special case where the plane is parallel to XY (including XY itself)
//Return void(0) the plane itself is undefined, NaN if not XY parallel, a zDepth if XY parallel
//Note: Theoretically there could also be a GetYdepth(), or GetXdepth() methods
if (!a && !b && !c) {return void(0);}
//Handle an incomplete plane (a single line, or a single point)
var pointA = (a)? a : (b) ? b : c;
var pointB = (b)? b : (c) ? c : a;
var pointC = (c)? c : (a) ? a : b;
var tolerance = pointA.GetTolerance();
if (Math.abs(pointA.z-pointB.z)<tolerance && Math.abs(pointA.z-pointC.z)<tolerance) {return pointA.z;} else {return NaN;}
}
this.Clear = function () {a = b = c = vecU = vecV = normal = void(0); boundingUV.Reset();}
this.Set = function (p1,p2,p3) {Initialize(p1,p2,p3);}
this.Has = function (query, isDurable, endCount)
{ //Check coplanarity with query. 'Has' is interpreted not in an object sense but in a mathematical sense (a plane has an infinite number of points)
//Note: Each check expands the plane's bounding box horizon
//Note: A single point would be coplanar to any other point. A single line (two points) would be coplanar to any other point
//Note: If the plane is undefined (non of its points are set) then the first three comparisons will pass and those first three points will become the plane
//Note: 'query' could be a point, a plane, or an array of points
//Note: 'isDurable' is an optional boolean. If explicitly false, any coplanarity fail will burst the plane to NaN.
//Note: 'endCount' is an optional value used for checking only a specified number of elements from the end the query array. (Defaults to ALL elements)
//Note: The reason there is an 'endCount' instead of a startCount, is that elements are often added (pushed) at the end of arrays and those last elements need to be checked
if (Number.isNaN(a) || Number.isNaN(b) || Number.isNaN(c)) {return;} //coplanarity check has failed permanently on this plane
//Argument gate. Convert 'query' into an array of points.
var sourceArr = [];
if (query instanceof TypePlane)
{
if (query.IsFailed()) { if (isDurable==false) {SetFailed();} return;} //Comparison with a failed plane inherits the fail. SetFailed() is the burst command
if (query.IsEmpty()) {return true;} //Assume an empty plane represents infinite ambiguity and is compatible with all planes
let otherA = query.GetA(); if(otherA) {sourceArr.push(otherA);}
let otherB = query.GetB(); if(otherB) {sourceArr.push(otherB);}
let otherC = query.GetC(); if(otherC) {sourceArr.push(otherC);}
}
else if (IsArray(query)) {sourceArr = query;}
else if (query instanceof TypeXYZw) {sourceArr.push(query);}
else {return;}
//Do the comparisons
//Note: At this point the 'query' has been converted to an array of TypeXYZw points
var vertCount = sourceArr.length;
var startIdx = (!endCount || vertCount-endCount<=0)? 0:vertCount-endCount;
for (let i=startIdx; i<vertCount; i++)
{ //Walk through each point in the the sourceArr and check for coplanarity
let sourcePoint = sourceArr[i]; if (!(sourcePoint instanceof TypeXYZw)) {return;} //The array is not homogeneous
//Start forming the comparison plane if not already present (must be a valid plane)
if (!a) {a = sourcePoint;}
else if (!b) {b = (a.IsEqual(sourcePoint))? void(0) : sourcePoint;}
else if (!c) {c = (sourcePoint.IsCollinear(a,b))? void(0) : sourcePoint;}
//Set the UV vectors if needed
if (!vecU && a && b) {vecU = b.Minus(a).ResizeTo(1);}
if (!vecV && vecU && c) {vecV = c.Minus(a).AsOrthoTo(vecU).ResizeTo(1);}
if (!normal && vecU && vecV) {normal = vecU.CrossProduct(vecV);}
//Coplanarity check
if(c && !sourcePoint.IsCoplanar(a,b,c)) {if(isDurable==false) {SetFailed();} return;}
boundingUV.Update(ComputeUVcoordinates(sourcePoint)); //Update the UV bounds
}
return true;
}
this.toString = function ()
{
var result = '[Object TypePlane]\n';
result += ' Point a:'+a+'\n';
result += ' Point b:'+b+'\n';
result += ' Point c:'+c;
return result;
}
//Initialization
Initialize(p1,p2,p3);
}
//---------------------------------------------------------------------------------------------------------------------------------------------------
function TypeTmatrix (incomingData)
{
//Properties
this.data = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]; //Follow math convention of [row][column]
//PRIVATE methods
var IsProperMatrixArray = function (dataArr)
{ //Check if it is a 4x4 array
if (!IsArray(dataArr) || dataArr.length!=4) {return false;}
for (let i=0;i<4;i++) {if (!IsArray(dataArr[i]) || dataArr[i].length!=4) {return false;} }
//Checks passed
return true;
}
//PUBLIC Methods
//The following methods are not destructive (they return a new object)
this.MultiplyWith = function (B)
{ //Non destructive multiplication
if (B == void(0)) {return;}
if (B instanceof TypeTmatrix)
{ //Matrix multiplication according to the 'Computer Systems book', probably unnecessary for such a small matrix
var c = new TypeTmatrix(); c.SetZero();
for (let i=0;i<4;i++) for (let k=0;k<4;k++) {let r=this.data[i][k]; for (let j=0;j<4;j++) c.data[i][j] += r * B.data[k][j];}
return c;
}
if (B instanceof TypeXYZw) {B=B.GetAsArray();}
if (IsArray(B))
{ //Multiply with a vector
var temp=[0,0,0,0];
for (let i=0;i<4;i++) for (let j=0;j<4;j++) temp[i] += this.data[i][j] * B[j];
return new TypeXYZw(temp[0],temp[1],temp[2],temp[3]); //Note: if any component of B is NaN the entire result will be NaN
}
if (!isNaN(B))
{ //Multiply with a scalar
var c = new TypeTmatrix();
for (let i=0;i<16;i++) {let row=~~(i/4), col=i%4; c.data[row][col] = this.data[row][col] * B; }
return c;
}
Say('WARNING: (MultiplyWith) Did not receive a TypeTmatrix, or a TypeXYZw vector, or a scalar to multiply',-1);
return;
}
this.RotateAboutX = function (angle)
{ //Non destructive roation transformation
angle = isNaN(angle) ? 0 : Number(angle);
var rotationMatrix = new TypeTmatrix();
rotationMatrix.data[1][1]= Math.cos(angle);
rotationMatrix.data[1][2]=-Math.sin(angle);
rotationMatrix.data[2][1]= Math.sin(angle);
rotationMatrix.data[2][2]= Math.cos(angle);
return rotationMatrix.MultiplyWith(this);
}
this.RotateAboutY = function (angle)
{ //Non destructive roation transformation
//left handed coordinate system -- from +Y looking to the origin
angle = isNaN(angle) ? 0 : Number(angle);
var rotationMatrix = new TypeTmatrix();
rotationMatrix.data[0][0]= Math.cos(angle);
rotationMatrix.data[0][2]= Math.sin(angle);
rotationMatrix.data[2][0]=-Math.sin(angle);
rotationMatrix.data[2][2]= Math.cos(angle);
return rotationMatrix.MultiplyWith(this);
}
this.RotateAboutZ = function (angle)
{ //Non destructive roation transformation
angle = isNaN(angle) ? 0 : Number(angle);
var rotationMatrix = new TypeTmatrix();
rotationMatrix.data[0][0]= Math.cos(angle);
rotationMatrix.data[0][1]=-Math.sin(angle);
rotationMatrix.data[1][0]= Math.sin(angle);
rotationMatrix.data[1][1]= Math.cos(angle);
return rotationMatrix.MultiplyWith(this);
}
this.Rotate3D = function (u,angle)
{ //Non destructive roation transformation about an arbitrary u vector
if (!(u instanceof TypeXYZw)) {return rotationMatrix;}
u = u.ResizeTo(1);
angle = isNaN(angle) ? 0 : Number(angle);
var rotationMatrix = new TypeTmatrix();
var cosTheta = Math.cos(angle);
var sinTheta = Math.sin(angle);
var compCos = 1-cosTheta;
rotationMatrix.data[0]=[cosTheta+u.x*u.x*compCos, u.x*u.y*compCos-u.z*sinTheta, u.x*u.z*compCos+u.y*sinTheta];
rotationMatrix.data[1]=[u.y*u.x*compCos+u.z*sinTheta, cosTheta+u.y*u.y*compCos, u.y*u.z*compCos-u.x*sinTheta];
rotationMatrix.data[2]=[u.z*u.x*compCos-u.y*sinTheta, u.z*u.y*compCos+u.x*sinTheta, cosTheta+u.z*u.z*compCos];
return rotationMatrix.MultiplyWith(this);
}
this.Rotate2D = function (angle) {this.RotateAboutZ (angle);}
this.Translate = function (dX,dY,dZ)
{ //Non destructive translation transformation
dX = isNaN(dX) ? 0 : Number(dX);
dY = isNaN(dY) ? 0 : Number(dY);
dZ = isNaN(dZ) ? 0 : Number(dZ);
var TranslationMatrix = new TypeTmatrix(this);
TranslationMatrix.data[0][3]+=dX;
TranslationMatrix.data[1][3]+=dY;
TranslationMatrix.data[2][3]+=dZ;
return TranslationMatrix;
}
this.GetRow = function (rowIdx) {rowIdx = ClipValue(rowIdx,3); return new TypeXYZw(this.data[rowIdx][0],this.data[rowIdx][1],this.data[rowIdx][2],this.data[rowIdx][3]);}
this.GetColumn = function (colIdx) {colIdx = ClipValue(colIdx,3); return new TypeXYZw(this.data[0][colIdx],this.data[1][colIdx],this.data[2][colIdx],this.data[3][colIdx]);}
this.GetCopy = function () {return new TypeTmatrix(this);}
this.Inverse = function ()
{ //Non destructive
//Using the Laplace expansion theorem
//c and s are arrays that hold determinants of varius 2x2 submatrices of this.data
var a = this.data;
var c = [];
c[0] = a[2][0]*a[3][1] - a[2][1]*a[3][0];
c[1] = a[2][0]*a[3][2] - a[2][2]*a[3][0];
c[2] = a[2][0]*a[3][3] - a[2][3]*a[3][0];
c[3] = a[2][1]*a[3][2] - a[2][2]*a[3][1];
c[4] = a[2][1]*a[3][3] - a[2][3]*a[3][1];
c[5] = a[2][2]*a[3][3] - a[2][3]*a[3][2];
var s = [];