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): -video records a range of logic frames as an mp4
Olcay Seygan355b15c61ce0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 33dbb5147..ad1cc1b56 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -960,6 +960,7 @@ found and fixed — EA's own, not port damage.**- Every fix was proved by putting the bug back and watching the test fail.- No debugger here: a crash symboliser, a sampling profiler, probes in live matches.- A graphics fix is argued with pixels: an unattended match can now be told where to point the camera and which frame to photograph, so the two builds are compared by counting the pixels between them. The river above changed 126,535 of them and the eye had been calling it "about the same".+- A picture cannot show a unit turning the wrong way, so an unattended match can now film itself: name the first and the last game frame and every frame between them is drawn once and saved, then stitched into an mp4 at the game's own 30 frames a second. A replay films the same way, which puts any match ever recorded on video without anybody sitting through it.- A unit's cost is argued with the same army twice. An unattended match can now take its army from a text file - spawn eight of that unit there on frame thirty, send them across the map on frame six hundred, stop them on frame nine hundred - and be told which faction each seat plays and to leave every seat without a computer player behind it. Before that, whatever was on the field came out of the seed: measuring what angry mobs cost meant waiting for a match that happened to build some, and two runs that drew different sides were never comparable in the first place.- And the other half of that: a running game will now take orders down a socket. Started with the switch for it, the game listens on this machine only and answers anything that can speak to a web page - start a match on this map with these players, put five of that unit there, send them across the map, take a picture, tell me the frame number and what everybody owns. The commands are the same lines the text file above takes. A twenty-line Python script can now set up a match, produce an army and read the result back, which is how the mob numbers in this list were produced.- Reverted and recorded: wide FOV, the whole group movement rework, tree shadows out of a stencildiff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.hindex 42c4d00bc..7ef8d2b0c 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h@@ -388,6 +388,9 @@ public:Int m_peaceTime; ///< -peacetime <n>: the lobby's peace time, in minutes, for an -autoskirmish runInt m_maxGameFrames; ///< -maxframes <n>: quit after n logic frames however the match is going (0 = no limit)Int m_screenShotFrame; ///< -screenshot <n>: save one picture when the run reaches logic frame n (0 = never)+ Int m_videoStartFrame; ///< -video <from> <to> [name]: the first logic frame recorded+ Int m_videoEndFrame; ///< -video: the last logic frame recorded (0 = no video)+ AsciiString m_videoName; ///< -video: the recording is Videos\<name>.mp4 next to the save gamesInt m_autoCameraSeconds; ///< -autocamera <n>: every n seconds, move the camera to wherever the fighting is (0 = off)Bool m_cameraLookSet; ///< -camera <x> <y>: point the camera at one map position once the match startsCoord2D m_cameraLook; ///< where -camera pointed itdiff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cppindex 6756aed71..c59cc693b 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp@@ -1361,6 +1361,70 @@ Int parseScreenShot(char *args[], int num)return 2;}+/* -video <from> <to> [name]: record logic frames <from> to <to> of the match as a movie.+ *+ * -screenshot shows one frame. A unit turning the wrong way, an animation that hitches or a+ * formation coming apart is a sequence, and a script cannot see a sequence one launch per picture.+ * Every logic frame in the range is drawn once and written as frameNNNNNN.bmp under Videos\<name>\+ * next to the save games; when the range is over, or the game exits first, ffmpeg.exe off the PATH+ * turns them into Videos\<name>.mp4 and the frames are deleted. Without ffmpeg they stay. The name+ * defaults to video_<from>_<to> and may hold letters, digits, '-' and '_' only, because it becomes a+ * directory and an argument on ffmpeg's command line. */+static Bool isVideoNameUsable(const char *name)+{+ if (*name == '\0')+ return FALSE;+ for (const char *letter = name; *letter; ++letter)+ {+ const Bool usable = (*letter >= 'a' && *letter <= 'z') || (*letter >= 'A' && *letter <= 'Z')+ || (*letter >= '0' && *letter <= '9') || *letter == '-' || *letter == '_';+ if (!usable)+ return FALSE;+ }+ return TRUE;+}++Int parseVideo(char *args[], int num)+{+ if (num < 3)+ {+ DEBUG_LOG(("-video: wants the first and the last logic frame to record, got %d arguments\n", num - 1));+ return num;+ }++ Int from = atoi(args[1]);+ if (from < 1)+ from = 1;+ const Int to = atoi(args[2]);++ AsciiString name;+ name.format("video_%d_%d", from, to);+ Int consumed = 3;+ if (num > 3 && args[3][0] != '-')+ {+ consumed = 4;+ if (isVideoNameUsable(args[3]))+ name = args[3];+ else+ DEBUG_LOG(("-video: '%s' is not a usable name (letters, digits, '-' and '_'), recording as %s\n",+ args[3], name.str()));+ }++ if (to < from)+ {+ DEBUG_LOG(("-video: the last frame %d comes before the first frame %d, so nothing is recorded\n", to, from));+ return consumed;+ }++ if (TheWritableGlobalData)+ {+ TheWritableGlobalData->m_videoStartFrame = from;+ TheWritableGlobalData->m_videoEndFrame = to;+ TheWritableGlobalData->m_videoName = name;+ }+ return consumed;+}+/* -autocamera [seconds]: every so often, put the camera wherever the fighting is.** A soak run watches from a free camera that never moves, and a camera that never moves is the@@ -2220,6 +2284,7 @@ static CommandLineParam params[] ={ "-headless", parseHeadless },{ "-maxframes", parseMaxGameFrames },{ "-screenshot", parseScreenShot },+ { "-video", parseVideo },{ "-msaa", parseMSAA },{ "-d3d9", parseDirect3D9 },{ "-dx11dump", parseDirect3D11Dump },diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cppindex 60eda11a4..5f1baaa81 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp@@ -1857,6 +1857,8 @@ static void updateHeadlessRun( void )AIUpdate_resetMoveTrace();extern void GroupDrill_reset( void );GroupDrill_reset();+ if (TheGlobalData->m_headless && TheGlobalData->m_videoEndFrame > 0)+ DEBUG_LOG(("-video: -headless draws nothing, so there is no video to record\n"));}const UnsignedInt frame = TheGameLogic->getFrame();@@ -1910,8 +1912,14 @@ static void updateHeadlessRun( void )}}+ /* A -video range that runs up to or past -maxframes keeps the run alive until its last picture is+ drawn, which happens on the pass after the logic reaches that frame. */+ Int maxGameFrames = TheGlobalData->m_maxGameFrames;+ if (maxGameFrames > 0 && !TheGlobalData->m_headless && TheGlobalData->m_videoEndFrame >= maxGameFrames)+ maxGameFrames = TheGlobalData->m_videoEndFrame + 1;+const char *why = GameEngine_headlessRunResult( frame, TheVictoryConditions->getEndFrame(),- TheGlobalData->m_maxGameFrames );+ maxGameFrames );if (why == NULL)return;@@ -2085,6 +2093,15 @@ void GameEngine::update( void )of an unattended run. */fastMode = fastMode || TheGlobalData->m_headless;+ /* -video: one logic frame a pass across the range being recorded, so the draw in front of each+ logic frame is the one picture of it. Paced by the wall clock, a pass that fell behind would+ run two logic frames back to back and the video would jump over one. */+ const Int videoLogicFrame = (Int)TheGameLogic->getFrame();+ fastMode = fastMode || ( TheGlobalData->m_videoEndFrame > 0 && TheGameLogic->isInGame()+ && !TheGameLogic->isInShellGame()+ && videoLogicFrame + 1 >= TheGlobalData->m_videoStartFrame+ && videoLogicFrame <= TheGlobalData->m_videoEndFrame );+static DWORD prevLogicTime = timeGetTime();static Real logicAccumMs = 0.0f;DWORD now = timeGetTime();diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cppindex 2ac49f87d..f07c0213d 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp@@ -695,6 +695,9 @@ GlobalData::GlobalData()m_headless = FALSE;m_maxGameFrames = 0; // run until the match endsm_screenShotFrame = 0; // take no picture unless -screenshot asks for one+ m_videoStartFrame = 0;+ m_videoEndFrame = 0; // record nothing unless -video asks for a range+ m_videoName.clear();m_autoCameraSeconds = 0; // the camera stays where it was putm_cameraLookSet = FALSE; // -camera not given: the map decides where the view startsm_cameraLook.x = m_cameraLook.y = 0.0f;diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cppindex cfb2375a6..12b2f8210 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp@@ -429,11 +429,15 @@ W3DDisplay::W3DDisplay()} // end W3DDisplay+static void finishVideo(void);+// W3DDisplay::~W3DDisplay ====================================================/** *///=============================================================================W3DDisplay::~W3DDisplay(){+ // a -video run that ended before its range did, on -maxframes or a decided match, still gets its movie+ finishVideo();// What -ffshader did, written from here because WW3D2 is built without RELEASE_DEBUG_LOGGING// and its own WWDEBUG_SAY does not exist in a shipping build. Before W3D shuts down, which is@@ -2031,6 +2035,7 @@ DECLARE_PERF_TIMER(BigAssRenderLoop)DECLARE_PERF_TIMER(W3DDisplay_draw)static Bool s_screenShotPending = FALSE; // F12 pressed: save the frame at the end of the next draw()static void saveScreenShot(void);+static void captureVideoFrame(void);#ifdef DEBUG_LOGGING//@@ -2450,6 +2455,7 @@ AGAIN:s_screenShotPending = FALSE;saveScreenShot();}+ captureVideoFrame();// render is all done!WW3D::End_Render();@@ -3644,26 +3650,10 @@ void W3DDisplay::takeScreenShot(void)s_screenShotPending = TRUE;}-static void saveScreenShot(void)+/** Write the frame being drawn to pathname. FALSE when there was no picture to read, which is what+ * a device that has gone away gives. Runs before End_Render, while the back buffers still hold it. */+static Bool writeFrameBMP(char *pathname){- char leafname[256];- char pathname[1024];-- static int frame_number = 1;-- Bool done = false;- while (!done) {-#ifdef CAPTURE_TO_TARGA- snprintf( leafname, ARRAY_SIZE(leafname), "%s%.3d.tga", "sshot", frame_number++);-#else- snprintf( leafname, ARRAY_SIZE(leafname), "%s%.3d.bmp", "sshot", frame_number++);-#endif- strlcpy(pathname, TheGlobalData->getPath_UserData().str(), ARRAY_SIZE(pathname));- strlcat(pathname, leafname, ARRAY_SIZE(pathname));- if (_access( pathname, 0 ) == -1)- done = true;- }-// With -dx11present the picture on the screen is the Direct3D 11 one, so that is what a// screenshot has to be: reading the D3D9 back buffer here would photograph a frame nobody saw// and quietly compare the old renderer against itself. This runs before End_Render, while the@@ -3675,30 +3665,26 @@ static void saveScreenShot(void)unsigned capturePitch = 0;unsigned char *captured =Direct3D11_Capture_Back_Buffer(captureWidth, captureHeight, capturePitch);- if (captured != NULL)+ if (captured == NULL)+ return FALSE;++ char *rows = NEW char[3*captureWidth*captureHeight];+ for (unsigned row = 0; row < captureHeight; row++){- char *rows = NEW char[3*captureWidth*captureHeight];- for (unsigned row = 0; row < captureHeight; row++)+ // Bottom row first, which is the order a .bmp stores them.+ const unsigned char *in = captured + (captureHeight-1-row)*capturePitch;+ char *out = rows + row*captureWidth*3;+ for (unsigned column = 0; column < captureWidth; column++){- // Bottom row first, which is the order a .bmp stores them.- const unsigned char *in = captured + (captureHeight-1-row)*capturePitch;- char *out = rows + row*captureWidth*3;- for (unsigned column = 0; column < captureWidth; column++)- {- out[column*3+0] = (char)in[column*4+0];- out[column*3+1] = (char)in[column*4+1];- out[column*3+2] = (char)in[column*4+2];- }+ out[column*3+0] = (char)in[column*4+0];+ out[column*3+1] = (char)in[column*4+1];+ out[column*3+2] = (char)in[column*4+2];}- CreateBMPFile(pathname, rows, captureWidth, captureHeight);- delete [] rows;- Direct3D11_Release_Capture(captured);-- UnicodeString dx11FileName;- dx11FileName.translate(leafname);- TheInGameUI->message(TheGameText->fetch("GUI:ScreenCapture"), dx11FileName.str());}- return;+ CreateBMPFile(pathname, rows, captureWidth, captureHeight);+ delete [] rows;+ Direct3D11_Release_Capture(captured);+ return TRUE;}RECT bounds;@@ -3742,7 +3728,7 @@ static void saveScreenShot(void){if (fb != NULL)fb->Release();- return; // nothing to save; better than a fault+ return FALSE; // nothing to save; better than a fault}}@@ -3830,12 +3816,183 @@ static void saveScreenShot(void)#endifdelete [] image;+ return TRUE;+}++static void saveScreenShot(void)+{+ char leafname[256];+ char pathname[1024];++ static int frame_number = 1;++ Bool done = false;+ while (!done) {+#ifdef CAPTURE_TO_TARGA+ snprintf( leafname, ARRAY_SIZE(leafname), "%s%.3d.tga", "sshot", frame_number++);+#else+ snprintf( leafname, ARRAY_SIZE(leafname), "%s%.3d.bmp", "sshot", frame_number++);+#endif+ strlcpy(pathname, TheGlobalData->getPath_UserData().str(), ARRAY_SIZE(pathname));+ strlcat(pathname, leafname, ARRAY_SIZE(pathname));+ if (_access( pathname, 0 ) == -1)+ done = true;+ }++ if (!writeFrameBMP(pathname))+ return;UnicodeString ufileName;ufileName.translate(leafname);TheInGameUI->message(TheGameText->fetch("GUI:ScreenCapture"), ufileName.str());}+//=============================================================================+// -video <from> <to> [name]: one picture per logic frame across the range, written as numbered+// .bmp files under Videos\<name>\ and then handed to ffmpeg for Videos\<name>.mp4. GameEngine runs+// one logic frame a pass over the range, so a picture is a logic frame and a second of video is+// LOGICFRAMES_PER_SECOND of them.+//=============================================================================+static const char VIDEO_FRAME_PATTERN[] = "frame%06d.bmp";+static const char VIDEO_ENCODER[] = "ffmpeg.exe";++static Bool s_videoStarted = FALSE;+static Bool s_videoFinished = FALSE;+static UnsignedInt s_videoLastFrame = 0;+static Int s_videoFramesWritten = 0;+static Int s_videoFramesMissed = 0;+static char s_videoDirectory[_MAX_PATH];++static void buildVideoFramePath(char *pathname, size_t size, Int index)+{+ char leafname[32];+ snprintf(leafname, ARRAY_SIZE(leafname), VIDEO_FRAME_PATTERN, index);+ strlcpy(pathname, s_videoDirectory, size);+ strlcat(pathname, leafname, size);+}++// frames are numbered from 0 without a gap, so the first name that is not there is the end of them+static void deleteVideoFrames(void)+{+ char pathname[_MAX_PATH];+ for (Int index = 0; ; ++index)+ {+ buildVideoFramePath(pathname, ARRAY_SIZE(pathname), index);+ if (!DeleteFileA(pathname))+ return;+ }+}++static void finishVideo(void)+{+ if (!s_videoStarted || s_videoFinished)+ return;+ s_videoFinished = TRUE;++ DEBUG_LOG(("VIDEO: %d frames written to %s, %d logic frames went by without a picture\n",+ s_videoFramesWritten, s_videoDirectory, s_videoFramesMissed));+ if (s_videoFramesWritten == 0)+ return;++ char encoderPath[_MAX_PATH];+ if (SearchPathA(NULL, VIDEO_ENCODER, NULL, ARRAY_SIZE(encoderPath), encoderPath, NULL) == 0)+ {+ DEBUG_LOG(("VIDEO: %s is not on the PATH, so the frames stay where they are\n", VIDEO_ENCODER));+ return;+ }++ // the directory with its trailing backslash taken off is the movie's own name+ char moviePath[_MAX_PATH];+ strlcpy(moviePath, s_videoDirectory, ARRAY_SIZE(moviePath));+ moviePath[strlen(moviePath) - 1] = '\0';+ strlcat(moviePath, ".mp4", ARRAY_SIZE(moviePath));++ // yuv420p is what every player opens and it wants even dimensions, which a window need not have+ char commandLine[4 * _MAX_PATH];+ snprintf(commandLine, ARRAY_SIZE(commandLine),+ "\"%s\" -y -loglevel error -framerate %d -i \"%s%s\" -vf pad=ceil(iw/2)*2:ceil(ih/2)*2 "+ "-c:v libx264 -pix_fmt yuv420p -crf 18 \"%s\"",+ encoderPath, LOGICFRAMES_PER_SECOND, s_videoDirectory, VIDEO_FRAME_PATTERN, moviePath);++ STARTUPINFOA startup;+ memset(&startup, 0, sizeof(startup));+ startup.cb = sizeof(startup);+ PROCESS_INFORMATION process;+ if (!CreateProcessA(encoderPath, commandLine, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL,+ &startup, &process))+ {+ DEBUG_LOG(("VIDEO: %s would not start (error %u), so the frames stay where they are\n",+ encoderPath, (unsigned)GetLastError()));+ return;+ }++ WaitForSingleObject(process.hProcess, INFINITE);+ DWORD exitCode = 0;+ GetExitCodeProcess(process.hProcess, &exitCode);+ CloseHandle(process.hThread);+ CloseHandle(process.hProcess);++ if (exitCode != 0)+ {+ DEBUG_LOG(("VIDEO: %s exited with %u, so the frames stay where they are\n",+ encoderPath, (unsigned)exitCode));+ return;+ }++ deleteVideoFrames();+ RemoveDirectoryA(s_videoDirectory);+ DEBUG_LOG(("VIDEO: wrote %s\n", moviePath));+}++static void captureVideoFrame(void)+{+ if (TheGlobalData->m_videoEndFrame <= 0 || s_videoFinished || TheGameLogic == NULL+ || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame())+ return;++ const UnsignedInt frame = TheGameLogic->getFrame();+ if (frame < (UnsignedInt)TheGlobalData->m_videoStartFrame)+ return;++ if (frame > (UnsignedInt)TheGlobalData->m_videoEndFrame)+ {+ finishVideo();+ return;+ }++ if (!s_videoStarted)+ {+ s_videoStarted = TRUE;+ snprintf(s_videoDirectory, ARRAY_SIZE(s_videoDirectory), "%sVideos\\",+ TheGlobalData->getPath_UserData().str());+ CreateDirectoryA(s_videoDirectory, NULL);+ strlcat(s_videoDirectory, TheGlobalData->m_videoName.str(), ARRAY_SIZE(s_videoDirectory));+ strlcat(s_videoDirectory, "\\", ARRAY_SIZE(s_videoDirectory));+ CreateDirectoryA(s_videoDirectory, NULL);++ // a directory left over from an earlier run would hand ffmpeg its tail as well+ deleteVideoFrames();+ DEBUG_LOG(("VIDEO: recording logic frames %d to %d into %s\n",+ TheGlobalData->m_videoStartFrame, TheGlobalData->m_videoEndFrame, s_videoDirectory));+ }+ else if (frame == s_videoLastFrame)+ {+ return;+ }+ else if (frame > s_videoLastFrame + 1)+ {+ s_videoFramesMissed += frame - s_videoLastFrame - 1;+ }+ s_videoLastFrame = frame;++ char pathname[_MAX_PATH];+ buildVideoFramePath(pathname, ARRAY_SIZE(pathname), s_videoFramesWritten);+ if (writeFrameBMP(pathname))+ ++s_videoFramesWritten;+ else+ ++s_videoFramesMissed;+}+/** Start/Stop campturing an AVI movie*/void W3DDisplay::toggleMovieCapture(void){