forked from Safecast/Tilemap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bgeigie_viewer.js
3032 lines (2464 loc) · 113 KB
/
bgeigie_viewer.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
// ==============================================
// bGeigie Log Viewer
// ==============================================
// Nick Dolezal/Safecast, 2015
// This code is released into the public domain.
// ==============================================
// 2016-11-22 ND: - Make various static/class functions private, comment out dead code.
// 2015-04-05 ND: - Test fix for remaining known no-draw panning issue
// 2015-03-30 ND: - Fix for various no-draw panning issues.
// 2015-03-21 ND: - Support for retrieving all logids in string or limited number.
// 2015-03-20 ND: - Major changes to core rendering logic; quadkey clustering and per-tile rendering.
// 2015-02-17 ND: - Added direct log download function - BVM.GetLogFileDirectFromUrlAsync(url, logId);
// - Removed legacy query form refs.
// - Made "zoom to marker extent" the default behavior.
// - Added setter for above: BVM.SetZoomToLogExtent(bool);
// =================================
// Requirements (Files):
// =================================
// 1. bgeigie_viewer_min.js (this file)
// 2. bgeigie_viewer_worker_min.js (*not* optional!)
// =================================
// Use
// =================================
//
// 1. Prerequisites
// -------------------------------
// var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); // or whatever.
//
// 2. Instantiate
// -------------------------------
// var bvm = new BVM(map, null);
//
// 3. Add a log by URL directly
// -------------------------------
// bvm.GetLogFileDirectFromUrlAsync("https://safecast-production.s3.amazonaws.com/uploads/bgeigie_import/source/12070/100-1111.LOG", 12070);
//
// 3. Add a log by ID
// -------------------------------
// bvm.AddLogsByQueryFromString("12070");
//
// =================================
// Optional - Data Transfer UI
// =================================
//
// To display a UI showing download progress to the user, a div with a specific ID is required.
// This div is used to inject HTML, as Google Maps does with "map_canvas" above.
// External CSS styles and an image are also required.
//
// 1. HTML Div
// -------------------------------
// <div id="bv_transferBar" class="bv_transferBarHidden"></div>
//
// 2. World Map PNG (256x256)
// -------------------------------
// By default, "world_155a_z0.png" should be in the same path.
//
// 3. CSS Styles (many)
// -------------------------------
// Required styles are as follows.
//
// #bv_transferBar { position:absolute;top:0;bottom:0;left:0;right:0;margin:auto;padding:10px 0px 20px 20px;border:0px;background-color:rgba(255, 255, 255, 0.75);font-size:80%; }
// .bv_transferBarVisible { visibility:visible;z-index:8;width:276px;height:286px;overflow:visible; }
// .bv_transferBarHidden { visibility:hidden;z-index:-9000;width:0px;height:0px;overflow:hidden; }
// .bv_FuturaFont { font-size:100%;font-family:Futura,Futura-Medium,'Futura Medium','Futura ND Medium','Futura Std Medium','Futura Md BT','Century Gothic','Segoe UI',Helvetica,Arial,sans-serif; }
// .bv_hline { overflow:hidden;text-align:center; }
// .bv_hline:before, .bv_hline:after { background-color:#000;content:"";display:inline-block;height:1px;position:relative;vertical-align:middle;width:50%; }
// .bv_hline:before { right:0.5em;margin-left:-50%; }
// .bv_hline:after { left:0.5em;margin-right:-50%; }
//
// Note the font can be anything, but should be about that size.
// That font class is also used for marker info windows.
// bGeigie Log Viewer - Main
// Contains all useful instances of other objects and UI event handling.
// Messy and too broad but hey.
// NOTE: In most cases, null should be passed for "dataBinds".
// Only override this if you want to set custom styles or image/worker filepaths.
var BVM = (function()
{
function BVM(map, dataBinds)
{
this.mapRef = map;
this.isMobile = _IsPlatformMobile();
this.xfm = null; // data transfer manager
this.mks = null; // marker manager
this.wwm = null; // web worker manager
this.dataBinds = dataBinds;
this.did_add_gmaps_listeners = false; // todo: move to MKS
this.zoom_to_log_extent = true; // whether or not to zoom to the extent of the log(s) after processing.
if (this.dataBinds == null)
{
this.Init_DataBindDefaults();
}//if
this.Init();
}
// =======================================================================================================
// Mandatory Initialization
// =======================================================================================================
BVM.prototype.Init = function()
{
this.Init_XFM();
this.Init_MKS();
this.Init_WWM();
};
BVM.prototype.Init_DataBindDefaults = function()
{
var binds =
{
elementIds:
{
bv_transferBar:"bv_transferBar"
},
cssClasses:
{
bv_hline:"bv_hline",
bv_FuturaFont:"bv_FuturaFont",
bv_transferBarHidden:"bv_transferBarHidden",
bv_transferBarVisible:"bv_transferBarVisible"
},
urls:
{
world_155a_z0:"world_155a_z0.png",
bv_worker_min:"bgeigie_viewer_worker_min.js"
}
};
this.dataBinds = binds;
};
BVM.prototype.AddGmapsListener_Idle = function()
{
var fxRefresh = function()
{
this.mks.RemoveMarkersFromMapForCurrentVisibleExtent();
this.mks.AddMarkersToMapForCurrentVisibleExtent();
}.bind(this);
google.maps.event.addListener(this.mapRef, "idle", fxRefresh); // 2015-04-03 ND: idle isn't getting the bounds changed when panning north suddenly(?)
};
BVM.prototype.AddGmapsListener_OnStreetViewExit = function()
{
var pan = this.mapRef.getStreetView();
var fxRefreshIfDone = function()
{
if (!pan.getVisible()) // restore the markers to the map extent instead of street view
{
this.mks.RemoveMarkersFromMapForCurrentVisibleExtent();
this.mks.AddMarkersToMapForCurrentVisibleExtent();
}//if
else // seems to have issues with large data sets, see if this helps(?)
{
this.mks.RemoveAllMarkersFromMap();
var pos = pan.getPosition();
var lat = pos.lat();
var lon = pos.lng();
var x0 = lon - 0.005; // ~0.5km
var y0 = lat - 0.005;
var x1 = lon + 0.005;
var y1 = lat + 0.005;
var z = 21;
var last_ex = [ 0, 0, 0, 0, 0, 0, 0 ];
this.mks.RemoveAllMarkersFromMap();
this.mks.AddMarkersToMapForExtentTimer(x0, y0, x1, y1, -9000.0, -9000.0, z, last_ex, 0, 500, 0, null, null);
}//else
}.bind(this);
google.maps.event.addListener(pan, "visible_changed", fxRefreshIfDone);
};
BVM.prototype.AddGmapsListener_OnStreetViewPositionChanged = function()
{
var pan = this.mapRef.getStreetView();
var fxRefreshStreetView = function()
{
if (pan.getVisible())
{
var pos = pan.getPosition();
var lat = pos.lat();
var lon = pos.lng();
var x0 = lon - 0.005; // ~0.5km
var y0 = lat - 0.005;
var x1 = lon + 0.005;
var y1 = lat + 0.005;
var z = 21;
var last_ex = [ 0, 0, 0, 0, 0, 0, 0 ];
this.mks.RemoveAllMarkersFromMap();
this.mks.AddMarkersToMapForExtentTimer(x0, y0, x1, y1, -9000.0, -9000.0, z, last_ex, 0, 500, 0, null, null);
}//if
}.bind(this);
google.maps.event.addListener(pan, "position_changed", fxRefreshStreetView);
};
BVM.prototype.AddGmapsListeners_IfNeeded = function()
{
if (!this.did_add_gmaps_listeners)
{
this.AddGmapsListener_Idle();
this.AddGmapsListener_OnStreetViewExit();
this.AddGmapsListener_OnStreetViewPositionChanged();
this.did_add_gmaps_listeners = true;
}//if
};
BVM.prototype.Init_XFM = function()
{
var xfmcbs = function(userData) { this.TransferBar_SetHidden(false); }.bind(this);
var xfmcbe = function(userData)
{
this.xfm.ChangeMode(XFM.ModeCPU);
var sortcb = function()
{
this.wwm.TerminateWorkers();
if (this.zoom_to_log_extent) this.mks.ApplyMapVisibleExtentForMarkers();
this.mks.AddMarkersToMapForCurrentVisibleExtent();
this.AddGmapsListeners_IfNeeded();
setTimeout(function() { this.TransferBar_SetHidden(true); this.xfm.ChangeMode(XFM.ModeXF); }.bind(this), 2500);
}.bind(this);
var n = this.mks.cpms == null ? 0 : this.mks.cpms.length;
if (n > 0 && (n < 5000000 || (this.isMobile && n < 10000)))
{
this.wwm.SetFxReportDoneSortByQuadKey(sortcb);
this.mks.SortByQuadKey(); // 2015-03-13 ND: test QuadKey sort for performance
}//if
else
{
sortcb(); // bypass if likely to blow up due to RAM.
}//else
}.bind(this);
var el_bar = document.getElementById(this.dataBinds.elementIds.bv_transferBar);
this.xfm = new XFM(xfmcbs, xfmcbe, null, "Data Transfer", this.dataBinds.cssClasses.bv_hline, el_bar, this.dataBinds.cssClasses.bv_FuturaFont, this.isMobile, this.dataBinds.urls.world_155a_z0);
};
BVM.prototype.Init_MKS = function()
{
var fxGetWorkerForDispatch = function() { return this.wwm.GetWorkerForDispatch(); }.bind(this);
var fxClearAllLogIds = function() { this.xfm.ClearAllLogIds(); }.bind(this);
var fxReportResultsSuccessForLogId = function(logId) { this.xfm.ReportResultsSuccessForLogId(logId); }.bind(this);
this.mks = new MKS(this.mapRef, ICO.IconStyleMd, window.devicePixelRatio > 1.5, this.isMobile, this.dataBinds.cssClasses.bv_FuturaFont, fxGetWorkerForDispatch, fxClearAllLogIds, fxReportResultsSuccessForLogId);
};
BVM.prototype.Init_WWM = function()
{
var cb_rsuc = function(logId) { this.xfm.ReportResultsSuccessForLogId(logId); }.bind(this);
var cb_rspr = function(logId) { this.xfm.ReportStartParsingForLogId(logId); }.bind(this);
var cb_rdpr = function(logId) { this.xfm.ReportDoneParsingForLogId(logId); }.bind(this);
var cb_uimg = function(image) { this.xfm.UpdateGlobalImage(image); }.bind(this);
var cb_rdaz = function(logId) { this.xfm.ReportDoneAssignZForLogId(logId); }.bind(this);
var cb_gdpv = function(mxs, mys, minzs, cpms, alts, degs, times, logId, userData) { this.mks.GetDataAndDispatchPrefilterVec(mxs, mys, minzs, cpms, alts, degs, times, logId, userData); }.bind(this);
var cb_adat = function(lats, lons, minzs, cpms, alts, degs, logids, times, lutidxs, mxs, mys) { this.mks.AddData(lats, lons, minzs, cpms, alts, degs, logids, times, lutidxs, mxs, mys); }.bind(this);
var cb_upex = function(x0, y0, x1, y1) { this.mks.UpdateMarkerExtent(x0, y0, x1, y1); }.bind(this);
this.wwm = new WWM(this.isMobile, 0, cb_rsuc, cb_rspr, cb_rdpr, cb_uimg, cb_rdaz, cb_gdpv, cb_adat, cb_upex, this.dataBinds.urls.bv_worker_min);
};
// =======================================================================================================
// Event handlers - abstracted download methods
// =======================================================================================================
BVM.prototype.GetJSONAsyncByQuery_AllPages = function(base_url, xfType, pageIdx, pageLimit, extra_params)
{
var title = "API Query, Page " + pageIdx;
var cb = function(response, userData)
{
var success = response != null && response.length > 0;
if (success)
{
var obj = JSON.parse(response);
var j = 0;
for (var i=0; i<obj.length; i++)
{
if (obj[i] != null && obj[i].measurements_count != 0)
{
var logId = obj[i].id;
var responseType = window.TextDecoder != null ? "arraybuffer" : null;
var wcb = function(response, userData) { this.wwm.DispatchLogParseToVec(response, logId, userData); }.bind(this);
this.xfm.AddTask(obj[i].source.url, responseType, wcb, [obj[i].id], "bGeigie Log", XF.TypeLog, obj[i].id);
j++;
}//if
else
{
console.log("BVM.GetJSONAsyncByQuery_AllPages: Log ID=%d had 0 measurements, skipping.", obj[i].id);
}//else
}//for
success = j > 0 && userData[2] < userData[3];
// now, get the next page of results.
if (success)
{
this.GetJSONAsyncByQuery_AllPages(userData[0], userData[1], userData[2] + 1, userData[3], userData[4]);
}//if
}//if
if (!success)
{
var synth_url = userData[0] + (userData[2] > 1 ? "&page=" + userData[2] : "") + (userData[4] != null ? userData[4] : "");
this.xfm.ReportResultsErrorForURL(synth_url);
}//if
}.bind(this);
var page_url = base_url + (pageIdx > 1 ? "&page=" + pageIdx : "") + (extra_params != null ? extra_params : "");
this.xfm.AddTask(page_url, null, cb, [base_url, xfType, pageIdx, pageLimit, extra_params], title, xfType, 0);
};
BVM.prototype.GetJSONAsync = function(url)
{
var cb = function(response, userData)
{
var success = response != null && response.length > 0;
if (success)
{
var obj = JSON.parse(response);
if (obj != null && obj.source != null && obj.source.url != null && obj.source.url.length > 0)
{
var logId = obj.id;
var responseType = window.TextDecoder != null ? "arraybuffer" : null;
this.xfm.AddTask(obj.source.url, responseType, function(response, userData) { this.wwm.DispatchLogParseToVec(response, logId, userData); }.bind(this), [obj.id], "bGeigie Log", XF.TypeLog, obj.id);
}//if
else
{
success = false;
}//else
}//if
if (!success)
{
this.xfm.ReportResultsErrorForURL(url);
}//if
}.bind(this);
this.xfm.AddTask(url, null, cb, null, "API Query - Log", XF.TypeLogQueryByLog, 0);
};
BVM.prototype.GetLogFileDirectFromUrlAsync = function(url, logId)
{
var responseType = window.TextDecoder != null ? "arraybuffer" : null;
this.xfm.AddTask(url, responseType, function(response, userData) { this.wwm.DispatchLogParseToVec(response, logId, userData); }.bind(this), [logId], "bGeigie Log", XF.TypeLog, logId);
};
// =======================================================================================================
// Event handlers - abstracted query methods
// =======================================================================================================
BVM.prototype.AddLogsByQueryFromString = function(txt, extra_params, page_limit)
{
if (txt == null || txt.length == 0)
{
var url = "https://api.safecast.org/bgeigie_imports.json?order=created_at+desc";
this.GetJSONAsyncByQuery_AllPages(url, XF.TypeLogQueryByUser, 1, page_limit, extra_params);
}//if
if (txt != null && txt.length > 0 && txt.substring(0,1) == "c" && txt.indexOf("cosmic") == 0)
{
page_limit = 250;
var url = "https://api.safecast.org/bgeigie_imports.json?subtype=Cosmic";
this.GetJSONAsyncByQuery_AllPages(url, XF.TypeLogQueryByUser, 1, page_limit, extra_params);
}//if
if (txt != null && txt.length > 0 && txt.substring(0,1) == "u")
{
var url = _ParseUserInput_UserID(txt);
this.GetJSONAsyncByQuery_AllPages(url, XF.TypeLogQueryByUser, 1, page_limit, extra_params);
}//if
if (txt != null && txt.length > 0 && txt.substring(0,1) == "q")
{
var url = _ParseUserInput_QueryText(txt);
this.GetJSONAsyncByQuery_AllPages(url, XF.TypeLogQueryByText, 1, page_limit, extra_params);
}//if
var ids = _ParseUserInputIDs(txt);
for (var i=0; i<ids.length; i++)
{
var url = "https://api.safecast.org/bgeigie_imports/" + ids[i] + ".json";
this.GetJSONAsync(url);
}//for
};
BVM.prototype.AddLogsFromQueryTextWithOptions = function(query, queryTypeId, extraParams, pageLimit)
{
if (queryTypeId == 1 && query != null && query.length > 0)
{
query = "u" + query;
}
else if (queryTypeId == 2 && query != null && query.length > 0)
{
query = "q" + query;
}
this.AddLogsByQueryFromString(query, extraParams, pageLimit);
};
// =======================================================================================================
// Event handlers - UI
// =======================================================================================================
BVM.prototype.RemoveAllMarkersFromMapAndPurgeData = function()
{
this.mks.RemoveAllMarkersFromMapAndPurgeData();
};
BVM.prototype.TransferBar_SetHidden = function(isHidden)
{
_ChangeVisibilityForElementByIdByReplacingClass(this.dataBinds.elementIds.bv_transferBar, this.dataBinds.cssClasses.bv_transferBarHidden, this.dataBinds.cssClasses.bv_transferBarVisible, isHidden);
};
BVM.prototype.SetParallelism = function(p)
{
this.wwm.SetParallelism(p);
this.xfm.SetParallelism(p);
};
BVM.prototype.SetZoomToLogExtent = function(shouldZoom)
{
this.zoom_to_log_extent = shouldZoom;
};
BVM.prototype.SetNewCustomMarkerOptions = function(width, height, alpha_fill, alpha_stroke, shadow_radius, hasBearingTick)
{
this.mks.SetNewCustomMarkerOptions(width, height, alpha_fill, alpha_stroke, shadow_radius, hasBearingTick);
};
BVM.prototype.SetNewMarkerType = function(iconTypeId)
{
this.mks.SetNewMarkerType(iconTypeId);
};
BVM.prototype.GetLogIdsEncoded = function()
{
return this.xfm.GetLogIdsEncoded();
};
BVM.prototype.GetAllLogIdsEncoded = function()
{
return this.xfm.GetAllLogIdsEncoded();
};
BVM.prototype.GetLogCount = function()
{
return this.xfm == null || this.xfm.logIds == null ? 0 : this.xfm.logIds.length;
};
// =======================================================================================================
// Static/Class Methods
// =======================================================================================================
// returns value of querystring parameter "name"
var _GetParam = function(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
return results == null ? "" : results[1];
};
// http://stackoverflow.com/questions/11381673/detecting-a-mobile-browser
// returns true if useragent is detected as being a mobile platform, or "mobile=1" is set in querystring.
var _IsPlatformMobile = function()
{
var check = false;
var ovr_str = _GetParam("mobile");
if (ovr_str != null && ovr_str.length > 0)
{
check = parseInt(ovr_str) == 1;
}//if
else
{
(function(a,b){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte|android|ipad|playbook|silk\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
if (!check) check = navigator.userAgent.match(/iPad/i);
if (!check) check = navigator.userAgent.match(/Android/i);
if (!check) check = window.navigator.userAgent.indexOf("iPad") > 0;
if (!check) check = window.navigator.userAgent.indexOf("Android") > 0;
}//else
return check;
};
var _ChangeVisibilityForElementByIdByReplacingClass = function(elementid, classHidden, classVisible, isHidden)
{
var el = document.getElementById(elementid);
if (el != null && isHidden && el.className == classVisible) el.className = classHidden;
else if (el != null && !isHidden && el.className == classHidden) el.className = classVisible;
};
var _ParseUserInput_QueryText = function(txt)
{
var q = txt.length > 1 ? txt.substring(1, txt.length) : null;
var url = q != null ? "https://api.safecast.org/bgeigie_imports.json?q=" + q + "&order=created_at+desc" : null;
return url;
};
var _ParseUserInput_UserID = function(txt)
{
var user_id = txt.length > 1 ? txt.substring(1, txt.length) : null;
var url = user_id != null ? "https://api.safecast.org/bgeigie_imports.json?by_user_id=" + user_id + "&order=created_at+desc" : null;
return url;
};
var _ParseUserInputIDs = function(txt)
{
var dest = new Array();
if (txt != null && txt.length > 0)
{
var txt_ids = txt.split(",");
for (var i=0; i<txt_ids.length; i++)
{
var x = parseInt(txt_ids[i]);
if (x != null && x > 0)
{
dest.push(x);
}//if
}//for
}//if
return dest;
};
return BVM;
})();
// WWM: Web worker manager.
// Manages one or more web workers with coded handling for specific messages.
var WWM = (function()
{
function WWM(isMobile, parallelism, fxReportResultsSuccessForLogId, fxReportStartParsingForLogId, fxReportDoneParsingForLogId, fxUpdateGlobalImage, fxReportDoneAssignZForLogId, fxGetDataAndDispatchPrefilter, fxAddData, fxUpdateMarkerExtent, workerSrcUrl)
{
this.n = parallelism > 0 ? parallelism : navigator.hardwareConcurrency != null ? navigator.hardwareConcurrency : isMobile ? 2 : 4;
this.workers = new Array(this.n);
this.isBusy = new Uint8Array(this.n);
this.index = 0;
this.fxReportResultsSuccessForLogId = fxReportResultsSuccessForLogId; // xfm
this.fxReportStartParsingForLogId = fxReportStartParsingForLogId; // xfm
this.fxReportDoneParsingForLogId = fxReportDoneParsingForLogId; // xfm
this.fxUpdateGlobalImage = fxUpdateGlobalImage; // xfm
this.fxReportDoneAssignZForLogId = fxReportDoneAssignZForLogId; // xfm
this.fxReportDoneSortByQuadKey = null;
this.fxGetDataAndDispatchPrefilter = fxGetDataAndDispatchPrefilter; // mks
this.fxAddData = fxAddData; // mks
this.fxUpdateMarkerExtent = fxUpdateMarkerExtent; // mks
this.workerSrcUrl = workerSrcUrl;
this.summary_stats = new Array(); // 2015-03-31 ND: *** TEMP *** move elsewhere later.
for (var i=0; i<this.n; i++)
{
this.workers[i] = null;
}//for
}//WWM
WWM.prototype.SetFxReportDoneSortByQuadKey = function(cb)
{
this.fxReportDoneSortByQuadKey = cb;
};
WWM.prototype.SetParallelism = function(n)
{
var s = _sve(this.isBusy, 0, Math.min(this.n, this.workers.length));
this.n = n;
if (s == 0)
{
this.TerminateWorkers();
}//if
};
WWM.prototype.DispatchLogParseToVec = function(log, logId, userData)
{
var worker = this.GetWorkerForDispatch();
var bufs = null;
var args = { op:"PARSE_LOG_TO_VEC", log:log, logId:logId, userData:userData, deci:0, worker_id:worker[1] };
if (typeof log != "string") // Preferably, the log is downloaded as an arraybuffer. Arraybuffers are the only things
{ // that can be sent to a web worker without a slow-ass copy. But this is only done for
args.log = null; // platforms that support the new experimental affaybuffer->text decode. (currently Chrome, Firefox)
args.logbuffer = log;
bufs = [ log ];
}//if
worker[0].postMessage(args, bufs);
log = null;
userData = null;
};
WWM.prototype.GetWorkerForDispatch = function()
{
var idx = -1;
var max_i = Math.min(this.n, this.workers.length);
for (var i=0; i<max_i; i++)
{
if (this.isBusy[i] == 0)
{
idx = i;
}//if
}//for
if (idx == -1)
{
this.index = this.index < max_i - 1 ? this.index + 1 : 0;
idx = this.index;
}//if
this.isBusy[idx] = 1;
if (this.workers[idx] == null)
{
var worker = new Worker(this.workerSrcUrl);
this.AddWorkerCallback(worker);
this.workers[idx] = worker;
}//if
return [this.workers[idx], idx];
};
WWM.prototype.ReportWorkerIsDone = function(idx)
{
if (idx != null && idx > 0 && idx < this.isBusy.length)
{
this.isBusy[idx] = 0;
}//if
};
WWM.prototype.TerminateWorkers = function()
{
if (this.workers == null) return;
for (var i=0; i<this.workers.length; i++)
{
this.isBusy[i] = 1;
if (this.workers[i] != null)
{
this.workers[i].terminate();
}//if
}//for
this.isBusy = new Uint8Array(this.n);
this.workers = new Array(this.n);
this.index = 0;
for (var i=0; i<this.n; i++)
{
this.workers[i] = null;
}//for
};
WWM.prototype.AddWorkerCallback = function(worker)
{
worker.onerror = function(e)
{
var errline = e != null && e.lineno != null ? e.lineno : "<NULL>";
var errfile = e != null && e.filename != null ? e.filename : "<NULL>";
var errmsg = e != null && e.message != null ? e.message : "<NULL>";
console.log("WMM: ERROR from worker: Line " + errline + " in " + errfile + ": " + errmsg);
}.bind(this);
worker.onmessage = function(e)
{
if (e == null || e.data == null || e.data.op == null)
{
console.log("WWM: Message from worker: unknown.");
}//if
else if (e.data.op == "PARSE_LOG_TO_VEC")
{
var minzs = new Int8Array(e.data.minzs);
var cpms = new Float32Array(e.data.cpms);
var alts = new Int16Array(e.data.alts);
var degs = new Int8Array(e.data.degs);
var times = new Uint32Array(e.data.times);
var mxs = new Uint32Array(e.data.mxs);
var mys = new Uint32Array(e.data.mys);
var logId = e.data.userData[0];
var ex = e.data.ex;
this.fxReportDoneAssignZForLogId(logId);
this.fxUpdateMarkerExtent(e.data.ex[0], e.data.ex[1], e.data.ex[2], e.data.ex[3]);
this.ReportWorkerIsDone(e.data.worker_id);
this.fxGetDataAndDispatchPrefilter(mxs, mys, minzs, cpms, alts, degs, times, logId, e.data.userData);
}//else if
else if (e.data.op == "MSG_START_PARSING")
{
this.fxReportStartParsingForLogId(e.data.userData[0]);
}//else if
else if (e.data.op == "TILE_CALLBACK")
{
this.fxReportDoneParsingForLogId(e.data.userData[0]);
var tile_u08 = new Uint8Array(e.data.buffer);
this.fxUpdateGlobalImage(tile_u08);
}//else if
else if (e.data.op == "DATA_FOR_PARSED_LOG")
{
var minzs = new Int8Array(e.data.minzs);
var cpms = new Float32Array(e.data.cpms);
var alts = new Int16Array(e.data.alts);
var degs = new Int8Array(e.data.degs);
var logids = new Int32Array(e.data.logids);
var times = new Uint32Array(e.data.times);
var mxs = new Uint32Array(e.data.mxs);
var mys = new Uint32Array(e.data.mys);
if (e.data.shouldAdd_c > 0)
{
this.fxAddData(minzs, cpms, alts, degs, logids, times, mxs, mys);
}//if
this.ReportWorkerIsDone(e.data.worker_id);
this.fxReportResultsSuccessForLogId(e.data.logId);
}//else if
else if (e.data.op == "ORDER_BY_QUADKEY_ASC")
{
var minzs = new Int8Array(e.data.minzs);
var cpms = new Float32Array(e.data.cpms);
var alts = new Int16Array(e.data.alts);
var degs = new Int8Array(e.data.degs);
var logids = new Int32Array(e.data.logids);
var times = new Uint32Array(e.data.times);
var mxs = new Uint32Array(e.data.mxs);
var mys = new Uint32Array(e.data.mys);
this.fxAddData(minzs, cpms, alts, degs, logids, times, mxs, mys);
this.ReportWorkerIsDone(e.data.worker_id);
this.fxReportDoneSortByQuadKey();
}//else if
else if (e.data.op == "SUMMARY_STATS")
{
this.summary_stats.push(e.data.summary_stats);
// 2015-03-31 ND: summary stats should be maintained somewhere else, this is temporary
// get aggregate stats
var ss = { n:0, dist_meters:0.0, time_ss:0.0, sum_usvh:0.0, mean_usvh:0.0, de_usv:0.0, min_usvh:9000.0, max_usvh:-9000.0, min_kph:9000.0, max_kph:-9000.0, min_alt_meters:9000.0, max_alt_meters:-9000.0 };
for (var i=0; i<this.summary_stats.length; i++)
{
var s = this.summary_stats[i];
ss.n += s.n;
ss.dist_meters += s.dist_meters;
ss.time_ss += s.time_ss;
ss.sum_usvh += s.sum_usvh;
ss.de_usv += s.de_usv;
if (s.min_usvh < ss.min_usvh) ss.min_usvh = s.min_usvh;
if (s.max_usvh > ss.max_usvh) ss.max_usvh = s.max_usvh;
if (s.min_kph < ss.min_kph) ss.min_kph = s.min_kph;
if (s.max_kph > ss.max_kph) ss.max_kph = s.max_kph;
if (s.min_alt_meters < ss.min_alt_meters) ss.min_alt_meters = s.min_alt_meters;
if (s.max_alt_meters > ss.max_alt_meters) ss.max_alt_meters = s.max_alt_meters;
}//for
ss.mean_usvh = ss.sum_usvh / ss.n;
console.log("WWM: Aggregate [%d] summary stats: { n:%d, dist_km:%s, time_hh:%s, mean_usvh:%s, de_usv:%s, min_usvh:%s, max_usvh:%s, min_kph:%s, max_kph:%s, min_alt_meters:%s, max_alt_meters:%s };",
this.summary_stats.length,
ss.n,
(ss.dist_meters / 1000.0).toFixed(2),
(ss.time_ss / 360.0).toFixed(2),
ss.mean_usvh.toFixed(2),
ss.de_usv.toFixed(2),
ss.min_usvh.toFixed(2),
ss.max_usvh.toFixed(2),
ss.min_kph.toFixed(0),
ss.max_kph.toFixed(0),
ss.min_alt_meters.toFixed(0),
ss.max_alt_meters.toFixed(0));
}//else if
else if ("DEBUG_MSG")
{
console.log("WWM: Worker: %s", e.data.txt);
}//else if
else
{
console.log("WWM: Message from worker: unknown. op:[%s]", e.data.op);
}
}.bind(this);
};
var _sve = function(s,o,n) { var e=0;for(var i=o;i<o+n;i++)e+=s[i];return e; };
//var _vfill = function(x,d,n) { for(var i=0;i<n;i++)d[i]=x; }; // unused
return WWM;
})();
// XF: Data transfer task.
// Represents an instance of an object controlled by XFM, used for querying the API or downloading data.
var XF = (function()
{
function XF(xfId, tagId, ordinal, url, fxCallback, userData, xfTitle, xfType, responseType, XFM_progress)
{
this.xfId = xfId;
this.ordinal = ordinal;
this.url = url;
this.bytes = 0;
this.bytes_max = 0;
this.fxCallback = fxCallback;
this.userData = userData;
this.xfTitle = xfTitle + (xfType == XF.TypeLog ? " " + tagId : "");
this.xfType = xfType;
this.done = false;
this.error = false;
this.callbackDone = false;
this.tagId = tagId;
this.responseType = responseType; //"arraybuffer", "blob", "document", "json", and "text"
this.time_started = new Date();
this.time_done = null;
this.XFM_progress = XFM_progress;
this.statusText = "Connecting";
this._last_pct = 0.0;
this.isStarted = false;
this.isStartParsing = false;
this.isDoneParsing = false;
this.isDoneAssignZ = false;
}//XF
XF.prototype.SetSuccess = function()
{
this.callbackDone = true;
this.time_done = new Date();
this.XFM_progress(this);
};
// 0 unsent, 1 open, 2 connected, 3 transfer, 4 done
XF.prototype.HttpEventReadyStateChange = function(response, readyState, status)
{
var old_bytes = this.bytes;
var rlen = response == null ? 0 : this.responseType == "arraybuffer" ? response.byteLength : response.length;
if (rlen > this.bytes) this.bytes = rlen;
if (readyState === 4 && status == 200)
{
this.done = true;
this.statusText = "Done";
this.XFM_progress(this);
this.fxCallback(response, this.userData);
this.fxCallback = null;
this.userData = null;
if (this.xfType != XF.TypeLog)
{
this.SetSuccess();
}//if
}//if
else if (readyState === 4 && status != 200)
{
this.statusText = "Error";
this.done = true;
this.error = true;
this.fxCallback = null;
this.userData = null;
this.time_done = new Date();
this.XFM_progress(this);
}//else if
else if (old_bytes != this.bytes)
{
var pct = parseFloat(this.bytes) / parseFloat(this.bytes_max);
if (pct > this._last_pct * 1.01)
{
this.XFM_progress(this);
}//if
this._last_pct = pct;
}//else if
};
XF.prototype.HttpEventProgress = function(evt)
{
if (evt.lengthComputable && this.bytes_max == 0)
{
this.bytes_max = evt.total;
this.statusText = "Downloading";
}//if
if (evt.loaded > this.bytes)
{
this.bytes = evt.loaded;
var pct = parseFloat(this.bytes) / parseFloat(this.bytes_max);
if (pct > this._last_pct * 1.01)
{
this.XFM_progress(this);
}//if
this._last_pct = pct;
}//if
};
XF.prototype.HttpEventError = function(evt, eventName) // "error", "abort"
{
this.statusText = eventName == "error" ? "Error" : "Aborted";
this.done = true;
this.error = true;
this.fxCallback = null;
this.userData = null;
this.time_done = new Date();
this.XFM_progress(this);
};
XF.prototype.HttpGet = function()
{
this.isStarted = true;