-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathgeneticGPU.js
2271 lines (1781 loc) · 75.6 KB
/
geneticGPU.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//divisors
var numRows = 71;
var gl;
//camera stuff
var zoomAmount = -2;
var scaleAmount = 0.04;
var ourScaleTween = null;
var scaleVariablesForTween = null;
var globalYrotate = 10;
var globalXrotate = -80;
var angleLimit = 90;
var rotateOn = false;
var rotVariablesForTween = {
'x': globalXrotate,
'y': globalYrotate
};
var ourTween = null;
var tweenTime = 1000;
var tweenEasing = TWEEN.Easing.Cubic.EaseInOut;
var ourTweenOn = false;
var timeoutMinutes = 10;
var timeOnLoad = new Date();
var startTime = timeOnLoad.getTime();
var blendShaderObj = null;
//hacked up javascript clone object method from stackoverflow. certainly a blemish on the face of JS
function clone(obj) {
//3 simple types and null / undefined
if (null == obj || "object" != typeof obj) return obj;
//date
if (obj instanceof Date) {
var copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
//array
if (obj instanceof Array) {
var copy = [];
for (var i = 0; i < obj.length; ++i) {
copy[i] = clone(obj[i]);
}
return copy;
}
//object
if (obj instanceof Object) {
var copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
}
return copy;
}
throw new Error("object type not supported yet!");
}
/*****************CLASSES*******************/
var SearchWindow = function (sampleVars, fixedVars) {
this.sampleVars = sampleVars;
if (!fixedVars) {
fixedVars = [];
}
this.fixedVars = fixedVars;
this.windowAttributes = {};
this.minmaxList = [];
this.fixedList = [];
this.reset();
};
SearchWindow.prototype.updateFromNdPos = function(ndMin) {
//loop through and set the ones that are in our fixed vals
for(varName in ndMin)
{
//dont do anything if this is a normal sample var
if(this.fixedVars.indexOf(varName) == -1)
{
continue;
}
//get the name
var varNameFixed = "fixed" + varName.toUpperCase() + "val";
//set the val
if(!this.windowAttributes[varNameFixed])
{
console.warn("something seriously wrong for ",varName, "and ",varNameFixed," on me",this);
continue;
}
this.windowAttributes[varNameFixed].val = ndMin[varName];
}
//should be done! buffering will happen outside this call
};
SearchWindow.prototype.updateBoundsOnZ = function(otherWindow) {
var keys = ['minZ','maxZ'];
for(var i = 0; i < keys.length; i++)
{
var key = keys[i];
var theirVal = otherWindow.windowAttributes[key].val;
this.windowAttributes[key].val = theirVal;
}
};
SearchWindow.prototype.reset = function () {
this.minmaxList = [];
this.fixedList = [];
//include z for window attributes and minmax, but it's not a "sample var"
var attributeVars = this.sampleVars.concat(['z']);
for (var i = 0; i < attributeVars.length; i++) {
var min = "min" + attributeVars[i].toUpperCase();
var max = "max" + attributeVars[i].toUpperCase();
this.windowAttributes[min] = {
type: 'f',
val: -3
};
this.windowAttributes[max] = {
type: 'f',
val: 3
};
$j('#' + min).html(String(-3));
$j('#' + max).html(String(3));
this.minmaxList.push(min);
this.minmaxList.push(max);
}
for (var j = 0; j < this.fixedVars.length; j++) {
var fixedVal = "fixed" + this.fixedVars[j].toUpperCase() + "val";
this.windowAttributes[fixedVal] = {
type: 'f',
val: 1
};
$j('#' + fixedVal).html(String(1));
this.fixedList.push(fixedVal);
}
this.windowAttributes['pMatrix'] = {
type: '4fm',
val: orthogProjMatrix
};
this.windowAttributes['mvMatrix'] = {
type: '4fm',
val: standardMoveMatrix
};
};
SearchWindow.prototype.divideUpSearchSpace = function (numInGroup, totalNumInGroup) {
//we will divide up the first sample variable based on the min/max bounds we have.
var varToDivide = this.sampleVars[0];
//here the default min/max is just -3 and 3
var minVal = -3;
var maxVal = 3;
var range = maxVal - minVal;
var slice = range / totalNumInGroup;
var myMinBound = slice * (numInGroup - 1) + minVal;
var myMaxBound = slice * (numInGroup) + minVal;
var minName = 'min' + varToDivide.toUpperCase();
var maxName = 'max' + varToDivide.toUpperCase();
this.windowAttributes['min' + varToDivide.toUpperCase()].val = myMinBound;
this.windowAttributes['max' + varToDivide.toUpperCase()].val = myMaxBound;
//i should use event emitters, but instead we will just update the dom directly
$j('#' + minName).html(String(myMinBound));
$j('#' + maxName).html(String(myMaxBound));
};
SearchWindow.prototype.getAllVariables = function () {
return this.fixedVars.concat(this.sampleVars);
};
SearchWindow.prototype.makeZoomWindow = function (centerPosition, percent) {
//we will essentially "breed out" the search window here
//first clone the search window we have right now
//this used to be a call to the clone method, but that did not preserve the float32array type
//of our perspective matrices, so we will do it manually here
var copy = {};
copy.windowAttributes = {};
for (key in this.windowAttributes) {
var type = this.windowAttributes[key].type;
if (type != '4fm') //don't copy the matrices
{
copy.windowAttributes[key] = {
'type': String(type),
'val': Number(this.windowAttributes[key].val)
};
}
}
//the centerposition must contain all the sample variables and the z
//attribute. it has direct access to the value, NOT the typical "type/val" object
for (key in centerPosition) {
if (key == 'z') {
continue;
}
if (key != 'z' && this.sampleVars.indexOf(key) == -1) {
continue;
}
var min = "min" + key.toUpperCase();
var max = "max" + key.toUpperCase();
var maxVal = this.windowAttributes[max].val;
var minVal = this.windowAttributes[min].val;
var centerVal = centerPosition[key];
var range = maxVal - minVal;
var deltaEachSide = range * percent * 0.5;
//we could go outside the bounds here by accident, so make sure to
//floor these
var newMaxVal = centerVal + deltaEachSide;
newMaxVal = Math.min(newMaxVal, maxVal);
var newMinVal = centerVal - deltaEachSide;
newMinVal = Math.max(newMinVal, minVal);
//set these new min / max's in the new window
copy.windowAttributes[max].val = newMaxVal;
copy.windowAttributes[min].val = newMinVal;
}
//should be done "zooming" on a point from a window
return copy;
};
var Problem = function (equationString, userSpecifiedFixedVariables, fixAllBut2) {
//here the equationString is the given equation we want to parse. the fixedVariables
//are the variables we want fixed, aka gravity or conductivity or something else similar
if (!userSpecifiedFixedVariables) {
userSpecifiedFixedVariables = [];
}
//check if its valid. validateequationstring will throw errors on bad strings,
//so these need to be caught by a try / catch block
equationString = this.validateEquationString(equationString);
//first add the colon if it's not there
if (!equationString.match(/;/)) {
equationString = equationString + ";";
}
//ok so we have a valid equation
//get all the variables besides z
this.equationString = equationString;
var es = equationString;
//first see if "time" is there, aka we want to use time
//to drive the simulation in some way (but its not a dimensional variable to solve for)
var timeIsThere = false;
if (es.match(/time/)) {
timeIsThere = true;
}
this.wantsTime = timeIsThere;
//first replace all the "pow" operations and such. this will also remove time because that's a
//multicharacter match
var es = equationString;
es = es.replace(/([a-zA-Z][a-zA-Z]+)/g, "");
//now extract out all single variables, except for z because that's the cost function. note the
//a-y in the regex for omitting z
var allVariables = es.match(/([a-yA-Y])/g);
//make variables unique! we will no longer abuse jquery here and abuse javascript objects
//abusing jquery didnt work because it would catch two instances of "x" for some reason,
//it was confused between the object x and the string containing "x" i guess
var varSet = {};
for (var i = 0; i < allVariables.length; i++) {
varSet[allVariables[i]] = true;
}
allVariables = [];
for (key in varSet) {
allVariables.push(key);
}
//sort so hopefully x and y are at the back
allVariables = allVariables.sort()
console.log("after sorting", allVariables);
if (allVariables.length < 2) {
throw new Error("Specify at least 2 variables!");
}
//we need to determine which are sample variables in the problem and which are
//fixed variables specified by the user.
var sampleVariables = [];
var fixedVariables = [];
//now we will loop through these variables, either adding them to sample variables or fixed variables
for (var i = 0; i < allVariables.length; i++) {
var thisVar = allVariables[i];
if (userSpecifiedFixedVariables.indexOf(thisVar) != -1) {
fixedVariables.push(thisVar);
} else {
sampleVariables.push(thisVar);
}
}
//also, there's an optional mode to fix all but 2 of the variables. so here...
if (fixAllBut2) {
console.log("fixing all but 2 as you specified");
var length = sampleVariables.length;
var sampleOnes = sampleVariables.slice(length - 2);
var fixedOnes = sampleVariables.slice(0, length - 2);
sampleVariables = sampleOnes;
fixedVariables = fixedVariables.concat(fixedOnes);
}
console.log("all variables", allVariables);
console.log("results: fixed", fixedVariables, " sample", sampleVariables);
if(this.wantsTime && sampleVariables.length > 2)
{
throw new Error("Sorry! You can't do N-D search with time as a driving factor. Try the static examples");
}
//go build a window for these variables.
//z is included as a sample variable because it has bounds that need to be updated as the function scales
//the fixed variables will be given uniform attributes that can be easily modified
this.baseSearchWindow = new SearchWindow(sampleVariables, fixedVariables);
//ok so now we have our base search window. if our number of sample variables is just two,
//the 2d sampler base window is the same as the base search window. if not, we have to
//fix the sample variables one by one until we achieve a 2d sample space
var sampleVariablesFor2d = sampleVariables.slice(0);
var fixedVariablesFor2d = fixedVariables.slice(0);
var variablesWeHadToFixFor2d = [];
while (sampleVariablesFor2d.length > 2) {
var thisVar = sampleVariablesFor2d.splice(0, 1)[0];
fixedVariablesFor2d.push(thisVar);
variablesWeHadToFixFor2d.push(thisVar);
}
//ok now we are guaranteed that we have a 2d search space for this window. go make a search window
this.searchWindow2d = new SearchWindow(sampleVariablesFor2d, fixedVariablesFor2d);
//very long variable name. but this is a very important list. we don't want to iterate through
//user-specified constants, but we want to iterate through the fixed variables we created to
//reduce the dimensionality down to 2
this.searchWindow2d.variablesWeHadToFixFor2d = variablesWeHadToFixFor2d;
//also do control HTML
this.renderControlHTML();
};
Problem.prototype.validateEquationString = function (equationString) {
//first remove all the valid digits
var es = equationString;
var toReturn = equationString;
//first check that it begins with "z = " something
if (!es.match(/^[ ]*z[ ]*=/g)) {
throw new Error("the equation must start with z = something. Z is your cost function that you are trying to minimize with non-convex optimization");
}
//see if there are any digits with no period before and after
if (es.match(/([^.0-9]\d+[^.0-9])|([^.0-9]\d+$)|(^\d+[^.0-9])/g)) {
//this is a giant pain but we have to replace them specifically by index
var shouldContinue = true;
var regex = /([^.0-9]\d+[^.0-9])|([^.0-9]\d+$)|(^\d+[^.0-9])/;
var num = 0;
while (true) {
num++;
if (num > 10) {
break;
}
var indexFirst = es.search(regex);
if (indexFirst == -1) {
break;
}
var matchString = es.match(regex)[0];
//extract just the number and get the rest
//GOD this is a pain
var numWithin = matchString.match(/(\d+)/)[0];
var numWithinIndex = matchString.search(/(\d+)/);
var withinPart1 = matchString.substring(0, numWithinIndex);
var withinPart2 = matchString.substring(numWithinIndex + numWithin.length);
var matchString = es.match(regex)[0];
//extract just the number and get the rest
//GOD this is a pain
var numWithin = matchString.match(/(\d+)/)[0];
var numWithinIndex = matchString.search(/(\d+)/);
var withinPart1 = matchString.substring(0, numWithinIndex);
var withinPart2 = matchString.substring(numWithinIndex + numWithin.length);
var matchLength = matchString.length;
var firstPart = es.substring(0, indexFirst);
var secondPart = es.substring(indexFirst + matchLength);
es = firstPart + withinPart1 + numWithin + ".0" + withinPart2 + secondPart;
}
}
//probably valid, still need to compile it of course though but this catches the user mistakes
return es;
};
var getSource = function (obj) {
if (obj.match) {
//its a string, return it
return obj;
}
if (obj.length) {
//its a jquery array, get first element and get the text there
return obj[0].text;
}
//its an html element
return obj.text;
};
Problem.prototype.renderControlHTML = function () {
//this is a big pain
$j('#equationStringTextArea').text(this.equationString);
var sampleVarsToRender = this.baseSearchWindow.sampleVars.concat(['z']);
var sampleVariablesHTML = "";
for (var i = 0; i < sampleVarsToRender.length; i++) {
var varName = sampleVarsToRender[i];
var minKey = 'min' + varName.toUpperCase();
var maxKey = 'max' + varName.toUpperCase();
var minVal = this.baseSearchWindow.windowAttributes[minKey].val;
var maxVal = this.baseSearchWindow.windowAttributes[maxKey].val;
var line = "<p>" + varName + ":";
line = line + " Minimum ";
line = line + '<span class="frobSpanner" id="' + minKey + '">' + String(minVal) + '</span>';
line = line + " Maximum ";
line = line + '<span class="frobSpanner" id="' + maxKey + '">' + String(maxVal) + '</span>';
line = line + "</p>";
sampleVariablesHTML = sampleVariablesHTML + line;
}
var fixedVariablesHTML = "";
for (var i = 0; i < this.baseSearchWindow.fixedVars.length; i++) {
var varName = this.baseSearchWindow.fixedVars[i];
//we need to construct the "key" here
var key = "fixed" + varName.toUpperCase() + "val";
var varValue = this.baseSearchWindow.windowAttributes[key].val;
var line = "<p>" + varName + ": Value of ";
line = line + '<span class="frobSpanner" id="' + key + '">' + String(varValue) + '</span>';
line = line + '<a class="uiButtonWhite unfixButton" style="display:inline-block;margin-left:10px;" id="';
line = line + varName + '">Unfix</a>';
line = line + "</p>";
fixedVariablesHTML += line;
}
$j('#fixedVariablesList').html(fixedVariablesHTML);
$j('#sampleVariablesList').html(sampleVariablesHTML);
};
var ShaderTemplateRenderer = function (problem, fixedVars, vertexShaderSrc, fragShaderSrc) {
if (!vertexShaderSrc) {
vertexShaderSrc = $j('#shader-box-vs');
}
if (!fragShaderSrc) {
fragShaderSrc = $j('#shader-box-fs');
}
if (!fixedVars) {
fixedVars = [];
}
if (!problem) {
throw new Error("Specify a problem!");
}
//getSource takes in a string, an HTML element, or a jquery query
this.vertexShaderTemplateUniform = getSource(vertexShaderSrc);
this.vertexShaderTemplateRandom = getSource(vertexShaderSrc);
this.fragShaderTemplate = getSource(fragShaderSrc);
this.problem = problem;
//first format the templates, aka add the minimum / max attributes to the vertex shader and eliminate the hue stuff
this.formatTemplates();
var solvingObjectsUniform = this.buildShaders(this.problem.searchWindow2d.sampleVars, 'uniform');
var solvingObjectsRandom = this.buildShaders(this.problem.baseSearchWindow.sampleVars, 'random');
//first make a shader that just draws the surface
//in order to get a shader like this, we will grab the source code from the first uniform shader for the
//vertices and then simply use our old frag shader src
var graphicalShader = new myShader(solvingObjectsUniform.shaders[0].vShaderSrc, fragShaderSrc, problem.searchWindow2d.windowAttributes, false);
//now we have all the necessary shaders and extractors for an equation and everything. let's go build a solver
//with all of this
var solver = new Solver(this.problem, solvingObjectsUniform, solvingObjectsRandom, graphicalShader);
this.solver = solver;
//usually the template is not kept in memory, the solver is what the person is interested in
}
ShaderTemplateRenderer.prototype.formatTemplates = function () {
//first remove the hue code, its not needed
this.fragShaderTemplate = this.fragShaderTemplate.replace(/\/\/hueStart[\s\S]*?\/\/hueEnd/g, "");
/*******
* The big operation here is to replace the uniform attribute declaration of each shader
* with the proper variable names. The tricky part is that these variable names are different
* depending on the search window, so we basically have to do this twice with the uniform and
* base search windows
*********/
//next, add all the uniform variables for the two different windows we have
var minmaxListRandom = this.problem.baseSearchWindow.minmaxList;
var fixedListRandom = this.problem.baseSearchWindow.fixedList;
var minmaxListUniform = this.problem.searchWindow2d.minmaxList;
var fixedListUniform = this.problem.searchWindow2d.fixedList;
var allToAddRandom = minmaxListRandom.concat(fixedListRandom);
var allToAddUniform = minmaxListUniform.concat(fixedListUniform);
var uniformsToAddRandom = "";
var uniformsToAddUniform = "";
for (var i = 0; i < allToAddRandom.length; i++) {
var thisLine = "uniform float " + allToAddRandom[i] + ";\n";
uniformsToAddRandom = uniformsToAddRandom + thisLine;
}
for (var i = 0; i < allToAddUniform.length; i++) {
var thisLine = "uniform float " + allToAddUniform[i] + ";\n";
uniformsToAddUniform = uniformsToAddUniform + thisLine;
}
//replace the uniform section with this
this.vertexShaderTemplateUniform = this.vertexShaderTemplateUniform.replace(/\/\/uniformStart[\s\S]*?\/\/uniformEnd/, uniformsToAddUniform);
this.vertexShaderTemplateRandom = this.vertexShaderTemplateRandom.replace(/\/\/uniformStart[\s\S]*?\/\/uniformEnd/, uniformsToAddRandom);
//we should be done! Go do specific shader builds
}
ShaderTemplateRenderer.prototype.buildShaders = function (varsToSolve, type) {
//ok so essentially loop through in groups of 1-3 variables and compile the shader object to extract them
//copy this array.
var varsToSolve = varsToSolve.slice(0);
var myShaders = [];
var myExtractors = [];
var numPerShader = 3;
while (varsToSolve.length > 0) {
//for now we do one variable per shader
//OPTION for variables per shader
var varsToExtract = varsToSolve.splice(0, numPerShader);
console.log("building shader for these vars");
console.log(varsToExtract);
//SWITCH: random vs uniform shader
//the shader will render this surface with these variables as the rgb
var thisShader = null;
if (type == 'random') {
thisShader = this.buildRandomShaderForVariables(varsToExtract);
} else {
thisShader = this.buildUniformShaderForVariables(varsToExtract);
}
//the extractor will take in RGB / a window and return the estimated variable value. it uses closures
var thisExtractor = this.buildExtractorForVariables(varsToExtract);
//add this shader to our shaders
myShaders.push(thisShader);
myExtractors.push(thisExtractor);
}
return {
'shaders': myShaders,
'extractors': myExtractors
};
};
ShaderTemplateRenderer.prototype.buildExtractorForVariables = function (varsToExtract) {
//i know this code is a bit repetitive but I didn't want to further complicate it
var minR = "min" + varsToExtract[0].toUpperCase();
var maxR = "max" + varsToExtract[0].toUpperCase();
var minG = null;
var maxG = null;
if (varsToExtract.length > 1) {
minG = "min" + varsToExtract[1].toUpperCase();
maxG = "max" + varsToExtract[1].toUpperCase();
}
var minB = null;
var maxB = null;
if (varsToExtract.length > 2) {
minB = "min" + varsToExtract[2].toUpperCase();
maxB = "max" + varsToExtract[2].toUpperCase();
}
var extractor = function (colors, searchWindow) {
if(!searchWindow[maxR])
{
console.log("trying to get this r value", maxR,"from thsi window",searchWindow);
}
var rRange = searchWindow[maxR].val - searchWindow[minR].val;
var rPos = (colors.r / 255.0) * rRange + searchWindow[minR].val;
//we also need the original places in the grid in order to do graphical display of the minimum
var rPosOrig = (colors.r / 255.0) * 2 - 1;
var gPos = null;
var bPos = null;
var gPosOrig = null;
var bPosOrig = null;
if (minG) {
var gRange = searchWindow[maxG].val - searchWindow[minG].val;
gPos = (colors.g / 255.0) * gRange + searchWindow[minG].val;
gPosOrig = (colors.g / 255.0) * 2 - 1;
}
if (minB) {
var bRange = searchWindow[maxB].val - searchWindow[minB].val;
bPos = (colors.b / 255.0) * bRange + searchWindow[minB].val;
bPosOrig = (colors.b / 255.0) * 2 - 1;
}
var toReturn = {};
toReturn[varsToExtract[0]] = rPos;
toReturn[varsToExtract[0] + "Orig"] = rPosOrig;
if (gPos) {
toReturn[varsToExtract[1]] = gPos;
toReturn[varsToExtract[1] + "Orig"] = gPosOrig;
}
if (bPos) {
toReturn[varsToExtract[2]] = bPos;
toReturn[varsToExtract[2] + "Orig"] = bPosOrig;
}
return toReturn;
};
return extractor;
};
ShaderTemplateRenderer.prototype.doBaseShaderTemplateFormatting = function (varsToExtract, vShaderSrc) {
//first copy the variable array
varsToExtract = varsToExtract.slice(0);
//stick in zeros where there is no variable
if (varsToExtract.length == 1) {
varsToExtract = varsToExtract.concat(["0.0", "0.0"]);
}
if (varsToExtract.length == 2) {
varsToExtract.push("0.0");
}
if (varsToExtract.length != 3) {
console.log(varsToExtract);
throw new Error("what! something is wrong with variable length and array pushing");
}
//building and compiling a shader requires a few things. first, we must replace the equation line with the given equationString. then, we must replace
//the varying vec3 varData with our given variables in the correctly scaled manner. We have to declare all the variables the user wants as floats
//And finally, we must assign the variables that we are sampling. For the two 'sample directions', these will be derived from their grid positions,
//but for the fixed variables, it will be a fixed amount.
var fShaderSrc = this.fragShaderTemplate;
//here we need all the variables in the problem...
var allVariables = this.problem.baseSearchWindow.getAllVariables();
//the declaration as floats
var varDeclarationString = "float " + allVariables.join(',') + ';';
//replace it
vShaderSrc = vShaderSrc.replace(/\/\/varDeclaration[\s\S]*?\/\/varDeclarationEnd/, varDeclarationString);
//the template for the varData assignment
var varDataString = "varData = vec3(%var0,%var1,%var2);\n";
//insert variable strings into the vardata assignment or 0.0 if there's no variable there
for (var i = 0; i < 3; i++) {
if (varsToExtract[i] == "0.0") {
varDataString = varDataString.replace("%var" + String(i), varsToExtract[i]);
continue;
}
//we need to scale these variables to a 0->1 range
//as well for the extractors to work property
var min = "min" + varsToExtract[i].toUpperCase();
var max = "max" + varsToExtract[i].toUpperCase();
var scaled = "(" + varsToExtract[i] + " - " + min + ")/(" + max + " - " + min + ")";
varDataString = varDataString.replace("%var" + String(i), scaled);
}
//vardata assignment string
vShaderSrc = vShaderSrc.replace(/\/\/varDataAssignment[\s\S]*?\/\/varDataAssignmentEnd/, varDataString);
//equation string replace
vShaderSrc = vShaderSrc.replace(/\/\/equationString[\s\S]*?\/\/equationStringEnd/, this.problem.equationString);
return {
'vShaderSrc': vShaderSrc,
'fShaderSrc': fShaderSrc
};
};
ShaderTemplateRenderer.prototype.buildUniformShaderForVariables = function (varsToExtract) {
var baseSource = this.doBaseShaderTemplateFormatting(varsToExtract, this.vertexShaderTemplateUniform);
var vShaderSrc = baseSource.vShaderSrc;
var fShaderSrc = baseSource.fShaderSrc;
//here we must also change the variable assignments for the "sample directions."
//For all the sample variables, their value is based on the grid, but for the fixed variables,
//it's a buffered value on the GPU that we will just assign
var sampleVars = this.problem.searchWindow2d.sampleVars;
var fixedVars = this.problem.searchWindow2d.fixedVars;
var varAssignmentBlock = "";
if (sampleVars.length > 2) {
throw new Error("we cant sample more than 2 variables at once in 3d space!");
}
//for the sample variables it needs to be:
//x = ((aVertexPosition[variableIndex] + 1.0)/(2.0)) * (maxX - minX) + minX;
for (var i = 0; i < sampleVars.length; i++) {
var min = "min" + sampleVars[i].toUpperCase();
var max = "max" + sampleVars[i].toUpperCase();
var line = sampleVars[i] + " = ";
line = line + "((aVertexPosition[" + String(i) + "] + 1.0)/(2.0))";
line = line + " * (" + max + " - " + min + ") + " + min + ";\n";
varAssignmentBlock = varAssignmentBlock + line;
}
//for the fixed variables it needs to be:
//g = fixedGval;
for (var i = 0; i < fixedVars.length; i++) {
var fixed = "fixed" + fixedVars[i].toUpperCase() + "val";
var line = fixedVars[i] + " = " + fixed + ";\n";
varAssignmentBlock = varAssignmentBlock + line;
}
//replace entire assignment block
vShaderSrc = vShaderSrc.replace(/\/\/varAssignment[\s\S]*?\/\/varAssignmentEnd/, varAssignmentBlock);
/****Source code modification done!***/
//now that we have our sources, go compile our shader object with these sources
var shaderObj = new myShader(vShaderSrc, fShaderSrc, this.problem.searchWindow2d.windowAttributes, false);
console.log("Generated Shader uniform source for vertex!");
//console.log(vShaderSrc);
console.log({
'src': vShaderSrc
});
console.log("Generated shader uniform source for frag!");
//console.log(fShaderSrc);
console.log({
'src': fShaderSrc
});
return shaderObj;
};
ShaderTemplateRenderer.prototype.buildRandomShaderForVariables = function (varsToExtract) {
//grab the base source and format the easy stuff
var baseSource = this.doBaseShaderTemplateFormatting(varsToExtract, this.vertexShaderTemplateRandom);
var vShaderSrc = baseSource.vShaderSrc;
var fShaderSrc = baseSource.fShaderSrc;
//now we must do every single sample variable assignment with the myRand() function and indexes to spice up the randomness
//except fix the fixed variables
var sampleVars = this.problem.baseSearchWindow.sampleVars;
var fixedVars = this.problem.baseSearchWindow.fixedVars;
var varAssignmentBlock = "";
for (var i = 0; i < sampleVars.length; i++) {
var min = "min" + sampleVars[i].toUpperCase();
var max = "max" + sampleVars[i].toUpperCase();
var iFloat = String(i + 1) + ".0";
var line = sampleVars[i] + " = ";
//an example of the compiled line is:
//x = myRand(pow(i,3.0) + i * i * float(aVertexPosition[0]) * 17 + i * float(aVertexPosition[1]) * 100) * (maxX - minX) + minX;
//--or with time--
//x = myRand(pow(i + time,3.0) + i * i * time * float(aVertexPosition[0]) * 17 + i * pow(time,2.0) * float(aVertexPosition[1]) * 100) * (maxX - minX) + minX;
//without time
//line = line + "myRand(pow(" + iFloat + ",3.0) + " + iFloat + " * " + iFloat + " * " + "float(aVertexPosition[0]) * 17.0";
//line = line + " + " + iFloat + " * float(aVertexPosition[1]) * 100.0) * (" + max + " - " + min + ") + " + min + ";\n";
//with time
line = line + "myRand(pow(" + iFloat + " + time,3.0) + " + iFloat + " * " + iFloat + " * " + " time * float(aVertexPosition[0]) * 17.0";
line = line + " + " + iFloat + " * pow(time,2.0) * float(aVertexPosition[1]) * 100.0 + time) * (" + max + " - " + min + ") + " + min + ";\n";
varAssignmentBlock = varAssignmentBlock + line;
}
for (var i = 0; i < fixedVars.length; i++) {
var fixed = "fixed" + fixedVars[i].toUpperCase() + "val";
var line = fixedVars[i] + " = " + fixed + ";\n";
varAssignmentBlock = varAssignmentBlock + line;
}
//replace entire assignments block
vShaderSrc = vShaderSrc.replace(/\/\/varAssignment[\s\S]*?\/\/varAssignmentEnd/, varAssignmentBlock);
/***Source code modification done****/
var shaderObj = new myShader(vShaderSrc, fShaderSrc, this.problem.baseSearchWindow.windowAttributes, false);
console.log("Generated Shader random source for vertex!");
console.log({
'src': vShaderSrc
});
//console.log(vShaderSrc);
console.log("Generated shader random source for frag!");
//console.log(fShaderSrc);
console.log({
'src': fShaderSrc
});
return shaderObj;
};
//this class will take in minimums from both networking and the hosts and update the DOM when a new one is found.
var MinimumSaver = function (problem) {
this.minHostPos = null;
this.minNetworkPos = null;
this.problem = problem;
this.minHostElem = $j('#hostMinimum')[0];
this.minNetworkElem = $j('#networkMinimum')[0];
this.active = true;
var blankMin = "<p>Unknown</p>";
$j(this.minHostElem).html(blankMin);
$j(this.minNetworkElem).html(blankMin);
};
MinimumSaver.prototype.isBetter = function (minOne, minTwo) {
//if our existing one is not defined, then its certainly better
if (!minTwo) {
return true;
}
//similarly if we are replacing a valid with null, dont do that
if (!minOne) {
return false;
}
//else, if our z is low
return minOne.z <= minTwo.z;
};
MinimumSaver.prototype.isStrictlyBetter = function (minOne, minTwo) {
if (!minOne || !minTwo) {
return false;
}
return minOne.z < minTwo.z;
};
MinimumSaver.prototype.updateDom = function (elem, pos, time) {
//look through our sample variables and post which ones
var domHtml = "";
var sampleVars = this.problem.baseSearchWindow.sampleVars.concat(['z']);
for (var i = 0; i < sampleVars.length; i++) {
var name = sampleVars[i];
var value = pos[name];
domHtml = domHtml + "<p>" + name + ": " + String(value).substring(0, 5);
domHtml = domHtml + "</p>";
}
//also need a time
var now = new Date();
domHtml = domHtml + "At time " + String(now.getHours()) + ":" + String(now.getMinutes());
domHtml = domHtml + ":" + String(now.getSeconds()) + ":" + String(now.getMilliseconds());
$j(elem).html(domHtml);
};
MinimumSaver.prototype.validateNetworkMin = function(min) {
var sampleVars = this.problem.baseSearchWindow.sampleVars.concat(['z']);
//all of the sample vars for the current problem have to be here
for(var i = 0; i < sampleVars.length; i++)
{
var name = sampleVars[i];
if(min[name] === undefined)
{
return false;
}
}
return true;
};
MinimumSaver.prototype.postHostResults = function (newMinPos) {
if (!this.active) {
return;
}
if (!this.isBetter(newMinPos, this.minHostPos)) {
//bounce out, because its not better
return;
}
//we want to update the dom when we reach an equivalent min, but
//we only want to broadcast when its strictly better
var trulyBetter = this.isStrictlyBetter(newMinPos, this.minHostPos);
//we have a new minimum!
this.minHostPos = newMinPos;
//update the dom
this.updateDom(this.minHostElem, this.minHostPos);
//set a timer to tell the network
if ((trulyBetter || this.minNetworkPos == null) && !this.broadcastTimer) {
var _this = this;
this.broadcastTimer = setTimeout(function () {
_this.broadcastMin();
}, 1000);
}
};
MinimumSaver.prototype.broadcastMin = function () {
this.broadcastTimer = null;
if (window.now && window.now.distributeMinimum) {
now.distributeMinimum(this.minHostPos);
}
};
MinimumSaver.prototype.receiveNetworkMin = function (networkMin) {
if (!this.active) {
return;
}
//first check that its from the same problem...
if(!this.validateNetworkMin(networkMin))
{
return;
}
//obviously dont update if its worse than ours, the other guy
//might have a crappy search window
if (!this.isBetter(networkMin, this.minNetworkPos)) {