Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
feat(gameengine): start a LAN match from the command line
Olcay Seygan458e7fc568ef
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 668cd673b..1df57b872 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1155,6 +1155,11 @@ the same match to the frame: run it twice and the winner, the frame it won on anthe board come out identical, so a run that turns up something strange can be replayed until itgives up the reason.+**And it can play itself over a network.** Two copies of the game on one machine, on opposite ends+of a real connection, playing the same match against each other with no lobby and nobody clicking+anything. That is the only way to reach the faults that live in a multiplayer game and nowhere else+— the ones where two machines quietly stop agreeing about what just happened.+**Every fix was proved non-vacuous.** Put the bug back, watch the exact test fail, restore the fix.A test that passes both ways is worth nothing, and there are none of those here.diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.hindex 3a84ec8e2..139be6c78 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h@@ -351,6 +351,8 @@ public:Bool m_autoSkirmishObserver; ///< -observer: the local slot of an auto-started skirmish watches instead of playingBool m_headless; ///< -headless: never draw a frame, never pace the logic tick, quit when the match endsInt m_maxGameFrames; ///< -maxframes <n>: quit after n logic frames however the match is going (0 = no limit)+ AsciiString m_netGameHosts; ///< -netgame <ip>[,<ip>...]: the slot list of a LAN game started from the command line (empty = off)+ Int m_netGameLocalSlot; ///< -netslot <n>: which of those addresses this copy of the game isInt m_maxParticleCount; ///< maximum number of particles that can existInt m_maxFieldParticleCount; ///< maximum number of field-type particles that can exist (roughly)diff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/LANAPI.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/LANAPI.hindex 784b27bb4..9791a635d 100644--- a/GeneralsMD/Code/GameEngine/Include/GameNetwork/LANAPI.h+++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/LANAPI.h@@ -212,6 +212,10 @@ public:virtual inline UnsignedInt GetLocalIP( void ) { return m_localIP; } ///< What's my IP?virtual void fillInLANMessage( LANMessage *msg ); ///< Fill in default paramsvirtual void checkMOTD( void );++ /// -netgame: build a game out of a slot list handed to us and start it, with no lobby traffic+ Bool StartAutomatedGame( AsciiString mapName, Int seed, const UnsignedInt *slotIPs,+ Int numSlots, Int localSlot );protected:enum PendingActionTypediff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/networkutil.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/networkutil.hindex aceeefbe9..49d1d2949 100644--- a/GeneralsMD/Code/GameEngine/Include/GameNetwork/networkutil.h+++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/networkutil.h@@ -32,6 +32,13 @@#include "GameNetwork/NetCommandMsg.h"UnsignedInt ResolveIP(AsciiString host);++/** Read a comma separated list of addresses - a -netgame slot list - into host order addresses,+ in the order they were given, since that order is the player order on every machine. Returns+ how many were read, or -1 if the list is longer than maxAddresses or one entry is not an+ address. ResolveIP() answers INADDR_NONE for a malformed dotted quad and 0 for a name it+ cannot look up; neither is a player, so both are refused here. */+Int ResolveHostList(AsciiString hosts, UnsignedInt *addresses, Int maxAddresses);UnsignedShort GenerateNextCommandID();Bool DoesCommandRequireACommandID(NetCommandType type);Bool CommandRequiresAck(NetCommandMsg *msg);diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cppindex 8fbdd3870..fcef2378b 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp@@ -1162,6 +1162,35 @@ Int parseMaxGameFrames(char *args[], int num)return 2;}+/* -netgame <ip>[,<ip>...] starts a LAN game against those addresses with no lobby in front of it,+ and -netslot <n> says which of them this copy is. Every machine is given the same slot list in+ the same order, which is all the lobby ever agreed on: the slot list, the map and the seed. A+ network game is the only kind of game whose replay exercises the multiplayer paths (a CRC per+ NET_CRC_INTERVAL frames, real remote players, a local slot that is not 0), so without this there+ is no way to produce one unattended. */+Int parseNetGame(char *args[], int num)+{+ if (TheWritableGlobalData && num > 1)+ {+ TheWritableGlobalData->m_netGameHosts = args[1];+ }+ return 2;+}++Int parseNetSlot(char *args[], int num)+{+ if (TheWritableGlobalData && num > 1)+ {+ Int slot = atoi(args[1]);+ if (slot < 0)+ slot = 0;+ if (slot >= MAX_SLOTS)+ slot = MAX_SLOTS - 1;+ TheWritableGlobalData->m_netGameLocalSlot = slot;+ }+ return 2;+}+/* -replay <file> plays a replay back without the menus, the way -autoskirmish starts a matchwithout them. The only route into playback was ReplayMenu's list box and the _DEBUG/_INTERNAL-file switch, so a Release build could record a game and then had no way to play it back@@ -1371,6 +1400,8 @@ static CommandLineParam params[] ={ "-headless", parseHeadless },{ "-maxframes", parseMaxGameFrames },{ "-replay", parseReplay },+ { "-netgame", parseNetGame },+ { "-netslot", parseNetSlot },//-allAdvice feature//{ "-allAdvice", parseAllAdvice },diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cppindex 616505e08..b5c7ab2ce 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp@@ -106,6 +106,8 @@#include "GameNetwork/NetworkInterface.h"#include "GameNetwork/WOLBrowser/WebBrowser.h"#include "GameNetwork/LANAPI.h"+#include "GameNetwork/LANAPICallbacks.h"+#include "GameNetwork/NetworkUtil.h"#include "GameNetwork/GameSpy/GameResultsThread.h"#include "Common/Version.h"@@ -367,6 +369,67 @@ static void startAutoSkirmish( void )observing ? "every slot AI, watching from the free camera" : "slot 0 is the local player"));}+/** -----------------------------------------------------------------------------------------------+ * -netgame <ip>[,<ip>...] -netslot <n>: play a LAN game against those addresses, with the slot+ * list, the map and the seed coming from the command line instead of from the lobby. Same job as+ * startAutoSkirmish() one level up, and the same restriction: the map has to be a multiplayer map+ * that is already in the cache on every machine, because nothing is transferred.+ *+ * Every copy has to be given the same list in the same order and its own -netslot, and the seed+ * has to match too - the factions, the colours and the start positions are all drawn from it, and+ * two machines that disagree about them desync on the first frame.+ */+static void startAutoNetGame( void )+{+ AsciiString mapName = TheGlobalData->m_mapName;+ if (mapName.isEmpty())+ {+ DEBUG_LOG(("-netgame: no -map was given\n"));+ return;+ }++ const MapMetaData *md = TheMapCache->findMap( mapName );+ if (md == NULL)+ {+ DEBUG_LOG(("-netgame: '%s' is not in the map cache\n", mapName.str()));+ return;+ }+ if (!md->m_isMultiplayer)+ {+ DEBUG_LOG(("-netgame: '%s' is not a multiplayer map\n", mapName.str()));+ return;+ }++ UnsignedInt slotIPs[ MAX_SLOTS ];+ Int numSlots = ResolveHostList( TheGlobalData->m_netGameHosts, slotIPs, MAX_SLOTS );+ if (numSlots < 2)+ {+ DEBUG_LOG(("-netgame: '%s' is not a list of 2 to %d addresses\n",+ TheGlobalData->m_netGameHosts.str(), MAX_SLOTS));+ return;+ }++ if (numSlots > md->m_numPlayers)+ {+ DEBUG_LOG(("-netgame: '%s' holds %d players, not %d\n", mapName.str(), md->m_numPlayers, numSlots));+ return;+ }++ /* The seed is what the host would have picked and sent round, so it has to be given here - an+ unseeded network game is one that disagrees with itself. */+ if (TheGlobalData->m_fixedSeed < 0)+ {+ DEBUG_LOG(("-netgame: needs a -seed, and the same one on every machine\n"));+ return;+ }++ if (TheLAN == NULL)+ TheLAN = NEW LANAPI();++ TheLAN->StartAutomatedGame( mapName, TheGlobalData->m_fixedSeed, slotIPs, numSlots,+ TheGlobalData->m_netGameLocalSlot );+}+/** -----------------------------------------------------------------------------------------------* Initialize the game engine by initializing the GameLogic and GameClient.*/@@ -787,6 +850,14 @@ void GameEngine::init( int argc, char *argv[] )thePendingReplayFile = fname;}}+ else if (TheGlobalData->m_netGameHosts.isNotEmpty())+ {+ /* Deferred for the same reason the replay is: the network game has to survive the+ resetAll() that ends init(), and TheRecorder has to be past its reset before the+ MSG_NEW_GAME that makes it start recording is queued. */+ TheWritableGlobalData->m_shellMapOn = FALSE;+ TheWritableGlobalData->m_playIntro = FALSE;+ }else if (TheGlobalData->m_autoSkirmishPlayers > 0){startAutoSkirmish();@@ -859,6 +930,11 @@ void GameEngine::init( int argc, char *argv[] )}thePendingReplayFile.clear();}++ if (TheGlobalData->m_netGameHosts.isNotEmpty() && TheGlobalData->m_initialFile.isEmpty())+ {+ startAutoNetGame();+ }} // end init/** -----------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cppindex 84a46126f..8aa8b5f2e 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp@@ -673,6 +673,8 @@ GlobalData::GlobalData()m_autoSkirmishObserver = FALSE;m_headless = FALSE;m_maxGameFrames = 0; // run until the match ends+ m_netGameHosts.clear(); // no network game from the command line+ m_netGameLocalSlot = 0;m_horizontalScrollSpeedFactor = 1.0;m_verticalScrollSpeedFactor = 1.0;diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPICallbacks.cppindex 9cfe45346..ae563e3ad 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp@@ -181,6 +181,122 @@ void LANAPI::OnHasMap( UnsignedInt playerIP, Bool status )}//if}// void LANAPI::OnHasMap( UnicodeString player, Bool status )+/** -----------------------------------------------------------------------------------------------+ * -netgame: start a LAN game from a slot list given on the command line instead of one negotiated+ * in the lobby. Everything the lobby ever produces is here - who is in which slot, at which+ * address, on which map, with which seed - so the announce/join/accept round trips can be skipped+ * entirely and the game set up in one call. This is OnGameStart() with the preferences, the GUI+ * and the map transfer taken out; the network setup below is deliberately kept identical to it,+ * because that is what decides who talks to whom.+ *+ * Every machine must be given the same list in the same order: the slot order is the player order,+ * and ConnectionManager::parseUserList picks the local slot out of it by IP, so each copy also+ * needs its own address (-netslot picks which one it is). Two copies on one machine therefore+ * want two addresses out of 127.0.0.0/8, which Windows routes to loopback in its entirety.+ */+Bool LANAPI::StartAutomatedGame( AsciiString mapName, Int seed, const UnsignedInt *slotIPs,+ Int numSlots, Int localSlot )+{+ if (numSlots < 2 || numSlots > MAX_SLOTS || localSlot < 0 || localSlot >= numSlots)+ {+ DEBUG_LOG(("-netgame: %d slots with the local player at %d makes no game\n", numSlots, localSlot));+ return FALSE;+ }++ /* init() binds the lobby socket to m_localIP, so the address has to be ours before it runs.+ Nothing is ever sent on that socket here - the lobby is only pumped from the LAN menus - but+ leaving it bound to INADDR_ANY would mean the second copy on a machine fails to bind. */+ m_localIP = slotIPs[localSlot];+ init();+ m_isInLANMenu = FALSE;+ m_inLobby = FALSE;++ LANGameInfo *game = NEW LANGameInfo;+ game->enterGame();+ /* enterGame() resets, and reset() seeds itself from GetTickCount() - so the seed we were+ handed has to be set after it, or the replay header records a clock reading and plays back+ a different game than the one that ran. */+ game->setSeed( seed );++ UnicodeString gameName;+ gameName.format( L"%8.8X", slotIPs[0] );+ game->setName( gameName );++ for (Int i = 0; i < numSlots; ++i)+ {+ /* The names have to differ: GameInfo looks players up by name, and the player list ends up+ with one side per slot named after it. */+ UnicodeString playerName;+ playerName.format( L"Player%d", i + 1 );++ LANGameSlot slot;+ slot.setState( SLOT_PLAYER, playerName );+ slot.setIP( slotIPs[i] );+ slot.setPort( NETWORK_BASE_PORT_NUMBER ); // one address per player, so one port does for all+ slot.setLastHeard( timeGetTime() );+ slot.setLogin( m_userName );+ slot.setHost( m_hostName );+ slot.setPlayerTemplate( PLAYERTEMPLATE_RANDOM );+ slot.setColor( -1 ); // -1 is "random" to populateRandomSideAndColor+ slot.setStartPos( -1 ); // and to populateRandomStartPosition+ slot.setTeamNumber( -1 ); // -1 is "no team", so everybody fights everybody+ slot.setAccept();+ game->setSlot( i, slot );++ if (i == localSlot)+ m_name = playerName;+ }++ game->setNext( NULL );+ game->setMap( mapName );+ game->setIsDirectConnect( FALSE );+ game->setLastHeard( timeGetTime() );+ game->setLocalIP( m_localIP );++ /* The map is not transferred, so both machines have to already have it - but say what we have,+ the way the game options screen does, since the replay header carries it. */+ const MapMetaData *md = TheMapCache->findMap( mapName );+ if (md != NULL)+ {+ game->setMapCRC( md->m_CRC );+ game->setMapSize( md->m_filesize );+ }++ m_currentGame = game;+ addGame( game );++ // Set up the game network - same order and same arguments as OnGameStart()+ if (TheNetwork != NULL)+ {+ delete TheNetwork;+ TheNetwork = NULL;+ }++ TheNetwork = NetworkInterface::createNetwork();+ TheNetwork->init();+ TheNetwork->setLocalAddress( m_localIP, NETWORK_BASE_PORT_NUMBER );+ TheNetwork->initTransport();+ TheNetwork->parseUserList( m_currentGame );++ if (TheGameLogic->isInGame())+ TheGameLogic->clearGameData();++ m_currentGame->startGame( 0 );++ TheWritableGlobalData->m_pendingFile = m_currentGame->getMap();+ TheWritableGlobalData->m_shellMapOn = FALSE;+ TheWritableGlobalData->m_playIntro = FALSE;++ GameMessage *msg = TheMessageStream->appendMessage( GameMessage::MSG_NEW_GAME );+ msg->appendIntegerArgument( GAME_LAN );++ InitRandom( seed );++ DEBUG_LOG(("-netgame: %d players on '%s', seed %d, we are slot %d at %8.8X\n",+ numSlots, mapName.str(), seed, localSlot, m_localIP));+ return TRUE;+}+void LANAPI::OnGameStartTimer( Int seconds ){UnicodeString text;diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/NetworkUtil.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/NetworkUtil.cppindex 754521b1a..1ae3df6cf 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/NetworkUtil.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/NetworkUtil.cpp@@ -115,6 +115,24 @@ UnsignedInt ResolveIP(AsciiString host)/*** Returns the next network command ID.*/+Int ResolveHostList(AsciiString hosts, UnsignedInt *addresses, Int maxAddresses)+{+ Int count = 0;+ AsciiString host;+ while (hosts.nextToken( &host, "," ))+ {+ if (count >= maxAddresses)+ return -1;++ UnsignedInt ip = ResolveIP( host );+ if (ip == 0 || ip == 0xffffffff)+ return -1;++ addresses[ count++ ] = ip;+ }+ return count;+}+UnsignedShort GenerateNextCommandID() {// The counter used to start at 64000, so the first wrap arrived about 1500 commands into the// very first match. It still wraps - it is sixteen bits wide - but IsCommandIdNewer, which isdiff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex 30f539bfb..81ad4e35a 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -50,6 +50,7 @@#include "GameNetwork/CrcAgreement.h"#include "GameLogic/GameLogic.h"#include "Common/EarlyCommandLine.h"+#include "GameNetwork/NetworkUtil.h"#include "Common/RadarShroudCache.h"#include "GameClient/Gadget.h"#include "GameNetwork/NetworkUtil.h"@@ -5361,3 +5362,32 @@ TEST(an_option_read_before_the_parser_exists_is_read_on_word_boundaries)CHECK_STR( tiny, "ab" );CHECK( !findCommandLineValueIn( L"-logPrefix abcdef", L"-logPrefix", tiny, 0 ) );}++TEST(a_netgame_slot_list_is_the_player_order_on_every_machine)+{+ /* -netgame carries what the LAN lobby otherwise agrees on: who plays, at which address, in+ which order. Every machine is handed the same list, and ConnectionManager::parseUserList+ finds the local player in it by address, so the order has to survive the read exactly. */+ UnsignedInt ips[ MAX_SLOTS ];++ CHECK_EQ( 2, ResolveHostList( "127.0.0.1,127.0.0.2", ips, MAX_SLOTS ) );+ CHECK_EQ( 0x7f000001, ips[0] ); // host order, the order LANGameSlot::setIP wants+ CHECK_EQ( 0x7f000002, ips[1] );++ CHECK_EQ( 3, ResolveHostList( "10.0.0.3,10.0.0.1,10.0.0.2", ips, MAX_SLOTS ) );+ CHECK_EQ( 0x0a000003, ips[0] ); // given order, not sorted+ CHECK_EQ( 0x0a000001, ips[1] );+ CHECK_EQ( 0x0a000002, ips[2] );++ // an empty list is no game, not a one player one+ CHECK_EQ( 0, ResolveHostList( "", ips, MAX_SLOTS ) );++ // more addresses than there are slots is refused rather than quietly cut short+ CHECK_EQ( -1, ResolveHostList( "10.0.0.1,10.0.0.2,10.0.0.3", ips, 2 ) );++ // and so is anything that is not an address, however ResolveIP says so+ CHECK_EQ( -1, ResolveHostList( "10.0.0.1,999.1.1.1", ips, MAX_SLOTS ) ); // INADDR_NONE++ // a stray separator is not a slot - the list is whatever stands between the commas+ CHECK_EQ( 2, ResolveHostList( "10.0.0.1,,10.0.0.2", ips, MAX_SLOTS ) );+}