-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
1358 lines (1129 loc) · 48.7 KB
/
index.html
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
<html manifest="cache.manifest" ng-app="myApp" content="text/html;charset=UTF-8">
<head>
<title>Archery Scope Interpolation</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes">
<link href='kghostview.png' rel='apple-touch-icon' type='image/png'>
<script src="svg.min.js"> </script>
<script src="FileSaver.min.js"> </script>
<script src="angular.min.js"></script>
<script src="numeric-1.2.6.js"></script>
<style type="">
.tdslope { width:250px }
table { margin:auto; font-family:monospace; border-width:1px; border-collapse: collapse; border-style: solid; }
td, th { min-width:50px; border-width:1px; border-style: solid; text-align:center; }
.tdcontrols { height:36px }
.parallax { background-color: #CCC; }
.parallax-wrong { text-decoration: line-through; }
.tenmeters { background-color: #FCC; font-weight: bold }
.twometers { background-color: #FFC; }
.storage-warning { max-width:260px; font-family:Helvetica; font-size:0.7rem; }
.helptext-td { max-width:360px; font-family:Helvetica; font-size:0.7rem; text-align: left; }
.polyfit-color-high { background-color:#FF5E23 }
.polyfit-color-low { background-color:#237BFF }
.parcour-highlight-tr { background-color:#FFCC33 }
/* disrupts jEdit syntax coloring */
@media screen
{
.parcour-tr:nth-child(even) { background-color:#DDDDDD }
}
@media print
{
.parcour-tr:nth-child(even) { background-color:#DDDDDD }
table { page-break-after:always; }
tr { page-break-inside:avoid; page-break-after:auto }
input, button { border-width:0px; border:none; }
.do-not-print { display:none; }
}
</style>
<script>
var app = angular.module('myApp', []);
app.config(['$controllerProvider', function($controllerProvider) {
// this option might be handy for migrating old apps, but please don't use it in new ones!
$controllerProvider.allowGlobals();
}]);
function getParameterByName(name) { // GET parameter ?data=
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : results[1];
}
var isInWebAppiOS = (window.navigator.standalone == true);
var isInWebAppChrome = (window.matchMedia('(display-mode: standalone)').matches);
function getHashbangParameter(parameterName,defaultValue)
{
if(parameterName instanceof Array)
{
for(var i in parameterName)
{
var ret = this.getHashbangParameter(parameterName[i], null);
if(ret !== null)
return ret;
}
return defaultValue;
}
defaultValue = defaultValue || null;
if( !parameterName )
throw new Error("getHashbangParameter: 'parameterName' is missing!");
// parameter schema: "/paramName/:paramValue/"
var regex = new RegExp("/"+parameterName+"/([^/#&]+)"); // [A-Za-z0-9_%]
var match = window.location.href.match(regex);
return match ? match[1] : defaultValue;
};
function calculateIntegerHashFromString(s)
{
if(!s)
return 0;
return s.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0);
}
// http://blog.ivank.net/interpolation-with-cubic-splines.html
function CSPL()
{
this.xs = [];
this.ys = [];
this.ks = [];
}
CSPL._gaussJ = {};
CSPL._gaussJ.solve = function(A, x) // in Matrix, out solutions
{
var m = A.length;
for(var k=0; k<m; k++) // column
{
// pivot for column
var i_max = 0; var vali = Number.NEGATIVE_INFINITY;
for(var i=k; i<m; i++) if(A[i][k]>vali) { i_max = i; vali = A[i][k];}
CSPL._gaussJ.swapRows(A, k, i_max);
if(A[i_max][i] == 0) console.log("matrix is singular!");
// for all rows below pivot
for(var i=k+1; i<m; i++)
{
for(var j=k+1; j<m+1; j++)
A[i][j] = A[i][j] - A[k][j] * (A[i][k] / A[k][k]);
A[i][k] = 0;
}
}
for(var i=m-1; i>=0; i--) // rows = columns
{
var v = A[i][m] / A[i][i];
x[i] = v;
for(var j=i-1; j>=0; j--) // rows
{
A[j][m] -= A[j][i] * v;
A[j][i] = 0;
}
}
}
CSPL._gaussJ.zerosMat = function(r,c) {var A = []; for(var i=0; i<r; i++) {A.push([]); for(var j=0; j<c; j++) A[i].push(0);} return A;}
CSPL._gaussJ.printMat = function(A){ for(var i=0; i<A.length; i++) console.log(A[i]); }
CSPL._gaussJ.swapRows = function(m, k, l) {var p = m[k]; m[k] = m[l]; m[l] = p;}
CSPL.prototype.getNaturalKs = function(xs, ys) // in x values, in y values, out k values
{
this.xs = xs;
this.ys = ys;
CSPL._getNaturalKs(xs, ys, this.ks);
};
CSPL._getNaturalKs = function(xs, ys, ks) // in x values, in y values, out k values
{
var n = xs.length-1;
var A = CSPL._gaussJ.zerosMat(n+1, n+2);
for(var i=1; i<n; i++) // rows
{
A[i][i-1] = 1/(xs[i] - xs[i-1]);
A[i][i ] = 2 * (1/(xs[i] - xs[i-1]) + 1/(xs[i+1] - xs[i])) ;
A[i][i+1] = 1/(xs[i+1] - xs[i]);
A[i][n+1] = 3*( (ys[i]-ys[i-1])/((xs[i] - xs[i-1])*(xs[i] - xs[i-1])) + (ys[i+1]-ys[i])/ ((xs[i+1] - xs[i])*(xs[i+1] - xs[i])) );
}
A[0][0 ] = 2/(xs[1] - xs[0]);
A[0][1 ] = 1/(xs[1] - xs[0]);
A[0][n+1] = 3 * (ys[1] - ys[0]) / ((xs[1]-xs[0])*(xs[1]-xs[0]));
A[n][n-1] = 1/(xs[n] - xs[n-1]);
A[n][n ] = 2/(xs[n] - xs[n-1]);
A[n][n+1] = 3 * (ys[n] - ys[n-1]) / ((xs[n]-xs[n-1])*(xs[n]-xs[n-1]));
CSPL._gaussJ.solve(A, ks);
};
CSPL.prototype.evalSpline = function(x)
{
return CSPL._evalSpline(x, this.xs, this.ys, this.ks);
};
CSPL._evalSpline = function(x, xs, ys, ks)
{
var i = 1;
while(xs[i]<x) // breaks beyond array undefined < any
i++;
// extrapolate far
if(i == xs.length)
i--;
var t = (x - xs[i-1]) / (xs[i] - xs[i-1]);
var a = ks[i-1]*(xs[i]-xs[i-1]) - (ys[i]-ys[i-1]);
var b = -ks[i ]*(xs[i]-xs[i-1]) + (ys[i]-ys[i-1]);
var q = (1-t)*ys[i-1] + t*ys[i] + t*(1-t)*(a*(1-t)+b*t);
return q;
};
function polynomialCurveFitting(xArray, yArray)
{
order = 2;
var xMatrix = [];
var xTemp = [];
var yMatrix = numeric.transpose([yArray]);
for (j=0;j<xArray.length;j++)
{
xTemp = [];
for(i=0;i<=order;i++)
{
xTemp.push(1*Math.pow(xArray[j],i));
}
xMatrix.push(xTemp);
}
var xMatrixT = numeric.transpose(xMatrix);
var dot1 = numeric.dot(xMatrixT,xMatrix);
var dotInv = numeric.inv(dot1);
var dot2 = numeric.dot(xMatrixT,yMatrix);
var solution = numeric.dot(dotInv,dot2);
//console.log("Coefficients a + bx^1 + cx^2...");
//console.log(solution);
return solution;
};
function LocalStorageManager(localStorageId, scope, objectKey, dbKey, defaultId, defaultObject)
{
// maintains localStorageId_current and localStorageId_DB
this.localStorageId = localStorageId;
this.scope = scope;
this.objectKey = objectKey;
this.dbKey = dbKey;
this.scope[this.objectKey] = {};
this.scope[this.objectKey]['key'] = defaultId;
this.scope[this.objectKey]['object'] = defaultObject;
this.scope[this.dbKey] = {}; // always { id1:object1, id2:object2, ... }
this.load();
this.restore(null);
}
LocalStorageManager.prototype._currentToJSON = function() // save the current Item temporarily in LS
{
return angular.toJson([this.scope[this.objectKey]['key'], this.scope[this.objectKey]['object']]);
}
LocalStorageManager.prototype._currentFromJSON = function(current) // save the current Item temporarily in LS
{
if(current[0])
{
this.scope[this.objectKey]['key'] = current[0];
this.scope[this.objectKey]['object'] = current[1];
}
};
LocalStorageManager.prototype.currentToURIComponent = function() // save the current Item temporarily in LS
{
var c = this._currentToJSON();
c = c.replace(/[^\x00-\xFF]/g, ""); // remove non ASCII components that cause exceptions in btoa
return btoa ? encodeURIComponent(btoa(c)) : "ERROR_btoa_not_supported";
};
LocalStorageManager.prototype.currentFromURIComponent = function(uric) // save the current Item temporarily in LS
{
var b64 = decodeURIComponent(uric);
try
{
var json = atob(b64);
this._currentFromJSON(this._fromJSONcatch(json));
return true;
}
catch(e)
{
console.log("Cannot decode! The data is invalid.");
}
return false;
};
LocalStorageManager.prototype.save = function() // save the current Item temporarily in LS
{
localStorage.setItem(this.localStorageId + "_current", this._currentToJSON());
//console.log("LS SAVE", this.scope[this.objectKey]['key']);
};
LocalStorageManager.prototype.load = function(id) // load current item os startup
{
var current = this._getItemAndDecode(this.localStorageId + "_current",[null, null]);
this._currentFromJSON(current);
};
LocalStorageManager.prototype.store = function() // save the current Item in LS DB
{
this.scope[this.dbKey] = this._getItemAndDecode(this.localStorageId + "_DB", {});
this.scope[this.dbKey][this.scope[this.objectKey]['key']] = this.scope[this.objectKey]['object'];
localStorage.setItem(this.localStorageId + "_DB", angular.toJson(this.scope[this.dbKey]));
};
LocalStorageManager.prototype.delete = function(idKey) // save the current Item in LS DB
{
this.scope[this.dbKey] = this._getItemAndDecode(this.localStorageId + "_DB", {});
delete this.scope[this.dbKey][idKey];
localStorage.setItem(this.localStorageId + "_DB", angular.toJson(this.scope[this.dbKey]));
};
LocalStorageManager.prototype.restore = function(idOrNull) // save the current Item in LS DB
{
this.scope[this.dbKey] = this._getItemAndDecode(this.localStorageId + "_DB", {});
if(!idOrNull)
return;
var obj = this.scope[this.dbKey][idOrNull];
if(obj)
{
this.scope[this.objectKey]['key'] = idOrNull;
this.scope[this.objectKey]['object'] = obj;
}
};
LocalStorageManager.prototype._getItemAndDecode = function(id, _default) // save the current Item in LS DB
{
var str = localStorage.getItem(id);
if(!str)
return _default;
return this._fromJSONcatch(str, _default);
};
LocalStorageManager.prototype._fromJSONcatch = function(jsonString, _default) // save the current Item in LS DB
{
try
{
return angular.fromJson(jsonString);
}
catch(e)
{
console.log("JSON PARSE ERROR");
}
return _default;
};
function Calculator($rootScope, $timeout)
{
this.scope = $rootScope;
DEBUG_SCOPE = $rootScope;
this.scope.Math = window.Math; // we need Math in the template
this.scope.inputs = {
arrow:{ grains:400, name:"Arrow One", v0fps:245, v0:74 },
settings:[], // [{ distance:, reading: }, ...]
maxDistance:60,
svgScaleX:1.0
};
this.scope.savedSettings = {}; // database { "settings-name": object, }
var me = this;
this.scope.parcour = null; // {key:, value:} Array of target objects { id:"1 Adler", d:10.5, a:-25 }, ...
this.scope.parcourStore = null; // Array of target objects { id:"1 Adler", d:10.5, a:-25 }, ...
this.localStorageParcour = new LocalStorageManager("ARCHISCOPE_parcour", this.scope, "parcour", "parcourStore", "WBSC Rot", [{ id:"1 Dachs", d:23, a:-11 }, { id:"2 Fuchs", d:24, a:-16 }]);
//this.scope.$watch("inputs.arrow.weightAll", function(){ me.scope.inputs.arrow.grams = me.scope.inputs.arrow.weightAll/me.scope.inputs.arrow.count; });
//this.scope.$watch("inputs.arrow.count", function(){ me.scope.inputs.arrow.grams = me.scope.inputs.arrow.weightAll/me.scope.inputs.arrow.count; });
//this.scope.$watch("inputs.arrow.grams", function(){ me.scope.inputs.arrow.grains = me.scope.inputs.arrow.grams * 15.432358; });
this.maxTable = 90;
this.parallax = 16; // meters
this.cubicSpline = null; // interpolator for 16+ meters
this.cubicSplineBunnyshot = null; // interpolator for few meters
this.load();
this._calculateUris();
this.scope.clearLocalStorage = function() { me.clear(); };
this.scope.saveSettings = function() { me.saveSettings(); };
this.scope.loadSettings = function(x) { me.loadSettings(x); };
this.scope.deleteSettings = function(x) { if(confirm('Delete?')) { me.deleteSettings(x); } };
this.scope.showScaleAndSVG = false; // disables calcSvgModel()
this.scope.$watch("inputs.svgScaleX", function(){ me.calcSvgModel(); });
this.scope.calculator = this;
var ls = localStorage.getItem('ARCHISCOPE_parcour_highlight');
this.parcourHighlightRow = ls ? parseInt(ls) : 0; // see also startWatches!
$timeout(function(){ me.startWatches(); },1);
$timeout(function(){
if(me.parcourHighlightRow > 0)
{
var element = document.getElementById("parcourTable")
var tdarray = element.getElementsByTagName("td");
var td = tdarray[me.parcourHighlightRow];
td.scrollIntoView(true);
}
},1000);
}
Calculator.prototype.startWatches = function()
{
var me = this;
this.scope.$watch("inputs.arrow.name", function(){
if(!me.scope.inputs.arrow)
me.scope.inputs["arrow"] = {};
if(!me.scope.inputs.arrow.name)
me.scope.inputs.arrow.name = "A1";
me.scope.currentSettingsName = me.scope.inputs.arrow.name + " " + (new Date()).toISOString().substring(2,10); });
this.scope.$watch("inputs.arrow.v0fps", function(){
if(!me.scope.inputs.arrow)
me.scope.inputs["arrow"] = {};
if(!me.scope.inputs.arrow.v0fps)
me.scope.inputs.arrow.v0fps = 265;
me.scope.inputs.arrow.v0 = Math.round(me.scope.inputs.arrow.v0fps * 0.3048);
me.calcTable(); });
this.scope.$watch("inputs.maxDistance", function(){ me.calcModel(); });
this.scope.$watch("model", function(){ me.calcTable(); }, true); // sets inputs.settings
this.scope.$watch("inputs", function(n,o){
//console.log("inputs changed!", o, n);
document.title = me.scope.currentSettingsName;
me.scope.inputsJSON = angular.toJson(me.scope.inputs);
me.save(); }, true);
this.scope.$watch("parcour", function(){ me.localStorageParcour.save(); me.updateUrlParameter("parcour"); }, true);
me.calcModel();
me.calcTable();
};
Calculator.prototype.setExpandedModelDistance = function(d)
{
var d = Math.floor(d/2)*2;
if(d == this.expandedModelDistance)
this.expandedModelDistance = 0;
else
this.expandedModelDistance = d;
}
Calculator.prototype.getUrlParameter = function() // return json as string
{
var data = null;
// 1. check the hashbang parameter #!/scope/{encodedData}
data = getHashbangParameter("sight",null);
// 2. else check the GET ?data= parameter for backwards compatibility
if(!data) // we have the GET parameter ?data=
data = getParameterByName("data");
if(!data)
return null;
// 3. decode the data
data = decodeURIComponent(data);
try
{
data = atob(data);
}
catch(e)
{
alert("Passed scope readings cannot be decoded! The data is invalid.");
return null;
}
return data; // return json as string
};
Calculator.prototype._calculateUris = function() // renew the hashbang parameter
{
this.scope.inputsURI = "/sight/" + (btoa ? encodeURIComponent(btoa(this.scope.inputsJSON)) : "ERROR_btoa_not_supported");
this.scope._dataParamHash = calculateIntegerHashFromString(this.scope.inputsJSON); // json string of this.scope.inputsJSON
if(getParameterByName("data")) // strip the old get parameter
window.history.replaceState(null, null, window.location.pathname);
this.scope.parcourURI = "/parcour/" + this.localStorageParcour.currentToURIComponent();
};
Calculator.prototype.updateUrlParameter = function(source) // renew the hashbang parameter
{
this._calculateUris();
document.title = this.scope.currentSettingsName;
if(getParameterByName("data")) // strip the old get parameter
window.history.replaceState(null, null, window.location.pathname);
window.location.hash = "!" + this.scope.inputsURI + this.scope.parcourURI;
console.log("SET #!", this.scope.inputsURI.length, this.scope.parcourURI.length, source)
};
Calculator.prototype.load = function()
{
var ls = localStorage.getItem('ARCHISCOPE_savedSettings'); // the database of arrows
if(ls)
{
try
{
this.scope.savedSettings = angular.fromJson(ls);
}
catch(e)
{
console.log("ARCHISCOPE_savedSettings JSON PARSE ERROR");
}
}
var inp = localStorage.getItem('ARCHISCOPE_scopeinputs'); // the CURRNT arrow
if(inp)
{
try
{
this.scope.inputs = angular.fromJson(inp);
if(this.scope.inputs.v0) // versioning
this.scope.inputs.arrow.v0 = this.scope.inputs.v0;
if(this.scope.inputs.v0fps) // versioning
this.scope.inputs.arrow.v0fps = this.scope.inputs.v0fps;
this.scope.inputsJSON = inp;
this.scope._dataParamHash = calculateIntegerHashFromString(inp); // json this.scope.inputsJSON
}
catch(e)
{
console.log("ARCHISCOPE_scopeinputs JSON PARSE ERROR");
}
}
if(inp && (isInWebAppiOS || isInWebAppChrome)) // restore from URL only if localStorage was wiped
return;
/* not reachable in standalone web app if ARCHISCOPE_scopeinputs localStorage is set
Web apps always ask to restore from URL parameter each time they are started, otherwise.
*/
var data = this.getUrlParameter(); // return json as string
var saveAll = false;
if(data) // we have the /sight/ parameter or ?data=
{
// avoid confirm on every opening of page, only if data= is new
var hash = calculateIntegerHashFromString(data);
if(hash != this.scope._dataParamHash)
{
if(confirm("Replace SCOPE data from URL?") === true)
{
this.scope.inputs = angular.fromJson(data);
this.scope._dataParamHash = hash;
// this.save(); // overwrites URL /parcour/!
saveAll = true;
}
}
}
var parcour = getHashbangParameter("parcour", null);
if(parcour)
{
var hashURIC = calculateIntegerHashFromString(parcour);
var hashCurrent = calculateIntegerHashFromString(this.localStorageParcour.currentToURIComponent());
if(hashURIC != hashCurrent)
{
if(confirm("Replace PARCOURS from URL?") === true)
{
this.localStorageParcour.currentFromURIComponent(parcour);
saveAll = true;
}
}
}
if(saveAll)
this.save();
// not reachable in standalone web app
};
Calculator.prototype.save = function() // this is the instant save function
{
this.scope.inputsJSON = angular.toJson(this.scope.inputs);
this.updateUrlParameter("save");
localStorage.setItem('ARCHISCOPE_scopeinputs', this.scope.inputsJSON);
var json = angular.toJson(this.scope.savedSettings);
localStorage.setItem('ARCHISCOPE_savedSettings', json);
this.localStorageParcour.save();
};
Calculator.prototype.clear = function()
{
// localStorage.clear(); removes all site settings, scoresheets, etc.
localStorage.removeItem('ARCHISCOPE_scopeinputs');
localStorage.removeItem('ARCHISCOPE_savedSettings');
localStorage.removeItem('ARCHISCOPE_parcour');
localStorage.removeItem('ARCHISCOPE_parcour_highlight');
window.location.search="?reload=1";
};
Calculator.prototype.saveSettings = function()
{
if(!this.scope.currentSettingsName) // undefined or empty
{
alert("Name of scope readings is empty! Cannot save.");
return;
}
this.scope.savedSettings[this.scope.currentSettingsName] = this.scope.inputs;
this.save();
};
Calculator.prototype.loadSettings = function(name)
{
if(this.scope.savedSettings[name] instanceof Array) // old version does not store arrow in settings
this.scope.inputs.settings = this.scope.savedSettings[name];
else
this.scope.inputs = this.scope.savedSettings[name];
this.scope.currentSettingsName = name; // me.scope.inputs.arrow.name+Date
this.calcModel();
};
Calculator.prototype.deleteSettings = function(name)
{
delete this.scope.savedSettings[name];
this.save();
};
Calculator.prototype.calcModel = function() // create the distance model; does not change when inputs are changed, see calcTable()
{
this.scope.model = [];
var max = Math.min(Math.max(30,this.scope.inputs.maxDistance), 120);
for(var j=0; j<this.scope.inputs.settings.length; j++) // do not discard user data
if(this.scope.inputs.settings[j].distance > max)
max = this.scope.inputs.settings[j].distance;
var i=0, step=1;
for(var d = 4; d <= max; d+=step) // d is the distance to the target
{
if(d>=this.expandedModelDistance && d<this.expandedModelDistance+2)
step = 0.25;
else
if(d>11) // above 11m switch to 2
step = 2;
else
step = 1;
if(typeof(this.scope.inputs.maxDistance) == "number" && d > max)
break;
this.scope.model[i] = {};
this.scope.model[i].distance = d;
this.scope.model[i].reading = 0;
for(var j=0; j<this.scope.inputs.settings.length; j++)
if(this.scope.inputs.settings[j].distance == d)
this.scope.model[i].reading = this.scope.inputs.settings[j].reading;
i++;
}
};
Calculator.prototype.calcTable = function() // copies distance/sight-reading to inputs
{
var settingsChanged = false, n = 0;
var newSettings = [];
var xs0=[], ys0=[], x0n = 0; // cubic spline
var xs=[], ys=[], xn = 0; // cubic spline
xs0[x0n] = 0;
ys0[x0n] = 80;
x0n++;
for(var i = 0; i < this.scope.model.length; i++)
{
if(this.scope.model[i].reading > 0) // COPY READING TO SETTINGS!
{
if(this.scope.inputs.settings[n] == undefined ||
this.scope.inputs.settings[n].distance != this.scope.model[i].distance ||
this.scope.inputs.settings[n].reading != this.scope.model[i].reading) // avoid firing $watch if no change took place
{
settingsChanged = true;
}
newSettings.push({ distance:this.scope.model[i].distance, reading:this.scope.model[i].reading });
n++;
if(this.scope.model[i].distance < this.parallax) // must avoid paralax error!!
{
xs0[x0n] = this.scope.model[i].distance;
ys0[x0n] = this.scope.model[i].reading;
x0n++;
}
else
{
xs[xn] = this.scope.model[i].distance;
ys[xn] = this.scope.model[i].reading;
xn++;
}
}
}
if(settingsChanged || this.scope.inputs.settings.length != newSettings.length)
{
this.scope.inputs.settings = newSettings;
console.log("inputs.settings = newSettings");
}
if(n < 3)
return;
if(xn >= 3) // more than 3 values > this.parallax
{
this.cubicSpline = new CSPL();
this.cubicSpline.getNaturalKs(xs, ys);
this.calcPolyfit();
}
else
this.cubicSpline = null;
if(x0n >= 3) // more than 3 values < this.parallax
{
// Join the splines ...
if(this.cubicSpline)
{
xs0[x0n] = this.parallax;
ys0[x0n] = this.cubicSpline.evalSpline(this.parallax);;
x0n++;
}
this.cubicSplineBunnyshot = new CSPL();
this.cubicSplineBunnyshot.getNaturalKs(xs0, ys0);
}
else
this.cubicSplineBunnyshot = null;
for(var i = 0; i < this.scope.model.length; i++)
{
this.scope.model[i].polyfit = this.evalPolyfit(this.scope.model[i].distance);
var y = this.evalSpline(this.scope.model[i].distance);
this.scope.model[i].interpolated = y.toFixed(2); // WARNING this is a String!
var y2 = this.evalSpline(this.scope.model[i].distance+1);
this.scope.model[i].delta1m = (y2-y).toFixed(2); // WARNING this is a String!
if(i>0) // 2nd derivative of change
this.scope.model[i].delta2nd= (this.scope.model[i].delta1m - this.scope.model[i-1].delta1m).toFixed(2); // WARNING this is a String!
}
this.calcSlope();
};
Calculator.prototype.evalSpline = function(distance) // handle parallax
{
if(distance < this.parallax)
{
if(this.cubicSplineBunnyshot)
return this.cubicSplineBunnyshot.evalSpline(distance);
return 0;
}
if(this.cubicSpline)
return this.cubicSpline.evalSpline(distance);
return 0;
}
Calculator.prototype.calcPolyfit = function()
{
var xMeters = [];
var yReadings = [];
for(var j=0; j<this.scope.inputs.settings.length; j++)
{
if(this.scope.inputs.settings[j].distance < 22)
continue;
xMeters.push(this.scope.inputs.settings[j].distance);
yReadings.push(this.scope.inputs.settings[j].reading);
// console.log(this.scope.inputs.settings[j].distance + "," + this.scope.inputs.settings[j].reading);
}
if(xMeters.length >= 2)
this.polynomial = polynomialCurveFitting(xMeters, yReadings);
else
this.polynomial = null;
};
Calculator.prototype.evalPolyfit = function(xMeters)
{
if(xMeters < 22 || !this.polynomial)
return NaN;
// var xMeters = model.distance;
var r = this.polynomial[0][0] + this.polynomial[1][0] * xMeters + this.polynomial[2][0] * xMeters * xMeters;
return Math.round(r*100)/100;
};
Calculator.prototype.calcSlope = function()
{
var d2r = Math.PI/180; // deg to rad
for(var i = 0; i < this.scope.model.length; i++)
{
var d = this.scope.model[i].distance;
var cd;
cd = Math.cos(10*d2r) * d; this.scope.model[i].down10 = cd.toFixed(1); // CSPL.evalSpline(cd, xs, ys, ks).toFixed(2);
cd = Math.cos(20*d2r) * d; this.scope.model[i].down20 = cd.toFixed(1); // CSPL.evalSpline(cd, xs, ys, ks).toFixed(2);
cd = Math.cos(30*d2r) * d; this.scope.model[i].down30 = cd.toFixed(1); // CSPL.evalSpline(cd, xs, ys, ks).toFixed(2);
cd = Math.cos(40*d2r) * d; this.scope.model[i].down40 = cd.toFixed(1); // CSPL.evalSpline(cd, xs, ys, ks).toFixed(2);
cd = Math.cos(50*d2r) * d; this.scope.model[i].down50 = cd.toFixed(1); // CSPL.evalSpline(cd, xs, ys, ks).toFixed(2);
var time = d/this.scope.inputs.arrow.v0;
var drop = 9.81/2.0*time*time*100;
this.scope.model[i].time = time.toFixed(2);
this.scope.model[i].drop = drop.toFixed(0); // excludes drag / air resistance
var t1 = (d-1)/this.scope.inputs.arrow.v0;
var d1 = 9.81/2.0*t1*t1*100; // *100 cm
this.scope.model[i].deltaScope = Math.round((drop-d1)/this.scope.model[i].delta1m); // 1 REV on scope is x cm on target
}
};
Calculator.prototype.calcSvgModel = function(sight)
{
if(false == this.scope.showScaleAndSVG) // hidden
return;
if(sight)
this._calcSvgModelSigthType = sight;
var mmPerRevolution = 0.99234;
var minLine = 6 * mmPerRevolution; // in mm for surelock
var maxLine = 88 * mmPerRevolution;
var textOffsetX = 55;
var textOffsetY = 0;
var textLinebreak = 4;
var angles = [10,15,20,25,30,40,50];
var anglesOffsets = {0:10, 10:8, 15:7, 20:6, 25:5, 30:4, 40:2, 50:0}; // 10-(m.angle)/5
switch(this._calcSvgModelSigthType)
{
case "shibuya":
mmPerRevolution = 1/24*25.4;
minLine = 0; // in mm
maxLine = 111.125; // 105.8333333333 at 10 111.125 = 10.5 * mmPerRevolution
textOffsetX = 1;
textOffsetY = 4.88;
textLinebreak = 5;
angles = [10,20,30,40];
anglesOffsets = {0:10, 10:8, 20:7, 30:6, 40:5};
break;
}
if(!this.sightTextOffsetX)
this.sightTextOffsetX = textOffsetX; // init template
else
textOffsetX = this.sightTextOffsetX; // copy from template
if(!this.sightTextOffsetY)
this.sightTextOffsetY = textOffsetY;
else
textOffsetY = this.sightTextOffsetY;
this.svgModel = [];
var me = this;
var calcOneAngle = function(a, model)
{
var minReading = 999;
var minDistance = 999;
for(var d=70; d>=10; d-=2) // parallax error prohibits plotting 5m values
{
var p = { distance:d , reading:0, angle:a };
var realD = p.distance * Math.cos(a * d2r);
p.reading = me.evalSpline(realD) * mmPerRevolution; // reading is actually mm from left side
minReading = Math.min(minReading, p.reading);
minDistance = Math.min(minDistance, p.distance);
//console.log(a, p.reading, minReading);
if(p.reading <= minReading) // avoid plotting parallax area
model.push(p);
}
return minDistance;
};
var d2r = Math.PI/180; // deg to rad
// for every range and angle calc a data point
var mind = calcOneAngle(0, this.svgModel);
for(var i=0;i<angles.length;i++)
calcOneAngle(angles[i], this.svgModel);
if(!this.svg)
this.svg = SVG('scale').attr({ width:"120mm", height:"20mm", preserveAspectRatio:"xMinYMin" }).viewbox(0,0,120,20)
else
this.svg.clear();
var group = this.svg.group().transform({scaleX: this.scope.inputs.svgScaleX });
for(var i in this.svgModel)
{
var m = this.svgModel[i];
//console.log(m.reading, m.angle);
var w = 0.1;
var h = 0.9;
var y0 = 0;
if(m.angle == 0) // make y-space for numbers
y0 = 0.1;
if(m.distance % 10 == 0)
{
w=0.4;
if(m.angle == 0)
group.text(""+m.distance).size(1.2).move(m.reading - w/2.0 -0.50, y0 + 8.75);
}
else if(m.distance % 2 == 0)
h=0.5;
group.rect(w, h).move(m.reading - w/2.0, y0 + anglesOffsets[m.angle]); console.log(10-(m.angle)/5)
}
// draw adjustment lines
group.rect(0.1, 20).move(minLine, 0); // height 11mm
group.rect(0.1, 20).move(maxLine, 0);
group.text(this.scope.currentSettingsName).size(3).move(textOffsetX, textOffsetY);
var px = this.getParallaxReadings(mind);
if(px)
{
var z1 = "", z2 = "", z3 = "";
for(var i=0;i< px.length; i++)
{
if(i<textLinebreak)
z1 += px[i]+" ";
else if(i<textLinebreak*2)
z2 += px[i]+" ";
else
z3 += px[i]+" ";
}
var y = textOffsetY + 3.2;
if(z1.length > 0) group.text(z1).size(2.5).move(textOffsetX, y);
if(z2.length > 0) group.text(z2).size(2.5).move(textOffsetX, y+2.6);
if(z3.length > 0) group.text(z3).size(2.5).move(textOffsetX, y+2.6+2.6);
}
var xml= document.getElementById('scale').innerHTML;
document.getElementById('svgxml').innerText = xml;
//return this.svgModel;
};
Calculator.prototype.getParallaxReadings = function(minReading)
{
var ret = []; // must not be ""
for(var i = 0; i < this.scope.model.length; i++)
{
if(this.scope.model[i].distance > minReading) // normal
continue;
if(this.scope.model[i].reading > 0)
ret.push(this.scope.model[i].distance +"/"+ this.scope.model[i].reading);
}
return ret;
};
Calculator.prototype.saveSvg = function()
{