-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathksaSurfaceOps.js
2028 lines (1759 loc) · 88.3 KB
/
ksaSurfaceOps.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
// refactor complete
function initializeMap() {
// create the map with some custom options
// details on Leaflet API can be found here - http://leafletjs.com/reference.html
ops.surface.map = new L.Map('map', {
crs: L.CRS.Kerbin.Equirectangular,
center: [0,0],
bodyControl: false,
layersControl: false,
scaleControl: true,
minZoom: 0,
maxZoom: 5,
zoom: 2,
maxBounds: [[-95,-190], [95,190]],
maxBoundsViscosity: 0.5,
closePopupOnClick: false,
fullscreenControl: true,
fullscreenControlOptions: {
position: 'topleft'
},
contextmenu: true,
contextmenuItems: [{
text: 'Copy Coordinates',
callback: coordCopy
}]
});
// define the icons for the various layer markers and events
flagIcon = L.icon({
iconUrl: 'button_vessel_flag.png',
iconSize: [16, 16],
iconAnchor: [6,21]
});
POIIcon = L.icon({
popupAnchor: [0, -43],
iconUrl: 'poi.png',
iconSize: [30, 40],
iconAnchor: [15, 40],
shadowUrl: 'markers-shadow.png',
shadowSize: [35, 16],
shadowAnchor: [10, 12]
});
anomalyIcon = L.icon({
popupAnchor: [0, -43],
iconUrl: 'anomaly.png',
iconSize: [30, 40],
iconAnchor: [15, 40],
shadowUrl: 'markers-shadow.png',
shadowSize: [35, 16],
shadowAnchor: [10, 12]
});
airportIcon = L.icon({
popupAnchor: [0, -43],
iconUrl: 'airport.png',
iconSize: [30, 40],
iconAnchor: [15, 40],
shadowUrl: 'markers-shadow.png',
shadowSize: [35, 16],
shadowAnchor: [10, 12]
});
omniIcon = L.icon({
popupAnchor: [0, -43],
iconUrl: 'pinOmni.png',
iconSize: [30, 40],
iconAnchor: [15, 40],
shadowUrl: 'markers-shadow.png',
shadowSize: [35, 16],
shadowAnchor: [10, 12]
});
dishIcon = L.icon({
popupAnchor: [0, -43],
iconUrl: 'pinDish.png',
iconSize: [30, 40],
iconAnchor: [15, 40],
shadowUrl: 'markers-shadow.png',
shadowSize: [35, 16],
shadowAnchor: [10, 12]
});
labelIcon = L.icon({
iconUrl: 'label.png',
iconSize: [10, 10],
});
sunIcon = L.icon({
iconUrl: 'sun.png',
iconSize: [16, 16],
iconAnchor: [8, 8]
});
apIcon = L.icon({
iconUrl: 'ap.png',
iconSize: [16, 16],
iconAnchor: [8, 18],
popupAnchor: [0, -4]
});
peIcon = L.icon({
iconUrl: 'pe.png',
iconSize: [16, 16],
iconAnchor: [8, 18],
popupAnchor: [0, -4]
});
soiExitIcon = L.icon({
iconUrl: 'soiexit.png',
iconSize: [16, 12],
iconAnchor: [9, 6]
});
soiEntryIcon = L.icon({
iconUrl: 'soientry.png',
iconSize: [16, 12],
iconAnchor: [9, 6]
});
nodeIcon = L.icon({
iconUrl: 'node.png',
iconSize: [16, 16],
iconAnchor: [8, 8]
});
// do not allow the user to close or resize the map when it is in fullscreen
ops.surface.map.on('enterFullscreen', function() {
if (mapCloseButton) mapCloseButton.disable();
if (mapResizeButton) mapResizeButton.disable();
isMapFullscreen = true;
});
ops.surface.map.on('exitFullscreen', function() {
if (mapCloseButton) mapCloseButton.enable();
if (mapResizeButton) mapResizeButton.enable();
isMapFullscreen = false;
});
// show controls only when the cursor is over the map, unless this is a touch device
if (!is_touch_device()) {
ops.surface.map.on('mouseover', function(e) {
$(".leaflet-top").fadeIn();
$(".leaflet-bottom.leaflet-left").fadeIn();
});
ops.surface.map.on('mouseout', function(e) {
$(".leaflet-top").fadeOut();
$(".leaflet-bottom.leaflet-left").fadeOut();
});
ops.surface.map.on('mousemove', function(e) {
// if we are still loading data, do not let the layer control collapse
if (ops.surface.layerControl && !ops.surface.layerControl.options.collapsed) ops.surface.layerControl._expand();
});
}
// extend the measurement control to allow the user to see the position of all the points they placed
var Ruler = L.Control.LinearMeasurement.extend({
layerSelected: function(e) {
var html = '<b>Selected Points:</b><p>';
e.points.forEach(function(latlng, index) {
if (index == 0) {
html += latlng[0].lat + "," + latlng[0].lng + "<br>";
html += latlng[1].lat + "," + latlng[1].lng + "<br>";
} else {
html += latlng[1].lat + "," + latlng[1].lng;
if (index < e.points.length-1) html += "<br>";
}
});
html += "</p>";
e.total_label.bindPopup(L.popup().setContent(html), { offset: [45, 0] });
e.total_label.openPopup();
}
});
ops.surface.map.addControl(new Ruler({
unitSystem: 'metric',
color: '#FFD800',
show_azimut: true,
show_last_node: true,
contrastingColor: '#FFD800'
}));
// add a coordinates control
L.control.mousePosition().addTo(ops.surface.map);
// add a scale control
L.control.scale().addTo(ops.surface.map);
// no idea why but doing this makes it work better for when loading straight to the map in the body view
setTimeout(function() {
if (ops.pageType != "vessel") {
$("#map").css("height", "885px");
ops.surface.map.invalidateSize();
}
}, 150);
}
function loadMap(map) {
// add a new layer control to let ppl know data is being loaded
if (ops.surface.layerControl) ops.surface.map.removeControl(ops.surface.layerControl);
ops.surface.layerControl = L.control.groupedLayers().addTo(ops.surface.map);
ops.surface.layerControl.addOverlay(L.layerGroup(), "<i class='fa fa-cog fa-spin'></i> Loading Data...");
ops.surface.layerControl._expand();
ops.surface.layerControl.options.collapsed = false;
// call up the map data to load
loadDB("loadMapData.asp?map=" + map + "&UT=" + currUT(), loadMapDataAJAX);
ops.surface.isLoading = true;
}
function loadMapDataAJAX(xhttp) {
ops.surface.isLoading = false;
// could be nothing to load, so just exit
if (xhttp.responseText == "null") {
ops.surface.Data = null;
return;
}
// parse out the data
var data = xhttp.responseText.split("^");
// assign the map data
ops.surface.Data = rsToObj(data[0]);
if (data[1] != "null") ops.updatesList.push({ type: "map",
id: ops.bodyCatalog.find(o => o.selected === true).Body,
UT: parseFloat(data[1]) });
// remove the previous control and load the base layer
if (ops.surface.layerControl) ops.surface.map.removeControl(ops.surface.layerControl);
ops.surface.layerControl = L.control.groupedLayers().addTo(ops.surface.map);
if (ops.surface.Data.Aerial) { var strSatLabel = "Aerial"; }
if (ops.surface.Data.Satellite) { var strSatLabel = "Satellite"; }
ops.surface.layerControl.addBaseLayer(
L.tileLayer.kerbalMaps({
body: ops.bodyCatalog.find(o => o.selected === true).Body.toLowerCase(),
style: "sat"
}
).addTo(ops.surface.map), strSatLabel);
// show the entire control until everything is finished loading
ops.surface.layerControl._expand();
ops.surface.layerControl.options.collapsed = false;
// load the rest of the tile layers, where available
if (ops.surface.Data.Slope) {
var slopeBase = L.tileLayer.kerbalMaps({
body: ops.bodyCatalog.find(o => o.selected === true).Body.toLowerCase(),
style: "slope"
}
);
ops.surface.layerControl.addBaseLayer(slopeBase, "Slope");
}
if (ops.surface.Data.Terrain) {
var reliefBase = L.tileLayer.kerbalMaps({
body: ops.bodyCatalog.find(o => o.selected === true).Body.toLowerCase(),
style: "color"
}
);
ops.surface.layerControl.addBaseLayer(reliefBase, "Color Relief");
}
if (ops.surface.Data.Biome) {
var biomeBase = L.tileLayer.kerbalMaps({
body: ops.bodyCatalog.find(o => o.selected === true).Body.toLowerCase(),
style: "biome"
}
);
ops.surface.layerControl.addBaseLayer(biomeBase, "Biome");
}
// place any and all flags
if (ops.surface.Data.Flags) {
var flagData = ops.surface.Data.Flags.split("|");
var flagMarker;
var layerFlags = L.layerGroup();
flagData.forEach(function(item) {
var flag = item.split(";");
flagMarker = L.marker([flag[0],flag[1]], { icon: flagIcon, zIndexOffset: 100 });
if (flag[4] = 'null') var strCrew = "";
else var strCrew = flag[4] + "<br />";
if (flag[8] = 'null') var strLink = "<span class='fauxLink' onclick=\"swapContent('vessel','" + flag[7] + "')\">View Vessel</span>";
else var strLink = "<a target='_blank' href='" + flag[7] + "'>" + flag[8] + "</a>";
if (flag[2] != "0") var strAlt = numeral(flag[2]/1000).format('0.000') + "km<br />";
else var strAlt = "";
flagMarker.bindPopup("<b>" + flag[3] + "</b><br />" + strCrew + UTtoDateTime(parseInt(flag[6])).split(" ")[0] + "<br />" + strAlt + "<br />"" + flag[5] + ""<br /><br />" + strLink, { offset: new L.Point(0,-9), autoClose: false });
layerFlags.addLayer(flagMarker);
// set the id to make the map click function ignore this popup and add it to the map
flagMarker._myId = -1;
});
// add the layer to the map and if it is asked for in the URL variable show it immediately
ops.surface.layerControl.addOverlay(layerFlags, "<img src='button_vessel_flag.png' style='width: 10px; vertical-align: 1px;'> Flags", "Ground Markers");
if (getParameterByName("layers").includes("flag")) layerFlags.addTo(ops.surface.map);
}
// place any and all points of interest
if (ops.surface.Data.POI) {
var POIData = ops.surface.Data.POI.split("|");
var POIMarker;
var layerPOI = L.layerGroup();
POIData.forEach(function(item) {
var POI = item.split(";");
POIMarker = L.marker([POI[0],POI[1]], { icon: POIIcon, zIndexOffset: 100 });
strHTML = "<b>" + POI[3] + "</b><br>" + numeral(POI[2]/1000).format('0.000') + " km";
if (POI[4] != "null") strHTML += "<p>" + POI[4] + "</p>";
POIMarker.bindPopup(strHTML, { autoClose: false });
layerPOI.addLayer(POIMarker);
POIMarker._myId = -1;
});
ops.surface.layerControl.addOverlay(layerPOI, "<img src='poi.png' style='width: 10px; vertical-align: 1px;'> Points of Interest", "Ground Markers");
if (getParameterByName("layers").includes("poi") || getParameterByName("layers").includes("interest")) {
layerPOI.addTo(ops.surface.map);
}
}
// place any and all anomalies
if (ops.surface.Data.Anomalies) {
var anomalyData = ops.surface.Data.Anomalies.split("|");
var anomalyMarker;
var layerAnomalies = L.layerGroup();
anomalyData.forEach(function(item) {
var anomaly = item.split(";");
anomalyMarker = L.marker([anomaly[0],anomaly[1]], { icon: anomalyIcon, zIndexOffset: 100 });
strHTML = "<b>";
if (anomaly[3] != "null") strHTML += anomaly[3];
else strHTML += "Unknown Anomaly";
strHTML += "</b><br>" + numeral(anomaly[2]/1000).format('0.000') + " km";
anomalyMarker.bindPopup(strHTML, { autoClose: false });
layerAnomalies.addLayer(anomalyMarker);
anomalyMarker._myId = -1;
});
ops.surface.layerControl.addOverlay(layerAnomalies, "<img src='anomaly.png' style='width: 10px; vertical-align: 1px;'> Anomalies", "Ground Markers");
if (getParameterByName("layers").includes("anom"))layerAnomalies.addTo(ops.surface.map);
}
// place any and all airports
if (ops.surface.Data.Airports) {
var aptData = ops.surface.Data.Airports.split("|");
var aptMarker;
var layerAirports = L.layerGroup();
aptData.forEach(function(item) {
var airport = item.split(";");
aptMarker = L.marker([airport[0],airport[1]], { icon: airportIcon, zIndexOffset: 100 });
strHTML = "<b>";
strHTML += airport[3];
strHTML += "</b><br>Altitude: " + numeral(airport[2]/1000).format('0.000') + " km";
aptMarker.bindPopup(strHTML, { autoClose: false });
layerAirports.addLayer(aptMarker);
aptMarker._myId = -1;
});
ops.surface.layerControl.addOverlay(layerAirports, "<img src='airport.png' style='width: 10px; vertical-align: 1px;'> Airports", "Ground Markers");
if (getParameterByName("layers").includes("apt") || getParameterByName("layers").includes("airport")) {
layerAirports.addTo(ops.surface.map);
}
}
// place any and all ground stations
if (ops.surface.Data.GroundStations) {
var grndData = ops.surface.Data.GroundStations.split("|");
var grndMarker;
var layerGrndStn = L.layerGroup();
grndData.forEach(function(item) {
var station = item.split(";");
if (station[4] == "0") grndMarker = L.marker([station[0],station[1]], { icon: dishIcon, zIndexOffset: 100 });
else grndMarker = L.marker([station[0],station[1]], { icon: omniIcon, zIndexOffset: 100 });
strHTML = "<b>";
strHTML += station[3];
strHTML += "</b><br>Altitude: " + numeral(station[2]/1000).format('0.000') + " km";
if (station[4] == "0") strHTML += "<br>Range: Entire Kerbin System";
else strHTML += "<br>Range: " + numeral(station[4]/1000).format('0.000') + " km";
grndMarker.bindPopup(strHTML, { autoClose: false });
layerGrndStn.addLayer(grndMarker);
grndMarker._myId = station[4];
});
ops.surface.layerControl.addOverlay(layerGrndStn, "<img src='pinGrndStation.png' style='width: 10px; vertical-align: 1px;'> Ground Stations", "Ground Markers");
if (getParameterByName("layers").includes("ground") || getParameterByName("layers").includes("grnd") || getParameterByName("layers").includes("station")) {
layerGrndStn.addTo(ops.surface.map);
}
}
// place any and all labels
if (ops.surface.Data.Labels) {
var labelData = ops.surface.Data.Labels.split("|");
var labelMarker;
var layerLabels = L.layerGroup();
labelData.forEach(function(item) {
var label = item.split(";");
labelMarker = L.marker([label[0],label[1]], { icon: labelIcon, zIndexOffset: 100 }).bindTooltip(label[2], { direction: 'top', offset: [0,-10] });
layerLabels.addLayer(labelMarker);
labelMarker._myId = -1;
// zoom the map all the way in and center on this marker when clicked
labelMarker.on('click', function(e) { ops.surface.map.setView(e.target.getLatLng(), 5); });
});
ops.surface.layerControl.addOverlay(layerLabels, "<img src='label.png' style='vertical-align: 1px;'> Labels", "Ground Markers");
if (getParameterByName("layers").includes("label") || getParameterByName("layers").includes("lbl")) {
layerLabels.addTo(ops.surface.map);
}
}
// if this is a different map than any orbit data already loaded, dump the other data
if (bodyPaths.bodyName && bodyPaths.bodyName != ops.surface.Data.Name) {
bodyPaths.bodyName = ops.surface.Data.Name;
// TODO - have to remove any layers that have already been created
} else if (!bodyPaths.bodyName) bodyPaths.bodyName = ops.surface.Data.Name;
// load surface track data for any vessels and moons in orbit around this body
// this is dependent on ops catalog data so needs to be in its own function
loadSurfaceTracks();
// the following only works for Kerbin at the moment
if (ops.surface.Data.Name == "Kerbin") {
// determine the current position of the sun given the body's degree of initial rotation and rotational period
var sunLon = -ops.bodyCatalog.find(o => o.selected === true).RotIni - (((currUT() / ops.bodyCatalog.find(o => o.selected === true).SolarDay) % 1) * 360);
var sunLat = 0
if (sunLon < -180) sunLon += 360;
// place the sun marker
sunMarker = L.marker([sunLat,sunLon], { icon: sunIcon, clickable: false });
layerSolar.addLayer(sunMarker);
// add to the layer selection control
ops.surface.layerControl.addOverlay(layerSolar, "<i class='fas fa-sun' style='color: #FFD800'></i> Sun/Terminator", "Ground Markers");
if (getParameterByName("layers").includes("sun") || getParameterByName("layers").includes("terminator")) {
layerSolar.addTo(ops.surface.map);
}
}
// hide map controls after 3 seconds if the user cursor isn't over the map (or dialog) at that time
// unless this is a touchscreen device
if (!is_touch_device()) {
setTimeout(function() {
if (!$('#map').is(":hover")) {
$(".leaflet-top").fadeOut();
$(".leaflet-bottom.leaflet-left").fadeOut();
}
}, 3000);
}
// load straight to a map location?
if (getParameterByName("center")) {
var mapLocation = getParameterByName("center").split(",");
ops.surface.map.setView([mapLocation[0], mapLocation[1]], 3);
if (ops.pageType == "body") showMap();
}
// load map pin(s) and caption(s)?
if (getParameterByName("loc")) {
layerPins = L.featureGroup();
var isMultiple = false;
var pin;
// get all pin locations and iterate through them
getQueryParams("loc").forEach(function(item, index) {
if (index > 0) isMultiple = true;
mapLocation = item.split(",");
// make a pin clickable only if it has a caption, not just a location
if (mapLocation.length > 2) {
pin = L.marker([mapLocation[0], mapLocation[1]]).bindPopup(mapLocation[2], { autoClose: false });
} else {
pin = L.marker([mapLocation[0], mapLocation[1]], { clickable: false });
}
layerPins.addLayer(pin);
pin._myId = -1;
});
// place the pins and size the map to show them all
layerPins.addTo(ops.surface.map);
ops.surface.layerControl.addOverlay(layerPins, "<img src='defPin.png' style='width: 10px; height: 14px; vertical-align: 1px;'> Custom Pins", "Ground Markers");
ops.surface.map.fitBounds(layerPins.getBounds());
// if only one marker was placed, open its popup
if (!isMultiple) pin.openPopup();
if (ops.pageType == "body") showMap();
}
// load flight paths, taking into account they may already be loaded
if (getParameterByName("flt") && ops.pageType == "body") {
flightsToLoad = getQueryParams("flt");
do {
var flight = flightsToLoad.shift();
if (!fltPaths || (fltPaths && !fltPaths.find(o => o.id === flight))) {
surfaceTracksDataLoad.fltTrackDataLoad = L.layerGroup();
ops.surface.layerControl._expand();
ops.surface.layerControl.options.collapsed = false;
ops.surface.layerControl.addOverlay(surfaceTracksDataLoad.fltTrackDataLoad, "<i class='fa fa-cog fa-spin'></i> Loading Data...", "Flight Tracks");
loadDB("loadFltData.asp?data=" + flight, loadFltDataAJAX);
break;
}
} while (flightsToLoad.length);
showMap();
}
// load straight to a map?
// Note that &map is required ONLY when viewing a body page if you want to show the map straight away without using any other commands
if ((window.location.href.includes("&map") || getParameterByName("layers")) && ops.pageType == "body") showMap();
// done with data load?
checkDataLoad();
}
function loadFltDataAJAX(xhttp) {
// split and parse the flight data
var fltInfo = rsToObj(xhttp.responseText.split("^")[0]);
var fltData = [];
xhttp.responseText.split("^")[1].split("|").forEach(function(item) { fltData.push(rsToObj(item)); });
// make sure we don't overstep bounds on the color index
if (fltPaths.length >= surfacePathColors.length) var colorIndex = fltPaths.length - (surfacePathColors.length * (Math.floor(fltPaths.length/surfacePathColors.length)));
else var colorIndex = fltPaths.length;
fltPaths.push({ info: fltInfo,
fltData: fltData,
layer: L.featureGroup(),
pins: [],
html: null,
id: xhttp.responseText.split("^")[2],
deleted: false,
elev: false,
color: surfacePathColors[colorIndex],
index: fltPaths.length
});
// make sure that if a layer is hidden the current popup is too if that belongs to the layer
fltPaths[fltPaths.length-1].layer._myId = fltPaths[fltPaths.length-1].info.Title;
fltPaths[fltPaths.length-1].layer.on('remove', function(e) {
if (flightPositionPopup.getContent() && flightPositionPopup.getContent().includes(e.target._myId)) ops.surface.map.closePopup(flightPositionPopup);
});
// draw the ground track
renderFltPath(fltPaths.length-1);
// delete the loading layer and add the flight path layer to the control and the map
ops.surface.layerControl.removeLayer(surfaceTracksDataLoad.fltTrackDataLoad);
ops.surface.layerControl.addOverlay(fltPaths[fltPaths.length-1].layer, "<i class='fa fa-minus' style='color: " + fltPaths[fltPaths.length-1].color + "'></i> " + fltPaths[fltPaths.length-1].info.Title, "Flight Tracks");
fltPaths[fltPaths.length-1].layer.addTo(ops.surface.map)
// get more flight data?
if (flightsToLoad) {
if (flightsToLoad.length) {
surfaceTracksDataLoad.fltTrackDataLoad = L.layerGroup();
ops.surface.layerControl.addOverlay(surfaceTracksDataLoad.fltTrackDataLoad, "<i class='fa fa-cog fa-spin'></i> Loading Data...", "Flight Tracks");
loadDB("loadFltData.asp?data=" + flightsToLoad.shift(), loadFltDataAJAX);
// done with data load?
} else {
surfaceTracksDataLoad.fltTrackDataLoad = null;
flightsToLoad = null;
checkDataLoad();
// if there was only one track...
if (fltPaths.length == 1) {
// select it in the menu
selectMenuItem(fltPaths[0].id);
// check for in-progress flight
if (!inFlight(fltPaths[0])) {
// if there are more than two layers the plot wraps around the meridian so just show the whole map
// otherwise zoom in to fit the size of the plot
// https://stackoverflow.com/questions/5223/length-of-a-javascript-object
if (Object.keys(fltPaths[0].layer._layers).length > 1) ops.surface.map.setView([0,0], 1);
else ops.surface.map.fitBounds(Object.values(fltPaths[0].layer._layers)[0]._bounds);
}
// multiple tracks...
} else {
// just select and open the category
w2ui['menu'].select("aircraft");
w2ui['menu'].expand("aircraft");
w2ui['menu'].expandParents("aircraft");
w2ui['menu'].scrollIntoView("aircraft");
// get the combined bounds of all the plots
var isDblPlotted = false;
var groupBounds = null;
fltPaths.forEach(function(item) {
// if there are more than two layers the plot wraps around the meridian
if (Object.keys(item.layer._layers).length > 1) isDblPlotted = true;
else {
if (!groupBounds) groupBounds = Object.values(item.layer._layers)[0]._bounds;
else groupBounds.extend(Object.values(item.layer._layers)[0]._bounds);
}
});
// if there is a double plot, just show the whole map otherwise fit the bounds
if (isDblPlotted) ops.surface.map.setView([0,0], 1);
else ops.surface.map.fitBounds(groupBounds);
}
}
} else {
// check for in-progress flight
if (!inFlight(fltPaths[fltPaths.length-1])) {
// zoom out to the full map if the new plot jumps the meridian otherwise fit its bounds
if (Object.keys(fltPaths[fltPaths.length-1].layer._layers).length > 1) ops.surface.map.setView([0,0], 1);
else ops.surface.map.fitBounds(Object.values(fltPaths[fltPaths.length-1].layer._layers)[0]._bounds);
}
surfaceTracksDataLoad.fltTrackDataLoad = null;
checkDataLoad();
}
if (strFltTrackLoading) strFltTrackLoading = null;
showMap();
}
function renderMapData() {
if (!ops.currentVesselPlot) {
ops.currentVesselPlot = {
obtData: [],
events: {
pe: { marker: null, UT: null },
ap: { marker: null, UT: null },
soiEntry: { marker: null },
soiExit: { marker: null },
node: { marker: null}
},
id: ops.currentVessel.Catalog.DB,
eph: ops.currentVessel.Orbit.Eph
};
}
// check if we need to wait for the vessel to finish loading or if we need to wait for the base map layers to finish loading
// or if we have to wait for the GGB to finish loading or if we need to wait for the content area to stop moving
if ((!ops.currentVessel && ops.pageType == "vessel") ||
(ops.surface.layerControl && !ops.surface.layerControl.options.collapsed) ||
!isGGBAppletLoaded || isContentMoving) return setTimeout(renderMapData, 150);
// close the dialog in case it was left open from another vessel
$("#mapDialog").dialog("close");
// don't let this proceed if there is no orbital data!
if (!ops.currentVessel.Orbit.Eph) return;
// check for any SOI events that may have already occured
if (ops.currentVessel.Orbit.SOIEvent && parseInt(ops.currentVessel.Orbit.SOIEvent.split(";")[0]) <= currUT()) {
var latlng = { lat: parseFloat(ops.currentVessel.Orbit.SOIEvent.split(";")[3]),
lng: parseFloat(ops.currentVessel.Orbit.SOIEvent.split(";")[4]) };
if (ops.currentVessel.Orbit.SOIEvent.split(";")[1] == "entry") {
ops.currentVesselPlot.events.soiEntry.marker = L.marker([latlng.lat, latlng.lng], { icon: soiEntryIcon }).addTo(ops.surface.map);
ops.currentVesselPlot.events.soiEntry.marker.bindPopup("<center>" + UTtoDateTime(parseInt(ops.currentVessel.Orbit.SOIEvent.split(";")[0])).split("@")[1] + " UTC <br>Telemetry data invalid due to " + ops.currentVessel.Orbit.SOIEvent.split(";")[2] + "<br>Please stand by for update</center>", { autoClose: false });
ops.surface.map.setView(ops.currentVesselPlot.events.soiEntry.marker.getLatLng(), 3);
ops.currentVesselPlot.events.soiEntry.marker.openPopup();
} else if (ops.currentVessel.Orbit.SOIEvent.split(";")[1] == "exit") {
ops.currentVesselPlot.events.soiExit.marker = L.marker([latlng.lat, latlng.lng], { icon: soiExitIcon }).addTo(ops.surface.map);
ops.currentVesselPlot.events.soiExit.marker.bindPopup("<center>" + UTtoDateTime(parseInt(ops.currentVessel.Orbit.SOIEvent.split(";")[0])).split("@")[1] + " UTC <br>Telemetry data invalid due to " + ops.currentVessel.Orbit.SOIEvent.split(";")[2] + "<br>Please stand by for update</center>", { autoClose: false });
ops.surface.map.setView(ops.currentVesselPlot.events.soiExit.marker.getLatLng(), 3);
ops.currentVesselPlot.events.soiExit.marker.openPopup();
}
// if there is a paused calculation we are returning to, then just resume calling the orbital batch
} else if (ops.currentVessel && strPausedVesselCalculation == ops.currentVessel.Catalog.DB) {
// first re-show the progress dialog and reset the load state of the map
$("#mapDialog").dialog("open");
ops.surface.layerControl._expand();
ops.surface.layerControl.options.collapsed = false;
surfaceTracksDataLoad.obtTrackDataLoad = L.layerGroup();
ops.surface.layerControl.addOverlay(surfaceTracksDataLoad.obtTrackDataLoad, "<i class='fa fa-cog fa-spin'></i> Loading Data...", "Orbital Tracks");
strPausedVesselCalculation = null;
isOrbitRenderTerminated = false;
orbitalCalc(renderVesselOrbit, ops.currentVessel.Orbit);
// otherwise we need to calculate surface tracks for a single vessel
} else if (ops.pageType == "vessel") {
// if a current orbit happens to be under calculation at this time, cancel it
if (!ops.surface.layerControl.options.collapsed) {
if (surfaceTracksDataLoad.obtTrackDataLoad) ops.surface.layerControl.removeLayer(surfaceTracksDataLoad.obtTrackDataLoad);
surfaceTracksDataLoad.obtTrackDataLoad = null;
isOrbitRenderTerminated = true;
ops.surface.layerControl.options.collapsed = true;
}
clearSurfacePlots();
strPausedVesselCalculation = null;
// if 3 orbits are longer than 100,000s we need to inform the user that this could take a while
if ((ops.currentVessel.Orbit.OrbitalPeriod * 3) > 100000) {
$("#mapDialog").dialog( "option", "buttons", [{
text: "Render Single Orbit",
click: function() {
beginOrbitalCalc(1);
}
},{
text: "Render All Orbits",
click: function() {
beginOrbitalCalc();
}
}]);
$("#mapDialog").dialog( "option", "title", "Calculation Notice");
$("#dialogTxt").html("Calculating 3 orbits for this vessel could take a long time, but you can also cancel at any time and show what has been done up to that point if you wish");
$("#dialogTxt").fadeIn();
$("#progressbar").hide();
// gives time for any map buttons to hide
mapDialogDelay = setTimeout(function() {
$("#mapDialog").dialog("open");
mapDialogDelay = null;
}, 1000);
// render out the default 3 orbits for this vessel
} else beginOrbitalCalc();
// this is not a vessel with any orbital data
} else {
}
}
// does the initial display and configuration for vessel orbital data loading
function beginOrbitalCalc(numOrbitRenders = 3) {
if (ops.currentVesselPlot) ops.currentVesselPlot.obtData.length = 0;
ops.currentVesselPlot = {
obtData: [],
events: {
pe: { marker: null, UT: null },
ap: { marker: null, UT: null },
soiEntry: { marker: null },
soiExit: { marker: null },
node: { marker: null}
},
id: ops.currentVessel.Catalog.DB,
eph: ops.currentVessel.Orbit.Eph
};
isOrbitRenderCancelled = false;
isOrbitRenderTerminated = false;
$("#mapDialog").dialog( "option", "title", "Calculating Orbit #1 of " + numOrbitRenders);
$("#mapDialog").dialog( "option", "buttons", [{
text: "Cancel and Display",
click: function() {
isOrbitRenderCancelled = true;
}
}]);
$(".ui-progressbar-value").css("background-color", vesselOrbitColors[ops.currentVesselPlot.obtData.length]);
$("#dialogTxt").hide();
$("#progressbar").progressbar("value", 0);
$("#progressbar").fadeIn();
$("#mapDialog").dialog("open");
ops.surface.layerControl._expand();
ops.surface.layerControl.options.collapsed = false;
surfaceTracksDataLoad.obtTrackDataLoad = L.layerGroup();
ops.surface.layerControl.addOverlay(surfaceTracksDataLoad.obtTrackDataLoad, "<i class='fa fa-cog fa-spin'></i> Loading Data...", "Orbital Tracks");
// set the current UT from which the orbital data will be propagated forward
obtCalcUT = currUT();
orbitDataCalc.length = 0;
orbitalCalc(renderVesselOrbit, ops.currentVessel.Orbit, numOrbitRenders);
}
// draws the entire path of a vessel over a single or multiple orbits
function renderVesselOrbit(numOrbitRenders) {
// we have completed a batch of calculations, store the data
ops.currentVesselPlot.obtData.push({
orbit: orbitDataCalc.slice(0),
layer: L.featureGroup(),
startUT: obtCalcUT-orbitDataCalc.length,
endUT: obtCalcUT
});
// get the times we'll reach Ap and Pe along this orbit if we haven't already done so
if (!ops.currentVesselPlot.events.ap.marker || !ops.currentVesselPlot.events.pe.marker) {
var n = Math.sqrt(ops.bodyCatalog.find(o => o.selected === true).Gm/(Math.pow(Math.abs(ops.currentVessel.Orbit.SMA),3)));
var newMean = toMeanAnomaly(Math.radians(ops.currentVessel.Orbit.TrueAnom), ops.currentVessel.Orbit.Eccentricity) + n * ((obtCalcUT-orbitDataCalc.length) - ops.currentVessel.Orbit.Eph);
if (newMean < 0 || newMean > 2*Math.PI) {
newMean = Math.abs(newMean - (2*Math.PI) * Math.floor(newMean / (2*Math.PI)));
}
var apTime = Math.round((Math.PI - newMean)/n);
var peTime = Math.round((Math.PI*2 - newMean)/n);
// close to Ap/Pe we can get a negative value, so handle that by just adding the period
if (apTime <= 0) apTime += Math.round(ops.currentVessel.Orbit.OrbitalPeriod);
if (peTime <= 0) peTime += Math.round(ops.currentVessel.Orbit.OrbitalPeriod);
// stash away the times but convert them to UT instead of seconds from the start of this orbit
ops.currentVesselPlot.events.pe.UT = peTime + (obtCalcUT-orbitDataCalc.length);
ops.currentVesselPlot.events.ap.UT = apTime + (obtCalcUT-orbitDataCalc.length);
// configure the Ap/Pe icons, ensuring that enough orbit has been plotted to display them
if (!ops.currentVesselPlot.events.ap.marker && apTime < orbitDataCalc.length) {
// add the marker, assign its information popup and give it a callback for instant update when opened, then add it to the current layer
ops.currentVesselPlot.events.ap.marker = L.marker(orbitDataCalc[apTime].latlng, {icon: apIcon});
var strTimeDate = UTtoDateTime(obtCalcUT-orbitDataCalc.length + apTime);
ops.currentVesselPlot.events.ap.marker.bindPopup("<center>Time to Apoapsis<br><span id='apTime'>" + formatTime(apTime) + "</span><br><span id='apDate'>" + strTimeDate.split("@")[0] + '<br>' + strTimeDate.split("@")[1] + "</span> UTC</center>", { autoClose: false });
ops.currentVesselPlot.events.ap.marker.on('click', function(e) {
$('#apTime').html(formatTime(ops.currentVesselPlot.events.ap.UT - currUT()));
});
ops.currentVesselPlot.obtData[ops.currentVesselPlot.obtData.length-1].layer.addLayer(ops.currentVesselPlot.events.ap.marker);
}
if (!ops.currentVesselPlot.events.pe.marker && peTime < orbitDataCalc.length) {
ops.currentVesselPlot.events.pe.marker = L.marker(orbitDataCalc[peTime].latlng, {icon: peIcon});
var strTimeDate = UTtoDateTime(obtCalcUT-orbitDataCalc.length + peTime);
ops.currentVesselPlot.events.pe.marker.bindPopup("<center>Time to Periapsis<br><span id='peTime'>" + formatTime(peTime) + "</span><br><span id='peDate'>" + strTimeDate.split("@")[0] + '<br>' + strTimeDate.split("@")[1] + "</span> UTC</center>", { autoClose: false });
ops.currentVesselPlot.events.pe.marker.on('click', function(e) {
$('#peTime').html(formatTime(ops.currentVesselPlot.events.pe.UT - currUT()));
});
ops.currentVesselPlot.obtData[ops.currentVesselPlot.obtData.length-1].layer.addLayer(ops.currentVesselPlot.events.pe.marker);
}
}
// does this path terminate in an entry to Kerbin's atmosphere?
if (orbitDataCalc[orbitDataCalc.length-1].alt <= 70) {
// add the marker, assign its information popup and give it a callback for instant update when opened, then add it to the current layer
ops.currentVesselPlot.events.soiEntry.UT = obtCalcUT;
ops.currentVesselPlot.events.soiEntry.marker = L.marker(orbitDataCalc[orbitDataCalc.length-1].latlng, {icon: soiEntryIcon});
var strTimeDate = UTtoDateTime(ops.currentVesselPlot.events.soiEntry.UT);
ops.currentVesselPlot.events.soiEntry.marker.bindPopup("<center>Time to Atmospheric Entry<br><span id='soiEntryTime'>" + formatTime(ops.currentVesselPlot.events.soiEntry.UT) + "</span><br><span id='soiEntryDate'>" + strTimeDate.split("@")[0] + '<br>' + strTimeDate.split("@")[1] + "</span> UTC</center>", { autoClose: false });
ops.currentVesselPlot.events.soiEntry.marker.on('click', function(e) {
$('#soiEntryTime').html(formatTime(ops.currentVesselPlot.events.soiEntry.UT - currUT()));
});
ops.currentVesselPlot.obtData[ops.currentVesselPlot.obtData.length-1].layer.addLayer(ops.currentVesselPlot.events.soiEntry.marker);
}
// does this path terminate in an exit of Kerbin's SOI?
else if (orbitDataCalc[orbitDataCalc.length-1].alt >= 83559.2865) {
// add the marker, assign its information popup and give it a callback for instant update when opened, then add it to the current layer
ops.currentVesselPlot.events.soiExit.UT = obtCalcUT;
ops.currentVesselPlot.events.soiExit.marker = L.marker(orbitDataCalc[orbitDataCalc.length-1].latlng, {icon: soiExitIcon});
var strTimeDate = UTtoDateTime(ops.currentVesselPlot.events.soiExit.UT);
ops.currentVesselPlot.events.soiExit.marker.bindPopup("<center>Time to Kerbin SOI Exit<br><span id='soiExitTime'>" + formatTime(ops.currentVesselPlot.events.soiExit.UT) + "</span><br><span id='soiExitDate'>" + strTimeDate.split("@")[0] + '<br>' + strTimeDate.split("@")[1] + "</span> UTC</center>", { autoClose: false });
ops.currentVesselPlot.events.soiExit.marker.on('click', function(e) {
$('#soiExitTime').html(formatTime(ops.currentVesselPlot.events.soiExit.UT - currUT()));
});
ops.currentVesselPlot.obtData[ops.currentVesselPlot.obtData.length-1].layer.addLayer(ops.currentVesselPlot.events.soiExit.marker);
}
// gather up the lat/lng positions into the paths to render
var path = [];
ops.currentVesselPlot.obtData[ops.currentVesselPlot.obtData.length-1].orbit.forEach(function(position) {
// detect if we've crossed off the edge of the map and need to cut the orbital line
// compare this lng to the prev and if it changed from negative to positive or vice versa, we hit the edge
// (check if the lng is over 100 to prevent detecting a sign change while crossing the meridian)
if (path.length && (((position.latlng.lng < 0 && path[path.length-1].lng > 0) && Math.abs(position.latlng.lng) > 100) || ((position.latlng.lng > 0 && path[path.length-1].lng < 0) && Math.abs(position.latlng.lng) > 100))) {
// time to cut this path off and create a surface track to setup
// add this path to the layer and reset to start building a new path
ops.currentVesselPlot.obtData[ops.currentVesselPlot.obtData.length-1].layer.addLayer(setupVesselSurfacePath(path, ops.currentVesselPlot.obtData.length-1));
path.length = 0;
}
path.push(position.latlng);
});
// setup the final path stretch and add it to the layer
ops.currentVesselPlot.obtData[ops.currentVesselPlot.obtData.length-1].layer.addLayer(setupVesselSurfacePath(path, ops.currentVesselPlot.obtData.length-1));
// add the orbital layer to the control and the map
ops.surface.layerControl.addOverlay(ops.currentVesselPlot.obtData[ops.currentVesselPlot.obtData.length-1].layer, "<i class='fa fa-minus' style='color: " + vesselOrbitColors[ops.currentVesselPlot.obtData.length-1] + "'></i> Vessel Orbit #" + (ops.currentVesselPlot.obtData.length), "Orbital Tracks");
ops.currentVesselPlot.obtData[ops.currentVesselPlot.obtData.length-1].layer.addTo(ops.surface.map)
// delete and re-add the loading layer so it stays below the added paths
ops.surface.layerControl.removeLayer(surfaceTracksDataLoad.obtTrackDataLoad);
surfaceTracksDataLoad.obtTrackDataLoad = L.layerGroup();
ops.surface.layerControl.addOverlay(surfaceTracksDataLoad.obtTrackDataLoad, "<i class='fa fa-cog fa-spin'></i> Loading Data...", "Orbital Tracks");
// are there still more orbits to render? Don't continue if the rendering has been cancelled or there are SOI markers present
if (numOrbitRenders > ops.currentVesselPlot.obtData.length && !isOrbitRenderCancelled && (!ops.currentVesselPlot.events.soiExit.marker && !ops.currentVesselPlot.events.soiEntry.marker)) {
// update the dialog box and call another round
$(".ui-progressbar-value").css("background-color", vesselOrbitColors[ops.currentVesselPlot.obtData.length]);
$("#progressbar").progressbar("value", 0);
orbitDataCalc.length = 0;
orbitalCalc(renderVesselOrbit, ops.currentVessel.Orbit, numOrbitRenders);
// calculation has been completed or cancelled
} else {
// warn the user if they cancelled the calculations early before a full orbit was rendered
if (ops.currentVesselPlot.obtData[0].orbit.length < ops.currentVessel.Orbit.OrbitalPeriod && isOrbitRenderCancelled) {
$("#mapDialog").dialog( "option", "title", "Render Notice");
$("#progressbar").fadeOut();
$("#dialogTxt").fadeIn();
$("#dialogTxt").html("You have cancelled orbital calculation prior to one full orbit. As a result, some markers (Pe, Ap, node, etc) may be missing from the plot that is rendered");
$("#mapDialog").dialog( "option", "buttons", [{
text: "Okay",
click: function() {
$("#mapDialog").dialog("close");
}
}]);
} else { $("#mapDialog").dialog("close"); }
// done with the loading notice
ops.surface.layerControl.removeLayer(surfaceTracksDataLoad.obtTrackDataLoad);
surfaceTracksDataLoad.obtTrackDataLoad = null;
checkDataLoad();
// reset loading flags/triggers
strPausedVesselCalculation = null;
isOrbitRenderCancelled = false;
// place the craft marker and assign its popup
vesselIcon = L.icon({iconUrl: 'button_vessel_' + ops.currentVessel.Catalog.Type + '.png', iconSize: [16, 16]});
vesselMarker = L.marker(ops.currentVesselPlot.obtData[0].orbit[0].latlng, {icon: vesselIcon, zIndexOffset: 100}).addTo(ops.surface.map);
vesselMarker.bindPopup("Lat: <span id='lat'>-000.0000°S</span><br>Lng: <span id='lng'>-000.0000°W</span><br>Alt: <span id='alt'>000,000.000km</span><br>Vel: <span id='vel'>000,000.000km/s</span>", {autoClose: false});
// set up a listener for popup events so we can immediately update the information and not have to wait for the next tick event
vesselMarker.on('popupopen', function(e) {
var now = getPlotIndex();
var cardinal = getLatLngCompass(ops.currentVesselPlot.obtData[now.obtNum].orbit[now.index].latlng);
$('#lat').html(numeral(ops.currentVesselPlot.obtData[now.obtNum].orbit[now.index].latlng.lat).format('0.0000') + "°" + cardinal.lat);
$('#lng').html(numeral(ops.currentVesselPlot.obtData[now.obtNum].orbit[now.index].latlng.lng).format('0.0000') + "°" + cardinal.lng);
$('#alt').html(numeral(ops.currentVesselPlot.obtData[now.obtNum].orbit[now.index].alt).format('0,0.000') + " km");
$('#vel').html(numeral(ops.currentVesselPlot.obtData[now.obtNum].orbit[now.index].vel).format('0,0.000') + " km/s");
});
// focus in on the vessel position
ops.surface.map.setView(vesselMarker.getLatLng(), 3);
// open the vessel popup then hide it after 5s
vesselMarker.openPopup();
setTimeout(function() { if (vesselMarker) vesselMarker.closePopup(); }, 5000);
// allow the user to refresh the orbit render whenever they want
addMapRefreshButton();
}
}
function renderBodyOrbit() {
}
// this function will continually call itself to batch-run orbital calculations and not completely lock up the browser
// will calculate a full orbital period unless cancelled or otherwise interrupted by an event along the orbit, then pass control to the callback
function orbitalCalc(callback, orbit, numOrbitRenders, batchCount = 1000, limit) {
if (!limit) limit = orbit.OrbitalPeriod;
if (isOrbitRenderTerminated) return;
var bAltLimit = false;
// update the dialog title with the current date & time being calculated
var strDialogTitle = "Calculating Orbit #" + (ops.currentVesselPlot.obtData.length + 1) + " of " + numOrbitRenders + " - ";
strDialogTitle += UTtoDateTime(obtCalcUT, true);
$("#mapDialog").dialog( "option", "title", strDialogTitle);
// load up on some data-fetching and conversions so we're not repeating them in the batch loop
var gmu = ops.bodyCatalog.find(o => o.selected === true).Gm;
var rotPeriod = ops.bodyCatalog.find(o => o.selected === true).RotPeriod;
var rotInit = Math.radians(ops.bodyCatalog.find(o => o.selected === true).RotIni);
var bodRad = ops.bodyCatalog.find(o => o.selected === true).Radius;
var inc = Math.radians(orbit.Inclination);
var raan = Math.radians(orbit.RAAN);
var arg = Math.radians(orbit.Arg);
var mean = toMeanAnomaly(Math.radians(orbit.TrueAnom), orbit.Eccentricity);
for (x=0; x<=batchCount; x++) {
//////////////////////
// computeMeanMotion()
// all function comments are from https://github.com/Arrowstar/ksptot
//////////////////////////////////////////////////////////////////////
// adjust for motion since the time of this orbit
var n = Math.sqrt(gmu/(Math.pow(Math.abs(orbit.SMA),3)));
var newMean = mean + n * (obtCalcUT - orbit.Eph);
////////////////
// solveKepler()
////////////////
var EccA = -1;
if (orbit.Eccentricity < 1) {
if (newMean < 0 || newMean > 2*Math.PI) {
// expanded AngleZero2Pi() function
// abs(mod(real(Angle),2*pi));
// javascript has a modulo operator, but it doesn't work the way we need. Or something
// so using the mod() function implementation from Math.js: x - y * floor(x / y)
newMean = Math.abs(newMean - (2*Math.PI) * Math.floor(newMean / (2*Math.PI)));
}
if (Math.abs(newMean - 0) < 1E-8) {
EccA = 0;
} else if (Math.abs(newMean - Math.PI) < 1E-8 ) {
EccA = Math.PI;
}
/////////////
// keplerEq()
/////////////
// since there is no function return to break ahead of this statement, test if variable was modified
if (EccA == -1) {
var En = newMean;
var Ens = En - (En-orbit.Eccentricity*Math.sin(En) - newMean)/(1 - orbit.Eccentricity*Math.cos(En));
while (Math.abs(Ens-En) > 1E-10) {
En = Ens;
Ens = En - (En - orbit.Eccentricity*Math.sin(En) - newMean)/(1 - orbit.Eccentricity*Math.cos(En));
}
EccA = Ens;
}
// hyperbolic orbit
} else {
if (Math.abs(newMean - 0) < 1E-8) {
EccA = 0;
} else {
////////////////
// keplerEqHyp()
////////////////