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): play a match with no picture and quit (-headless)
Olcay Seygan9d37f45ce13a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5de67436e..668cd673b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1145,6 +1145,16 @@ speeding the *game* up rather than the picture, which is why every countdown onalmost as soon as it appeared. The picture and the rules are on separate clocks now, and that switchrespects the difference.+**And now it can play itself with the picture turned off entirely.** Drawing is most of what a+frame costs, so a match nobody is watching does not pay for it: a twenty-three minute skirmish+between two hard opponents plays out in thirty-eight seconds, thirty-six times faster than real+time. The run closes itself the moment the match is decided - or after a set number of turns,+since a stalemate between computer players never ends on its own - and writes down who won and+what every side built, earned, lost and destroyed on the way. The same starting number gives back+the same match to the frame: run it twice and the winner, the frame it won on and every score on+the board come out identical, so a run that turns up something strange can be replayed until it+gives up the reason.+**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 a8b76af42..3a84ec8e2 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h@@ -349,6 +349,8 @@ public:Int m_autoSkirmishPlayers; ///< -autoskirmish <n>: start an n player skirmish straight from the command line (0 = off)Int m_autoSkirmishAIState; ///< SlotState the AI slots of an auto-started skirmish get (-aidiff)Bool m_autoSkirmishObserver; ///< -observer: the local slot of an auto-started skirmish watches instead of playing+ Bool m_headless; ///< -headless: never draw a frame, never pace the logic tick, quit when the match ends+ Int m_maxGameFrames; ///< -maxframes <n>: quit after n logic frames however the match is going (0 = no limit)Int 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/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cppindex b23dae231..c3fe0e1a2 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp@@ -1128,6 +1128,40 @@ Int parseNoFPSLimit(char *args[], int num)return 1;}+/* -headless is the unattended-run switch: no frame is ever drawn, the logic tick runs flat out+ instead of being paced against wall clock, audio is silenced, and the process quits by itself+ the moment the match is decided. A window and a D3D device are still created - W3D reaches into+ drawables and the asset manager throughout, so a true null display is a much larger change than+ skipping the one draw call is worth. Pair it with -autoskirmish and -observer for a soak run.++ Audio goes off because at several hundred logic frames a second the game hands the mixer a few+ thousand events a second that nobody will hear; -headless is for a machine, not a listener. */+Int parseHeadless(char *args[], int num)+{+ if (TheWritableGlobalData)+ {+ TheWritableGlobalData->m_headless = TRUE;+ TheWritableGlobalData->m_audioOn = FALSE;+ TheWritableGlobalData->m_musicOn = FALSE;+ TheWritableGlobalData->m_soundsOn = FALSE;+ TheWritableGlobalData->m_speechOn = FALSE;+ TheWritableGlobalData->m_videoOn = FALSE;+ }+ return 1;+}++/* -maxframes <n> bounds a headless run in logic frames rather than in seconds, so the cutoff is+ the same on every machine and in every replay. A stalemate between eight brutal AIs is a real+ outcome and it does not end on its own. */+Int parseMaxGameFrames(char *args[], int num)+{+ if (TheWritableGlobalData && num > 1)+ {+ TheWritableGlobalData->m_maxGameFrames = atoi(args[1]);+ }+ return 2;+}+Int parseDumpAssetUsage(char *args[], int num){if (TheWritableGlobalData)@@ -1315,6 +1349,8 @@ static CommandLineParam params[] ={ "-autoskirmish", parseAutoSkirmish },{ "-aidiff", parseAIDifficulty },{ "-observer", parseObserver },+ { "-headless", parseHeadless },+ { "-maxframes", parseMaxGameFrames },//-allAdvice feature//{ "-allAdvice", parseAllAdvice },diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cppindex 4dbf2b558..e7244eeab 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp@@ -36,6 +36,7 @@#include "Common/PlayerTemplate.h"#include "Common/Team.h"#include "Common/PlayerList.h"+#include "Common/Player.h"#include "Common/GameAudio.h"#include "Common/GameEngine.h"#include "Common/INI.h"@@ -921,6 +922,84 @@ static Real engineElapsedMS( const Int64 &from, const Int64 &to )}#endif+/** -----------------------------------------------------------------------------------------------+ * Why an unattended run is over, or NULL while it is still going. The string is what the log line+ * says, so the reason and the report of it cannot drift apart.+ *+ * VictoryConditions publishes the end frame for a free-camera observer too, so nothing here+ * re-derives who won. It has one trap: 'not decided yet' and 'decided on frame 0' are the same+ * stored zero, and the check starts running before a map has finished placing its objects - at+ * which point every player owns nothing and therefore looks eliminated. Requiring the end frame to+ * be past the first second is what keeps an unpopulated map from reading as an instant draw.+ */+const char *GameEngine_headlessRunResult( UnsignedInt frame, UnsignedInt victoryEndFrame, Int maxGameFrames )+{+ const UnsignedInt SETTLE_FRAMES = 30;+ if (victoryEndFrame > SETTLE_FRAMES)+ return "decided";+ if (maxGameFrames > 0 && frame >= (UnsignedInt)maxGameFrames)+ return "frame limit reached";+ return NULL;+}++/** -----------------------------------------------------------------------------------------------+ * -headless: decide whether the unattended run is finished, and if it is, write down how it went+ * and quit. Two ways to finish: the match is decided, or -maxframes ran out.+ */+static void updateHeadlessRun( void )+{+ if (!TheGlobalData->m_headless || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame())+ return;++ static DWORD runStartTime = 0;+ static UnsignedInt runStartFrame = 0;+ if (runStartTime == 0)+ {+ runStartTime = timeGetTime();+ runStartFrame = TheGameLogic->getFrame();+ }++ const UnsignedInt frame = TheGameLogic->getFrame();+ const char *why = GameEngine_headlessRunResult( frame, TheVictoryConditions->getEndFrame(),+ TheGlobalData->m_maxGameFrames );+ if (why == NULL)+ return;++ const DWORD wallMs = timeGetTime() - runStartTime;+ const Real logicFps = wallMs ? (Real)(frame - runStartFrame) * 1000.0f / (Real)wallMs : 0.0f;++ DEBUG_LOG(("HEADLESS RESULT: %s on frame %d (%d frames in %.1fs wall, %.0f logic fps, %.1fx real time)\n",+ why, frame,+ frame - runStartFrame, wallMs / 1000.0f, logicFps,+ logicFps / (Real)TheGameEngine->getFramesPerSecondLimit()));++ for( Int i = 0; i < ThePlayerList->getPlayerCount(); ++i )+ {+ Player *p = ThePlayerList->getNthPlayer( i );+ // The list also carries the civilian and neutral slots and, with -observer, the camera the+ // run is watched from. None of them plays, so none of them has a result worth a line.+ if (!p->isPlayableSide() || p->isPlayerObserver())+ continue;++ ScoreKeeper *score = p->getScoreKeeper();+ DEBUG_LOG(("HEADLESS PLAYER %d '%ls': %s | score %d | money %d earned %d spent | units %d built %d lost %d killed | buildings %d built %d lost\n",+ i, p->getPlayerDisplayName().str(),+ TheVictoryConditions->hasAchievedVictory(p) ? "WON" :+ (TheVictoryConditions->hasSinglePlayerBeenDefeated(p) ? "eliminated" : "alive"),+ score->calculateScore(),+ score->getTotalMoneyEarned(), score->getTotalMoneySpent(),+ score->getTotalUnitsBuilt(), score->getTotalUnitsLost(), score->getTotalUnitsDestroyed(),+ score->getTotalBuildingsBuilt(), score->getTotalBuildingsLost()));+ }++ /* Tear the match down the way the benchmark timer does, so the replay of the run is closed and+ written rather than left half-flushed by the process going away. */+ if (TheRecorder->getMode() == RECORDERMODETYPE_RECORD)+ TheRecorder->stopRecording();+ TheGameLogic->clearGameData();+ TheGameEngine->setQuitting( TRUE );+}+void GameEngine::update( void ){USE_PERF_TIMER(GameEngine_update)@@ -972,6 +1051,12 @@ void GameEngine::update( void )#endiffastMode = fastMode || TheTacticalView->getTimeMultiplier() > 1 || TheScriptEngine->isTimeFast();+ /* -headless has no picture to pace the tick against and nobody watching it go by, so it runs+ a logic frame every pass and the match plays out as fast as the machine manages. Same+ branch as fast-forward, different reason: this one is not a cheat, it is the whole point+ of an unattended run. */+ fastMode = fastMode || TheGlobalData->m_headless;+static DWORD prevLogicTime = timeGetTime();static Real logicAccumMs = 0.0f;DWORD now = timeGetTime();@@ -1038,6 +1123,8 @@ void GameEngine::update( void )#endif}+ updateHeadlessRun();+#ifdef DEBUG_LOGGINGfpsFrames++;fpsClientTotal += clientMS;diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cppindex aa8235d0b..84a46126f 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp@@ -671,6 +671,8 @@ GlobalData::GlobalData()m_autoSkirmishPlayers = 0; // no skirmish from the command linem_autoSkirmishAIState = SLOT_BRUTAL_AI;m_autoSkirmishObserver = FALSE;+ m_headless = FALSE;+ m_maxGameFrames = 0; // run until the match endsm_horizontalScrollSpeedFactor = 1.0;m_verticalScrollSpeedFactor = 1.0;diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cppindex 66d33780b..fa93d3fee 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp@@ -780,7 +780,11 @@ void GameClient::update( void )// redraw all views, update the GUI//if(TheGameLogic->getFrame() >= 2)- TheDisplay->DRAW();+ /* -headless never draws. The device and every drawable stay alive - this skips the frame,+ not the client - which is what makes an unattended run fast: rendering is the larger half+ of the loop's wall clock in a normal match. */+ if (!TheGlobalData->m_headless)+ TheDisplay->DRAW();}{diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex db3f32bf4..a76950f60 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -5274,3 +5274,31 @@ TEST(each_start_position_gets_flat_ground_to_build_on)}}}++//////////////////////////////////////////////////////////////////////////////+// Headless runs+//////////////////////////////////////////////////////////////////////////////++extern const char *GameEngine_headlessRunResult( UnsignedInt frame, UnsignedInt victoryEndFrame, Int maxGameFrames );++TEST(headless_run_ends_on_a_decision_or_on_the_frame_limit)+{+ // nothing decided and no limit asked for: the run keeps going, however long that is+ CHECK( GameEngine_headlessRunResult( 5000, 0, 0 ) == NULL );++ // the first second is the trap. A map that has not finished placing its objects has every+ // player owning nothing, which reads as eliminated, and VictoryConditions stores that as an end+ // frame inside the settle window - an unattended run must not take it for a result.+ CHECK( GameEngine_headlessRunResult( 40, 1, 0 ) == NULL );+ CHECK( GameEngine_headlessRunResult( 40, 30, 0 ) == NULL );+ CHECK_STR( GameEngine_headlessRunResult( 40, 31, 0 ), "decided" );++ // -maxframes is the floor under a stalemate, and the comparison is >= so a limit that was+ // already passed still ends the run rather than never matching+ CHECK( GameEngine_headlessRunResult( 2999, 0, 3000 ) == NULL );+ CHECK_STR( GameEngine_headlessRunResult( 3000, 0, 3000 ), "frame limit reached" );+ CHECK_STR( GameEngine_headlessRunResult( 4000, 0, 3000 ), "frame limit reached" );++ // a real result outranks the limit on the frame they land together+ CHECK_STR( GameEngine_headlessRunResult( 3000, 2000, 3000 ), "decided" );+}