forked from CnCNet/xna-cncnet-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCnCNetGameLobby.cs
More file actions
1976 lines (1598 loc) · 75.2 KB
/
CnCNetGameLobby.cs
File metadata and controls
1976 lines (1598 loc) · 75.2 KB
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 ClientCore;
using ClientCore.CnCNet5;
using ClientGUI;
using DTAClient.Domain.Multiplayer;
using DTAClient.Domain;
using DTAClient.DXGUI.Generic;
using DTAClient.DXGUI.Multiplayer.CnCNet;
using DTAClient.DXGUI.Multiplayer.GameLobby.CommandHandlers;
using DTAClient.Online;
using DTAClient.Online.EventArguments;
using Microsoft.Xna.Framework;
using Rampastring.Tools;
using Rampastring.XNAUI;
using Rampastring.XNAUI.XNAControls;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using DTAClient.Domain.Multiplayer.CnCNet;
using ClientCore.Extensions;
namespace DTAClient.DXGUI.Multiplayer.GameLobby
{
public class CnCNetGameLobby : MultiplayerGameLobby
{
private const int HUMAN_PLAYER_OPTIONS_LENGTH = 3;
private const int AI_PLAYER_OPTIONS_LENGTH = 2;
private const double GAME_BROADCAST_INTERVAL = 30.0;
private const double GAME_BROADCAST_ACCELERATION = 10.0;
private const double INITIAL_GAME_BROADCAST_DELAY = 10.0;
private static readonly Color ERROR_MESSAGE_COLOR = Color.Yellow;
private const string MAP_SHARING_FAIL_MESSAGE = "MAPFAIL";
private const string MAP_SHARING_DOWNLOAD_REQUEST = "MAPOK";
private const string MAP_SHARING_UPLOAD_REQUEST = "MAPREQ";
private const string MAP_SHARING_DISABLED_MESSAGE = "MAPSDISABLED";
private const string CHEAT_DETECTED_MESSAGE = "CD";
private const string DICE_ROLL_MESSAGE = "DR";
private const string CHANGE_TUNNEL_SERVER_MESSAGE = "CHTNL";
public CnCNetGameLobby(
WindowManager windowManager,
TopBar topBar,
CnCNetManager connectionManager,
TunnelHandler tunnelHandler,
GameCollection gameCollection,
CnCNetUserData cncnetUserData,
MapLoader mapLoader,
DiscordHandler discordHandler,
PrivateMessagingWindow pmWindow
) : base(windowManager, "MultiplayerGameLobby", topBar, mapLoader, discordHandler, pmWindow)
{
this.connectionManager = connectionManager;
localGame = ClientConfiguration.Instance.LocalGame;
this.tunnelHandler = tunnelHandler;
this.gameCollection = gameCollection;
this.cncnetUserData = cncnetUserData;
this.pmWindow = pmWindow;
ctcpCommandHandlers = new CommandHandlerBase[]
{
new IntCommandHandler("OR", HandleOptionsRequest),
new IntCommandHandler("R", HandleReadyRequest),
new StringCommandHandler("PO", ApplyPlayerOptions),
new StringCommandHandler(PlayerExtraOptions.CNCNET_MESSAGE_KEY, ApplyPlayerExtraOptions),
new StringCommandHandler("GO", ApplyGameOptions),
new StringCommandHandler("START", NonHostLaunchGame),
new NotificationHandler("AISPECS", HandleNotification, AISpectatorsNotification),
new NotificationHandler("GETREADY", HandleNotification, GetReadyNotification),
new NotificationHandler("INSFSPLRS", HandleNotification, InsufficientPlayersNotification),
new NotificationHandler("TMPLRS", HandleNotification, TooManyPlayersNotification),
new NotificationHandler("CLRS", HandleNotification, SharedColorsNotification),
new NotificationHandler("SLOC", HandleNotification, SharedStartingLocationNotification),
new NotificationHandler("LCKGME", HandleNotification, LockGameNotification),
new IntNotificationHandler("NVRFY", HandleIntNotification, NotVerifiedNotification),
new IntNotificationHandler("INGM", HandleIntNotification, StillInGameNotification),
new StringCommandHandler(MAP_SHARING_UPLOAD_REQUEST, HandleMapUploadRequest),
new StringCommandHandler(MAP_SHARING_FAIL_MESSAGE, HandleMapTransferFailMessage),
new StringCommandHandler(MAP_SHARING_DOWNLOAD_REQUEST, HandleMapDownloadRequest),
new NoParamCommandHandler(MAP_SHARING_DISABLED_MESSAGE, HandleMapSharingBlockedMessage),
new NoParamCommandHandler("STRTD", GameStartedNotification),
new NoParamCommandHandler("RETURN", ReturnNotification),
new IntCommandHandler("TNLPNG", HandleTunnelPing),
new StringCommandHandler("FHSH", FileHashNotification),
new StringCommandHandler("MM", CheaterNotification),
new StringCommandHandler(DICE_ROLL_MESSAGE, HandleDiceRollResult),
new NoParamCommandHandler(CHEAT_DETECTED_MESSAGE, HandleCheatDetectedMessage),
new StringCommandHandler(CHANGE_TUNNEL_SERVER_MESSAGE, HandleTunnelServerChangeMessage)
};
MapSharer.MapDownloadFailed += MapSharer_MapDownloadFailed;
MapSharer.MapDownloadComplete += MapSharer_MapDownloadComplete;
MapSharer.MapUploadFailed += MapSharer_MapUploadFailed;
MapSharer.MapUploadComplete += MapSharer_MapUploadComplete;
AddChatBoxCommand(new ChatBoxCommand("TUNNELINFO",
"View tunnel server information".L10N("Client:Main:TunnelInfoCommand"), false, PrintTunnelServerInformation));
AddChatBoxCommand(new ChatBoxCommand("CHANGETUNNEL",
"Change the used CnCNet tunnel server (game host only)".L10N("Client:Main:ChangeTunnelCommand"),
true, (s) => ShowTunnelSelectionWindow("Select tunnel server:".L10N("Client:Main:SelectTunnelServerCommand"))));
AddChatBoxCommand(new ChatBoxCommand("DOWNLOADMAP",
"Download a map from CNCNet's map server using a map ID and an optional filename.\nExample: \"/downloadmap MAPID [2] My Battle Map\"".L10N("Client:Main:DownloadMapCommandDescription"),
false, DownloadMapByIdCommand));
}
public event EventHandler GameLeft;
private TunnelHandler tunnelHandler;
private TunnelSelectionWindow tunnelSelectionWindow;
private XNAClientButton btnChangeTunnel;
private Channel channel;
private CnCNetManager connectionManager;
private string localGame;
private GameCollection gameCollection;
private CnCNetUserData cncnetUserData;
private readonly PrivateMessagingWindow pmWindow;
private GlobalContextMenu globalContextMenu;
private string hostName;
private CommandHandlerBase[] ctcpCommandHandlers;
private IRCColor chatColor;
private XNATimerControl gameBroadcastTimer;
private int playerLimit;
private bool closed = false;
private int skillLevel = ClientConfiguration.Instance.DefaultSkillLevelIndex;
private bool isCustomPassword = false;
private string gameFilesHash;
private List<string> hostUploadedMaps = new List<string>();
private List<string> chatCommandDownloadedMaps = new List<string>();
private MapSharingConfirmationPanel mapSharingConfirmationPanel;
/// <summary>
/// The SHA1 of the latest selected map.
/// Used for map sharing.
/// </summary>
private string lastMapSHA1;
/// <summary>
/// The map name of the latest selected map.
/// Used for map sharing.
/// </summary>
private string lastMapName;
/// <summary>
/// The game mode of the latest selected map.
/// Used for map sharing.
/// </summary>
private string lastGameMode;
/// <summary>
/// Set to true if host has selected invalid tunnel server.
/// </summary>
private bool tunnelErrorMode;
public override void Initialize()
{
IniNameOverride = nameof(CnCNetGameLobby);
base.Initialize();
btnChangeTunnel = FindChild<XNAClientButton>(nameof(btnChangeTunnel));
btnChangeTunnel.LeftClick += BtnChangeTunnel_LeftClick;
gameBroadcastTimer = new XNATimerControl(WindowManager);
gameBroadcastTimer.AutoReset = true;
gameBroadcastTimer.Interval = TimeSpan.FromSeconds(GAME_BROADCAST_INTERVAL);
gameBroadcastTimer.Enabled = false;
gameBroadcastTimer.TimeElapsed += GameBroadcastTimer_TimeElapsed;
tunnelSelectionWindow = new TunnelSelectionWindow(WindowManager, tunnelHandler);
tunnelSelectionWindow.Initialize();
tunnelSelectionWindow.DrawOrder = 1;
tunnelSelectionWindow.UpdateOrder = 1;
DarkeningPanel.AddAndInitializeWithControl(WindowManager, tunnelSelectionWindow);
tunnelSelectionWindow.CenterOnParent();
tunnelSelectionWindow.Disable();
tunnelSelectionWindow.TunnelSelected += TunnelSelectionWindow_TunnelSelected;
mapSharingConfirmationPanel = new MapSharingConfirmationPanel(WindowManager);
MapPreviewBox.AddChild(mapSharingConfirmationPanel);
mapSharingConfirmationPanel.MapDownloadConfirmed += MapSharingConfirmationPanel_MapDownloadConfirmed;
WindowManager.AddAndInitializeControl(gameBroadcastTimer);
globalContextMenu = new GlobalContextMenu(WindowManager, connectionManager, cncnetUserData, pmWindow);
AddChild(globalContextMenu);
MultiplayerNameRightClicked += MultiplayerName_RightClick;
PostInitialize();
}
private void MultiplayerName_RightClick(object sender, MultiplayerNameRightClickedEventArgs args)
{
globalContextMenu.Show(new GlobalContextMenuData()
{
PlayerName = args.PlayerName,
PreventJoinGame = true
}, GetCursorPoint());
}
private void BtnChangeTunnel_LeftClick(object sender, EventArgs e) => ShowTunnelSelectionWindow("Select tunnel server:".L10N("Client:Main:SelectTunnelServer"));
private void GameBroadcastTimer_TimeElapsed(object sender, EventArgs e) => BroadcastGame();
public void SetUp(Channel channel, bool isHost, int playerLimit,
CnCNetTunnel tunnel, string hostName, bool isCustomPassword,
int skillLevel)
{
this.channel = channel;
channel.MessageAdded += Channel_MessageAdded;
channel.CTCPReceived += Channel_CTCPReceived;
channel.UserKicked += Channel_UserKicked;
channel.UserQuitIRC += Channel_UserQuitIRC;
channel.UserLeft += Channel_UserLeft;
channel.UserAdded += Channel_UserAdded;
channel.UserNameChanged += Channel_UserNameChanged;
channel.UserListReceived += Channel_UserListReceived;
this.hostName = hostName;
this.playerLimit = playerLimit;
this.isCustomPassword = isCustomPassword;
this.skillLevel = skillLevel;
if (isHost)
{
RandomSeed = new Random().Next();
RefreshMapSelectionUI();
btnChangeTunnel.Enable();
}
else
{
channel.ChannelModesChanged += Channel_ChannelModesChanged;
AIPlayers.Clear();
btnChangeTunnel.Disable();
}
tunnelHandler.CurrentTunnel = tunnel;
tunnelHandler.CurrentTunnelPinged += TunnelHandler_CurrentTunnelPinged;
connectionManager.ConnectionLost += ConnectionManager_ConnectionLost;
connectionManager.Disconnected += ConnectionManager_Disconnected;
Refresh(isHost);
}
private void TunnelHandler_CurrentTunnelPinged(object sender, EventArgs e) => UpdatePing();
public void OnJoined()
{
FileHashCalculator fhc = new FileHashCalculator();
fhc.CalculateHashes();
gameFilesHash = fhc.GetCompleteHash();
if (IsHost)
{
connectionManager.SendCustomMessage(new QueuedMessage(
string.Format("MODE {0} +klnNs {1} {2}", channel.ChannelName,
channel.Password, playerLimit),
QueuedMessageType.SYSTEM_MESSAGE, 50));
connectionManager.SendCustomMessage(new QueuedMessage(
string.Format("TOPIC {0} :{1}", channel.ChannelName,
ProgramConstants.CNCNET_PROTOCOL_REVISION + ";" + localGame.ToLower()),
QueuedMessageType.SYSTEM_MESSAGE, 50));
gameBroadcastTimer.Enabled = true;
gameBroadcastTimer.Start();
gameBroadcastTimer.SetTime(TimeSpan.FromSeconds(INITIAL_GAME_BROADCAST_DELAY));
}
else
{
channel.SendCTCPMessage("FHSH " + gameFilesHash, QueuedMessageType.SYSTEM_MESSAGE, 10);
}
TopBar.AddPrimarySwitchable(this);
TopBar.SwitchToPrimary();
WindowManager.SelectedControl = tbChatInput;
ResetAutoReadyCheckbox();
UpdatePing();
UpdateDiscordPresence(true);
}
private void UpdatePing()
{
if (tunnelHandler.CurrentTunnel == null)
return;
channel.SendCTCPMessage("TNLPNG " + tunnelHandler.CurrentTunnel.PingInMs, QueuedMessageType.SYSTEM_MESSAGE, 10);
PlayerInfo pInfo = Players.Find(p => p.Name.Equals(ProgramConstants.PLAYERNAME));
if (pInfo != null)
{
pInfo.Ping = tunnelHandler.CurrentTunnel.PingInMs;
UpdatePlayerPingIndicator(pInfo);
}
}
protected override void CopyPlayerDataToUI()
{
base.CopyPlayerDataToUI();
for (int i = AIPlayers.Count + Players.Count; i < MAX_PLAYER_COUNT; i++)
{
StatusIndicators[i].SwitchTexture(
i < playerLimit ? PlayerSlotState.Empty : PlayerSlotState.Unavailable);
}
}
private void PrintTunnelServerInformation(string s)
{
if (tunnelHandler.CurrentTunnel == null)
{
AddNotice("Tunnel server unavailable!".L10N("Client:Main:TunnelUnavailable"));
}
else
{
AddNotice(string.Format("Current tunnel server: {0} {1} (Players: {2}/{3}) (Official: {4})".L10N("Client:Main:TunnelInfo"),
tunnelHandler.CurrentTunnel.Name, tunnelHandler.CurrentTunnel.Country, tunnelHandler.CurrentTunnel.Clients, tunnelHandler.CurrentTunnel.MaxClients, tunnelHandler.CurrentTunnel.Official
));
}
}
private void ShowTunnelSelectionWindow(string description)
{
tunnelSelectionWindow.Open(description,
tunnelHandler.CurrentTunnel?.Address);
}
private void TunnelSelectionWindow_TunnelSelected(object sender, TunnelEventArgs e)
{
channel.SendCTCPMessage($"{CHANGE_TUNNEL_SERVER_MESSAGE} {e.Tunnel.Address}:{e.Tunnel.Port}",
QueuedMessageType.SYSTEM_MESSAGE, 10);
HandleTunnelServerChange(e.Tunnel);
}
public void ChangeChatColor(IRCColor chatColor)
{
this.chatColor = chatColor;
tbChatInput.TextColor = chatColor.XnaColor;
}
public override void Clear()
{
base.Clear();
if (channel != null)
{
channel.MessageAdded -= Channel_MessageAdded;
channel.CTCPReceived -= Channel_CTCPReceived;
channel.UserKicked -= Channel_UserKicked;
channel.UserQuitIRC -= Channel_UserQuitIRC;
channel.UserLeft -= Channel_UserLeft;
channel.UserAdded -= Channel_UserAdded;
channel.UserNameChanged -= Channel_UserNameChanged;
channel.UserListReceived -= Channel_UserListReceived;
if (!IsHost)
{
channel.ChannelModesChanged -= Channel_ChannelModesChanged;
}
connectionManager.RemoveChannel(channel);
}
Disable();
PlayerExtraOptionsPanel?.Disable();
connectionManager.ConnectionLost -= ConnectionManager_ConnectionLost;
connectionManager.Disconnected -= ConnectionManager_Disconnected;
gameBroadcastTimer.Enabled = false;
closed = false;
tbChatInput.Text = string.Empty;
tunnelHandler.CurrentTunnel = null;
tunnelHandler.CurrentTunnelPinged -= TunnelHandler_CurrentTunnelPinged;
GameLeft?.Invoke(this, EventArgs.Empty);
TopBar.RemovePrimarySwitchable(this);
ResetDiscordPresence();
}
public void LeaveGameLobby()
{
if (IsHost)
{
closed = true;
BroadcastGame();
}
Clear();
channel?.Leave();
}
private void ConnectionManager_Disconnected(object sender, EventArgs e) => HandleConnectionLoss();
private void ConnectionManager_ConnectionLost(object sender, ConnectionLostEventArgs e) => HandleConnectionLoss();
private void HandleConnectionLoss()
{
Clear();
Disable();
}
private void Channel_UserNameChanged(object sender, UserNameChangedEventArgs e)
{
Logger.Log("CnCNetGameLobby: Nickname change: " + e.OldUserName + " to " + e.User.Name);
int index = Players.FindIndex(p => p.Name == e.OldUserName);
if (index > -1)
{
PlayerInfo player = Players[index];
player.Name = e.User.Name;
ddPlayerNames[index].Items[0].Text = player.Name;
AddNotice(string.Format("Player {0} changed their name to {1}".L10N("Client:Main:PlayerRename"), e.OldUserName, e.User.Name));
}
}
protected override void BtnLeaveGame_LeftClick(object sender, EventArgs e) => LeaveGameLobby();
protected override void UpdateDiscordPresence(bool resetTimer = false)
{
if (discordHandler == null)
return;
PlayerInfo player = FindLocalPlayer();
if (player == null || Map == null || GameMode == null)
return;
string side = "";
if (ddPlayerSides.Length > Players.IndexOf(player))
side = (string)ddPlayerSides[Players.IndexOf(player)].SelectedItem.Tag;
string currentState = ProgramConstants.IsInGame ? "In Game" : "In Lobby"; // not UI strings
discordHandler.UpdatePresence(
Map.UntranslatedName, GameMode.UntranslatedUIName, "Multiplayer",
currentState, Players.Count, playerLimit, side,
channel.UIName, IsHost, isCustomPassword, Locked, resetTimer);
}
private void Channel_UserQuitIRC(object sender, UserNameEventArgs e)
{
RemovePlayer(e.UserName);
if (e.UserName == hostName)
{
connectionManager.MainChannel.AddMessage(new ChatMessage(
ERROR_MESSAGE_COLOR, "The game host abandoned the game.".L10N("Client:Main:HostAbandoned")));
BtnLeaveGame_LeftClick(this, EventArgs.Empty);
}
else
UpdateDiscordPresence();
}
private void Channel_UserLeft(object sender, UserNameEventArgs e)
{
RemovePlayer(e.UserName);
if (e.UserName == hostName)
{
connectionManager.MainChannel.AddMessage(new ChatMessage(
ERROR_MESSAGE_COLOR, "The game host abandoned the game.".L10N("Client:Main:HostAbandoned")));
BtnLeaveGame_LeftClick(this, EventArgs.Empty);
}
else
UpdateDiscordPresence();
}
private void Channel_UserKicked(object sender, UserNameEventArgs e)
{
if (e.UserName == ProgramConstants.PLAYERNAME)
{
connectionManager.MainChannel.AddMessage(new ChatMessage(
ERROR_MESSAGE_COLOR, "You were kicked from the game!".L10N("Client:Main:YouWereKicked")));
Clear();
this.Visible = false;
this.Enabled = false;
return;
}
int index = Players.FindIndex(p => p.Name == e.UserName);
if (index > -1)
{
Players.RemoveAt(index);
CopyPlayerDataToUI();
UpdateDiscordPresence();
ClearReadyStatuses();
}
}
private void Channel_UserListReceived(object sender, EventArgs e)
{
if (!IsHost)
{
if (channel.Users.Find(hostName) == null)
{
connectionManager.MainChannel.AddMessage(new ChatMessage(
ERROR_MESSAGE_COLOR, "The game host has abandoned the game.".L10N("Client:Main:HostHasAbandoned")));
BtnLeaveGame_LeftClick(this, EventArgs.Empty);
}
}
UpdateDiscordPresence();
}
private void Channel_UserAdded(object sender, ChannelUserEventArgs e)
{
PlayerInfo pInfo = new PlayerInfo(e.User.IRCUser.Name);
Players.Add(pInfo);
if (Players.Count + AIPlayers.Count > MAX_PLAYER_COUNT && AIPlayers.Count > 0)
AIPlayers.RemoveAt(AIPlayers.Count - 1);
sndJoinSound.Play();
#if WINFORMS
WindowManager.FlashWindow();
#endif
if (!IsHost)
{
CopyPlayerDataToUI();
return;
}
if (e.User.IRCUser.Name != ProgramConstants.PLAYERNAME)
{
// Changing the map applies forced settings (co-op sides etc.) to the
// new player, and it also sends an options broadcast message
//CopyPlayerDataToUI(); This is also called by ChangeMap()
ChangeMap(GameModeMap);
BroadcastPlayerOptions();
BroadcastPlayerExtraOptions();
UpdateDiscordPresence();
}
else
{
Players[0].Ready = true;
CopyPlayerDataToUI();
}
if (Players.Count >= playerLimit)
{
AddNotice("Player limit reached. The game room has been locked.".L10N("Client:Main:GameRoomNumberLimitReached"));
LockGame();
}
}
private void RemovePlayer(string playerName)
{
PlayerInfo pInfo = Players.Find(p => p.Name == playerName);
if (pInfo != null)
{
Players.Remove(pInfo);
CopyPlayerDataToUI();
// This might not be necessary
if (IsHost)
BroadcastPlayerOptions();
}
sndLeaveSound.Play();
if (IsHost && Locked && !ProgramConstants.IsInGame)
{
UnlockGame(true);
}
}
private void Channel_ChannelModesChanged(object sender, ChannelModeEventArgs e)
{
if (e.ModeString == "+i")
{
if (Players.Count >= playerLimit)
AddNotice("Player limit reached. The game room has been locked.".L10N("Client:Main:GameRoomNumberLimitReached"));
else
AddNotice("The game host has locked the game room.".L10N("Client:Main:RoomLockedByHost"));
Locked = true;
}
else if (e.ModeString == "-i")
{
AddNotice("The game room has been unlocked.".L10N("Client:Main:GameRoomUnlocked"));
Locked = false;
}
}
private void Channel_CTCPReceived(object sender, ChannelCTCPEventArgs e)
{
Logger.Log("CnCNetGameLobby_CTCPReceived");
foreach (CommandHandlerBase cmdHandler in ctcpCommandHandlers)
{
if (cmdHandler.Handle(e.UserName, e.Message))
{
UpdateDiscordPresence();
return;
}
}
Logger.Log("Unhandled CTCP command: " + e.Message + " from " + e.UserName);
}
private void Channel_MessageAdded(object sender, IRCMessageEventArgs e)
{
if (cncnetUserData.IsIgnored(e.Message.SenderIdent))
{
lbChatMessages.AddMessage(new ChatMessage(Color.Silver,
string.Format("Message blocked from {0}".L10N("Client:Main:MessageBlockedFromPlayer"), e.Message.SenderName)));
}
else
{
lbChatMessages.AddMessage(e.Message);
if (e.Message.SenderName != null)
sndMessageSound.Play();
}
}
/// <summary>
/// Starts the game for the game host.
/// </summary>
protected override void HostLaunchGame()
{
if (Players.Count > 1)
{
AddNotice("Contacting tunnel server...".L10N("Client:Main:ConnectingTunnel"));
List<int> playerPorts = tunnelHandler.CurrentTunnel.GetPlayerPortInfo(Players.Count);
if (playerPorts.Count < Players.Count)
{
ShowTunnelSelectionWindow(("An error occured while contacting " +
"the CnCNet tunnel server.\nTry picking a different tunnel server:").L10N("Client:Main:ConnectTunnelError1"));
AddNotice(("An error occured while contacting the specified CnCNet " +
"tunnel server. Please try using a different tunnel server").L10N("Client:Main:ConnectTunnelError2") + " ", ERROR_MESSAGE_COLOR);
return;
}
StringBuilder sb = new StringBuilder("START ");
sb.Append(UniqueGameID);
for (int pId = 0; pId < Players.Count; pId++)
{
Players[pId].Port = playerPorts[pId];
sb.Append(";");
sb.Append(Players[pId].Name);
sb.Append(";");
sb.Append("0.0.0.0:");
sb.Append(playerPorts[pId]);
}
channel.SendCTCPMessage(sb.ToString(), QueuedMessageType.SYSTEM_MESSAGE, 10);
}
else
{
Logger.Log("One player MP -- starting!");
}
cncnetUserData.AddRecentPlayers(Players.Select(p => p.Name), channel.UIName);
StartGame();
}
protected override void RequestPlayerOptions(int side, int color, int start, int team)
{
byte[] value = new byte[]
{
(byte)side,
(byte)color,
(byte)start,
(byte)team
};
int intValue = BitConverter.ToInt32(value, 0);
channel.SendCTCPMessage(
string.Format("OR {0}", intValue),
QueuedMessageType.GAME_SETTINGS_MESSAGE, 6);
}
protected override void RequestReadyStatus()
{
if (Map == null || GameMode == null)
{
AddNotice(("The game host needs to select a different map or " +
"you will be unable to participate in the match.").L10N("Client:Main:HostMustReplaceMap"));
if (chkAutoReady.Checked)
channel.SendCTCPMessage("R 0", QueuedMessageType.GAME_PLAYERS_READY_STATUS_MESSAGE, 5);
return;
}
PlayerInfo pInfo = Players.Find(p => p.Name == ProgramConstants.PLAYERNAME);
if (pInfo == null)
return;
int readyState = 0;
if (chkAutoReady.Checked)
readyState = 2;
else if (!pInfo.Ready)
readyState = 1;
channel.SendCTCPMessage($"R {readyState}", QueuedMessageType.GAME_PLAYERS_READY_STATUS_MESSAGE, 5);
}
protected override void AddNotice(string message, Color color) => channel.AddMessage(new ChatMessage(color, message));
/// <summary>
/// Handles player option requests received from non-host players.
/// </summary>
private void HandleOptionsRequest(string playerName, int options)
{
if (!IsHost)
return;
if (ProgramConstants.IsInGame)
return;
PlayerInfo pInfo = Players.Find(p => p.Name == playerName);
if (pInfo == null)
return;
byte[] bytes = BitConverter.GetBytes(options);
int side = bytes[0];
int color = bytes[1];
int start = bytes[2];
int team = bytes[3];
if (side < 0 || side > SideCount + RandomSelectorCount)
return;
if (color < 0 || color > MPColors.Count)
return;
var disallowedSides = GetDisallowedSides();
if (side > 0 && side <= SideCount && disallowedSides[side - 1])
return;
if (GameModeMap?.CoopInfo != null)
{
if (GameModeMap.CoopInfo.DisallowedPlayerSides.Contains(side - 1) || side == SideCount + RandomSelectorCount)
return;
if (GameModeMap.CoopInfo.DisallowedPlayerColors.Contains(color - 1))
return;
}
if (!(start == 0 || (GameModeMap?.AllowedStartingLocations?.Contains(start) ?? true)))
return;
if (team < 0 || team > 4)
return;
if (side != pInfo.SideId
|| start != pInfo.StartingLocation
|| team != pInfo.TeamId)
{
ClearReadyStatuses();
}
pInfo.SideId = side;
pInfo.ColorId = color;
pInfo.StartingLocation = start;
pInfo.TeamId = team;
CopyPlayerDataToUI();
BroadcastPlayerOptions();
}
/// <summary>
/// Handles "I'm ready" messages received from non-host players.
/// </summary>
private void HandleReadyRequest(string playerName, int readyStatus)
{
if (!IsHost)
return;
PlayerInfo pInfo = Players.Find(p => p.Name == playerName);
if (pInfo == null)
return;
pInfo.Ready = readyStatus > 0;
pInfo.AutoReady = readyStatus > 1;
CopyPlayerDataToUI();
BroadcastPlayerOptions();
}
/// <summary>
/// Broadcasts player options to non-host players.
/// </summary>
protected override void BroadcastPlayerOptions()
{
// Broadcast player options
StringBuilder sb = new StringBuilder("PO ");
foreach (PlayerInfo pInfo in Players.Concat(AIPlayers))
{
if (pInfo.IsAI)
sb.Append(pInfo.AILevel);
else
sb.Append(pInfo.Name);
sb.Append(";");
// Combine the options into one integer to save bandwidth in
// cases where the player uses default options (this is common for AI players)
// Will hopefully make GameSurge kicking people a bit less common
byte[] byteArray = new byte[]
{
(byte)pInfo.TeamId,
(byte)pInfo.StartingLocation,
(byte)pInfo.ColorId,
(byte)pInfo.SideId,
};
int value = BitConverter.ToInt32(byteArray, 0);
sb.Append(value);
sb.Append(";");
if (!pInfo.IsAI)
{
if (pInfo.AutoReady && !pInfo.IsInGame && !LastMapChangeWasInvalid)
sb.Append(2);
else
sb.Append(Convert.ToInt32(pInfo.Ready));
sb.Append(';');
}
}
channel.SendCTCPMessage(sb.ToString(), QueuedMessageType.GAME_PLAYERS_MESSAGE, 11);
}
protected override void PlayerExtraOptions_OptionsChanged(object sender, EventArgs e)
{
base.PlayerExtraOptions_OptionsChanged(sender, e);
BroadcastPlayerExtraOptions();
}
protected override void BroadcastPlayerExtraOptions()
{
if (!IsHost)
return;
var playerExtraOptions = GetPlayerExtraOptions();
channel.SendCTCPMessage(playerExtraOptions.ToCncnetMessage(), QueuedMessageType.GAME_PLAYERS_EXTRA_MESSAGE, 11, true);
}
/// <summary>
/// Handles player option messages received from the game host.
/// </summary>
private void ApplyPlayerOptions(string sender, string message)
{
if (sender != hostName)
return;
Players.Clear();
AIPlayers.Clear();
string[] parts = message.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < parts.Length;)
{
PlayerInfo pInfo = new PlayerInfo();
string pName = parts[i];
int converted = Conversions.IntFromString(pName, -1);
if (converted > -1)
{
pInfo.IsAI = true;
pInfo.AILevel = converted;
pInfo.Name = AILevelToName(converted);
}
else
{
pInfo.Name = pName;
// If we can't find the player from the channel user list,
// ignore the player
// They've either left the channel or got kicked before the
// player options message reached us
if (channel.Users.Find(pName) == null)
{
i += HUMAN_PLAYER_OPTIONS_LENGTH;
continue;
}
}
if (parts.Length <= i + 1)
return;
int playerOptions = Conversions.IntFromString(parts[i + 1], -1);
if (playerOptions == -1)
return;
byte[] byteArray = BitConverter.GetBytes(playerOptions);
int team = byteArray[0];
int start = byteArray[1];
int color = byteArray[2];
int side = byteArray[3];
if (side < 0 || side > SideCount + RandomSelectorCount)
return;
if (color < 0 || color > MPColors.Count)
return;
if (start < 0 || start > MAX_PLAYER_COUNT)
return;
if (team < 0 || team > 4)
return;
pInfo.TeamId = byteArray[0];
pInfo.StartingLocation = byteArray[1];
pInfo.ColorId = byteArray[2];
pInfo.SideId = byteArray[3];
if (pInfo.IsAI)
{
pInfo.Ready = true;
AIPlayers.Add(pInfo);
i += AI_PLAYER_OPTIONS_LENGTH;
}
else
{
if (parts.Length <= i + 2)
return;
int readyStatus = Conversions.IntFromString(parts[i + 2], -1);
if (readyStatus == -1)
return;
pInfo.Ready = readyStatus > 0;
pInfo.AutoReady = readyStatus > 1;
if (pInfo.Name == ProgramConstants.PLAYERNAME)
btnLaunchGame.Text = pInfo.Ready ? BTN_LAUNCH_NOT_READY : BTN_LAUNCH_READY;
Players.Add(pInfo);
i += HUMAN_PLAYER_OPTIONS_LENGTH;
}
}
CopyPlayerDataToUI();
}
/// <summary>
/// Broadcasts game options to non-host players
/// when the host has changed an option.
/// </summary>
protected override void OnGameOptionChanged()
{
base.OnGameOptionChanged();
if (!IsHost)
return;
bool[] optionValues = new bool[CheckBoxes.Count];
for (int i = 0; i < CheckBoxes.Count; i++)
optionValues[i] = CheckBoxes[i].Checked;
// Let's pack the booleans into bytes
List<byte> byteList = Conversions.BoolArrayIntoBytes(optionValues).ToList();
while (byteList.Count % 4 != 0)
byteList.Add(0);
int integerCount = byteList.Count / 4;
byte[] byteArray = byteList.ToArray();
ExtendedStringBuilder sb = new ExtendedStringBuilder("GO ", true, ';');
for (int i = 0; i < integerCount; i++)
sb.Append(BitConverter.ToInt32(byteArray, i * 4));
// We don't gain much in most cases by packing the drop-down values
// (because they're bytes to begin with, and usually non-zero),
// so let's just transfer them as usual