forked from TheSuperHackers/GeneralsGameCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLANAPI.cpp
More file actions
1300 lines (1148 loc) · 32.7 KB
/
LANAPI.cpp
File metadata and controls
1300 lines (1148 loc) · 32.7 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
/*
** Command & Conquer Generals Zero Hour(tm)
** Copyright 2025 Electronic Arts Inc.
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////////////////////////////////////////////////////////////////////////////////
// //
// (c) 2001-2003 Electronic Arts Inc. //
// //
////////////////////////////////////////////////////////////////////////////////
#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine
#define WIN32_LEAN_AND_MEAN // only bare bones windows stuff wanted
#include "Common/crc.h"
#include "Common/GameState.h"
#include "Common/Registry.h"
#include "GameNetwork/LANAPI.h"
#include "GameNetwork/networkutil.h"
#include "Common/GlobalData.h"
#include "Common/RandomValue.h"
#include "GameClient/GameText.h"
#include "GameClient/MapUtil.h"
#include "Common/UserPreferences.h"
#include "GameLogic/GameLogic.h"
static const UnsignedShort lobbyPort = 8086; ///< This is the UDP port used by all LANAPI communication
AsciiString GetMessageTypeString(UnsignedInt type);
const UnsignedInt LANAPI::s_resendDelta = 10 * 1000; ///< This is how often we announce ourselves to the world
/*
LANGame::LANGame( void )
{
m_gameName = L"";
int player;
for (player = 0; player < MAX_SLOTS; ++player)
{
m_playerName[player] = L"";
m_playerIP[player]= 0;
m_playerAccepted[player] = false;
}
m_lastHeard = 0;
m_inProgress = false;
m_next = nullptr;
}
*/
LANAPI::LANAPI( void ) : m_transport(nullptr)
{
DEBUG_LOG(("LANAPI::LANAPI() - max game option size is %d, sizeof(LANMessage)=%d, MAX_PACKET_SIZE=%d",
m_lanMaxOptionsLength, sizeof(LANMessage), MAX_PACKET_SIZE));
m_lastResendTime = 0;
//
m_lobbyPlayers = nullptr;
m_games = nullptr;
m_name = L""; // safe default?
m_pendingAction = ACT_NONE;
m_expiration = 0;
m_localIP = 0;
m_inLobby = true;
m_isInLANMenu = TRUE;
m_currentGame = nullptr;
m_broadcastAddr = INADDR_BROADCAST;
m_directConnectRemoteIP = 0;
m_actionTimeout = 5000; // ms
m_lastUpdate = 0;
m_transport = new Transport;
m_isActive = TRUE;
}
LANAPI::~LANAPI( void )
{
reset();
delete m_transport;
}
void LANAPI::init( void )
{
m_gameStartTime = 0;
m_gameStartSeconds = 0;
m_transport->reset();
m_transport->init(m_localIP, lobbyPort);
m_transport->allowBroadcasts(true);
m_pendingAction = ACT_NONE;
m_expiration = 0;
m_inLobby = true;
m_isInLANMenu = TRUE;
m_currentGame = nullptr;
m_directConnectRemoteIP = 0;
m_lastGameopt = "";
#if TELL_COMPUTER_IDENTITY_IN_LAN_LOBBY
char userName[UNLEN + 1];
DWORD bufSize = ARRAY_SIZE(userName);
if (GetUserNameA(userName, &bufSize))
{
m_userName.set(userName, bufSize - 1);
}
else
{
m_userName = "unknown";
}
char computerName[MAX_COMPUTERNAME_LENGTH + 1];
bufSize = ARRAY_SIZE(computerName);
if (GetComputerNameA(computerName, &bufSize))
{
m_hostName.set(computerName, bufSize - 1);
}
else
{
m_hostName = "unknown";
}
#endif
}
void LANAPI::reset( void )
{
if (m_inLobby)
{
LANMessage msg;
fillInLANMessage( &msg );
msg.messageType = LANMessage::MSG_REQUEST_LOBBY_LEAVE;
sendMessage(&msg);
}
m_transport->update();
LANGameInfo *theGame = m_games;
LANGameInfo *deletableGame = nullptr;
while (theGame)
{
deletableGame = theGame;
theGame = theGame->getNext();
delete deletableGame;
}
LANPlayer *thePlayer = m_lobbyPlayers;
LANPlayer *deletablePlayer = nullptr;
while (thePlayer)
{
deletablePlayer = thePlayer;
thePlayer = thePlayer->getNext();
delete deletablePlayer;
}
m_games = nullptr;
m_lobbyPlayers = nullptr;
m_directConnectRemoteIP = 0;
m_pendingAction = ACT_NONE;
m_expiration = 0;
m_inLobby = true;
m_isInLANMenu = TRUE;
m_currentGame = nullptr;
}
void LANAPI::sendMessage(LANMessage *msg, UnsignedInt ip /* = 0 */)
{
if (ip != 0)
{
m_transport->queueSend(ip, lobbyPort, (unsigned char *)msg, sizeof(LANMessage) /*, 0, 0 */);
}
else if ((m_currentGame != nullptr) && (m_currentGame->getIsDirectConnect()))
{
Int localSlot = m_currentGame->getLocalSlotNum();
for (Int i = 0; i < MAX_SLOTS; ++i)
{
if (i != localSlot) {
GameSlot *slot = m_currentGame->getSlot(i);
if ((slot != nullptr) && (slot->isHuman())) {
m_transport->queueSend(slot->getIP(), lobbyPort, (unsigned char *)msg, sizeof(LANMessage) /*, 0, 0 */);
}
}
}
}
else
{
m_transport->queueSend(m_broadcastAddr, lobbyPort, (unsigned char *)msg, sizeof(LANMessage) /*, 0, 0 */);
}
}
AsciiString GetMessageTypeString(UnsignedInt type)
{
AsciiString returnString;
switch (type)
{
case LANMessage::MSG_REQUEST_LOCATIONS:
returnString.format( "Request Locations (%d)",type);
break;
case LANMessage::MSG_GAME_ANNOUNCE:
returnString.format("Game Announce (%d)",type);
break;
case LANMessage::MSG_LOBBY_ANNOUNCE:
returnString.format("Lobby Announce (%d)",type);
break;
case LANMessage::MSG_REQUEST_JOIN:
returnString.format("Request Join (%d)",type);
break;
case LANMessage::MSG_JOIN_ACCEPT:
returnString.format("Join Accept (%d)",type);
break;
case LANMessage::MSG_JOIN_DENY:
returnString.format("Join Deny (%d)",type);
break;
case LANMessage::MSG_REQUEST_GAME_LEAVE:
returnString.format("Request Game Leave (%d)",type);
break;
case LANMessage::MSG_REQUEST_LOBBY_LEAVE:
returnString.format("Request Lobby Leave (%d)",type);
break;
case LANMessage::MSG_SET_ACCEPT:
returnString.format("Set Accept(%d)",type);
break;
case LANMessage::MSG_CHAT:
returnString.format("Chat (%d)",type);
break;
case LANMessage::MSG_GAME_START:
returnString.format("Game Start (%d)",type);
break;
case LANMessage::MSG_GAME_START_TIMER:
returnString.format("Game Start Timer (%d)",type);
break;
case LANMessage::MSG_GAME_OPTIONS:
returnString.format("Game Options (%d)",type);
break;
case LANMessage::MSG_REQUEST_GAME_INFO:
returnString.format("Request GameInfo (%d)", type);
break;
case LANMessage::MSG_INACTIVE:
returnString.format("Inactive (%d)", type);
break;
default:
returnString.format("Unknown Message (%d)",type);
}
return returnString;
}
void LANAPI::checkMOTD( void )
{
#if defined(RTS_DEBUG)
if (TheGlobalData->m_useLocalMOTD)
{
// for a playtest, let's log some play statistics, eh?
if (TheGlobalData->m_playStats <= 0)
TheWritableGlobalData->m_playStats = 30;
static UnsignedInt oldMOTDCRC = 0;
UnsignedInt newMOTDCRC = 0;
AsciiString asciiMOTD;
char buf[4096];
FILE *fp = fopen(TheGlobalData->m_MOTDPath.str(), "r");
Int len;
if (fp)
{
while( (len = fread(buf, 1, 4096, fp)) > 0 )
{
buf[len] = 0;
asciiMOTD.concat(buf);
}
fclose(fp);
CRC crcObj;
crcObj.computeCRC(asciiMOTD.str(), asciiMOTD.getLength());
newMOTDCRC = crcObj.get();
}
if (oldMOTDCRC != newMOTDCRC)
{
// different MOTD... display it
oldMOTDCRC = newMOTDCRC;
AsciiString line;
while (asciiMOTD.nextToken(&line, "\n"))
{
if (line.getCharAt(line.getLength()-1) == '\r')
line.removeLastChar(); // there is a trailing '\r'
if (line.isEmpty())
{
line = " ";
}
UnicodeString uniLine;
uniLine.translate(line);
OnChat( L"MOTD", 0, uniLine, LANCHAT_SYSTEM );
}
}
}
#endif
}
extern Bool LANbuttonPushed;
extern Bool LANSocketErrorDetected;
void LANAPI::update( void )
{
if(LANbuttonPushed)
return;
static const UnsignedInt LANAPIUpdateDelay = 200;
UnsignedInt now = timeGetTime();
if( now > m_lastUpdate + LANAPIUpdateDelay)
{
m_lastUpdate = now;
}
else
{
return;
}
// Let the UDP socket breathe
if ((m_transport->update() == FALSE) && (LANSocketErrorDetected == FALSE)) {
if (m_isInLANMenu == TRUE) {
LANSocketErrorDetected = TRUE;
}
}
// Handle any new messages
int i;
for (i=0; i<MAX_MESSAGES && !LANbuttonPushed; ++i)
{
if (m_transport->m_inBuffer[i].length > 0)
{
// Process the new message
UnsignedInt senderIP = m_transport->m_inBuffer[i].addr;
if (senderIP == m_localIP)
{
m_transport->m_inBuffer[i].length = 0;
continue;
}
LANMessage *msg = (LANMessage *)(m_transport->m_inBuffer[i].data);
//DEBUG_LOG(("LAN message type %s from %ls (%s@%s)", GetMessageTypeString(msg->messageType).str(),
// msg->name, msg->userName, msg->hostName));
switch (msg->messageType)
{
// Location specification
case LANMessage::MSG_REQUEST_LOCATIONS: // Hey, where is everybody?
DEBUG_LOG(("LANAPI::update - got a MSG_REQUEST_LOCATIONS from %d.%d.%d.%d", PRINTF_IP_AS_4_INTS(senderIP)));
handleRequestLocations( msg, senderIP );
break;
case LANMessage::MSG_GAME_ANNOUNCE: // Here someone is, and here's his game info!
DEBUG_LOG(("LANAPI::update - got a MSG_GAME_ANNOUNCE from %d.%d.%d.%d", PRINTF_IP_AS_4_INTS(senderIP)));
handleGameAnnounce( msg, senderIP );
break;
case LANMessage::MSG_LOBBY_ANNOUNCE: // Hey, I'm in the lobby!
DEBUG_LOG(("LANAPI::update - got a MSG_LOBBY_ANNOUNCE from %d.%d.%d.%d", PRINTF_IP_AS_4_INTS(senderIP)));
handleLobbyAnnounce( msg, senderIP );
break;
case LANMessage::MSG_REQUEST_GAME_INFO:
DEBUG_LOG(("LANAPI::update - got a MSG_REQUEST_GAME_INFO from %d.%d.%d.%d", PRINTF_IP_AS_4_INTS(senderIP)));
handleRequestGameInfo( msg, senderIP );
break;
// Joining games
case LANMessage::MSG_REQUEST_JOIN: // Let me in! Let me in!
DEBUG_LOG(("LANAPI::update - got a MSG_REQUEST_JOIN from %d.%d.%d.%d", PRINTF_IP_AS_4_INTS(senderIP)));
handleRequestJoin( msg, senderIP );
break;
case LANMessage::MSG_JOIN_ACCEPT: // Okay, you can join.
DEBUG_LOG(("LANAPI::update - got a MSG_JOIN_ACCEPT from %d.%d.%d.%d", PRINTF_IP_AS_4_INTS(senderIP)));
handleJoinAccept( msg, senderIP );
break;
case LANMessage::MSG_JOIN_DENY: // Go away! We don't want any!
DEBUG_LOG(("LANAPI::update - got a MSG_JOIN_DENY from %d.%d.%d.%d", PRINTF_IP_AS_4_INTS(senderIP)));
handleJoinDeny( msg, senderIP );
break;
// Leaving games, lobby
case LANMessage::MSG_REQUEST_GAME_LEAVE: // I'm outa here!
DEBUG_LOG(("LANAPI::update - got a MSG_REQUEST_GAME_LEAVE from %d.%d.%d.%d", PRINTF_IP_AS_4_INTS(senderIP)));
handleRequestGameLeave( msg, senderIP );
break;
case LANMessage::MSG_REQUEST_LOBBY_LEAVE: // I'm outa here!
DEBUG_LOG(("LANAPI::update - got a MSG_REQUEST_LOBBY_LEAVE from %d.%d.%d.%d", PRINTF_IP_AS_4_INTS(senderIP)));
handleRequestLobbyLeave( msg, senderIP );
break;
// Game options, chat, etc
case LANMessage::MSG_SET_ACCEPT: // I'm cool with everything as is.
handleSetAccept( msg, senderIP );
break;
case LANMessage::MSG_MAP_AVAILABILITY: // Map status
handleHasMap( msg, senderIP );
break;
case LANMessage::MSG_CHAT: // Just spouting my mouth off.
handleChat( msg, senderIP );
break;
case LANMessage::MSG_GAME_START: // Hold on; we're starting!
handleGameStart( msg, senderIP );
break;
case LANMessage::MSG_GAME_START_TIMER:
handleGameStartTimer( msg, senderIP );
break;
case LANMessage::MSG_GAME_OPTIONS: // Here's some info about the game.
DEBUG_LOG(("LANAPI::update - got a MSG_GAME_OPTIONS from %d.%d.%d.%d", PRINTF_IP_AS_4_INTS(senderIP)));
handleGameOptions( msg, senderIP );
break;
case LANMessage::MSG_INACTIVE: // someone is telling us that we're inactive.
handleInActive( msg, senderIP );
break;
default:
DEBUG_LOG(("Unknown LAN message type %d", msg->messageType));
}
// Mark it as read
m_transport->m_inBuffer[i].length = 0;
}
}
if(LANbuttonPushed)
return;
// Send out periodic I'm Here messages
if (now > s_resendDelta + m_lastResendTime)
{
m_lastResendTime = now;
if (m_inLobby)
{
RequestSetName(m_name);
}
else if (m_currentGame && !m_currentGame->isGameInProgress())
{
if (AmIHost())
{
RequestGameOptions( GenerateGameOptionsString(), true );
RequestGameAnnounce( );
}
else
{
#if TELL_COMPUTER_IDENTITY_IN_LAN_LOBBY
AsciiString text;
text.format("User=%s", m_userName.str());
RequestGameOptions( text, true );
text.format("Host=%s", m_hostName.str());
RequestGameOptions( text, true );
#endif
RequestGameOptions( "HELLO", false );
}
}
else if (m_currentGame)
{
// game is in progress - RequestGameAnnounce will check if we should send it
RequestGameAnnounce();
}
}
Bool playerListChanged = false;
Bool gameListChanged = false;
// Weed out people we haven't heard from in a while
LANPlayer *player = m_lobbyPlayers;
while (player)
{
if (player->getLastHeard() + s_resendDelta*2 < now)
{
// He's gone!
removePlayer(player);
LANPlayer *nextPlayer = player->getNext();
delete player;
player = nextPlayer;
playerListChanged = true;
}
else
{
player = player->getNext();
}
}
// Weed out people we haven't heard from in a while
LANGameInfo *game = m_games;
while (game)
{
if (game != m_currentGame && game->getLastHeard() + s_resendDelta*2 < now)
{
// He's gone!
removeGame(game);
LANGameInfo *nextGame = game->getNext();
delete game;
game = nextGame;
gameListChanged = true;
}
else
{
game = game->getNext();
}
}
if ( m_currentGame && !m_currentGame->isGameInProgress() )
{
if ( !AmIHost() && (m_currentGame->getLastHeard() + s_resendDelta*16 < now) )
{
// We haven't heard from the host in a while. Bail.
// Actually, fake a host leaving message. :)
LANMessage msg;
fillInLANMessage( &msg );
msg.messageType = LANMessage::MSG_REQUEST_GAME_LEAVE;
wcslcpy(msg.name, m_currentGame->getPlayerName(0).str(), ARRAY_SIZE(msg.name));
handleRequestGameLeave(&msg, m_currentGame->getIP(0));
UnicodeString text;
text = TheGameText->fetch("LAN:HostNotResponding");
OnChat(UnicodeString::TheEmptyString, m_localIP, text, LANCHAT_SYSTEM);
}
else if ( AmIHost() )
{
// Check each player for timeouts
for (int p=1; p<MAX_SLOTS; ++p)
{
if (m_currentGame->getIP(p) && m_currentGame->getPlayerLastHeard(p) + s_resendDelta*8 < now)
{
LANMessage msg;
fillInLANMessage( &msg );
UnicodeString theStr;
theStr.format(TheGameText->fetch("LAN:PlayerDropped"), m_currentGame->getPlayerName(p).str());
msg.messageType = LANMessage::MSG_REQUEST_GAME_LEAVE;
wcslcpy(msg.name, m_currentGame->getPlayerName(p).str(), ARRAY_SIZE(msg.name));
handleRequestGameLeave(&msg, m_currentGame->getIP(p));
OnChat(UnicodeString::TheEmptyString, m_localIP, theStr, LANCHAT_SYSTEM);
}
}
}
}
if (playerListChanged)
{
OnPlayerList(m_lobbyPlayers);
}
if (gameListChanged)
{
OnGameList(m_games);
}
// Time out old actions
if (m_pendingAction != ACT_NONE && now > m_expiration)
{
switch (m_pendingAction)
{
case ACT_JOIN:
OnGameJoin(RET_TIMEOUT, nullptr);
m_pendingAction = ACT_NONE;
m_currentGame = nullptr;
m_inLobby = true;
break;
case ACT_LEAVE:
OnPlayerLeave(m_name);
m_pendingAction = ACT_NONE;
m_currentGame = nullptr;
m_inLobby = true;
break;
case ACT_JOINDIRECTCONNECT:
OnGameJoin(RET_TIMEOUT, nullptr);
m_pendingAction = ACT_NONE;
m_currentGame = nullptr;
m_inLobby = true;
break;
default:
m_pendingAction = ACT_NONE;
}
}
// send out "game starting" messages
if ( m_gameStartTime && m_gameStartSeconds && m_gameStartTime <= now )
{
// m_gameStartTime is when the next message goes out
// m_gameStartSeconds is how many seconds remain in the message
RequestGameStartTimer( m_gameStartSeconds );
}
else if (m_gameStartTime && m_gameStartTime <= now)
{
// DEBUG_LOG(("m_gameStartTime=%d, now=%d, m_gameStartSeconds=%d", m_gameStartTime, now, m_gameStartSeconds));
ResetGameStartTimer();
RequestGameStart();
}
// Check for an MOTD every few seconds
static UnsignedInt lastMOTDCheck = 0;
static const UnsignedInt motdInterval = 30000;
if (now > lastMOTDCheck + motdInterval)
{
checkMOTD();
lastMOTDCheck = now;
}
}
// Request functions generate network traffic
void LANAPI::RequestLocations( void )
{
LANMessage msg;
msg.messageType = LANMessage::MSG_REQUEST_LOCATIONS;
fillInLANMessage( &msg );
sendMessage(&msg);
}
void LANAPI::RequestGameJoin( LANGameInfo *game, UnsignedInt ip /* = 0 */ )
{
if ((m_pendingAction != ACT_NONE) && (m_pendingAction != ACT_JOINDIRECTCONNECT))
{
OnGameJoin( RET_BUSY, nullptr );
return;
}
if (!game)
{
OnGameJoin( RET_GAME_GONE, nullptr );
return;
}
LANMessage msg;
msg.messageType = LANMessage::MSG_REQUEST_JOIN;
fillInLANMessage( &msg );
msg.GameToJoin.gameIP = game->getSlot(0)->getIP();
msg.GameToJoin.exeCRC = TheGlobalData->m_exeCRC;
msg.GameToJoin.iniCRC = TheGlobalData->m_iniCRC;
AsciiString s;
GetStringFromRegistry("\\ergc", "", s);
strlcpy(msg.GameToJoin.serial, s.str(), ARRAY_SIZE(msg.GameToJoin.serial));
sendMessage(&msg, ip);
m_pendingAction = ACT_JOIN;
m_expiration = timeGetTime() + m_actionTimeout;
}
void LANAPI::RequestGameJoinDirectConnect(UnsignedInt ipaddress)
{
if (m_pendingAction != ACT_NONE)
{
OnGameJoin( RET_BUSY, nullptr );
return;
}
if (ipaddress == 0)
{
OnGameJoin( RET_GAME_GONE, nullptr );
return;
}
m_directConnectRemoteIP = ipaddress;
LANMessage msg;
msg.messageType = LANMessage::MSG_REQUEST_GAME_INFO;
fillInLANMessage(&msg);
msg.PlayerInfo.ip = GetLocalIP();
wcslcpy(msg.PlayerInfo.playerName, m_name.str(), ARRAY_SIZE(msg.PlayerInfo.playerName));
sendMessage(&msg, ipaddress);
m_pendingAction = ACT_JOINDIRECTCONNECT;
m_expiration = timeGetTime() + m_actionTimeout;
}
void LANAPI::RequestGameLeave( void )
{
LANMessage msg;
msg.messageType = LANMessage::MSG_REQUEST_GAME_LEAVE;
fillInLANMessage( &msg );
wcslcpy(msg.PlayerInfo.playerName, m_name.str(), ARRAY_SIZE(msg.PlayerInfo.playerName));
sendMessage(&msg);
m_transport->update(); // Send immediately, before OnPlayerLeave below resets everything.
if (m_currentGame && m_currentGame->getIP(0) == m_localIP)
{
// Exit out immediately if we're hosting
OnPlayerLeave(m_name);
removeGame(m_currentGame);
m_currentGame = nullptr;
m_inLobby = true;
}
else
{
m_pendingAction = ACT_LEAVE;
m_expiration = timeGetTime() + m_actionTimeout;
}
}
void LANAPI::RequestGameAnnounce( void )
{
// In game - are we a game host?
if (m_currentGame && !(m_currentGame->getIsDirectConnect()))
{
if (m_currentGame->getIP(0) == m_localIP || (m_currentGame->isGameInProgress() && TheNetwork && TheNetwork->isPacketRouter())) // if we're in game we should reply if we're the packet router
{
LANMessage reply;
fillInLANMessage( &reply );
reply.messageType = LANMessage::MSG_GAME_ANNOUNCE;
AsciiString gameOpts = GameInfoToAsciiString(m_currentGame);
strlcpy(reply.GameInfo.options,gameOpts.str(), ARRAY_SIZE(reply.GameInfo.options));
wcslcpy(reply.GameInfo.gameName, m_currentGame->getName().str(), ARRAY_SIZE(reply.GameInfo.gameName));
reply.GameInfo.inProgress = m_currentGame->isGameInProgress();
reply.GameInfo.isDirectConnect = m_currentGame->getIsDirectConnect();
sendMessage(&reply);
}
}
}
void LANAPI::RequestAccept( void )
{
if (m_inLobby || !m_currentGame)
return;
LANMessage msg;
fillInLANMessage( &msg );
msg.messageType = LANMessage::MSG_SET_ACCEPT;
msg.Accept.isAccepted = true;
wcslcpy(msg.Accept.gameName, m_currentGame->getName().str(), ARRAY_SIZE(msg.Accept.gameName));
sendMessage(&msg);
}
void LANAPI::RequestHasMap( void )
{
if (m_inLobby || !m_currentGame)
return;
LANMessage msg;
fillInLANMessage( &msg );
msg.messageType = LANMessage::MSG_MAP_AVAILABILITY;
msg.MapStatus.hasMap = m_currentGame->getSlot(m_currentGame->getLocalSlotNum())->hasMap();
wcslcpy(msg.MapStatus.gameName, m_currentGame->getName().str(), ARRAY_SIZE(msg.MapStatus.gameName));
CRC mapNameCRC;
//mapNameCRC.computeCRC(m_currentGame->getMap().str(), m_currentGame->getMap().getLength());
AsciiString portableMapName = TheGameState->realMapPathToPortableMapPath(m_currentGame->getMap());
mapNameCRC.computeCRC(portableMapName.str(), portableMapName.getLength());
msg.MapStatus.mapCRC = mapNameCRC.get();
sendMessage(&msg);
if (!msg.MapStatus.hasMap)
{
UnicodeString text;
UnicodeString mapDisplayName;
const MapMetaData *mapData = TheMapCache->findMap( m_currentGame->getMap() );
Bool willTransfer = TRUE;
if (mapData)
{
mapDisplayName.format(L"%ls", mapData->m_displayName.str());
if (mapData->m_isOfficial)
willTransfer = FALSE;
}
else
{
mapDisplayName.format(L"%hs", TheGameState->getMapLeafName(m_currentGame->getMap()).str());
willTransfer = WouldMapTransfer(m_currentGame->getMap());
}
if (willTransfer)
text.format(TheGameText->fetch("GUI:LocalPlayerNoMapWillTransfer"), mapDisplayName.str());
else
text.format(TheGameText->fetch("GUI:LocalPlayerNoMap"), mapDisplayName.str());
OnChat(L"SYSTEM", m_localIP, text, LANCHAT_SYSTEM);
}
}
void LANAPI::RequestChat( UnicodeString message, ChatType format )
{
LANMessage msg;
fillInLANMessage( &msg );
wcslcpy(msg.Chat.gameName, (m_currentGame) ? m_currentGame->getName().str() : L"", ARRAY_SIZE(msg.Chat.gameName));
msg.messageType = LANMessage::MSG_CHAT;
msg.Chat.chatType = format;
wcslcpy(msg.Chat.message, message.str(), ARRAY_SIZE(msg.Chat.message));
sendMessage(&msg);
OnChat(m_name, m_localIP, message, format);
}
void LANAPI::RequestGameStart( void )
{
if (m_inLobby || !m_currentGame || m_currentGame->getIP(0) != m_localIP)
return;
LANMessage msg;
msg.messageType = LANMessage::MSG_GAME_START;
fillInLANMessage( &msg );
sendMessage(&msg);
m_transport->update(); // force a send
OnGameStart();
}
void LANAPI::ResetGameStartTimer( void )
{
m_gameStartTime = 0;
m_gameStartSeconds = 0;
}
void LANAPI::RequestGameStartTimer( Int seconds )
{
if (m_inLobby || !m_currentGame || m_currentGame->getIP(0) != m_localIP)
return;
UnsignedInt now = timeGetTime();
m_gameStartTime = now + 1000;
m_gameStartSeconds = (seconds) ? seconds - 1 : 0;
LANMessage msg;
msg.messageType = LANMessage::MSG_GAME_START_TIMER;
msg.StartTimer.seconds = seconds;
fillInLANMessage( &msg );
sendMessage(&msg);
m_transport->update(); // force a send
OnGameStartTimer(seconds);
}
void LANAPI::RequestGameOptions( AsciiString gameOptions, Bool isPublic, UnsignedInt ip /* = 0 */ )
{
DEBUG_ASSERTCRASH(gameOptions.getLength() < m_lanMaxOptionsLength, ("Game options string is too long!"));
if (!m_currentGame)
return;
LANMessage msg;
fillInLANMessage( &msg );
msg.messageType = LANMessage::MSG_GAME_OPTIONS;
strlcpy(msg.GameOptions.options, gameOptions.str(), ARRAY_SIZE(msg.GameOptions.options));
sendMessage(&msg, ip);
m_lastGameopt = gameOptions;
int player;
for (player = 0; player<MAX_SLOTS; ++player)
{
if (m_currentGame->getIP(player) == m_localIP)
{
OnGameOptions(m_localIP, player, AsciiString(msg.GameOptions.options));
break;
}
}
// We can request game options (side, color, etc) while we don't have a slot yet. Of course, we don't need to
// call OnGameOptions for those, so it's okay to silently fail.
//DEBUG_ASSERTCRASH(player != MAX_SLOTS, ("Requested game options, but we're not in slot list!");
}
void LANAPI::RequestGameCreate( UnicodeString gameName, Bool isDirectConnect )
{
// No games of the same name should exist... Ignore that for now.
/// @todo: make sure LAN games with identical names don't crash things like in RA2.
if ((!m_inLobby || m_currentGame) && !isDirectConnect)
{
DEBUG_ASSERTCRASH(m_inLobby && m_currentGame, ("Can't create a game while in one!"));
OnGameCreate(LANAPIInterface::RET_BUSY);
return;
}
if (m_pendingAction != ACT_NONE)
{
OnGameCreate(LANAPIInterface::RET_BUSY);
return;
}
// Create the local game object
m_inLobby = false;
LANGameInfo *myGame = NEW LANGameInfo;
myGame->setSeed(GetTickCount());
// myGame->setInProgress(false);
myGame->enterGame();
UnicodeString s;
s.format(L"%8.8X%8.8X", m_localIP, myGame->getSeed());
if (gameName.isEmpty())
s.concat(m_name);
else
s.concat(gameName);
s.truncateTo(g_lanGameNameLength);
DEBUG_LOG(("Setting local game name to '%ls'", s.str()));
myGame->setName(s);
LANGameSlot newSlot;
newSlot.setState(SLOT_PLAYER, m_name);
newSlot.setIP(m_localIP);
newSlot.setPort(NETWORK_BASE_PORT_NUMBER); // LAN game, everyone has a unique IP, so it's ok to use the same port.
newSlot.setLastHeard(0);
newSlot.setLogin(m_userName);
newSlot.setHost(m_hostName);
myGame->setSlot(0,newSlot);
myGame->setNext(nullptr);
LANPreferences pref;
AsciiString mapName = pref.getPreferredMap();
myGame->setMap(mapName);
myGame->setIsDirectConnect(isDirectConnect);
myGame->setLastHeard(timeGetTime());
m_currentGame = myGame;
/// @todo: Need to initialize the players elsewere.
/* for (int player = 1; player < MAX_SLOTS; ++player)
{
myGame->setPlayerName(player, L"");
myGame->setIP(player, 0);
myGame->setAccepted(player, false);
}*/
// Add the game to the local game list
addGame(myGame);
// Send an announcement
//RequestSlotList();
/*
LANMessage msg;
wcslcpy(msg.name, m_name.str(), ARRAY_SIZE(msg.name));
wcscpy(msg.GameInfo.gameName, myGame->getName().str());
for (player=0; player<MAX_SLOTS; ++player)
{
wcscpy(msg.GameInfo.name[player], myGame->getPlayerName(player).str());
msg.GameInfo.ip[player] = myGame->getIP(player);
msg.GameInfo.playerAccepted[player] = myGame->getAccepted(player);
}
msg.messageType = LANMessage::MSG_GAME_ANNOUNCE;
*/
OnGameCreate(LANAPIInterface::RET_OK);
}
/*static const char slotListID = 'S';
static const char gameOptionsID = 'G';
static const char acceptID = 'A';
static const char wannaStartID = 'W';
AsciiString LANAPI::createSlotString( void )
{
AsciiString slotList;
slotList.concat(slotListID);
for (int i=0; i<MAX_SLOTS; ++i)
{
LANGameSlot *slot = GetMyGame()->getLANSlot(i);
AsciiString str;
if (slot->isHuman())
{
str = "H";
LANPlayer *user = slot->getUser();
DEBUG_ASSERTCRASH(user, ("Human player has no User*!"));
AsciiString name;
name.translate(user->getName());
str.concat(name);
str.concat(',');
}
else if (slot->isAI())
{
if (slot->getState() == SLOT_EASY_AI)
str = "CE,";
if (slot->getState() == SLOT_MED_AI)
str = "CM,";
else
str = "CB,";
}
else if (slot->getState() == SLOT_OPEN)
{
str = "O,";
}
else if (slot->getState() == SLOT_CLOSED)
{
str = "X,";
}
else
{
DEBUG_ASSERTCRASH(false, ("Bad slot type"));
str = "X,";
}
slotList.concat(str);
}
return slotList;
}
*/