forked from TehGimp/KerbalMultiPlayer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKMPManager.cs
3622 lines (3096 loc) · 128 KB
/
KMPManager.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using System.Xml.Serialization;
namespace KMP
{
public class Bootstrap : KSP.Testing.UnitTest {
public Bootstrap() {
if (KMPManager.GameObjectInstance == null)
{
Debug.Log("*** KMP version " + KMPCommon.PROGRAM_VERSION + " started");
KMPManager.GameObjectInstance = new GameObject("KMPManager", typeof(KMPManager));
UnityEngine.Object.DontDestroyOnLoad(KMPManager.GameObjectInstance);
}
}
}
public class KMPManager : MonoBehaviour
{
public KMPManager()
{
//Initialize client
KMPClientMain.InitMPClient(this);
}
public struct VesselEntry
{
public KMPVessel vessel;
public float lastUpdateTime;
}
public struct VesselStatusInfo
{
public string ownerName;
public string vesselName;
public string detailText;
public Color color;
public KMPVesselInfo info;
public Orbit orbit;
public float lastUpdateTime;
public int currentSubspaceID;
}
//Singleton
public static GameObject GameObjectInstance;
//Properties
public const String GLOBAL_SETTINGS_FILENAME = "globalsettings.txt";
public const float INACTIVE_VESSEL_RANGE = 2500.0f;
public const float DOCKING_TARGET_RANGE = 200.0f;
public const int MAX_INACTIVE_VESSELS_PER_UPDATE = 16;
public const int STATUS_ARRAY_MIN_SIZE = 2;
public const int MAX_VESSEL_NAME_LENGTH = 32;
public const float VESSEL_TIMEOUT_DELAY = 6.0f;
public const float IDLE_DELAY = 120.0f;
public const float PLUGIN_DATA_WRITE_INTERVAL = 0.333f;
public const float GLOBAL_SETTINGS_SAVE_INTERVAL = 10.0f;
public const int INTEROP_MAX_QUEUE_SIZE = 64;
public const float INTEROP_WRITE_INTERVAL = 0.333f;
public const float INTEROP_WRITE_TIMEOUT = 6.0f;
public const float FULL_PROTOVESSEL_UPDATE_TIMEOUT = 45f;
public UnicodeEncoding encoder = new UnicodeEncoding();
public String playerName = String.Empty;
public byte inactiveVesselsPerUpdate = 0;
public float updateInterval = 1.0f;
public Dictionary<String, VesselEntry> vessels = new Dictionary<string, VesselEntry>();
public SortedDictionary<String, VesselStatusInfo> playerStatus = new SortedDictionary<string, VesselStatusInfo>();
public RenderingManager renderManager;
public PlanetariumCamera planetariumCam;
public Queue<byte[]> interopOutQueue = new Queue<byte[]>();
public Queue<byte[]> interopInQueue = new Queue<byte[]>();
public static object interopInQueueLock = new object();
private float lastGlobalSettingSaveTime = 0.0f;
private float lastPluginDataWriteTime = 0.0f;
private float lastPluginUpdateWriteTime = 0.0f;
private float lastInteropWriteTime = 0.0f;
private float lastKeyPressTime = 0.0f;
private float lastFullProtovesselUpdate = 0.0f;
private Queue<KMPVesselUpdate> vesselUpdateQueue = new Queue<KMPVesselUpdate>();
private Queue<KMPVesselUpdate> newVesselUpdateQueue = new Queue<KMPVesselUpdate>();
GUIStyle playerNameStyle, vesselNameStyle, stateTextStyle, chatLineStyle, screenshotDescriptionStyle;
private bool isEditorLocked = false;
private bool mappingGUIToggleKey = false;
private bool mappingScreenshotKey = false;
private bool addPressed = false;
private string newHost = "localhost";
private string newPort = "2076";
private bool forceQuit = false;
private bool gameRunning = false;
private bool activeTermination = false;
//Vessel dictionaries
public Dictionary<Guid, Vessel.Situations> sentVessels_Situations = new Dictionary<Guid, Vessel.Situations>();
public Dictionary<Guid, Guid> serverVessels_RemoteID = new Dictionary<Guid, Guid>();
public Dictionary<Guid, int> serverVessels_PartCounts = new Dictionary<Guid, int>();
public Dictionary<Guid, List<Part>> serverVessels_Parts = new Dictionary<Guid, List<Part>>();
public Dictionary<Guid, ConfigNode> serverVessels_ProtoVessels = new Dictionary<Guid, ConfigNode>();
public Dictionary<Guid, bool> serverVessels_InUse = new Dictionary<Guid, bool>();
public Dictionary<Guid, bool> serverVessels_IsPrivate = new Dictionary<Guid, bool>();
public Dictionary<Guid, bool> serverVessels_IsMine = new Dictionary<Guid, bool>();
public Dictionary<Guid, KeyValuePair<double,double>> serverVessels_LastUpdateDistanceTime = new Dictionary<Guid, KeyValuePair<double,double>>();
public Dictionary<Guid, float> serverVessels_LoadDelay = new Dictionary<Guid, float>();
public Dictionary<Guid, bool> serverVessels_InPresent = new Dictionary<Guid, bool>();
public Dictionary<Guid, float> serverVessels_ObtSyncDelay = new Dictionary<Guid, float>();
public Dictionary<Guid, KeyValuePair<double,double>> serverVessels_RendezvousSmoothPos = new Dictionary<Guid, KeyValuePair<double,double>>();
public Dictionary<Guid, KeyValuePair<double,double>> serverVessels_RendezvousSmoothVel = new Dictionary<Guid, KeyValuePair<double,double>>();
public Dictionary<Guid, float> newFlags = new Dictionary<Guid, float>();
private Krakensbane krakensbane;
public double lastTick = 0d;
public double targetTick = 0d;
public Vector3d kscPosition = Vector3d.zero;
public Vector3d activeVesselPosition = Vector3d.zero;
public Dictionary<Guid, Vector3d> dockingRelVel = new Dictionary<Guid, Vector3d>();
public GameObject ksc = null;
private bool warping = false;
private bool syncing = false;
private bool docking = false;
private float lastWarpRate = 1f;
private int chatMessagesWaiting = 0;
private Vessel lastEVAVessel = null;
private bool showServerSync = false;
public bool globalUIToggle
{
get
{
return renderManager == null || renderManager.uiElementsToDisable.Length < 1 || renderManager.uiElementsToDisable[0].activeSelf;
}
}
public bool shouldDrawGUI
{
get
{
switch (HighLogic.LoadedScene)
{
case GameScenes.SPACECENTER:
case GameScenes.EDITOR:
case GameScenes.FLIGHT:
case GameScenes.SPH:
case GameScenes.TRACKSTATION:
return KMPInfoDisplay.infoDisplayActive && globalUIToggle;
default:
return false;
}
}
}
public static bool isInFlight
{
get
{
return FlightGlobals.ready && FlightGlobals.ActiveVessel != null && KMPClientMain.handshakeCompleted && KMPClientMain.udpConnected && KMPClientMain.receivedSettings;
}
}
public bool isIdle
{
get
{
return lastKeyPressTime > 0.0f && (UnityEngine.Time.realtimeSinceStartup - lastKeyPressTime) > IDLE_DELAY;
}
}
//Keys
public bool getAnyKeyDown(ref KeyCode key)
{
foreach (KeyCode keycode in Enum.GetValues(typeof(KeyCode)))
{
if (Input.GetKeyDown(keycode))
{
key = keycode;
return true;
}
}
return false;
}
//Updates
public void updateStep()
{
try
{
if (HighLogic.LoadedScene == GameScenes.LOADING || !gameRunning)
return; //Don't do anything while the game is loading or not in KMP game
if (!isInFlight && HighLogic.LoadedScene == GameScenes.TRACKSTATION)
{
foreach (object button in GameObject.FindObjectsOfType(typeof(ScreenSafeUIButton)))
{
ScreenSafeUIButton ssUIButton = (ScreenSafeUIButton) button;
if (ssUIButton.tooltip == "Terminate") ssUIButton.Unlock();
}
}
if (isInFlight && FlightGlobals.ActiveVessel.mainBody.name == "Kerbin" && FlightGlobals.ActiveVessel.altitude < 40000d) {
if (ksc == null) ksc = GameObject.Find("KSC");
kscPosition = new Vector3d(ksc.transform.position[0],ksc.transform.position[1],ksc.transform.position[2]);
} else kscPosition = Vector3d.zero;
if (lastWarpRate != TimeWarp.CurrentRate)
{
lastWarpRate = TimeWarp.CurrentRate;
OnTimeWarpRateChanged();
}
if (warping) {
writeUpdates();
return;
}
//Update Tracking Station names for unavailable vessels
if (!isInFlight)
{
foreach (Vessel vessel in FlightGlobals.Vessels)
{
string baseName = vessel.vesselName;
if (baseName.StartsWith("* ")) baseName = baseName.Substring(2);
vessel.vesselName = (((serverVessels_InUse.ContainsKey(vessel.id) && serverVessels_InUse[vessel.id]) || (serverVessels_IsPrivate.ContainsKey(vessel.id) && serverVessels_IsPrivate[vessel.id] && serverVessels_IsMine.ContainsKey(vessel.id) && !serverVessels_IsMine[vessel.id])) ? "* " : "") + baseName;
}
}
else //Kill Kraken-debris, clean names
{
foreach (Vessel vessel in FlightGlobals.Vessels.FindAll(v => v.vesselName.Contains("> Debris")))
{
try {vessel.Die();} catch {}
}
}
//Ensure player never touches something under another player's control
if (isInFlight && !docking && serverVessels_InUse.ContainsKey(FlightGlobals.ActiveVessel.id))
{
if (serverVessels_InUse[FlightGlobals.ActiveVessel.id])
{
KMPClientMain.DebugLog("Selected occupied vessel");
kickToTrackingStation();
return;
}
}
//Ensure player never touches a private vessel they don't own
if (isInFlight && !docking && serverVessels_IsPrivate.ContainsKey(FlightGlobals.ActiveVessel.id) && serverVessels_IsMine.ContainsKey(FlightGlobals.ActiveVessel.id))
{
if (!serverVessels_IsMine[FlightGlobals.ActiveVessel.id] && serverVessels_IsPrivate[FlightGlobals.ActiveVessel.id])
{
KMPClientMain.DebugLog("Selected private vessel");
kickToTrackingStation();
return;
}
}
if (isInFlight && !docking)
{
if (FlightGlobals.fetch.VesselTarget != null && FlightGlobals.fetch.VesselTarget is ModuleDockingNode)
{
ModuleDockingNode vesselTarget = (ModuleDockingNode) FlightGlobals.fetch.VesselTarget;
if (vesselTarget.part.vessel != null && serverVessels_IsPrivate.ContainsKey(vesselTarget.part.vessel.id) && serverVessels_IsMine.ContainsKey(vesselTarget.part.vessel.id))
{
if (!serverVessels_IsMine[vesselTarget.part.vessel.id] && serverVessels_IsPrivate[vesselTarget.part.vessel.id])
{
KMPClientMain.DebugLog("Tried to dock with private vessel");
ScreenMessages.PostScreenMessage("Can't dock - Target vessel is Private", 4f, ScreenMessageStyle.UPPER_CENTER);
FlightGlobals.fetch.SetVesselTarget(null);
}
}
}
}
//Update universe time
try
{
double currentTick = Planetarium.GetUniversalTime();
if (isInFlight && targetTick > currentTick)
{
KMPClientMain.DebugLog("Syncing to new time " + targetTick + " from " + Planetarium.GetUniversalTime());
if (FlightGlobals.ActiveVessel.situation != Vessel.Situations.PRELAUNCH
&& FlightGlobals.ActiveVessel.situation != Vessel.Situations.LANDED
&& FlightGlobals.ActiveVessel.situation != Vessel.Situations.SPLASHED)
{
Vector3d oldObtVel = FlightGlobals.ActiveVessel.obt_velocity;
if (FlightGlobals.ActiveVessel.orbit.EndUT > 0)
{
double lastEndUT = FlightGlobals.ActiveVessel.orbit.EndUT;
while (FlightGlobals.ActiveVessel.orbit.EndUT > 0
&& FlightGlobals.ActiveVessel.orbit.EndUT < targetTick
&& FlightGlobals.ActiveVessel.orbit.EndUT > lastEndUT
&& FlightGlobals.ActiveVessel.orbit.nextPatch != null)
{
KMPClientMain.DebugLog("orbit EndUT < target: " + FlightGlobals.ActiveVessel.orbit.EndUT + " vs " + targetTick);
lastEndUT = FlightGlobals.ActiveVessel.orbit.EndUT;
FlightGlobals.ActiveVessel.orbitDriver.orbit = FlightGlobals.ActiveVessel.orbit.nextPatch;
FlightGlobals.ActiveVessel.orbitDriver.UpdateOrbit();
if (FlightGlobals.ActiveVessel.orbit.referenceBody == null) FlightGlobals.ActiveVessel.orbit.referenceBody = FlightGlobals.Bodies.Find(b => b.name == "Sun");
KMPClientMain.DebugLog("updated to next patch");
}
}
try
{
OrbitPhysicsManager.HoldVesselUnpack(1);
}
catch (NullReferenceException)
{
}
//Krakensbane shift to new orbital location to prevent vessel destruction
KMPClientMain.DebugLog("Krakensbane shift");
Vector3d diffPos = FlightGlobals.ActiveVessel.orbit.getPositionAtUT(targetTick) - FlightGlobals.ActiveVessel.GetWorldPos3D();
foreach (Vessel otherVessel in FlightGlobals.Vessels.Where(v => v.packed == false && (v.id != FlightGlobals.ActiveVessel.id || (v.loaded && Vector3d.Distance(FlightGlobals.ActiveVessel.GetWorldPos3D(),v.GetWorldPos3D()) < INACTIVE_VESSEL_RANGE))))
otherVessel.GoOnRails();
getKrakensbane().setOffset(diffPos);
//Update velocity
FlightGlobals.ActiveVessel.ChangeWorldVelocity((-1 * oldObtVel) + FlightGlobals.ActiveVessel.orbitDriver.orbit.getOrbitalVelocityAtUT(targetTick).xzy);
FlightGlobals.ActiveVessel.orbitDriver.vel = FlightGlobals.ActiveVessel.orbit.vel;
}
Planetarium.SetUniversalTime(targetTick);
KMPClientMain.DebugLog("sync completed");
}
} catch (Exception e) { KMPClientMain.DebugLog("error during sync: " + e.Message + " " + e.StackTrace); }
writeUpdates();
//Once all updates are processed, update the vesselUpdateQueue with new entries
vesselUpdateQueue = newVesselUpdateQueue;
//If in flight, check remote vessels, set position variable for docking-mode position updates
if (isInFlight)
{
InputLockManager.ClearControlLocks();
checkRemoteVesselIntegrity();
activeVesselPosition = FlightGlobals.ActiveVessel.findWorldCenterOfMass();
dockingRelVel.Clear();
}
//Handle all queued vessel updates
while (vesselUpdateQueue.Count > 0)
{
handleVesselUpdate(vesselUpdateQueue.Dequeue());
}
processClientInterop();
//Update the displayed player orbit positions
List<String> delete_list = new List<String>();
foreach (KeyValuePair<String, VesselEntry> pair in vessels) {
VesselEntry entry = pair.Value;
if ((UnityEngine.Time.realtimeSinceStartup-entry.lastUpdateTime) <= VESSEL_TIMEOUT_DELAY
&& entry.vessel != null && entry.vessel.gameObj != null)
{
entry.vessel.updateRenderProperties(!KMPGlobalSettings.instance.showInactiveShips && entry.vessel.info.state != State.ACTIVE);
entry.vessel.updatePosition();
}
else
{
delete_list.Add(pair.Key); //Mark the vessel for deletion
if (entry.vessel != null && entry.vessel.gameObj != null)
GameObject.Destroy(entry.vessel.gameObj);
}
}
//Delete what needs deletin'
foreach (String key in delete_list)
vessels.Remove(key);
delete_list.Clear();
//Delete outdated player status entries
foreach (KeyValuePair<String, VesselStatusInfo> pair in playerStatus)
{
if ((UnityEngine.Time.realtimeSinceStartup - pair.Value.lastUpdateTime) > VESSEL_TIMEOUT_DELAY)
{
KMPClientMain.DebugLog("deleted player status for timeout: " + pair.Key + " " + pair.Value.vesselName);
delete_list.Add(pair.Key);
}
}
foreach (String key in delete_list)
playerStatus.Remove(key);
//Prevent cases of remaining unfixed NREs from remote vessel updates from creating an inconsistent game state
if (HighLogic.fetch.log.Count > 100)
{
bool allNRE = true;
foreach (HighLogic.LogEntry logEntry in HighLogic.fetch.log.GetRange(HighLogic.fetch.log.Count-25,25))
{
if (!logEntry.condition.Contains("NullReferenceException")) allNRE = false;
}
if (allNRE)
{
KMPClientMain.DebugLog("Resynced due to NRE flood");
ScreenMessages.PostScreenMessage("Unexpected error! Re-syncing...");
GameEvents.onFlightReady.Remove(this.OnFlightReady);
HighLogic.CurrentGame = GamePersistence.LoadGame("start",HighLogic.SaveFolder,false,true);
HighLogic.CurrentGame.Start();
docking = true;
syncing = true;
Invoke("OnFirstFlightReady",1f);
}
}
} catch (Exception ex) { KMPClientMain.DebugLog("uS err: " + ex.Message + " " + ex.StackTrace); }
}
private void dockedKickToTrackingStation()
{
if (syncing && docking)
{
GameEvents.onFlightReady.Remove(this.OnFlightReady);
HighLogic.CurrentGame = GamePersistence.LoadGame("start",HighLogic.SaveFolder,false,true);
HighLogic.CurrentGame.Start();
Invoke("OnFirstFlightReady",1f);
}
}
private void kickToTrackingStation()
{
KMPClientMain.DebugLog("Selected unavailable vessel, switching");
ScreenMessages.PostScreenMessage("Selected vessel is occupied or private...", 5f,ScreenMessageStyle.UPPER_RIGHT);
syncing = true;
StartCoroutine(returnToTrackingStation());
}
private void writeUpdates()
{
if ((UnityEngine.Time.realtimeSinceStartup - lastPluginUpdateWriteTime) > updateInterval
&& (Time.realtimeSinceStartup - lastInteropWriteTime) < INTEROP_WRITE_TIMEOUT)
{
writePluginUpdate();
lastPluginUpdateWriteTime = UnityEngine.Time.realtimeSinceStartup;
}
if ((UnityEngine.Time.realtimeSinceStartup - lastPluginDataWriteTime) > PLUGIN_DATA_WRITE_INTERVAL)
{
writePluginData();
lastPluginDataWriteTime = UnityEngine.Time.realtimeSinceStartup;
}
//Write interop
if ((UnityEngine.Time.realtimeSinceStartup - lastInteropWriteTime) > INTEROP_WRITE_INTERVAL)
{
if (writePluginInterop())
lastInteropWriteTime = UnityEngine.Time.realtimeSinceStartup;
}
//Save global settings periodically
if ((UnityEngine.Time.realtimeSinceStartup - lastGlobalSettingSaveTime) > GLOBAL_SETTINGS_SAVE_INTERVAL)
{
saveGlobalSettings();
//Keep track of when the name was last read so we don't read it every time
lastGlobalSettingSaveTime = UnityEngine.Time.realtimeSinceStartup;
}
}
private void checkRemoteVesselIntegrity()
{
try
{
if (!isInFlight || syncing || warping || docking) return;
foreach (Vessel vessel in FlightGlobals.Vessels.FindAll(v => v.loaded && v.id != FlightGlobals.ActiveVessel.id && serverVessels_PartCounts.ContainsKey(v.id) && serverVessels_ProtoVessels.ContainsKey(v.id)))
{
if (serverVessels_PartCounts[vessel.id] > 0 && serverVessels_PartCounts[vessel.id] > vessel.Parts.Count)
{
KMPClientMain.DebugLog("checkRemoteVesselIntegrity killing vessel: " + vessel.id);
serverVessels_PartCounts[vessel.id] = 0;
foreach (Part part in serverVessels_Parts[vessel.id])
{
try { part.vessel.Die(); } catch {}
}
ProtoVessel protovessel = new ProtoVessel(serverVessels_ProtoVessels[vessel.id], HighLogic.CurrentGame);
addRemoteVessel(protovessel,vessel.id);
serverVessels_LoadDelay[vessel.id] = UnityEngine.Time.realtimeSinceStartup + 10f;
}
}
}
catch (Exception ex)
{
KMPClientMain.DebugLog("cRVI err: " + ex.Message + " " + ex.StackTrace);
}
}
public void disconnect(string message = "")
{
if (HighLogic.LoadedSceneIsFlight || HighLogic.LoadedSceneIsEditor)
{
ScreenMessages.PostScreenMessage("You have been disconnected. Please return to the Main Menu to reconnect.",300f,ScreenMessageStyle.UPPER_CENTER);
if (!String.IsNullOrEmpty(message)) ScreenMessages.PostScreenMessage(message, 300f,ScreenMessageStyle.UPPER_CENTER);
}
else
{
forceQuit = true;
ScreenMessages.PostScreenMessage("You have been disconnected. Please return to the Main Menu to reconnect.",300f,ScreenMessageStyle.UPPER_CENTER);
if (!String.IsNullOrEmpty(message)) ScreenMessages.PostScreenMessage(message, 300f,ScreenMessageStyle.UPPER_CENTER);
}
if (String.IsNullOrEmpty(message)) KMPClientMain.SetMessage("Disconnected");
else KMPClientMain.SetMessage("Disconnected: " + message);
gameRunning = false;
}
private void writePluginUpdate()
{
if (playerName == null || playerName.Length == 0)
return;
writePrimaryUpdate();
//nearby vessels
if (isInFlight && !syncing && !warping && (FlightGlobals.ActiveVessel.mainBody.bodyName != "Kerbin" || FlightGlobals.ActiveVessel.altitude > 35000d || kscPosition == Vector3d.zero || Vector3d.Distance(kscPosition,FlightGlobals.ActiveVessel.GetWorldPos3D()) > 40000d))
{
writeSecondaryUpdates();
}
}
private void writePrimaryUpdate()
{
if (!syncing && isInFlight && !warping
&& (FlightGlobals.ActiveVessel.mainBody.bodyName != "Kerbin" || FlightGlobals.ActiveVessel.altitude > 35000d || kscPosition == Vector3d.zero || Vector3d.Distance(kscPosition,FlightGlobals.ActiveVessel.GetWorldPos3D()) > 40000d))
{
lastTick = Planetarium.GetUniversalTime();
//Write vessel status
KMPVesselUpdate update = getVesselUpdate(FlightGlobals.ActiveVessel);
if (FlightGlobals.ActiveVessel.vesselType == VesselType.EVA) lastEVAVessel = FlightGlobals.ActiveVessel;
//Update the player vessel info
VesselStatusInfo my_status = new VesselStatusInfo();
my_status.info = update;
my_status.orbit = FlightGlobals.ActiveVessel.orbit;
my_status.color = KMPVessel.generateActiveColor(playerName);
my_status.ownerName = playerName;
if (FlightGlobals.ActiveVessel.vesselName.Contains(" <") && FlightGlobals.ActiveVessel.vesselName.Contains(">"))
FlightGlobals.ActiveVessel.vesselName = FlightGlobals.ActiveVessel.vesselName.Substring(0,FlightGlobals.ActiveVessel.vesselName.IndexOf(" <"));
if (String.IsNullOrEmpty(FlightGlobals.ActiveVessel.vesselName.Trim())) FlightGlobals.ActiveVessel.vesselName = "Unknown";
my_status.vesselName = FlightGlobals.ActiveVessel.vesselName;
my_status.lastUpdateTime = UnityEngine.Time.realtimeSinceStartup;
if (playerStatus.ContainsKey(playerName))
playerStatus[playerName] = my_status;
else
playerStatus.Add(playerName, my_status);
KMPClientMain.DebugLog("sending primary update");
try{
enqueuePluginInteropMessage(KMPCommon.PluginInteropMessageID.PRIMARY_PLUGIN_UPDATE, KSP.IO.IOUtils.SerializeToBinary(update));
} catch (Exception e) { KMPClientMain.DebugLog("err: " + e.Message); }
}
else
{
lastTick = 0d;
//Check if the player is building a ship
bool building_ship = HighLogic.LoadedSceneIsEditor
&& EditorLogic.fetch != null
&& EditorLogic.fetch.ship != null && EditorLogic.fetch.ship.Count > 0
&& EditorLogic.fetch.shipNameField != null
&& EditorLogic.fetch.shipNameField.Text != null && EditorLogic.fetch.shipNameField.Text.Length > 0;
String[] status_array = null;
if (building_ship)
{
status_array = new String[3];
//Vessel name
String shipname = EditorLogic.fetch.shipNameField.Text;
if (shipname.Length > MAX_VESSEL_NAME_LENGTH)
shipname = shipname.Substring(0, MAX_VESSEL_NAME_LENGTH); //Limit vessel name length
status_array[1] = "Building " + shipname;
//Vessel details
status_array[2] = "Parts: " + EditorLogic.fetch.ship.Count;
}
else if (warping)
{
status_array = new String[2];
status_array[1] = "Warping";
}
else if (syncing)
{
status_array = new String[2];
status_array[1] = "Synchronizing";
}
else
{
status_array = new String[2];
switch (HighLogic.LoadedScene)
{
case GameScenes.FLIGHT:
status_array[1] = "Preparing/launching from KSC";
break;
case GameScenes.SPACECENTER:
status_array[1] = "At Space Center";
break;
case GameScenes.EDITOR:
status_array[1] = "In Vehicle Assembly Building";
break;
case GameScenes.SPH:
status_array[1] = "In Space Plane Hangar";
break;
case GameScenes.TRACKSTATION:
status_array[1] = "At Tracking Station";
break;
default:
status_array[1] = String.Empty;
break;
}
}
//Check if player is idle
if (isIdle)
status_array[1] = "(Idle) " + status_array[1];
status_array[0] = playerName;
//Serialize the update
byte[] update_bytes = KSP.IO.IOUtils.SerializeToBinary(status_array);
enqueuePluginInteropMessage(KMPCommon.PluginInteropMessageID.PRIMARY_PLUGIN_UPDATE, update_bytes);
VesselStatusInfo my_status = statusArrayToInfo(status_array);
if (playerStatus.ContainsKey(playerName))
playerStatus[playerName] = my_status;
else
playerStatus.Add(playerName, my_status);
}
}
private void writeSecondaryUpdates()
{
if (inactiveVesselsPerUpdate > 0)
{
//Write the inactive vessels nearest the active vessel
SortedList<float, Vessel> nearest_vessels = new SortedList<float, Vessel>();
foreach (Vessel vessel in FlightGlobals.Vessels)
{
if (vessel != FlightGlobals.ActiveVessel && vessel.loaded && !vessel.name.Contains(" [Past]") && !vessel.name.Contains(" [Future]"))
{
float distance = (float)Vector3d.Distance(vessel.GetWorldPos3D(), FlightGlobals.ActiveVessel.GetWorldPos3D());
if (distance < INACTIVE_VESSEL_RANGE)
{
try
{
Part root = vessel.rootPart;
bool include = true;
if (serverVessels_InUse.ContainsKey(vessel.id) && !serverVessels_InUse[vessel.id])
{
foreach (Guid vesselID in serverVessels_Parts.Keys)
{
if (serverVessels_Parts[vesselID].Contains(root))
{
include=false;
break;
}
}
}
if (include) nearest_vessels.Add(distance, vessel);
}
catch (ArgumentException)
{
}
}
}
}
int num_written_vessels = 0;
//Write inactive vessels to file in order of distance from active vessel
IEnumerator<KeyValuePair<float, Vessel>> enumerator = nearest_vessels.GetEnumerator();
while (num_written_vessels < inactiveVesselsPerUpdate
&& num_written_vessels < MAX_INACTIVE_VESSELS_PER_UPDATE && enumerator.MoveNext())
{
bool newVessel = !serverVessels_RemoteID.ContainsKey(enumerator.Current.Value.id);
KMPVesselUpdate update = getVesselUpdate(enumerator.Current.Value);
if (update != null)
{
if ((update.situation == Situation.DESCENDING || update.situation == Situation.FLYING)
&& enumerator.Current.Value.mainBody.atmosphere
&& enumerator.Current.Value.altitude < enumerator.Current.Value.mainBody.maxAtmosphereAltitude
&& !newVessel)
update.situation = Situation.DESTROYED; //Don't keep sending a secondary vessel that will stay destroyed for any other client
update.distance = enumerator.Current.Key;
update.state = State.INACTIVE;
if (enumerator.Current.Value.loaded && serverVessels_InUse.ContainsKey(enumerator.Current.Value.id) && serverVessels_InUse[enumerator.Current.Value.id] && FlightGlobals.ActiveVessel.altitude > 10000d)
{
//Rendezvous relative position data
KMPClientMain.DebugLog ("sending docking-mode update, distance: " + enumerator.Current.Key);
update.relativeTo = FlightGlobals.ActiveVessel.id;
Vector3d w_pos = Vector3d.zero;
try
{
w_pos = enumerator.Current.Value.findWorldCenterOfMass() - FlightGlobals.ActiveVessel.findWorldCenterOfMass();
} catch {
KMPClientMain.DebugLog("couldn't get CoM!");
w_pos = enumerator.Current.Value.GetWorldPos3D() - FlightGlobals.ActiveVessel.GetWorldPos3D();
}
Vector3d o_vel = enumerator.Current.Value.GetObtVelocity() - FlightGlobals.ActiveVessel.GetObtVelocity();
update.clearProtoVessel();
for (int i = 0; i < 3; i++)
{
update.w_pos[i] = w_pos[i];
update.o_vel[i] = o_vel[i];
}
}
byte[] update_bytes = KSP.IO.IOUtils.SerializeToBinary(update);
KMPClientMain.DebugLog ("sending secondary update for: " + enumerator.Current.Value.id);
if (newVessel)
enqueuePluginInteropMessage(KMPCommon.PluginInteropMessageID.PRIMARY_PLUGIN_UPDATE, update_bytes);
else
enqueuePluginInteropMessage(KMPCommon.PluginInteropMessageID.SECONDARY_PLUGIN_UPDATE, update_bytes);
num_written_vessels++;
}
}
}
}
private void sendRemoveVesselMessage(Vessel vessel, bool isDocking = false)
{
KMPClientMain.DebugLog ("sendRemoveVesselMessage");
KMPVesselUpdate update = getVesselUpdate(vessel);
update.situation = Situation.DESTROYED;
update.state = FlightGlobals.ActiveVessel.id == vessel.id ? State.ACTIVE : State.INACTIVE;
update.isDockUpdate = isDocking;
update.clearProtoVessel();
byte[] update_bytes = KSP.IO.IOUtils.SerializeToBinary(update);
enqueuePluginInteropMessage(KMPCommon.PluginInteropMessageID.PRIMARY_PLUGIN_UPDATE, update_bytes);
}
private void sendVesselMessage(Vessel vessel, bool isDocking = false)
{
if (isInFlight)
{
KMPClientMain.DebugLog ("sendVesselMessage");
KMPVesselUpdate update = getVesselUpdate(vessel, true);
update.state = FlightGlobals.ActiveVessel.id == vessel.id ? State.ACTIVE : State.INACTIVE;
update.isDockUpdate = isDocking;
byte[] update_bytes = KSP.IO.IOUtils.SerializeToBinary(update);
enqueuePluginInteropMessage(KMPCommon.PluginInteropMessageID.PRIMARY_PLUGIN_UPDATE, update_bytes);
}
}
private KMPVesselUpdate getVesselUpdate(Vessel vessel, bool forceFullUpdate = false)
{
if (vessel == null || vessel.mainBody == null)
return null;
if (vessel.id == Guid.Empty) vessel.id = Guid.NewGuid();
//Create a KMPVesselUpdate from the vessel data
KMPVesselUpdate update;
if (!forceFullUpdate
&& serverVessels_PartCounts.ContainsKey(vessel.id)
&& !(vessel.id == FlightGlobals.ActiveVessel.id && FlightGlobals.ActiveVessel.ctrlState.mainThrottle == 0f && (UnityEngine.Time.realtimeSinceStartup - lastFullProtovesselUpdate) > FULL_PROTOVESSEL_UPDATE_TIMEOUT))
{
if (serverVessels_PartCounts.ContainsKey(vessel.id)
&& serverVessels_PartCounts[vessel.id] == vessel.Parts.Count
&& sentVessels_Situations.ContainsKey(vessel.id)
&& (sentVessels_Situations[vessel.id] == vessel.situation || sentVessels_Situations[vessel.id] == Vessel.Situations.LANDED))
{
if (!newFlags.ContainsKey(vessel.id) || (UnityEngine.Time.realtimeSinceStartup - newFlags[vessel.id]) < 65f)
update = new KMPVesselUpdate(vessel,false);
else
{
update = new KMPVesselUpdate(vessel);
newFlags.Remove(vessel.id);
}
}
else
{
//Vessel has changed
KMPClientMain.DebugLog("Full update: " + vessel.id);
update = new KMPVesselUpdate(vessel);
serverVessels_PartCounts[vessel.id] = vessel.Parts.Count;
}
}
else
{
//New vessel or forced protovessel update
update = new KMPVesselUpdate(vessel);
if (vessel.id == FlightGlobals.ActiveVessel.id)
{
KMPClientMain.DebugLog("First or forced proto update for active vessel: " + vessel.id);
lastFullProtovesselUpdate = UnityEngine.Time.realtimeSinceStartup;
}
if (!vessel.packed) serverVessels_PartCounts[vessel.id] = vessel.Parts.Count;
}
//Track vessel situation
sentVessels_Situations[vessel.id] = vessel.situation;
//Set privacy lock
if (serverVessels_IsPrivate.ContainsKey(vessel.id)) update.isPrivate = serverVessels_IsPrivate[vessel.id];
if (vessel.vesselName.Length <= MAX_VESSEL_NAME_LENGTH)
update.name = vessel.vesselName;
else
update.name = vessel.vesselName.Substring(0, MAX_VESSEL_NAME_LENGTH);
update.player = playerName;
update.id = vessel.id;
update.tick = Planetarium.GetUniversalTime();
update.crewCount = vessel.GetCrewCount();
if (serverVessels_RemoteID.ContainsKey(vessel.id)) update.kmpID = serverVessels_RemoteID[vessel.id];
else
{
KMPClientMain.DebugLog("Generating new remote ID for vessel: " + vessel.id);
Guid server_id = Guid.NewGuid();
serverVessels_RemoteID[vessel.id] = server_id;
update.kmpID = server_id;
if (vessel.vesselType == VesselType.Flag)
{
newFlags[vessel.id] = UnityEngine.Time.realtimeSinceStartup;
}
}
Vector3 pos = vessel.mainBody.transform.InverseTransformPoint(vessel.GetWorldPos3D());
Vector3 dir = vessel.mainBody.transform.InverseTransformDirection(vessel.transform.up);
Vector3 vel = vessel.mainBody.transform.InverseTransformDirection(vessel.GetObtVelocity());
Vector3d o_vel = vessel.obt_velocity;
Vector3d s_vel = vessel.srf_velocity;
Quaternion rot = vessel.transform.rotation;
for (int i = 0; i < 3; i++)
{
update.pos[i] = pos[i];
update.dir[i] = dir[i];
update.vel[i] = vel[i];
update.o_vel[i] = o_vel[i];
update.s_vel[i] = s_vel[i];
}
for (int i = 0; i < 4; i++)
{
update.rot[i] = rot[i];
}
update.w_pos[0] = vessel.orbit.LAN;
if (vessel.situation == Vessel.Situations.LANDED || vessel.situation == Vessel.Situations.SPLASHED)
{
update.w_pos[1] = vessel.latitude;
update.w_pos[2] = vessel.longitude;
}
//Determine situation
if ((vessel.loaded && vessel.GetTotalMass() <= 0.0) || (vessel.vesselType == VesselType.Debris && vessel.situation == Vessel.Situations.SUB_ORBITAL))
update.situation = Situation.DESTROYED;
else
{
switch (vessel.situation)
{
case Vessel.Situations.LANDED:
update.situation = Situation.LANDED;
break;
case Vessel.Situations.SPLASHED:
update.situation = Situation.SPLASHED;
break;
case Vessel.Situations.PRELAUNCH:
update.situation = Situation.PRELAUNCH;
break;
case Vessel.Situations.SUB_ORBITAL:
if (vessel.orbit.timeToAp < vessel.orbit.period / 2.0)
update.situation = Situation.ASCENDING;
else
update.situation = Situation.DESCENDING;
break;
case Vessel.Situations.ORBITING:
update.situation = Situation.ORBITING;
break;
case Vessel.Situations.ESCAPING:
if (vessel.orbit.timeToPe > 0.0)
update.situation = Situation.ENCOUNTERING;
else
update.situation = Situation.ESCAPING;
break;
case Vessel.Situations.DOCKED:
update.situation = Situation.DOCKED;
break;
case Vessel.Situations.FLYING:
update.situation = Situation.FLYING;
break;
default:
update.situation = Situation.UNKNOWN;
break;
}
}
if (vessel == FlightGlobals.ActiveVessel)
{
update.state = State.ACTIVE;
//Set vessel details since it's the active vessel
update.detail = getVesselDetail(vessel);
}
else if (vessel.isCommandable)
update.state = State.INACTIVE;
else
update.state = State.DEAD;
update.timeScale = (float)Planetarium.TimeScale;
update.bodyName = vessel.mainBody.bodyName;
return update;
}
private KMPVesselDetail getVesselDetail(Vessel vessel)
{
KMPVesselDetail detail = new KMPVesselDetail();
detail.idle = isIdle;
detail.mass = vessel.GetTotalMass();
bool is_eva = false;
bool parachutes_open = false;
//Check if the vessel is an EVA Kerbal
if (vessel.isEVA && vessel.parts.Count > 0 && vessel.parts.First().Modules.Count > 0)
{
foreach (PartModule module in vessel.parts.First().Modules)
{
if (module is KerbalEVA)
{
KerbalEVA kerbal = (KerbalEVA) module;
detail.percentFuel = (byte)Math.Round(kerbal.Fuel / kerbal.FuelCapacity * 100);
detail.percentRCS = byte.MaxValue;
detail.numCrew = byte.MaxValue;
is_eva = true;
break;
}
}
}
if (!is_eva)
{
if (vessel.GetCrewCapacity() > 0)
detail.numCrew = (byte)vessel.GetCrewCount();
else
detail.numCrew = byte.MaxValue;
Dictionary<string, float> fuel_densities = new Dictionary<string, float>();
Dictionary<string, float> rcs_fuel_densities = new Dictionary<string, float>();
bool has_engines = false;
bool has_rcs = false;
foreach (Part part in vessel.parts)
{
foreach (PartModule module in part.Modules)