-
Notifications
You must be signed in to change notification settings - Fork 0
/
MultiplayerMod.cs
1992 lines (1834 loc) · 93.8 KB
/
MultiplayerMod.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 BepInEx;
using Logger = BepInEx.Logging.Logger;
using PolyTechFramework;
using UnityEngine;
using HarmonyLib;
using System.Reflection;
using System.Collections.Generic;
using BepInEx.Configuration;
using PolyPhysics;
using System.Net.WebSockets;
using System.Threading;
using UnityEngine.UI;
using System.IO;
using System.Text;
using System.Collections;
namespace MultiplayerMod
{
[BepInPlugin(PluginGuid, PluginName, PluginVersion)]
// Specify the mod as a dependency of PTF
[BepInDependency(PolyTechMain.PluginGuid, BepInDependency.DependencyFlags.HardDependency)]
// This Changes from BaseUnityPlugin to PolyTechMod.
// This superclass is functionally identical to BaseUnityPlugin, so existing documentation for it will still work.
public partial class MultiplayerMod : PolyTechMod
{
public new const string
PluginGuid = "org.bepinex.plugins.MultiplayerMod",
PluginName = "Multiplayer Mod",
PluginVersion = "1.1.1";
public static ConfigDefinition
modEnabledDef = new ConfigDefinition("Multiplayer Mod", "Enable/Disable Mod");
public static ConfigEntry<bool>
modEnabled,
logActions,
showMice;
public static ConfigEntry<float>
backupFrequency,
writeToLogFrequency;
private static ConfigEntry<BepInEx.Configuration.KeyboardShortcut>
_keybind,
_toggleChatKeybind,
syncLayoutKeybind;
public static ConfigEntry<Color> mouseColor;
public static MultiplayerMod instance;
public static string ClientName = "";
public static string serverName = "";
//public bool clientEnabled = false;
public bool preventSendActions = false;
public ServerCommunication communication;
public Dictionary<actionType, bool> ClientRecieving = new Dictionary<actionType, bool> {};
public System.Timers.Timer BackupTimer = new System.Timers.Timer();
public List<string> logBuffer = new List<string> ();
public string backupFolder = "MultiplayerBackups";
public bool serverIsFrozen = false;
public ServerInfoModel serverInfo;
Coroutine GetServerInfo;
Coroutine SendMousePos;
public Dictionary<string, PointerHandler> mousePositions = new Dictionary<string, PointerHandler> {};
public GameObject canvas;
public GameObject _canvas;
public Dictionary<PointerMode, Sprite> pointerSprites = new Dictionary<PointerMode, Sprite> {};
public Sprite normalPointer;
public Sprite movePointer;
public Sprite toggleSelectPointer;
public List<SyncRequest> syncRequests = new List<SyncRequest> {};
void Awake()
{
this.repositoryUrl = "https://github.com/Conqu3red/PolyBridge2-Multiplayer-Mod/";
if (instance == null) instance = this;
// Use this if you wish to make the mod trigger cheat mode ingame.
// Set this true if your mod effects physics or allows mods that you can't normally do.
isCheat = false;
modEnabled = Config.Bind(modEnabledDef, true, new ConfigDescription("Enable Mod"));
logActions = Config.Bind("Multiplayer Mod", "Log Actions (only logs if you are host)", false);
backupFrequency = Config.Bind("Multiplayer Mod", "Backup Frequency (seconds)", 60f);
writeToLogFrequency = Config.Bind("Multiplayer Mod", "Save to action log every amount of lines", 100f);
_keybind = Config.Bind("Multiplayer Mod", "Keybind to open GUI", new BepInEx.Configuration.KeyboardShortcut(KeyCode.F3));
_toggleChatKeybind = Config.Bind("Multiplayer Mod", "Toggle Chat Visibility", new BepInEx.Configuration.KeyboardShortcut(KeyCode.F4));
syncLayoutKeybind = Config.Bind("Multiplayer Mod", "Sync Layout", new BepInEx.Configuration.KeyboardShortcut(KeyCode.F5));
mouseColor = Config.Bind("Multiplayer Mod", "Mouse Color", Color.red);
showMice = Config.Bind("Multiplayer Mod", "Show other users mice", true);
BackupTimer.Elapsed += (sender, args) => { backupLayout(); };
BackupTimer.AutoReset = true;
BackupTimer.Interval = backupFrequency.Value*1000;
BackupTimer.Start();
modEnabled.SettingChanged += onEnableDisable;
backupFrequency.SettingChanged += (object sender, EventArgs e) => {
if (backupFrequency.Value < 5){
backupFrequency.Value = 5;
}
BackupTimer.Interval = backupFrequency.Value*1000;
};
harmony = new Harmony("org.bepinex.plugins.MultiplayerMod");
harmony.PatchAll(Assembly.GetExecutingAssembly());
this.authors = new string[] {"Conqu3red"};
PolyTechMain.registerMod(this);
}
public bool clientEnabled
{
get {
if (communication != null){
return communication.IsConnected();
}
return false;
}
set {}
}
public bool clientConnecting
{
get {
if (communication != null){
return communication.IsConnecting();
}
return false;
}
set {}
}
public void Start(){
var windowBackground = new Texture2D(1, 1, TextureFormat.ARGB32, false);
windowBackground.SetPixel(0, 0, new Color(0.5f, 0.5f, 0.5f, 1));
windowBackground.Apply();
WindowBackground = windowBackground;
var chatBackground = new Texture2D(1, 1, TextureFormat.ARGB32, false);
chatBackground.SetPixel(0, 0, new Color(0.5f, 0.5f, 0.5f, 0.2f));
chatBackground.Apply();
ChatBackground = chatBackground;
_canvas = new GameObject("cursorCanvas");
DontDestroyOnLoad(_canvas);
canvas = Instantiate(_canvas, base.transform);
DontDestroyOnLoad(canvas);
}
[HarmonyPatch(typeof(GameUI), "StartManual")]
public static class GameUIStartPatch {
public static void Postfix(){
instance.normalPointer = Sprite.Create(
GameUI.m_Instance.m_PointerNormalTexture,
new Rect(0, 0, GameUI.m_Instance.m_PointerNormalTexture.width, GameUI.m_Instance.m_PointerNormalTexture.height),
new Vector2(0f, 15/16f),
96f
);
instance.movePointer = Sprite.Create(
GameUI.m_Instance.m_PointerMoveTexture,
new Rect(0, 0, GameUI.m_Instance.m_PointerMoveTexture.width, GameUI.m_Instance.m_PointerMoveTexture.height),
new Vector2(0.5f, 0.5f),
96f
);
instance.toggleSelectPointer = Sprite.Create(
GameUI.m_Instance.m_PointerSelectToggleTexture,
new Rect(0, 0, GameUI.m_Instance.m_PointerSelectToggleTexture.width, GameUI.m_Instance.m_PointerSelectToggleTexture.height),
new Vector2(0f,15/16f),
96f
);
instance.pointerSprites[PointerMode.INVALID] = instance.normalPointer;
instance.pointerSprites[PointerMode.NORMAL] = instance.normalPointer;
instance.pointerSprites[PointerMode.MOVE] = instance.movePointer;
instance.pointerSprites[PointerMode.SELECT_TOGGLE] = instance.toggleSelectPointer;
instance.pointerSprites[PointerMode.ERASE] = instance.normalPointer;
}
}
public void Update(){
if (!DisplayingWindow && _keybind.Value.IsUp())
{
DisplayingWindow = true;
}
if (_toggleChatKeybind.Value.IsUp())
{
DisplayingChat = !DisplayingChat;
}
if (communication != null) {
communication.Update();
if (serverIsFrozen || Bridge.IsSimulating() || !showMice.Value){
if (canvas.activeInHierarchy){
canvas.SetActive(false);
}
}
else if (!canvas.activeInHierarchy){
canvas.SetActive(true);
}
}
if (syncLayoutKeybind.Value.IsUp()) syncLayout();
if (syncRequests.Count > 0 && GameStateManager.GetState() != GameState.SIM){
processSyncRequest(syncRequests[0]);
syncRequests.RemoveAt(0);
}
//UpdateMouseDrawers();
}
/// <summary>
/// Method called after connection with server was established.
/// </summary>
public void OnConnectedToServer()
{
instance.communication.Lobby.OnConnectedToServer -= instance.OnConnectedToServer;
instance.communication.Lobby.OnBridgeAction += instance.OnBridgeAction;
GetServerInfo = StartCoroutine(InvokeRepeat("ConnectionInfo", 0, 2.5f));
SendMousePos = StartCoroutine(InvokeRepeat("SendMousePosition", 0, 0.1f)); // this is a bit spammy but eh
}
IEnumerator InvokeRepeat(string function, float delay, float interval) {
yield return new WaitForSecondsRealtime(delay);
while (true) {
Invoke(function, 0f);
yield return new WaitForSecondsRealtime(interval);
}
}
public void OnBridgeAction(BridgeActionModel message)
{
// TODO: send joints/edges as a list so less packets need to be sent when bulk deleting etc
BridgeEdgeProxy edgeProxy;
BridgeEdge edge;
BridgeSpringProxy springProxy;
PistonProxy pistonProxy;
BridgeJointProxy jointProxy;
BridgeJoint joint;
int offset = 0;
instance.Logger.LogInfo($"<CLIENT> received {message.action}");
if (instance.communication.isOwner) {
ActionLog($"Recieved {message.action} from user {message.username}");
}
// switch to handle actions
switch (message.action){
case actionType.CREATE_EDGE:
edgeProxy = new BridgeEdgeProxy(10, message.content, ref offset);
//BridgeEdges.CreateEdgeFromProxy(edgeProxy);
edge = BridgeEdges.FindDisabledEdgeByJointGuids(
edgeProxy.m_NodeA_Guid,
edgeProxy.m_NodeB_Guid,
edgeProxy.m_Material
);
if (edge){
edge.ForceEnable();
edge.RefreshJointSelectorNumbers();
break;
}
var NodeA = BridgeJoints.FindByGuid(edgeProxy.m_NodeA_Guid);
var NodeB = BridgeJoints.FindByGuid(edgeProxy.m_NodeB_Guid);
if (!NodeA || !NodeB){
AlertRecieveError("Node/Joint Missing when trying to create edge");
break;
}
BridgeEdge edgeFromJoints = BridgeEdges.GetEdgeFromJoints(
NodeA,
NodeB
);
if (edgeFromJoints){
edgeFromJoints.ForceDisable();
}
instance.ClientRecieving[actionType.CREATE_EDGE] = true;
edge = BridgeEdges.CreateEdgeWithPistonOrSpring(
NodeA,
NodeB,
edgeProxy.m_Material
);
if (message.playSound){
//BridgeAudio.PlayCreateEdge(edgeProxy.m_Material);
}
instance.ClientRecieving[actionType.CREATE_EDGE] = false;
//if (edge.IsPiston()) // I don't think this code should be running
//{
// Pistons.GetPistonOnEdge(edge).m_Slider.MakeVisible();
//}
//if (edge.IsSpring())
//{
// edge.m_SpringCoilVisualization.m_Slider.MakeVisible();
//}
break;
case actionType.CREATE_JOINT:
jointProxy = new BridgeJointProxy(25, message.content, ref offset);
joint = BridgeJoints.FindByGuid(jointProxy.m_Guid);
if (joint)
{
joint.gameObject.SetActive(true);
break;
}
instance.ClientRecieving[actionType.CREATE_JOINT] = true;
BridgeJoints.CreateJointFromProxy(jointProxy);
instance.ClientRecieving[actionType.CREATE_JOINT] = false;
break;
case actionType.DELETE_EDGE:
edgeProxy = new BridgeEdgeProxy(10, message.content, ref offset);
edge = BridgeEdges.FindEnabledEdgeByJointGuids(edgeProxy.m_NodeA_Guid, edgeProxy.m_NodeB_Guid, edgeProxy.m_Material);
if (edge){
edge.ForceDisable();
edge.SetStressColor(0f);
if (message.playSound){
//InterfaceAudio.Play("ui_build_delete");
}
}
BridgeJoints.DeleteOrphanedJoints();
break;
case actionType.DELETE_JOINT:
jointProxy = new BridgeJointProxy(25, message.content, ref offset);
joint = BridgeJoints.FindByGuid(jointProxy.m_Guid);
if (joint){
joint.gameObject.SetActive(false);
}
BridgeJoints.DeleteOrphanedJoints();
break;
case actionType.TRANSLATE_JOINT:
jointProxy = new BridgeJointProxy(25, message.content, ref offset);
joint = BridgeJoints.FindByGuid(jointProxy.m_Guid);
if (joint){
joint.transform.position = jointProxy.m_Pos;
joint.m_BuildPos = joint.transform.position;
joint.TryRecreateSpringVisualizationForAttachedEdges();
}
break;
case actionType.SPRING_SLIDER_TRANSLATE:
springProxy = new BridgeSpringProxy(message.content, ref offset);
var spring = BridgeEdges.FindEnabledEdgeByJointGuids(
springProxy.m_NodeA_Guid,
springProxy.m_NodeB_Guid,
BridgeMaterialType.SPRING
);
if (spring){
spring.m_SpringCoilVisualization.m_Slider.SetNormalizedValue(springProxy.m_NormalizedValue);
spring.m_SpringCoilVisualization.UpdateFreeLengthFromSliderPos();
spring.m_SpringCoilVisualization.MaybeRecreateLinks();
spring.m_SpringCoilVisualization.UpdateLinks();
}
break;
case actionType.PISTON_SLIDER_TRANSLATE:
pistonProxy = new PistonProxy(25, message.content, ref offset);
var piston = Pistons.GetPistonOnEdge(BridgeEdges.FindEnabledEdgeByJointGuids(
pistonProxy.m_NodeA_Guid,
pistonProxy.m_NodeB_Guid,
BridgeMaterialType.HYDRAULICS
));
if (piston){
piston.m_Slider.SetNormalizedValue(pistonProxy.m_NormalizedValue);
}
break;
case actionType.SPLIT_JOINT:
jointProxy = new BridgeJointProxy(25, message.content, ref offset);
joint = BridgeJoints.FindByGuid(jointProxy.m_Guid);
if (joint){
instance.ClientRecieving[actionType.SPLIT_JOINT] = true;
joint.Split();
joint.ResetJointSelectors();
instance.ClientRecieving[actionType.SPLIT_JOINT] = false;
}
break;
case actionType.UNSPLIT_JOINT:
jointProxy = new BridgeJointProxy(25, message.content, ref offset);
joint = BridgeJoints.FindByGuid(jointProxy.m_Guid);
if (joint){
instance.ClientRecieving[actionType.UNSPLIT_JOINT] = true;
joint.UnSplit();
instance.ClientRecieving[actionType.UNSPLIT_JOINT] = false;
}
break;
case actionType.SPLIT_MODIFY:
edgeProxy = new BridgeEdgeProxy(10, message.content, ref offset);
edge = BridgeEdges.FindEnabledEdgeByJointGuids(edgeProxy.m_NodeA_Guid, edgeProxy.m_NodeB_Guid, edgeProxy.m_Material);
if (edge){
edge.m_JointAPart = edgeProxy.m_JointAPart;
edge.m_JointBPart = edgeProxy.m_JointBPart;
edge.RefreshJointSelectorNumbers();
}
break;
case actionType.HYDRAULIC_CONTROLLER_ACTION:
HydraulicsControllerActionModel content = new HydraulicsControllerActionModel(message.content, ref offset);
instance.Logger.LogInfo("- " + content.action.ToString());
// figure out what phases we are applying this to
List<HydraulicsControllerPhase> phases = new List<HydraulicsControllerPhase> ();
if (content.doForEveryPhase) phases = HydraulicsController.m_ControllerPhases;
else {
HydraulicsPhase hydraulicsPhase = HydraulicsPhases.FindByGuid(content.phaseGuid);
HydraulicsControllerPhase hydraulicsControllerPhase = HydraulicsController.FindControllerPhaseWithHydraulicsPhase(hydraulicsPhase);
phases.Add(hydraulicsControllerPhase);
}
if (content.phaseMustBeAcceptingAdditions){
List<HydraulicsControllerPhase> phases2 = new List<HydraulicsControllerPhase> ();
foreach (var phase in phases){
if (!phase.m_DisableNewAdditions) phases2.Add(phase);
}
phases = phases2;
}
if (content.action == HydraulicsControllerAction.SET_THREE_WAY_SPLIT_JOINT_TOGGLE_STATE){
GameUI.m_Instance.m_HydraulicsController.m_ThreeWayJointsToggle.isOn = content.ThreeWaySplitJointToggleState;
SandboxSettings.m_ThreeWaySplitJointsEnabled = GameUI.m_Instance.m_HydraulicsController.m_ThreeWayJointsToggle.isOn;
Profile.Save();
break;
}
foreach (HydraulicsControllerPhase hydraulicsControllerPhase in phases){
if (hydraulicsControllerPhase == null) continue;
switch (content.action){
case HydraulicsControllerAction.ADD_SPLIT_JOINT:
if (content.doForEverySplitJoint){
foreach (BridgeJoint bridgeJoint in BridgeJoints.m_Joints)
{
if (bridgeJoint.m_IsSplit && bridgeJoint.gameObject.activeInHierarchy)
{
if (!hydraulicsControllerPhase.AffectsSplitJoint(bridgeJoint))
{
hydraulicsControllerPhase.AddSplitJoint(bridgeJoint, SplitJointState.ALL_SPLIT);
}
else
{
hydraulicsControllerPhase.SetStateForJoint(bridgeJoint, SplitJointState.ALL_SPLIT);
}
}
}
}
else {
joint = BridgeJoints.FindByGuid(content.jointGuid);
hydraulicsControllerPhase.AddSplitJoint(joint, (joint.m_SplitJointState == SplitJointState.NONE_SPLIT) ? SplitJointState.ALL_SPLIT : joint.m_SplitJointState);
}
break;
case HydraulicsControllerAction.REMOVE_SPLIT_JOINT:
if (content.doForEverySplitJoint){
hydraulicsControllerPhase.RemoveAllSplitJoints();
}
else if (content.weirdRemoveFlagForJointBeingDestroyed){
joint = BridgeJoints.FindByGuid(content.jointGuid);
foreach (BridgeSplitJoint bridgeSplitJoint in hydraulicsControllerPhase.m_SplitJoints)
{
if (bridgeSplitJoint.m_BridgeJoint == joint)
{
hydraulicsControllerPhase.m_SplitJoints.Remove(bridgeSplitJoint);
break;
}
}
}
else {
joint = BridgeJoints.FindByGuid(content.jointGuid);
hydraulicsControllerPhase.RemoveSplitJoint(joint);
}
break;
case HydraulicsControllerAction.ADD_PISTON:
if (content.doForEveryPiston){
foreach (Piston item in Pistons.m_Pistons)
{
if (!hydraulicsControllerPhase.m_Pistons.Contains(item))
{
hydraulicsControllerPhase.m_Pistons.Add(item);
}
}
}
else {
pistonProxy = JsonUtility.FromJson<PistonProxy>(content.pistonProxySerialized);
piston = Pistons.GetPistonOnEdge(BridgeEdges.FindEnabledEdgeByJointGuids(
pistonProxy.m_NodeA_Guid,
pistonProxy.m_NodeB_Guid,
BridgeMaterialType.HYDRAULICS
));
if (!hydraulicsControllerPhase.m_Pistons.Contains(piston)){
hydraulicsControllerPhase.m_Pistons.Add(piston);
}
}
break;
case HydraulicsControllerAction.REMOVE_PISTON:
if (content.doForEveryPiston){
hydraulicsControllerPhase.m_Pistons.Clear();
}
else {
pistonProxy = JsonUtility.FromJson<PistonProxy>(content.pistonProxySerialized);
piston = Pistons.GetPistonOnEdge(BridgeEdges.FindEnabledEdgeByJointGuids(
pistonProxy.m_NodeA_Guid,
pistonProxy.m_NodeB_Guid,
BridgeMaterialType.HYDRAULICS
));
if (hydraulicsControllerPhase.m_Pistons.Contains(piston)){
hydraulicsControllerPhase.m_Pistons.Remove(piston);
}
}
break;
case HydraulicsControllerAction.SET_DISABLE_NEW_ADDITIONS:
foreach (var phase in phases){
phase.m_DisableNewAdditions = content.DisableAdditonsState;
}
break;
case HydraulicsControllerAction.SET_SPLIT_JOINT_STATE:
joint = BridgeJoints.FindByGuid(content.jointGuid);
hydraulicsControllerPhase.SetStateForJoint(joint, content.splitJointState);
break;
default:
instance.Logger.LogError("Unrecognized Hydraulic controller action! " + content.action.ToString());
break;
}
if (hydraulicsControllerPhase != null && hydraulicsControllerPhase.m_HydraulicsPhase != null)
{
EventStage stageWithUnit = EventTimelines.GetStageWithUnit(hydraulicsControllerPhase.m_HydraulicsPhase.gameObject);
if (stageWithUnit != null && GameUI.m_Instance.m_HydraulicsController.isActiveAndEnabled)
{
GameUI.m_Instance.m_HydraulicsController.m_Stages.EnableOffIconForStage(stageWithUnit, hydraulicsControllerPhase.m_DisableNewAdditions);
}
}
}
break;
case actionType.SYNC_LAYOUT:
syncRequests.Add(new SyncRequest { requestActive = true, message = message});
break;
case actionType.FREEZE:
serverIsFrozen = message.content == new byte[] {1} ? true : false;
instance.Logger.LogInfo(serverIsFrozen);
if (serverIsFrozen){
PopUpMessage.DisplayOkOnly("Changes frozen by host.", null);
}
break;
default:
instance.Logger.LogError("<CLIENT> recieved unexpected action");
break;
}
}
public void processSyncRequest(SyncRequest request){
BridgeActionModel message = request.message;
int offset = 0;
SyncLayoutModel layout = new SyncLayoutModel();
BridgeActionModel _message = new BridgeActionModel { action = actionType.SYNC_LAYOUT };
if (instance.communication.isOwner){
instance.Logger.LogInfo("sending layout as requested");
layout.layoutData = SandboxLayout.SerializeToProxies(SandboxLayout.CURRENT_VERSION).SerializeBinary();
_message.content = layout.Serialize();
instance.communication.Lobby.SendBridgeAction(_message);
return;
}
layout = new SyncLayoutModel(message.content, ref offset);
preventSendActions = true;
int num = 0;
var result = new SandboxLayoutData(layout.layoutData, ref num);
Sandbox.Clear();
Sandbox.Load(result.m_ThemeStubKey, result, true);
SandboxUndo.Clear();
SandboxUndo.SnapShot();
PointsOfView.OnLayoutLoaded();
if (GameStateManager.GetState() == GameState.BUILD)
{
GameStateBuild.SetWaterProperties();
GameStateBuild.SetOverrideColorsForBuildMode();
}
preventSendActions = false;
PopUpMessage.DisplayOkOnly("The host has synced their layout with you", null);
}
public static Dictionary<string, string> getOptionalParams(List<string> parameters){
Dictionary<string, string> optional_params = new Dictionary<string, string>();
foreach (var p in parameters){
//instance.Logger.LogInfo(p);
string[] split = p.Split('=');
//instance.Logger.LogInfo($"{split[0].ToString()} {split[1].ToString()}");
optional_params[split[0].ToString()] = split[1].ToString();
}
return optional_params;
}
public static void AlertRecieveError(string message){
if (!instance.communication.isOwner){
PopUpMessage.Display(
"A problem occurred: " + message + " - Press tick to attempt to sync layout with the host or cross to dismiss this message.",
() => syncLayout(),
() => {}
);
}
}
public static void ActionLog(string message){
string logItem;
if (!logActions.Value) return;
if (instance.logBuffer.Count >= 100){
string path = Path.Combine(SandboxLayout.GetSavePath(), instance.backupFolder);
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
path = Path.Combine(path, instance.communication.logFileName);
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path)) {}
}
using (StreamWriter sw = File.AppendText(path))
{
while (instance.logBuffer.Count > 0){
logItem = instance.logBuffer[instance.logBuffer.Count-1];
instance.logBuffer.RemoveAt(instance.logBuffer.Count-1);
sw.WriteLine(logItem);
}
}
return;
}
string prefix = string.Format("[{0:yyyy-MM-dd HH:mm:ss}]", DateTime.Now);
instance.logBuffer.Add($"{prefix} {message}");
}
public void backupLayout(){
if (!clientEnabled) return;
if (!communication.isOwner) return;
if (GameStateManager.GetState() == GameState.SIM) return;
try {
string filename = string.Format("{0:yyyy-MM-dd HH-mm-ss}.layout", DateTime.Now);
Logger.LogInfo("Performing Layout Backup...");
byte[] layoutData = SandboxLayout.SerializeToProxies(SandboxLayout.CURRENT_VERSION).SerializeBinary();
string path = Path.Combine(SandboxLayout.GetSavePath(), backupFolder);
//Logger.LogInfo(path + " " + filename);
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
Utils.WriteBytes(path, filename, layoutData);
}
catch (Exception ex){
Logger.LogError($"Caught error when backing up layout: {ex.Message}");
}
}
public static void RaiseConnectionError(string error){
GUIValues.ConnectionResponse = $"<color=red>Connection Error occured: {error}</color>";
}
public static void Connect(){
//if (instance.clientEnabled){
// uConsole.Log("Already Connected to a server");
// return;
//}
//
//if (uConsole.GetNumParameters() < 3){
// uConsole.Log("Usage (? signifies optional): Connect <host_ip> <port> <server_name> <?password>");
// return;
//}
if (GameStateManager.GetState() != GameState.BUILD){
GUIValues.ConnectionResponse = "You must be in build mode to start/connect to a session";
return;
}
string hostIP = GUIValues.ip;
int port;
try {
port = int.Parse(GUIValues.port);
}
catch {
RaiseConnectionError("Invalid port");
return;
}
serverName = GUIValues.sessionName;
string password, invite;
ClientName = Workshop.GetLocalPlayerDisplayName();
string id = Workshop.GetLocalPlayerId();
password = GUIValues.password;
invite = GUIValues.invite;
if (serverName == ""){
RaiseConnectionError("Invalid Session Name");
return;
}
if (hostIP == ""){
RaiseConnectionError("Invalid host IP");
return;
}
instance.communication = new ServerCommunication();
instance.communication.useLocalhost = false;
instance.communication.hostIP = hostIP;
instance.communication.path = $"{serverName}?username={ClientName}&id={id}";
if (password != "") instance.communication.path += $"&password={password}";
if (invite != "") instance.communication.path += $"&invite={invite}";
instance.communication.port = port;
instance.communication.ssl = GUIValues.secureConnection;
instance.communication.Init();
instance.communication.Lobby.OnConnectedToServer += instance.OnConnectedToServer;
instance.communication.ConnectToServer();
ChatValues.Reset();
//uConsole.Log("Enabled Client");
}
public static void Disconnect(){
//if (!instance.clientEnabled){
// uConsole.Log("You aren't connected to anything.");
// return;
//}
try {
if (instance != null && instance.communication != null){
instance.communication.client.ws.CloseAsync(
WebSocketCloseStatus.NormalClosure,
"closed",
new CancellationToken()
);
}
}
catch {
}
instance.communication = null;
instance.serverInfo = null;
instance.logBuffer.Clear();
GUIValues.Reset();
if (instance.GetServerInfo != null) instance.StopCoroutine(instance.GetServerInfo);
if (instance.SendMousePos != null) instance.StopCoroutine(instance.SendMousePos);
foreach (string key in instance.mousePositions.Keys){
Destroy(instance.mousePositions[key].Container);
}
instance.mousePositions.Clear();
//uConsole.Log("Disabled Client");
//instance.clientEnabled = false;
}
public void ConnectionInfo(){
if (!clientEnabled) return;
communication.SendRequest(
new MessageModel {
type = LobbyMessaging.ServerInfo
}.Serialize()
);
}
public void SendMousePosition(){
if (Bridge.IsSimulating()) return;
Vector3 pos = Cameras.MainCamera().ScreenToWorldPoint(Input.mousePosition);
communication.SendRequest(
new MessageModel {
type = LobbyMessaging.MousePosition,
content = new MousePositionModel {
position = pos,
pointerMode = GameUI.GetPointerMode(),
pointerColor = mouseColor.Value
}.Serialize()
}.Serialize()
);
}
public void HandleMousePositionRecieved(MousePositionModel mousePosition){
PointerHandler handler;
SpriteRenderer renderer;
if (!mousePositions.TryGetValue(mousePosition.username, out handler)){
Debug.Log("new mouse: " + mousePosition.username);
handler = new PointerHandler();
handler.Container.transform.parent = canvas.transform;
mousePositions[mousePosition.username] = handler;
}
mousePosition.position.z = -2.5f;
renderer = handler.Container.GetComponent<SpriteRenderer>();
renderer.transform.position = mousePosition.position;
renderer.sprite = pointerSprites[mousePosition.pointerMode];
handler.color = mousePosition.pointerColor;
renderer.color = handler.color;
}
public static void RemoveDisconnectedUsersFromMousePositions(){
var foundUser = false;
List<string> UsersToRemove = new List<string> {};
foreach (var username in instance.mousePositions.Keys){
foundUser = false;
foreach (string userConnected in instance.serverInfo.playerNames){
if (username == userConnected){
// user mouse already accounted for
foundUser = true;
break;
}
}
// user is no longer connected, set their mouse for removal
if (!foundUser) UsersToRemove.Add(username);
}
foreach (string username in UsersToRemove){
Destroy(instance.mousePositions[username].Container);
instance.mousePositions.Remove(username);
//instance.Logger.LogInfo($"Removed {username}");
}
foreach (string key in instance.mousePositions.Keys){
//instance.Logger.LogInfo($"{key} : {instance.mousePositions[key]}");
}
}
public void SetFreeze(bool value){
var message = new BridgeActionModel {
action = actionType.FREEZE,
content = BitConverter.GetBytes(true)
};
instance.Logger.LogInfo($"<CLIENT> sending {message.action}");
instance.communication.Lobby.SendBridgeAction(message);
PopUpMessage.DisplayOkOnly(
"Changes frozen until you sync your layout with all connected users.",
null
);
instance.serverIsFrozen = true;
}
public static void KickUser(string username){
if (!instance.clientEnabled){
//uConsole.Log("You aren't connected to anything.");
return;
}
var content = new KickUserModel {
username = username,
reason = GUIValues.kickUserReason
};
var message = new MessageModel {
type = LobbyMessaging.KickUser,
content = content.Serialize()
};
instance.communication.SendRequest(message.Serialize());
}
public static void setPassword(){
if (!instance.clientEnabled){
//uConsole.Log("You aren't connected to anything.");
return;
}
string password = GUIValues.changingPassword;
var content = new ServerConfigModel {
action = ConfigAction.CHANGE_PASSWORD,
newPassword = password
};
var message = new MessageModel {
type = LobbyMessaging.ServerConfig,
content = content.Serialize()
};
instance.communication.SendRequest(message.Serialize());
}
public static void setUserCap(){
if (!instance.clientEnabled){
//uConsole.Log("You aren't connected to anything.");
return;
}
int userCap;
try {
userCap = int.Parse(GUIValues.userCap);
}
catch {
return;
}
var content = new ServerConfigModel {
action = ConfigAction.USER_CAP,
userCap = userCap
};
var message = new MessageModel {
type = LobbyMessaging.ServerConfig,
content = content.Serialize()
};
instance.communication.SendRequest(message.Serialize());
}
public static void setAcceptConnections(){
if (!instance.clientEnabled){
//uConsole.Log("You aren't connected to anything.");
return;
}
bool acceptingConnections = GUIValues.acceptingConnections;
var content = new ServerConfigModel {
action = ConfigAction.ACCEPTING_CONNECTIONS,
acceptingConnections = acceptingConnections
};
var message = new MessageModel {
type = LobbyMessaging.ServerConfig,
content = content.Serialize()
};
instance.communication.SendRequest(message.Serialize());
}
public static void setLobbyMode(LobbyMode mode){
if (!instance.clientEnabled){
//uConsole.Log("You aren't connected to anything.");
return;
}
var content = new ServerConfigModel {
action = ConfigAction.CHANGE_LOBBY_MODE,
lobbyMode = mode
};
var message = new MessageModel {
type = LobbyMessaging.ServerConfig,
content = content.Serialize()
};
instance.communication.SendRequest(message.Serialize());
}
public static void CreateInvite(){
if (!instance.clientEnabled){
//uConsole.Log("You aren't connected to anything.");
return;
}
int uses = 1;
int.TryParse(GUIValues.inviteUses, out uses);
GUIValues.inviteUses = uses.ToString();
var message = new MessageModel {
type = LobbyMessaging.CreateInvite,
content = BitConverter.GetBytes(uses)
};
instance.communication.SendRequest(message.Serialize());
}
public static void syncLayout(){
if (!instance.clientEnabled){
//uConsole.Log("You aren't connected to anything.");
return;
}
if (GameStateManager.GetState() == GameState.SIM){
PopUpMessage.DisplayOkOnly("You must exit the simulation before syncing layout.", null);
return;
}
SyncLayoutModel layout = new SyncLayoutModel();
var message = new BridgeActionModel { action = actionType.SYNC_LAYOUT };
if (instance.communication.isOwner){
if (instance.serverIsFrozen){
instance.communication.Lobby.SendBridgeAction(
new BridgeActionModel {
action = actionType.FREEZE,
content = BitConverter.GetBytes(false)
}
);
instance.serverIsFrozen = false;
}
//uConsole.Log("Force Syncing layout with all connected clients...");
layout.layoutData = SandboxLayout.SerializeToProxies(SandboxLayout.CURRENT_VERSION).SerializeBinary();
layout.targetAllUsers = true;
message.content = layout.Serialize();
instance.communication.Lobby.SendBridgeAction(message);
return;
}
if (instance.serverIsFrozen){
//uConsole.Log("Changes are currently frozen.");
return;
}
//uConsole.Log("Requesting owner for layout...");
message.content = layout.Serialize();
instance.communication.Lobby.SendBridgeAction(message);
}
public void onEnableDisable(object sender, EventArgs e)
{
this.isEnabled = modEnabled.Value;
if (modEnabled.Value)
{
enableMod();
}
else
{
disableMod();
}
}
public override void enableMod()
{
modEnabled.Value = true;
}
// Use this method to execute code that will be ran when the mod is disabled.
public override void disableMod()
{
modEnabled.Value = false;
}
[HarmonyPatch(typeof(GameStateManager), "ChangeState")]
public static class EnterBuildStatePatch {
public static void Prefix(GameState state, ref GameState ___m_GameState){
var prevState = ___m_GameState;
if (state != GameState.BUILD) return;
if (prevState != GameState.SIM && prevState != GameState.SANDBOX) return;
//instance.Logger.LogInfo($"changing to {state} from {prevState}");
instance.ClientRecieving[actionType.CREATE_EDGE] = true;
instance.ClientRecieving[actionType.CREATE_JOINT] = true;
}
public static void Postfix(GameState state, ref GameState ___m_PrevGameState){
var prevState = ___m_PrevGameState;
if (state != GameState.BUILD) return;
if (prevState != GameState.SIM && prevState != GameState.SANDBOX) return;
//instance.Logger.LogInfo($"changed to {state} from {prevState}");
instance.ClientRecieving[actionType.CREATE_EDGE] = false;
instance.ClientRecieving[actionType.CREATE_JOINT] = false;
}
}
[HarmonyPatch(typeof(BridgeEdges), "CreateEdge")]
public static class CreateEdgePatch {
public static void Postfix(
BridgeJoint jointA,
BridgeJoint jointB,
BridgeMaterialType materialType,
ref BridgeEdge __result,
Edge physicsEdge_onlyUsedWhenBreakingEdgesInSimulation = null