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
fix(gameengine): write the replay on its own thread, no disk stall
Olcay Seygancf4cdd287f0c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7d605a288..99d6e702f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -271,6 +271,7 @@ found and fixed — EA's own, not port damage.**- Late in a match the picture caught less often. Every ten seconds each computer player looked over its economy, its spending and the enemy army all in one step, 8 to 10ms of work landing on a single picture. Those three now run a fifth of a second apart. With four Hard computer players on Twilight Flame at minutes 24 and 25, pictures slower than 16.7ms went from 29 a minute to 22, and the slowest one in a hundred from 14.7ms to 14.0ms. Two more hitches got smaller in the same match. The map of where units can drive is rebuilt whenever a building goes up or comes down, and that rebuild went from 9.9ms to 7.4ms, with the ones over 8ms halved (90 to 43). A Hard computer steering its Particle Cannon beam now weighs the ground around it in 0.9ms instead of 2.6ms. Neither changes a single move: the match ends on the same checksum.- The game no longer freezes for seconds when your hard drive is busy. It writes a log of the match as it plays, and once a second the battle itself stopped to push that log to disk. On a drive already busy with something else, Windows can hold such a write back for seconds, and the whole game stood still behind it: a 2v2 against the computer froze for 7.8 seconds on a single step. The log is written on the side now and the battle never waits for it. Three matches played while another program kept the drive busy froze for 6.2 seconds in two of them before; with the change, the slowest step in all three took 48ms.- The game's log no longer grows without limit. Players sent us logs of half a gigabyte up to 19 GB, enough to fill a disk, and the launcher could not open them to report a crash. Most of it was the network code writing a line for every order and every frame, which only a developer's build writes now: a 100-second two-player network match went from 10.9 MB of log to 175 KB, and a skirmish from 600 KB to 166 KB. Past 64 MB the log keeps its first 8 MB, which say how the game started and on what machine, and its most recent lines, so it stays under 64 MB however long you play.+- The replay no longer stops the battle either. Every order given in a match went to the replay file on disk the moment it was recorded, and on a busy hard drive Windows held each of those writes back. Two long matches against the computer, played while another program kept the drive busy, stalled 115 times for over a tenth of a second, the worst for 0.63 seconds. The replay is written on the side now, about once a second. The same two matches never stalled past 35ms and finished 40% sooner. The file itself has not changed: a replay recorded by the old game and the new one from the same match is identical byte for byte, the clock times aside. A game that crashes still saves its replay up to the crash; one killed from Task Manager can lose its last second.- Every animation runs on a clock instead of counting frames.- Tanks and trucks move the same at any frame rate. Their treads scrolled a fixed step every picture, so at 120 frames a second they ran four times too fast, and a tank turning on the spot rolled both treads forward as if it were driving. Each tread now covers exactly the ground under it. In a tight turn the two run against each other, and backing up runs them backwards. Wheels spin with the distance driven the same way. The hull's springs used to settle four times too fast as well, and every start or stop threw the chassis to its full tilt in a single picture. Now a tank squats as it pulls away and dips its nose when it brakes, easing in over a tenth of a second and settling within half a second. In a corner it leans out, a Crusader up to two and a half degrees. The Humvee, which never moved on its springs at all, rocks too. A run drawing one picture per game tick and one drawing fourteen put every tank in the same pose, to the last digit, for as long as neither skipped a tick.- A scroll that starts after the camera has stood still no longer lurches. The first frame of the move was timed from the last time the camera moved, so after a few seconds of looking at one spot it was worth three frames of scrolling at once. The clock runs while the camera is still now, and the first frame moves one frame's worth.diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifestindex d488e3dd8..a3386455b 100644--- a/GeneralsMD/Code/BuildFingerprint.manifest+++ b/GeneralsMD/Code/BuildFingerprint.manifest@@ -428,6 +428,7 @@ GameEngine/Include/Common/Energy.hGameEngine/Include/Common/Errors.hGameEngine/Include/Common/ExecutableDirectory.hGameEngine/Include/Common/FileSystem.h+GameEngine/Include/Common/FileWriteQueue.hGameEngine/Include/Common/FunctionLexicon.hGameEngine/Include/Common/GameAudio.hGameEngine/Include/Common/GameCommon.h@@ -1086,6 +1087,7 @@ GameEngine/Source/Common/System/DisabledTypes.cppGameEngine/Source/Common/System/ExecutableDirectory.cppGameEngine/Source/Common/System/File.cppGameEngine/Source/Common/System/FileSystem.cpp+GameEngine/Source/Common/System/FileWriteQueue.cppGameEngine/Source/Common/System/FunctionLexicon.cppGameEngine/Source/Common/System/GameCommon.cppGameEngine/Source/Common/System/GameMemory.cppdiff --git a/GeneralsMD/Code/GameEngine/Include/Common/FileWriteQueue.h b/GeneralsMD/Code/GameEngine/Include/Common/FileWriteQueue.hnew file mode 100644index 000000000..4ea51edb4--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Include/Common/FileWriteQueue.h@@ -0,0 +1,94 @@+/*+** 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/>.+*/+// Modified 2026 by Olcay Seygan for Zero Hour Reforged; see the git history.++// FILE: FileWriteQueue.h /////////////////////////////////////////////////////////////////////////+// Desc: A file written by a thread of its own: the debug log and the replay.+////////////////////////////////////////////////////////////////////////////////////////////////////++#pragma once++#include <cstdio>+#include <condition_variable>+#include <mutex>+#if !defined(_WIN32)+#include <pthread.h>+#endif++/* The thread that has something to write never waits for the disk. D: here is a spinning disk, and+ with other copies of the game, a build and a video dump writing to it Windows holds a writer back+ for seconds: a flush inside a logic frame froze a 2v2 skirmish for 7.8 s. write() copies the bytes+ into a queue under a lock held for that copy; the writer thread takes the queue once a second and+ writes and flushes it with the lock released. The file's bytes and their order are what the same+ calls made directly on the FILE would have left; only when they reach the disk changes.++ Whatever reads the file back first calls flush() (or stop()), which writes the queue out on the+ calling thread and returns once it is on disk. Crash paths call flushAll() before they _exit.++ Nothing in here calls operator new: the debug log opens from inside the first operator new,+ before the memory manager exists, and builds its queue in place in static storage. The queue's+ bytes are malloc'd and the thread is the platform's own, not std::thread. */+class FileWriteQueue+{+public:+ FileWriteQueue();+ ~FileWriteQueue(); ///< stop()++ /// Takes writes for file and starts the writer. afterWrite, if given, runs on whichever thread+ /// wrote a batch, right after its flush, with fileLock held.+ void start(FILE *file, void (*afterWrite)(FILE *file) = NULL);+ /// The writer joined and the queue written out; the file is the caller's again, to close. A+ /// stopped queue drops what it is given.+ void stop();++ void write(const void *data, size_t length); ///< at the end of the file+ void writeAt(long offset, const void *data, size_t length); ///< over earlier bytes, as fseek, fwrite and a seek back did++ /// Everything queued so far into the file and flushed, on the caller's thread.+ void flush();+ /// flush() on every started queue: crash paths, before _exit skips the C library's own flush.+ static void flushAll();++ /// Held while a batch is written. ReleaseCrash takes the debug log's for good, so that no other+ /// thread's lines cut into its report. Recursive: a crash on the writer thread flushes from+ /// inside a flush.+ std::recursive_mutex fileLock;++ void runWriter(); ///< the writer thread's loop++private:+ void queue(long offset, const void *data, size_t length);++ std::mutex m_queueLock;+ std::condition_variable m_wake;+ FILE *m_file;+ void (*m_afterWrite)(FILE *file);+ char *m_text; ///< records: a RecordHeader, then its bytes+ size_t m_used;+ size_t m_size;+ size_t m_lastAppend; ///< where the last record starts when it appends, so the next append joins it+ char *m_batch; ///< what flush() writes from, swapped with m_text; fileLock's+ size_t m_batchSize;+#if defined(_WIN32)+ void *m_thread;+#else+ pthread_t m_thread;+#endif+ bool m_running;+ bool m_quit;+};diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cppindex e35b25a05..1f5a68e73 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp@@ -29,6 +29,7 @@#include "Lib/WideCharFns.h"#include "Common/Recorder.h"+#include "Common/FileWriteQueue.h"#include "Common/LocalFileSystem.h"#include "Common/FileSystem.h"#include "Common/PlayerList.h"@@ -69,25 +70,42 @@ static const UnsignedInt desyncOffset = framesOffset + sizeof(UnsignedInt);static const UnsignedInt quitEarlyOffset = desyncOffset + sizeof(Bool);static const UnsignedInt disconOffset = quitEarlyOffset + sizeof(Bool);+/* The replay being recorded is written by a thread of its own. It used to be flushed after every+ command, on the logic's thread: on a busy hard disk Windows holds such a write back for seconds,+ and the match stood still behind it, as it did behind the debug log's (FileWriteQueue.h). Every+ write below goes to this queue instead, in the order the FILE calls made them, so the file comes+ out byte for byte the same; the writer puts it on disk about once a second. stopRecording and+ reset drain it before anything reads or copies the file, and crash paths flush it before _exit.+ A process killed outright loses the last second of commands. */+static FileWriteQueue theReplayQueue;++template <typename T> static void replayWrite(const T &value)+{+ theReplayQueue.write(&value, sizeof(value));+}++/// What WideCharFilePut did on the replay's binary stream: the unit's two bytes, low first.+static void replayWriteWideChar(WideChar c)+{+ const unsigned char unit[2] = { (unsigned char)(c & 0xFF), (unsigned char)((c >> 8) & 0xFF) };+ theReplayQueue.write(unit, sizeof(unit));+}++/// WideCharFileWrite and the WideCharFilePut(0) after it.+static void replayWriteWideString(const WideChar *s)+{+ for (; *s != 0; ++s)+ replayWriteWideChar(*s);+ replayWriteWideChar(0);+}+void RecorderClass::logGameStart(AsciiString options){if (!m_file)return;time(&startTime);- UnsignedInt fileSize = ftell(m_file);- // move to appropriate offset- if (!fseek(m_file, startTimeOffset, SEEK_SET))- {- // save off start time- fwrite(&startTime, sizeof(time_t), 1, m_file);- }- // move back to end of stream-#ifdef DEBUG_CRASHING- Int res =-#endif- fseek(m_file, fileSize, SEEK_SET);- DEBUG_ASSERTCRASH(res == 0, ("Could not seek to end of file!"));+ theReplayQueue.writeAt(startTimeOffset, &startTime, sizeof(time_t));#if defined(_DEBUG) || defined(_INTERNAL)if (TheNetwork && TheGlobalData->m_saveStats)@@ -135,20 +153,9 @@ void RecorderClass::logPlayerDisconnect(UnicodeString player, Int slot){return;}- UnsignedInt fileSize = ftell(m_file);- // move to appropriate offset- if (!fseek(m_file, disconOffset + slot*sizeof(Bool), SEEK_SET))- {- // save off discon status- Bool b = TRUE;- fwrite(&b, sizeof(Bool), 1, m_file);- }- // move back to end of stream-#ifdef DEBUG_CRASHING- Int res =-#endif- fseek(m_file, fileSize, SEEK_SET);- DEBUG_ASSERTCRASH(res == 0, ("Could not seek to end of file!"));+ // save off discon status+ Bool b = TRUE;+ theReplayQueue.writeAt(disconOffset + slot*sizeof(Bool), &b, sizeof(Bool));#if defined(_DEBUG) || defined(_INTERNAL)if (TheGlobalData->m_saveStats)@@ -180,20 +187,9 @@ void RecorderClass::logCRCMismatch( void )if (!m_file)return;- UnsignedInt fileSize = ftell(m_file);- // move to appropriate offset- if (!fseek(m_file, desyncOffset, SEEK_SET))- {- // save off desync status- Bool b = TRUE;- fwrite(&b, sizeof(Bool), 1, m_file);- }- // move back to end of stream-#ifdef DEBUG_CRASHING- Int res =-#endif- fseek(m_file, fileSize, SEEK_SET);- DEBUG_ASSERTCRASH(res == 0, ("Could not seek to end of file!"));+ // save off desync status+ Bool b = TRUE;+ theReplayQueue.writeAt(desyncOffset, &b, sizeof(Bool));#if defined(_DEBUG) || defined(_INTERNAL)if (TheGlobalData->m_saveStats)@@ -229,25 +225,8 @@ void RecorderClass::logGameEnd( void )time_t t;time(&t);UnsignedInt duration = TheGameLogic->getFrame();- UnsignedInt fileSize = ftell(m_file);- // move to appropriate offset- if (!fseek(m_file, endTimeOffset, SEEK_SET))- {- // save off end time- fwrite(&t, sizeof(time_t), 1, m_file);- }- // move to appropriate offset- if (!fseek(m_file, framesOffset, SEEK_SET))- {- // save off duration- fwrite(&duration, sizeof(UnsignedInt), 1, m_file);- }- // move back to end of stream-#ifdef DEBUG_CRASHING- Int res =-#endif- fseek(m_file, fileSize, SEEK_SET);- DEBUG_ASSERTCRASH(res == 0, ("Could not seek to end of file!"));+ theReplayQueue.writeAt(endTimeOffset, &t, sizeof(time_t)); // end time+ theReplayQueue.writeAt(framesOffset, &duration, sizeof(UnsignedInt)); // duration#if defined(_DEBUG) || defined(_INTERNAL)if (TheNetwork && TheGlobalData->m_saveStats)@@ -293,6 +272,7 @@ void RecorderClass::logGameEnd( void )void RecorderClass::cleanUpReplayFile( void ){+ theReplayQueue.flush(); // the copy below may be taken mid-match#if defined(_DEBUG) || defined(_INTERNAL)if (TheGlobalData->m_saveStats){@@ -428,6 +408,7 @@ void RecorderClass::init() {* Reset the recorder to the "initialized state."*/void RecorderClass::reset() {+ theReplayQueue.stop(); // a recording's last commands into its file before it closesif (m_file != NULL) {fclose(m_file);m_file = NULL;@@ -496,9 +477,8 @@ void RecorderClass::stopPlayback() {* Update function for recording a game. Basically all the pertinant logic commands for this frame are written out* to a file.*/-void RecorderClass::updateRecord()+void RecorderClass::updateRecord(){- Bool needFlush = FALSE;static Int lastFrame = -1;GameMessage *msg = TheCommandList->getFirstMessage();while (msg != NULL) {@@ -535,16 +515,11 @@ void RecorderClass::updateRecord()(msg->getType() < GameMessage::MSG_END_NETWORK_MESSAGES)) {// Only write the important messages to the file.writeToFile(msg);- needFlush = TRUE;}}}msg = msg->next();}-- if (needFlush) {- fflush(m_file);- }}/**@@ -571,7 +546,8 @@ void RecorderClass::startRecording(GameDifficulty diff, Int originalGameMode, InDEBUG_ASSERTCRASH(m_file != NULL, ("Failed to create replay file"));return;}- fprintf(m_file, "GENREP");+ theReplayQueue.start(m_file);+ theReplayQueue.write("GENREP", 6);//// save space for stats to be filled in.@@ -579,48 +555,43 @@ void RecorderClass::startRecording(GameDifficulty diff, Int originalGameMode, In// **** if this changes, change the LAN code above ****//time_t t = 0;- fwrite(&t, sizeof(time_t), 1, m_file); // reserve space for start time- fwrite(&t, sizeof(time_t), 1, m_file); // reserve space for end time+ replayWrite(t); // reserve space for start time+ replayWrite(t); // reserve space for end timeUnsignedInt frames = 0;- fwrite(&frames, sizeof(UnsignedInt), 1, m_file); // reserve space for duration in frames+ replayWrite(frames); // reserve space for duration in framesBool b = FALSE;- fwrite(&b, sizeof(Bool), 1, m_file); // reserve space for flag (true if we desync)- fwrite(&b, sizeof(Bool), 1, m_file); // reserve space for flag (true if we quit early)+ replayWrite(b); // reserve space for flag (true if we desync)+ replayWrite(b); // reserve space for flag (true if we quit early)for (Int i=0; i<MAX_SLOTS; ++i){- fwrite(&b, sizeof(Bool), 1, m_file); // reserve space for flag (true if player i disconnects)+ replayWrite(b); // reserve space for flag (true if player i disconnects)}// Print out the name of the replay.//- // WideCharFileWrite and WideCharFilePut rather than fwprintf and fputwc: this FILE* also carries- // fwrite, and a stream may not mix wide and byte calls - MSVC tolerated it, a POSIX C library- // fails one kind. They write what the wide calls wrote on a binary stream, each code unit as- // two bytes, low first, so the format is unchanged; readUnicodeString reads it back with- // WideCharFileGet. See Lib/WideCharFns.h.+ // Each code unit as two bytes, low first, as fputwc wrote it on a binary stream under MSVC, so+ // the format is unchanged; readUnicodeString reads it back with WideCharFileGet. See+ // Lib/WideCharFns.h.UnicodeString replayName;replayName = TheGameText->fetch("GUI:LastReplay");- WideCharFileWrite(m_file, replayName.str());- WideCharFilePut(m_file, 0);+ replayWriteWideString(replayName.str());// Date and TimeWallClockTime systemTime;getLocalWallClock( &systemTime );- fwrite(&systemTime, sizeof(WallClockTime), 1, m_file);+ replayWrite(systemTime);// write out version infoUnicodeString versionString = TheVersion->getUnicodeVersion();UnicodeString versionTimeString = TheVersion->getUnicodeBuildTime();UnsignedInt versionNumber = TheVersion->getVersionNumber();- WideCharFileWrite(m_file, versionString.str());- WideCharFilePut(m_file, 0);- WideCharFileWrite(m_file, versionTimeString.str());- WideCharFilePut(m_file, 0);- fwrite(&versionNumber, sizeof(UnsignedInt), 1, m_file);- fwrite(&(TheGlobalData->m_exeCRC), sizeof(UnsignedInt), 1, m_file);- fwrite(&(TheGlobalData->m_iniCRC), sizeof(UnsignedInt), 1, m_file);+ replayWriteWideString(versionString.str());+ replayWriteWideString(versionTimeString.str());+ replayWrite(versionNumber);+ theReplayQueue.write(&(TheGlobalData->m_exeCRC), sizeof(UnsignedInt));+ theReplayQueue.write(&(TheGlobalData->m_iniCRC), sizeof(UnsignedInt));// Number of players/*@@ -677,9 +648,10 @@ void RecorderClass::startRecording(GameDifficulty diff, Int originalGameMode, InDEBUG_LOG(("RecorderClass::startRecording - theSlotList = %s\n", theSlotList.str()));// write slot list (starting spots, color, alliances, etc- fwrite(theSlotList.str(), theSlotList.getLength() + 1, 1, m_file);- fprintf(m_file, "%d", localIndex);- fputc(0, m_file);+ theReplayQueue.write(theSlotList.str(), theSlotList.getLength() + 1);+ char localIndexText[ 16 ];+ snprintf(localIndexText, sizeof(localIndexText), "%d", localIndex);+ theReplayQueue.write(localIndexText, strlen(localIndexText) + 1); // with its terminator/*/// @todo fix this to use starting spots and player alliances when those are put in the game.@@ -704,16 +676,16 @@ void RecorderClass::startRecording(GameDifficulty diff, Int originalGameMode, In*/// Write the game difficulty.- fwrite(&diff, sizeof(Int), 1, m_file);+ theReplayQueue.write(&diff, sizeof(Int));// Write original game mode- fwrite(&originalGameMode, sizeof(originalGameMode), 1, m_file);+ replayWrite(originalGameMode);// Write rank points to add at game start- fwrite(&rankPoints, sizeof(rankPoints), 1, m_file);+ replayWrite(rankPoints);// Write maxFPS chosen- fwrite(&maxFPS, sizeof(maxFPS), 1, m_file);+ replayWrite(maxFPS);DEBUG_LOG(("RecorderClass::startRecording() - diff=%d, mode=%d, FPS=%d\n", diff, originalGameMode, maxFPS));@@ -732,6 +704,7 @@ void RecorderClass::startRecording(GameDifficulty diff, Int originalGameMode, In*/void RecorderClass::stopRecording() {logGameEnd();+ theReplayQueue.stop(); // all of it on disk: cleanUpReplayFile and archiveReplay copy the fileif (TheNetwork){//if (TheLAN)@@ -782,15 +755,15 @@ void RecorderClass::archiveReplay(const AsciiString& fileName)void RecorderClass::writeToFile(GameMessage * msg) {// Write the frame number for this command.UnsignedInt frame = TheGameLogic->getFrame();- fwrite(&frame, sizeof(frame), 1, m_file);+ replayWrite(frame);// Write the command typeGameMessage::Type type = msg->getType();- fwrite(&type, sizeof(type), 1, m_file);+ replayWrite(type);// Write the player indexInt playerIndex = msg->getPlayerIndex();- fwrite(&playerIndex, sizeof(playerIndex), 1, m_file);+ replayWrite(playerIndex);#ifdef DEBUG_LOGGINGAsciiString commandName = msg->getCommandAsAsciiString();@@ -811,15 +784,15 @@ void RecorderClass::writeToFile(GameMessage * msg) {GameMessageParser *parser = newInstance(GameMessageParser)(msg);UnsignedByte numTypes = parser->getNumTypes();- fwrite(&numTypes, sizeof(numTypes), 1, m_file);+ replayWrite(numTypes);GameMessageParserArgumentType *argType = parser->getFirstArgumentType();while (argType != NULL) {UnsignedByte type = (UnsignedByte)(argType->getType());- fwrite(&type, sizeof(type), 1, m_file);+ replayWrite(type);UnsignedByte argTypeCount = (UnsignedByte)(argType->getArgCount());- fwrite(&argTypeCount, sizeof(argTypeCount), 1, m_file);+ replayWrite(argTypeCount);argType = argType->getNext();}@@ -831,33 +804,31 @@ void RecorderClass::writeToFile(GameMessage * msg) {parser->deleteInstance();parser = NULL;-- fflush(m_file); ///< @todo should this be in the final release?}void RecorderClass::writeArgument(GameMessageArgumentDataType type, const GameMessageArgumentType arg) {if (type == ARGUMENTDATATYPE_INTEGER) {- fwrite(&(arg.integer), sizeof(arg.integer), 1, m_file);+ replayWrite(arg.integer);} else if (type == ARGUMENTDATATYPE_REAL) {- fwrite(&(arg.real), sizeof(arg.real), 1, m_file);+ replayWrite(arg.real);} else if (type == ARGUMENTDATATYPE_BOOLEAN) {- fwrite(&(arg.boolean), sizeof(arg.boolean), 1, m_file);+ replayWrite(arg.boolean);} else if (type == ARGUMENTDATATYPE_OBJECTID) {- fwrite(&(arg.objectID), sizeof(arg.objectID), 1, m_file);+ replayWrite(arg.objectID);} else if (type == ARGUMENTDATATYPE_DRAWABLEID) {- fwrite(&(arg.drawableID), sizeof(arg.drawableID), 1, m_file);+ replayWrite(arg.drawableID);} else if (type == ARGUMENTDATATYPE_TEAMID) {- fwrite(&(arg.teamID), sizeof(arg.teamID), 1, m_file);+ replayWrite(arg.teamID);} else if (type == ARGUMENTDATATYPE_LOCATION) {- fwrite(&(arg.location), sizeof(arg.location), 1, m_file);+ replayWrite(arg.location);} else if (type == ARGUMENTDATATYPE_PIXEL) {- fwrite(&(arg.pixel), sizeof(arg.pixel), 1, m_file);+ replayWrite(arg.pixel);} else if (type == ARGUMENTDATATYPE_PIXELREGION) {- fwrite(&(arg.pixelRegion), sizeof(arg.pixelRegion), 1, m_file);+ replayWrite(arg.pixelRegion);} else if (type == ARGUMENTDATATYPE_TIMESTAMP) {- fwrite(&(arg.timestamp), sizeof(arg.timestamp), 1, m_file);+ replayWrite(arg.timestamp);} else if (type == ARGUMENTDATATYPE_WIDECHAR) {- fwrite(&(arg.wChar), sizeof(arg.wChar), 1, m_file);+ replayWrite(arg.wChar);}}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cppindex 11d09d37b..821c9e445 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp@@ -83,16 +83,13 @@ extern HWND ApplicationHWnd;#endif#include <thread> // the main thread's id off Windows (Windows uses GetCurrentThreadId); GameDataGone's yield#include <atomic> // GameDataGone's state, set from whichever thread's read failed-#include <chrono>-#include <condition_variable>-#include <mutex>#include <new>#if defined(_WIN32)#include <io.h> // _chsize_s, DebugCutLogFile#else-#include <pthread.h>#include <unistd.h> // ftruncate, DebugCutLogFile#endif+#include "Common/FileWriteQueue.h"extern char *gAppPrefix; /// So WB can have a different log file name.@@ -180,141 +177,41 @@ static const long LOG_KEEP_BYTES = 24 * 1024 * 1024;static char theLogPath[ _MAX_PATH ];static long theLogHeadEnd = 0; // where the head ends: the end of the batch that took the file past LOG_HEAD_BYTES-/* The log file is written by a thread of its own, never by the thread that logs. Flushing once a- second from the logging thread still put a disk write inside whichever logic frame came due, and- D: here is a spinning disk: with other copies of the game, a build and a video dump writing to it,- Windows holds a writer back for seconds, and one 2v2 skirmish logged a 7.8 s logic frame with all- of it in the AI, the phase that logs the most. A line goes into theLogQueue under a lock held for- a copy; the writer takes the queue once a second and writes it with that lock released.- fileLock keeps the writer and a crash path's flushLogQueue from reordering two batches.- The log opens during static initialisation, from inside the first operator new, before this- file's statics are constructed and before the memory manager exists. So the queue is built in- place in static storage when the file opens, and its text is malloc'd, never operator new. */-struct LogQueue-{- std::mutex queueLock;- std::recursive_mutex fileLock; // recursive: a crash on the writer thread flushes from inside a flush- std::condition_variable wake;- char *text;- size_t used;- size_t size;- // a platform thread, not std::thread, whose start is an operator new before the memory manager exists-#if defined(_WIN32)- HANDLE writer;-#else- pthread_t writer;-#endif- bool running;- bool quit;-};-alignas(LogQueue) static unsigned char theLogQueueStorage[ sizeof(LogQueue) ];-static LogQueue *theLogQueue = NULL;+/* The log file is written by a thread of its own (FileWriteQueue), never by the thread that logs.+ Flushing once a second from the logging thread still put a disk write inside whichever logic frame+ came due, and one 2v2 skirmish logged a 7.8 s logic frame with all of it in the AI, the phase that+ logs the most. The log opens during static initialisation, from inside the first operator new,+ before this file's statics are constructed and before the memory manager exists. So the queue is+ built in place in static storage when the file opens. */+alignas(FileWriteQueue) static unsigned char theLogQueueStorage[ sizeof(FileWriteQueue) ];+static FileWriteQueue *theLogQueue = NULL;static void queueLogOutput(const char *text){- const size_t length = strlen(text);- std::lock_guard<std::mutex> lock(theLogQueue->queueLock);- if (theLogQueue->used + length > theLogQueue->size)- {- theLogQueue->size = 2 * (theLogQueue->used + length);- theLogQueue->text = (char *)realloc(theLogQueue->text, theLogQueue->size);- }- memcpy(theLogQueue->text + theLogQueue->used, text, length);- theLogQueue->used += length;+ theLogQueue->write(text, strlen(text));}-/// Everything queued so far into the file and flushed, on the caller's thread. Crash paths and shutdown.-static void flushLogQueue(void)+/// The cap, after each batch the writer puts in the file.+static void capLogFile(FILE *file){- if (theLogQueue == NULL)- return; // a crash before the log opened- std::lock_guard<std::recursive_mutex> fileLock(theLogQueue->fileLock);- // the writer's own buffer, swapped with the queue's so a line queued meanwhile goes on the next batch- static char *batch = NULL;- static size_t batchSize = 0;- size_t batchUsed;- {- std::lock_guard<std::mutex> lock(theLogQueue->queueLock);- std::swap(batch, theLogQueue->text);- std::swap(batchSize, theLogQueue->size);- batchUsed = theLogQueue->used;- theLogQueue->used = 0;- }- if (theLogFile == NULL || batchUsed == 0)- return;- fwrite(batch, 1, batchUsed, theLogFile);- fflush(theLogFile);- const long size = ftell(theLogFile);+ const long size = ftell(file);if (theLogHeadEnd == 0 && size >= LOG_HEAD_BYTES)theLogHeadEnd = size;if (size > LOG_CAP_BYTES)- DebugCutLogFile(theLogFile, theLogPath, theLogHeadEnd, LOG_KEEP_BYTES);+ DebugCutLogFile(file, theLogPath, theLogHeadEnd, LOG_KEEP_BYTES);}-static void logWriterMain(void)-{- std::unique_lock<std::mutex> lock(theLogQueue->queueLock);- while (!theLogQueue->quit)- {- theLogQueue->wake.wait_for(lock, std::chrono::seconds(1));- lock.unlock();- flushLogQueue();- lock.lock();- }-}--#if defined(_WIN32)-static DWORD WINAPI logWriterThread(LPVOID)-{- logWriterMain();- return 0;-}-#else-static void *logWriterThread(void *)-{- logWriterMain();- return NULL;-}-#endif-static void startLogWriter(void){if (theLogQueue == NULL)- {- theLogQueue = new (theLogQueueStorage) LogQueue;- theLogQueue->text = NULL;- theLogQueue->used = 0;- theLogQueue->size = 0;- }- theLogQueue->quit = false;-#if defined(_WIN32)- theLogQueue->writer = CreateThread(NULL, 0, logWriterThread, NULL, 0, NULL);- theLogQueue->running = theLogQueue->writer != NULL;-#else- theLogQueue->running = pthread_create(&theLogQueue->writer, NULL, logWriterThread, NULL) == 0;-#endif+ theLogQueue = new (theLogQueueStorage) FileWriteQueue;+ theLogQueue->start(theLogFile, capLogFile);}static void stopLogWriter(void){- if (theLogQueue == NULL)- return;- if (theLogQueue->running)- {- {- std::lock_guard<std::mutex> lock(theLogQueue->queueLock);- theLogQueue->quit = true;- }- theLogQueue->wake.notify_one();-#if defined(_WIN32)- WaitForSingleObject(theLogQueue->writer, INFINITE);- CloseHandle(theLogQueue->writer);-#else- pthread_join(theLogQueue->writer, NULL);-#endif- theLogQueue->running = false;- }- flushLogQueue();+ if (theLogQueue != NULL)+ theLogQueue->stop();}#endif#define LARGE_BUFFER 8192@@ -439,7 +336,7 @@ int MessageBoxWrapper( const char *lpText, const char *lpCaption, unsigned int uchar line[ 4096 ]; // no operator new here: this can run before the memory manager existssnprintf(line, sizeof(line), "[message box] %s%s%s\n", lpCaption, (lpCaption && lpCaption[0]) ? ": " : "", lpText);queueLogOutput(line);- flushLogQueue(); // a box is often the last thing before an _exit, and its reason must reach the file+ FileWriteQueue::flushAll(); // a box is often the last thing before an _exit, and its reason must reach the file}#endifreturn (uType & MSGBOX_ABORTRETRYIGNORE)?MSGBOX_ID_IGNORE:MSGBOX_ID_YES;@@ -559,8 +456,8 @@ static int doCrashBox(const char *buffer, Bool logResult)#ifdef DEBUG_LOGGINGif (logResult)DebugLog("[Abort]\n");- flushLogQueue();#endif+ FileWriteQueue::flushAll(); // the log and the replay: _exit skips the C library's flush_exit(1);break;case MSGBOX_ID_RETRY:@@ -642,7 +539,7 @@ static int __cdecl unattendedCrtReport( int, char *message, int *returnValue )#ifdef DEBUG_STACKTRACEdoStackDump();#endif- flushLogQueue();+ FileWriteQueue::flushAll();#endifif (returnValue != NULL)*returnValue = 0; // no debugger@@ -1047,9 +944,10 @@ double SimpleProfiler::getAverageTime()void ReleaseCrash(const char *reason){+ // the debug log and the replay are written by threads of their own once a second, and this+ // function ends in _exit+ FileWriteQueue::flushAll();#ifdef DEBUG_LOGGING- // the debug log is written by its own thread once a second, and this function ends in _exit- flushLogQueue();// From here to _exit the file is this thread's alone, so the writer cannot cut into the report// with other threads' lines. Never released; what is queued meanwhile goes out before each _exit.if (theLogQueue != NULL)@@ -1111,9 +1009,7 @@ void ReleaseCrash(const char *reason)fclose(theReleaseCrashLogFile);theReleaseCrashLogFile = NULL;}-#ifdef DEBUG_LOGGING- flushLogQueue(); // the "could not write" line above, if there was one-#endif+ FileWriteQueue::flushAll(); // the "could not write" line above, if there was onehideFullScreenWindowForMessage();// the log is written by now; a run nobody is watching should die rather than wait for a click@@ -1192,9 +1088,7 @@ static void gameDataGoneExit( void )"put to sleep. Reconnect it and start the game again.", theGameDataGoneWhat );DEBUG_LOG(( "GAME DATA GONE: %s\n", text ));-#ifdef DEBUG_LOGGING- flushLogQueue(); // written once a second otherwise, and _exit below skips the CRT's flush-#endif+ FileWriteQueue::flushAll(); // written once a second otherwise, and _exit below skips the CRT's flushfprintf( stderr, "GAME DATA GONE: %s\n", text );fflush( stderr );@@ -1226,9 +1120,10 @@ void GameDataGoneCheck( void )void ReleaseCrashLocalized(const AsciiString& p, const AsciiString& m){+ // see ReleaseCrash: the log and the replay are written once a second and _exit below skips the+ // CRT's flush+ FileWriteQueue::flushAll();#ifdef DEBUG_LOGGING- // see ReleaseCrash: the log is written once a second and _exit below skips the CRT's flush- flushLogQueue();if (theLogQueue != NULL)theLogQueue->fileLock.lock(); // the report uninterrupted, as in ReleaseCrash#endif@@ -1309,9 +1204,7 @@ void ReleaseCrashLocalized(const AsciiString& p, const AsciiString& m)fclose(theReleaseCrashLogFile);theReleaseCrashLogFile = NULL;}-#ifdef DEBUG_LOGGING- flushLogQueue();-#endif+ FileWriteQueue::flushAll();_exit(1);}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/FileWriteQueue.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/FileWriteQueue.cppnew file mode 100644index 000000000..42af692ee--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/FileWriteQueue.cpp@@ -0,0 +1,231 @@+/*+** 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/>.+*/+// Modified 2026 by Olcay Seygan for Zero Hour Reforged; see the git history.++// FILE: FileWriteQueue.cpp ///////////////////////////////////////////////////////////////////////+// Desc: A file written by a thread of its own; see FileWriteQueue.h.+////////////////////////////////////////////////////////////////////////////////////////////////////++#include "PreRTS.h"+#include "Common/FileWriteQueue.h"++#include <chrono>+#include <cstdlib>+#include <cstring>+#include <utility>++/// A record in the queue: offset -1 appends, anything else is a writeAt.+struct RecordHeader+{+ long offset;+ size_t length;+};++static const size_t NO_APPEND = (size_t)-1;++// ponytail: a fixed table read without a lock by crash paths; there are two queues, the debug log+// and the replay, and a crash racing a start or stop at worst misses one flush.+static FileWriteQueue *theStartedQueues[ 4 ];++FileWriteQueue::FileWriteQueue() :+ m_file(NULL),+ m_afterWrite(NULL),+ m_text(NULL),+ m_used(0),+ m_size(0),+ m_lastAppend(NO_APPEND),+ m_batch(NULL),+ m_batchSize(0),+ m_running(false),+ m_quit(false)+{+}++FileWriteQueue::~FileWriteQueue()+{+ stop();+ free(m_text);+ free(m_batch);+}++#if defined(_WIN32)+static DWORD WINAPI writerThread(LPVOID queue)+{+ ((FileWriteQueue *)queue)->runWriter();+ return 0;+}+#else+static void *writerThread(void *queue)+{+ ((FileWriteQueue *)queue)->runWriter();+ return NULL;+}+#endif++void FileWriteQueue::start(FILE *file, void (*afterWrite)(FILE *file))+{+ {+ std::lock_guard<std::mutex> lock(m_queueLock);+ m_file = file;+ m_afterWrite = afterWrite;+ m_quit = false;+ }+#if defined(_WIN32)+ m_thread = CreateThread(NULL, 0, writerThread, this, 0, NULL);+ m_running = m_thread != NULL;+#else+ m_running = pthread_create(&m_thread, NULL, writerThread, this) == 0;+#endif+ for (size_t i = 0; i < ARRAY_SIZE(theStartedQueues); ++i)+ {+ if (theStartedQueues[i] == NULL)+ {+ theStartedQueues[i] = this;+ break;+ }+ }+}++void FileWriteQueue::stop()+{+ if (m_running)+ {+ {+ std::lock_guard<std::mutex> lock(m_queueLock);+ m_quit = true;+ }+ m_wake.notify_one();+#if defined(_WIN32)+ WaitForSingleObject((HANDLE)m_thread, INFINITE);+ CloseHandle((HANDLE)m_thread);+#else+ pthread_join(m_thread, NULL);+#endif+ m_running = false;+ }+ flush();+ for (size_t i = 0; i < ARRAY_SIZE(theStartedQueues); ++i)+ {+ if (theStartedQueues[i] == this)+ theStartedQueues[i] = NULL;+ }+ std::lock_guard<std::mutex> lock(m_queueLock);+ m_file = NULL;+ m_used = 0; // a write that raced the flush above, never to lead the next file+ m_lastAppend = NO_APPEND;+}++void FileWriteQueue::queue(long offset, const void *data, size_t length)+{+ std::lock_guard<std::mutex> lock(m_queueLock);+ if (m_file == NULL)+ return; // stopped+ const bool append = offset < 0;+ const size_t needed = m_used + sizeof(RecordHeader) + length;+ if (needed > m_size)+ {+ m_size = 2 * needed;+ m_text = (char *)realloc(m_text, m_size);+ }+ if (append && m_lastAppend != NO_APPEND)+ {+ RecordHeader header;+ memcpy(&header, m_text + m_lastAppend, sizeof(header));+ header.length += length;+ memcpy(m_text + m_lastAppend, &header, sizeof(header));+ }+ else+ {+ const RecordHeader header = { offset, length };+ m_lastAppend = append ? m_used : NO_APPEND;+ memcpy(m_text + m_used, &header, sizeof(header));+ m_used += sizeof(header);+ }+ memcpy(m_text + m_used, data, length);+ m_used += length;+}++void FileWriteQueue::write(const void *data, size_t length)+{+ queue(-1, data, length);+}++void FileWriteQueue::writeAt(long offset, const void *data, size_t length)+{+ queue(offset, data, length);+}++void FileWriteQueue::flush()+{+ std::lock_guard<std::recursive_mutex> file(fileLock);+ size_t used;+ FILE *f;+ {+ // swapped, so what is queued while this batch is written goes on the next one+ std::lock_guard<std::mutex> lock(m_queueLock);+ std::swap(m_batch, m_text);+ std::swap(m_batchSize, m_size);+ used = m_used;+ m_used = 0;+ m_lastAppend = NO_APPEND;+ f = m_file;+ }+ if (f == NULL || used == 0)+ return;+ for (size_t at = 0; at < used; )+ {+ RecordHeader header;+ memcpy(&header, m_batch + at, sizeof(header));+ at += sizeof(header);+ if (header.offset < 0)+ fwrite(m_batch + at, 1, header.length, f);+ else+ {+ const long end = ftell(f);+ if (fseek(f, header.offset, SEEK_SET) == 0)+ fwrite(m_batch + at, 1, header.length, f);+ fseek(f, end, SEEK_SET);+ }+ at += header.length;+ }+ fflush(f);+ if (m_afterWrite != NULL)+ m_afterWrite(f);+}++void FileWriteQueue::flushAll()+{+ for (size_t i = 0; i < ARRAY_SIZE(theStartedQueues); ++i)+ {+ FileWriteQueue *queue = theStartedQueues[i];+ if (queue != NULL)+ queue->flush();+ }+}++void FileWriteQueue::runWriter()+{+ std::unique_lock<std::mutex> lock(m_queueLock);+ while (!m_quit)+ {+ m_wake.wait_for(lock, std::chrono::seconds(1));+ lock.unlock();+ flush();+ lock.lock();+ }+}diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex 98c31aa0c..cc37d116b 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -34,6 +34,7 @@#include "Common/INIException.h"#include "Common/STLTypedefs.h"#include "Common/DataChunk.h"+#include "Common/FileWriteQueue.h"#include "Common/MapObject.h"#include "Common/RandomMapGenerator.h"#include "Common/StackDump.h"@@ -18161,3 +18162,59 @@ TEST(debug_log_cut_keeps_the_head_and_the_last_whole_lines)const std::string ending = "line 0999\nwritten after the cut\n";CHECK( text.compare( text.size() - ending.size(), ending.size(), ending ) == 0 );}++// The replay's writer: appends and header patches through the queue leave the bytes the same calls+// made straight on the FILE did, the way RecorderClass makes them.+TEST(file_write_queue_writes_what_the_file_calls_wrote)+{+ const std::string queued = (std::filesystem::temp_directory_path() / "zh_fwq_queued.bin").string();+ const std::string direct = (std::filesystem::temp_directory_path() / "zh_fwq_direct.bin").string();++ FILE *d = fopen( direct.c_str(), "wb" );+ FileWriteQueue queue;+ FILE *q = fopen( queued.c_str(), "wb" );+ queue.start( q );+ const char head[] = "GENREP\0\0\0\0";+ fwrite( head, 1, 10, d );+ queue.write( head, 10 );+ const UnsignedInt patch = 0x11223344;+ long end = ftell( d ); // a patch before the first flush, as logGameStart's+ fseek( d, 6, SEEK_SET );+ fwrite( &patch, sizeof( patch ), 1, d );+ fseek( d, end, SEEK_SET );+ queue.writeAt( 6, &patch, sizeof( patch ) );+ for( UnsignedInt frame = 0; frame < 5000; ++frame )+ {+ fwrite( &frame, sizeof( frame ), 1, d );+ queue.write( &frame, sizeof( frame ) );+ if( frame == 2500 )+ queue.flush(); // a batch boundary in the middle+ }+ const unsigned char flag = 1;+ end = ftell( d );+ fseek( d, 9, SEEK_SET );+ fwrite( &flag, 1, 1, d );+ fseek( d, end, SEEK_SET );+ queue.writeAt( 9, &flag, 1 );+ fwrite( "tail", 1, 4, d );+ queue.write( "tail", 4 );+ queue.stop();+ queue.write( "dropped", 7 ); // a stopped queue takes nothing+ fclose( q );+ fclose( d );++ CHECK( std::filesystem::file_size( queued ) == std::filesystem::file_size( direct ) );+ FILE *a = fopen( queued.c_str(), "rb" );+ FILE *b = fopen( direct.c_str(), "rb" );+ Int ca, cb;+ do+ {+ ca = fgetc( a );+ cb = fgetc( b );+ } while( ca == cb && ca != EOF );+ fclose( a );+ fclose( b );+ std::filesystem::remove( queued );+ std::filesystem::remove( direct );+ CHECK( ca == cb );+}