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): rewind a replay in place from checkpoints
Olcay Seyganbdea54deff63
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 112625af2..6395750a2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -314,7 +314,7 @@ found and fixed — EA's own, not port damage.**## Every replay, not just the last one-- A replay is watched the way an observer watches a match. The empty command grid and portrait plate are gone from the bottom of the screen, and in their place is a timeline with the time reached and the whole length. Click anywhere on it to jump there: forward, the replay races ahead to that moment; back, it starts over and races to it. Beside it are pause and five speeds, from half to eight times the speed the game was played at.+- A replay is watched the way an observer watches a match. The empty command grid and portrait plate are gone from the bottom of the screen, and in their place is a timeline with the time reached and the whole length. Click anywhere on it to jump there: forward, the replay races ahead to that moment; back, the picture stops for about a second and the replay carries on from the moment you clicked. There is no loading screen and no start over from the beginning: the replay keeps its place every half minute as it plays, and a jump back picks up from the last of those. Beside it are pause and five speeds, from half to eight times the speed the game was played at.- Replays stopped crashing when an order took every unit out of the selection it was given to. The game throws an empty selection away at once, and with the recorded camera switched on the replay went on to read the one it had just thrown away.- Replay archiving saves each match under its own date-and-time name.- Long lists scroll the whole way, past two thousand rows.diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GameState.h b/GeneralsMD/Code/GameEngine/Include/Common/GameState.hindex 9271cd5e2..2c07a5f04 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GameState.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GameState.h@@ -39,6 +39,8 @@#include "Common/UnicodeString.h"#include "GameNetwork/NetworkDefs.h"+#include <functional>+// FORWARD REFERENCES /////////////////////////////////////////////////////////////////////////////class GameWindow;class WindowLayout;@@ -169,6 +171,11 @@ public:SnapshotType which = SNAPSHOT_SAVELOAD ); ///< save a gameSaveCode missionSave( void ); ///< do a in between mission saveSaveCode loadGame( AvailableGameInfo gameInfo ); ///< load a save file+ /// A replay's rewind checkpoint: the whole world into a file at this path, and back out of it.+ /// Nothing on screen says so, and the load calls afterReset once the engine is empty and before+ /// the world goes back in, which is where the recorder picks its file up again.+ void saveCheckpoint( AsciiString filepath );+ void loadCheckpoint( AsciiString filepath, const std::function< void( void ) > &afterReset );SaveGameInfo *getSaveGameInfo( void ) { return &m_gameInfo; }// snapshot interactiondiff --git a/GeneralsMD/Code/GameEngine/Include/Common/NameKeyGenerator.h b/GeneralsMD/Code/GameEngine/Include/Common/NameKeyGenerator.hindex 02e7b6d75..ee32a87b4 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/NameKeyGenerator.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/NameKeyGenerator.h@@ -38,6 +38,8 @@#include "Common/GameMemory.h"#include "Common/AsciiString.h"+#include <vector>+//-------------------------------------------------------------------------------------------------/**Note that NameKeyType isn't a "real" enum, but an enum type used to enforce the@@ -102,11 +104,9 @@ public:NameKeyType nameToKey(const char* name);NameKeyType nameToLowercaseKey(const char *name);- /**+ /**given a key, return the name. this is almost never needed,- except for a few rare cases like object serialization. also- note that it's not particularly fast; it does a dumb linear- search for the key.+ except for a few rare cases like object serialization.*/AsciiString keyToName(NameKeyType key);@@ -125,6 +125,9 @@ private:Bucket* m_sockets[SOCKET_COUNT]; ///< Catalog of all Buckets already generatedUnsignedInt m_nextID; ///< Next available ID+ /// Every bucket again, at its key less one. keyToName used to walk all 45007 sockets for each+ /// call, and a player's AI scripts ask it thousands of times: a fifth of a replay rewind.+ std::vector<Bucket*> m_bucketsByKey;}; // end class NameKeyGeneratordiff --git a/GeneralsMD/Code/GameEngine/Include/Common/RandomValue.h b/GeneralsMD/Code/GameEngine/Include/Common/RandomValue.hindex b18b4896e..17dbfbce6 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/RandomValue.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/RandomValue.h@@ -38,6 +38,15 @@ extern void InitRandom( UnsignedInt seed );extern UnsignedInt GetGameLogicRandomSeed( void ); ///< Get the seed (used for replays)extern UnsignedInt GetGameLogicRandomSeedCRC( void );///< Get the seed (used for CRCs)+/// the whole logic stream, for a replay's rewind checkpoint+struct GameLogicRandomState+{+ UnsignedInt seed[ 6 ];+ UnsignedInt baseSeed;+};+extern GameLogicRandomState GetGameLogicRandomState( void );+extern void SetGameLogicRandomState( const GameLogicRandomState &state );+//--------------------------------------------------------------------------------------------------------------#endif // _RANDOM_VALUE_H_diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Recorder.h b/GeneralsMD/Code/GameEngine/Include/Common/Recorder.hindex e95f8da5c..dc5dbabe5 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/Recorder.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/Recorder.h@@ -110,6 +110,18 @@ public:Bool testVersionPlayback(AsciiString filename); ///< Returns if the playback is a valid playback file for this version or not.AsciiString getCurrentReplayFilename( void ); ///< valid during playback onlyUnsignedInt getPlaybackFrameDuration( void ); ///< the replay's length in logic frames, from its header; 0 when not playing back++ /// Where playback stands between two logic frames: enough to pick the replay up again there after+ /// the engine has been reset under it, for a rewind to a checkpoint.+ struct PlaybackCursor+ {+ Int filePosition;+ UnsignedInt nextFrame;+ CRCInfo crcInfo;+ };+ PlaybackCursor getPlaybackCursor( void );+ Bool hasPlaybackLeft( void ) { return m_mode == RECORDERMODETYPE_PLAYBACK && m_file != NULL; } ///< FALSE once the last command is read+ void resumePlayback( AsciiString filename, const PlaybackCursor &cursor );Int getPlaybackFramesPerSecond( void ); ///< the logic rate the game was played at, 0 when it was not recordedvoid stopPlayback(); ///< Stops playback. Its fine to call this even if not playing back a file.#if defined _DEBUG || defined _INTERNAL@@ -175,6 +187,7 @@ protected:AsciiString readAsciiString(); ///< Read the next string from m_file using ascii characters.UnicodeString readUnicodeString(); ///< Read the next string from m_file using unicode characters.+ Bool openPlayback(AsciiString filename, Int &difficulty, Int &rankPoints, Int &maxFPS); ///< Open a replay and read up to its first command.void readNextFrame(); ///< Read the next frame number to execute a command on.void appendNextCommand(); ///< Read the next GameMessage and append it to TheCommandList.void writeArgument(GameMessageArgumentDataType type, const GameMessageArgumentType arg);diff --git a/GeneralsMD/Code/GameEngine/Include/Common/XferSave.h b/GeneralsMD/Code/GameEngine/Include/Common/XferSave.hindex 58c3a315f..6c22c01c2 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/XferSave.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/XferSave.h@@ -35,6 +35,8 @@// USER INCLUDES //////////////////////////////////////////////////////////////////////////////////#include "Common/Xfer.h"+#include <vector>+// FORWARD REFERENCES /////////////////////////////////////////////////////////////////////////////class XferBlockData;class Snapshot;@@ -71,6 +73,10 @@ protected:FILE * m_fileFP; ///< pointer to fileXferBlockData *m_blockStack; ///< stack of block data+ /// The whole file, written out in one go on close. Written straight to the file, every endBlock+ /// sought back to fill its size in and forward again, and each seek emptied the CRT's buffer: a+ /// replay checkpoint took 30 to 60ms that way and takes 6 to 13 from memory.+ std::vector< char > m_data;};diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.hindex ab33dbc08..0a665c954 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h@@ -181,6 +181,7 @@ public://void setGameLoading( Bool loading ) { m_loadingScene = loading; }void setLoadingMap( Bool loading ) { m_loadingMap = loading; }void setLoadingSave( Bool loading ) { m_loadingSave = loading; }+ void setLoadingWithoutScreen( Bool without ) { m_loadingWithoutScreen = without; } ///< a replay's rewind: the picture holds insteadvoid setClearingGameData( Bool clearing ) { m_clearingGameData = clearing; }void setGameMode( Int mode );@@ -346,6 +347,7 @@ private://Bool m_loadingScene;Bool m_loadingMap;Bool m_loadingSave;+ Bool m_loadingWithoutScreen;Bool m_clearingGameData;Bool m_isInUpdate;diff --git a/GeneralsMD/Code/GameEngine/Source/Common/NameKeyGenerator.cpp b/GeneralsMD/Code/GameEngine/Source/Common/NameKeyGenerator.cppindex 9488b5bf0..b1c3bed4f 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/NameKeyGenerator.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/NameKeyGenerator.cpp@@ -85,6 +85,7 @@ void NameKeyGenerator::freeSockets()}m_sockets[i] = NULL;}+ m_bucketsByKey.clear();} // end freeSockets@@ -111,15 +112,11 @@ inline UnsignedInt calcHashForLowercaseString(const char* p)//-------------------------------------------------------------------------------------------------AsciiString NameKeyGenerator::keyToName(NameKeyType key){- for (Int i = 0; i < SOCKET_COUNT; ++i)- {- for (Bucket *b = m_sockets[i]; b; b = b->m_nextInSocket)- {- if (key == b->m_key)- return b->m_nameString;- }- }- return AsciiString::TheEmptyString;+ // NAMEKEY_INVALID wraps to the largest index and misses with every other unknown key+ const UnsignedInt index = (UnsignedInt)key - 1;+ if (index >= m_bucketsByKey.size())+ return AsciiString::TheEmptyString;+ return m_bucketsByKey[index]->m_nameString;}//-------------------------------------------------------------------------------------------------@@ -142,6 +139,7 @@ NameKeyType NameKeyGenerator::nameToKey(const char* nameString)b->m_nameString = nameString;b->m_nextInSocket = m_sockets[hash];m_sockets[hash] = b;+ m_bucketsByKey.push_back(b);NameKeyType result = b->m_key;@@ -190,6 +188,7 @@ NameKeyType NameKeyGenerator::nameToLowercaseKey(const char* nameString)b->m_nameString = nameString;b->m_nextInSocket = m_sockets[hash];m_sockets[hash] = b;+ m_bucketsByKey.push_back(b);NameKeyType result = b->m_key;diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RandomValue.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RandomValue.cppindex 37cb88d20..167a7d418 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/RandomValue.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/RandomValue.cpp@@ -153,6 +153,23 @@ UnsignedInt GetGameLogicRandomSeedCRC( void )return c.get();}+/* The logic stream exactly as it stands, for a replay's rewind checkpoint. A save game never wrote+ it down - a loaded game only has to go on playing, not play the same game it would have - but a+ rewound replay has to draw the same numbers the recording drew. */+GameLogicRandomState GetGameLogicRandomState( void )+{+ GameLogicRandomState state;+ memcpy( state.seed, theGameLogicSeed, sizeof( state.seed ) );+ state.baseSeed = theGameLogicBaseSeed;+ return state;+}++void SetGameLogicRandomState( const GameLogicRandomState &state )+{+ memcpy( theGameLogicSeed, state.seed, sizeof( theGameLogicSeed ) );+ theGameLogicBaseSeed = state.baseSeed;+}+void InitRandom( void ){#ifdef DETERMINISTICdiff --git a/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cppindex 5db91a8a2..13220e7d2 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp@@ -1091,7 +1091,7 @@ Bool RecorderClass::testVersionPlayback(AsciiString filename)* Start playback of the file. Return true or false depending on if the file is* a valid replay file or not.*/-Bool RecorderClass::playbackFile(AsciiString filename)+Bool RecorderClass::playbackFile(AsciiString filename){if (!m_doingAnalysis){@@ -1101,6 +1101,69 @@ Bool RecorderClass::playbackFile(AsciiString filename)}}+ Int difficulty = 0;+ Int rankPoints = 0;+ Int maxFPS = 0;+ if (!openPlayback(filename, difficulty, rankPoints, maxFPS))+ return FALSE;++ if (replayIsMissingFirstCRC( m_originalGameMode ))+ {+ m_crcInfo->skipFirstCRC();+ }++ readNextFrame();++ // send a message to the logic for a new game+ if (!m_doingAnalysis)+ {+ GameMessage *msg = TheMessageStream->appendMessage( GameMessage::MSG_NEW_GAME );+ msg->appendIntegerArgument(GAME_REPLAY);+ msg->appendIntegerArgument(difficulty);+ msg->appendIntegerArgument(rankPoints);+ if( maxFPS != 0 )+ msg->appendIntegerArgument(maxFPS);+ InitRandom( m_gameInfo.getSeed() );+ }++ return TRUE;+}++RecorderClass::PlaybackCursor RecorderClass::getPlaybackCursor( void )+{+ PlaybackCursor cursor;+ cursor.filePosition = ftell(m_file);+ cursor.nextFrame = m_nextFrame;+ cursor.crcInfo = *m_crcInfo;+ return cursor;+}++/**+ * Pick a replay up again where getPlaybackCursor left it, once an engine reset has closed it. The+ * header is read the same way playbackFile reads it, for the players the new game is built from.+ */+void RecorderClass::resumePlayback(AsciiString filename, const PlaybackCursor &cursor)+{+ Int difficulty = 0;+ Int rankPoints = 0;+ Int maxFPS = 0;+ openPlayback(filename, difficulty, rankPoints, maxFPS);+ // the checkpoint names its own map, and no new game will come along to use this one up+ TheWritableGlobalData->m_pendingFile.clear();+ // the load starts a game, and a replay's random sides and start positions are drawn off this+ // seed: drawn off any other, the sides come out different and the checkpoint's teams do not fit+ InitRandom( m_gameInfo.getSeed() );+ fseek(m_file, cursor.filePosition, SEEK_SET);+ m_nextFrame = cursor.nextFrame;+ *m_crcInfo = cursor.crcInfo;+}++/**+ * Open a replay and read everything in front of its first command: the header, the difficulty, the+ * original game mode, the rank points and the frame rate the game was played at.+ */+Bool RecorderClass::openPlayback(AsciiString filename, Int &difficulty, Int &rankPoints, Int &maxFPS)+{m_mode = RECORDERMODETYPE_PLAYBACK;ReplayHeader header;@@ -1172,39 +1235,17 @@ Bool RecorderClass::playbackFile(AsciiString filename)REPLAY_CRC_INTERVAL = m_gameInfo.getCRCInterval();DEBUG_LOG(("Player index is %d, replay CRC interval is %d\n", m_crcInfo->getLocalPlayer(), REPLAY_CRC_INTERVAL));- Int difficulty = 0;fread(&difficulty, sizeof(difficulty), 1, m_file);fread(&m_originalGameMode, sizeof(m_originalGameMode), 1, m_file);- Int rankPoints = 0;fread(&rankPoints, sizeof(rankPoints), 1, m_file);-- Int maxFPS = 0;+fread(&maxFPS, sizeof(maxFPS), 1, m_file);m_playbackFramesPerSecond = maxFPS;DEBUG_LOG(("RecorderClass::playbackFile() - original game was mode %d\n", m_originalGameMode));- if (replayIsMissingFirstCRC( m_originalGameMode ))- {- m_crcInfo->skipFirstCRC();- }-- readNextFrame();-- // send a message to the logic for a new game- if (!m_doingAnalysis)- {- GameMessage *msg = TheMessageStream->appendMessage( GameMessage::MSG_NEW_GAME );- msg->appendIntegerArgument(GAME_REPLAY);- msg->appendIntegerArgument(difficulty);- msg->appendIntegerArgument(rankPoints);- if( maxFPS != 0 )- msg->appendIntegerArgument(maxFPS);- InitRandom( m_gameInfo.getSeed() );- }-m_currentReplayFilename = filename;return TRUE;}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cppindex 248619c0e..48b0272b2 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp@@ -651,6 +651,48 @@ SaveCode GameState::missionSave( void )} // end missionSave+// ------------------------------------------------------------------------------------------------+/** A replay's rewind checkpoint. saveGame without the save list: any path, no description, and+ * nothing told to the player, since one is taken every half minute of the replay. */+// ------------------------------------------------------------------------------------------------+void GameState::saveCheckpoint( AsciiString filepath )+{+ getSaveGameInfo()->saveFileType = SAVE_FILE_TYPE_NORMAL;+ getSaveGameInfo()->missionMapName.clear();++ XferSave xferSave;+ xferSave.open( filepath );+ xferSaveData( &xferSave, SNAPSHOT_SAVELOAD );+ xferSave.close();+}++// ------------------------------------------------------------------------------------------------+/** loadGame for a checkpoint, with the recorder's turn between the reset and the load: the reset+ * closes the replay, and the load's new game reads the players out of it. */+// ------------------------------------------------------------------------------------------------+void GameState::loadCheckpoint( AsciiString filepath, const std::function< void( void ) > &afterReset )+{+ TheGameStateMap->clearScratchPadMaps();++ XferLoad xferLoad;+ xferLoad.open( filepath );++ TheGameEngine->reset();+ afterReset();++ TheGhostObjectManager->saveLockGhostObjects( TRUE );+ TheGameLogic->setLoadingWithoutScreen( TRUE );+ {+ LatchRestore<Bool> inLoadGame( m_isInLoadGame, TRUE );+ xferSaveData( &xferLoad, SNAPSHOT_SAVELOAD );+ }+ TheGameLogic->setLoadingWithoutScreen( FALSE );+ xferLoad.close();+ TheGhostObjectManager->saveLockGhostObjects( FALSE );++ gameStatePostProcessLoad();+}+// ------------------------------------------------------------------------------------------------/** Load the save game pointed to by filename */// ------------------------------------------------------------------------------------------------@@ -1456,6 +1498,9 @@ void GameState::xferSaveData( Xfer *xfer, SnapshotType which )} // end if+ // DEBUG_CRASH below is compiled out of a release build, so this is the only word of which+ // block a load died in+ DEBUG_LOG(("Loading block '%s'\n", token.str()));try{diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/XferSave.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/XferSave.cppindex 4cd232389..44b67c5e8 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/XferSave.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/XferSave.cpp@@ -146,9 +146,17 @@ void XferSave::close( void )} // end if- // close the file+ // write the file and close it+ const size_t size = m_data.size();+ const Bool written = size == 0 || fwrite( &m_data[ 0 ], size, 1, m_fileFP ) == 1;fclose( m_fileFP );m_fileFP = NULL;+ m_data.clear();+ if( !written )+ {+ DEBUG_LOG(( "XferSave - Error writing %u bytes to file '%s'\n", (UnsignedInt)size, m_identifier.str() ));+ throw XFER_WRITE_ERROR;+ }// erase the filenamem_identifier.clear();@@ -170,18 +178,11 @@ Int XferSave::beginBlock( void )m_identifier.str()) );// get the current file position so we can back up here for the next end block call- XferFilePos filePos = ftell( m_fileFP );+ XferFilePos filePos = (XferFilePos)m_data.size();// write a placeholderXferBlockSize blockSize = 0;- if( fwrite( &blockSize, sizeof( XferBlockSize ), 1, m_fileFP ) != 1 )- {-- DEBUG_CRASH(( "XferSave::beginBlock - Error writing block size in '%s'\n",- m_identifier.str() ));- return XFER_WRITE_ERROR;-- } // end if+ xferImplementation( &blockSize, sizeof( XferBlockSize ) );// save this block position on the top of the "stack"XferBlockData *top = newInstance(XferBlockData);@@ -224,27 +225,16 @@ void XferSave::endBlock( void )} // end if// save our current file position- XferFilePos currentFilePos = ftell( m_fileFP );+ XferFilePos currentFilePos = (XferFilePos)m_data.size();// pop the block descriptor off the top of the block stackXferBlockData *top = m_blockStack;m_blockStack = m_blockStack->next;- // rewind the file to the block position- fseek( m_fileFP, top->filePos, SEEK_SET );-// write the size in bytes between the block position and what is our current file position+ // over the placeholderXferBlockSize blockSize = currentFilePos - top->filePos - sizeof( XferBlockSize );- if( fwrite( &blockSize, sizeof( XferBlockSize ), 1, m_fileFP ) != 1 )- {-- DEBUG_CRASH(( "Error writing block size to file '%s'\n", m_identifier.str() ));- throw XFER_WRITE_ERROR;-- } // end if-- // place the file pointer back to the current position- fseek( m_fileFP, currentFilePos, SEEK_SET );+ memcpy( &m_data[ top->filePos ], &blockSize, sizeof( XferBlockSize ) );// delete the block data as it's all used up nowtop->deleteInstance();@@ -262,8 +252,8 @@ void XferSave::skip( Int dataSize )m_identifier.str()) );- // skip forward dataSize bytes- fseek( m_fileFP, dataSize, SEEK_CUR );+ // skip forward dataSize bytes, which a file sought past its end fills with zeros+ m_data.resize( m_data.size() + dataSize, 0 );} // end skip@@ -346,13 +336,8 @@ void XferSave::xferImplementation( void *data, Int dataSize )DEBUG_ASSERTCRASH( m_fileFP != NULL, ("XferSave - file pointer for '%s' is NULL\n",m_identifier.str()) );- // write data to file- if( fwrite( data, dataSize, 1, m_fileFP ) != 1 )- {+ // the file is written out on close+ const char *bytes = (const char *)data;+ m_data.insert( m_data.end(), bytes, bytes + dataSize );- DEBUG_CRASH(( "XferSave - Error writing to file '%s'\n", m_identifier.str() ));- throw XFER_WRITE_ERROR;-- } // end if-} // end xferImplementationdiff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cppindex 95f2baa88..08501a072 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp@@ -35,6 +35,8 @@#include "Common/DrawnPath.h"#include "Common/GameAudio.h"#include "Common/GameEngine.h"+#include "Common/GameState.h"+#include "Common/RandomValue.h"#include "Common/GameType.h"#include "Common/MessageStream.h"#include "Common/PerfTimer.h"@@ -2207,12 +2209,14 @@ static void fillSpectatorCameraValues( std::vector< HtmlValues > &follows, HtmlV// The replay strip, on the spectator's page where a player's command grid stands: the timeline and// the playback speed. data-click="replay:seek" on #track jumps to the frame under the pointer,// "replay:pause" pauses and resumes, and "replay:speed:N" plays at N percent of the logic rate the-// game was played at. A seek forward fast-forwards, one-// picture in thirty drawn, until the frame is reached; a seek back has nothing to rewind to and-// starts the replay over, then runs forward the same way.+// game was played at. A seek forward fast-forwards, one picture in thirty drawn, until the frame+// is reached. A seek back loads the last checkpoint in front of the frame and runs forward from+// there: the simulation keeps no history to step back through, so the replay saves the whole world+// every half minute of it as it plays. The load puts no loading screen up; the picture holds.//-------------------------------------------------------------------------------------------------static const std::string REPLAY_ACTION = "replay:";static const std::string REPLAY_SEEK = REPLAY_ACTION + "seek";+static const std::string REPLAY_SEEK_TO = REPLAY_SEEK + ":";static const std::string REPLAY_PAUSE = REPLAY_ACTION + "pause";static const std::string REPLAY_SPEED = REPLAY_ACTION + "speed:";static const char *const REPLAY_TRACK = "#track";@@ -2254,28 +2258,170 @@ static void fillReplayValues( HtmlValues &values )values[ REPLAY_SPEED + std::to_string( REPLAY_SPEEDS[ each ] ) ] = speed == REPLAY_SPEEDS[ each ] ? "on" : "";}+/** A rewind checkpoint: the world saved between two logic frames, where playback stood in the+ * replay, and the CRCs the last logic frame posted that the next one has yet to compare. Those+ * are messages on their way, and the load's reset empties the stream they are in. */+struct ReplayCheckpoint+{+ AsciiString path;+ RecorderClass::PlaybackCursor cursor;+ GameLogicRandomState random; ///< a save game does not carry the logic's random stream+ std::vector< std::pair< Int, Bool > > postedCRCs;+};++static const UnsignedInt REPLAY_CHECKPOINT_FRAMES = LOGICFRAMES_PER_SECOND * 30;+static const char *const REPLAY_CHECKPOINT_FOLDER = "ReplayRewind";++/** The checkpoints of the replay TheReplayCheckpointsOf names, by frame. Not members, for the same+ * reason as the seek frame: loading one resets the interface. */+static std::map< UnsignedInt, ReplayCheckpoint > TheReplayCheckpoints;+static AsciiString TheReplayCheckpointsOf;++/** A seek back is carried out on the next client pass rather than in the click: the load resets the+ * message stream, and the click is a message the stream is in the middle of handing round. */+static Bool TheReplayRewindWaiting = FALSE;+static void seekReplay( UnsignedInt target ){TheGameLogic->setGamePaused( FALSE );- if( target <= TheGameLogic->getFrame() )+ // the first checkpoint is taken on the first frame, so only frame 0 has none behind it+ TheReplayRewindWaiting = target <= TheGameLogic->getFrame() && !TheReplayCheckpoints.empty();+ TheReplaySeekFrame = target;+}++/** A folder of this process's own: two copies of the game watching replays at once each keep their+ * checkpoints apart, and a copy that died leaves nothing another will take for its own. */+static AsciiString replayCheckpointFolder( void )+{+ AsciiString leaf;+ leaf.format( "%s\\%u", REPLAY_CHECKPOINT_FOLDER, (UnsignedInt)GetCurrentProcessId() );+ return TheGameState->getFilePathInSaveDirectory( leaf );+}++/** Every checkpoint file in the folder, not only the ones in the map, so nothing outlives the replay. */+static void forgetReplayCheckpoints( void )+{+ const AsciiString folder = replayCheckpointFolder();+ AsciiString pattern;+ pattern.format( "%s\\*.sav", folder.str() );+ WIN32_FIND_DATAA found;+ HANDLE search = FindFirstFileA( pattern.str(), &found );+ if( search != INVALID_HANDLE_VALUE ){- // the way the quit menu restarts one: no score screen between the two- const AsciiString replayFile = TheRecorder->getCurrentReplayFilename();- TheGameLogic->clearGameData( FALSE );- TheGameEngine->setQuitting( FALSE );- TheRecorder->playbackFile( replayFile );+ do+ {+ AsciiString path;+ path.format( "%s\\%s", folder.str(), found.cFileName );+ DeleteFileA( path.str() );+ } while( FindNextFileA( search, &found ) );+ FindClose( search );}- TheReplaySeekFrame = target;+ TheReplayCheckpoints.clear();+}++static void collectPostedCRCs( GameMessageList *list, std::vector< std::pair< Int, Bool > > &crcs )+{+ for( GameMessage *message = list->getFirstMessage(); message; message = message->next() )+ if( message->getType() == GameMessage::MSG_LOGIC_CRC )+ crcs.push_back( std::make_pair( message->getArgument( 0 )->integer, message->getArgument( 1 )->boolean ) );}-/** Every client pass, so a seek stops on its frame and not on the next picture drawn. The new game- * a seek back starts turns fast-forward off while it loads; this turns it on again. */+static void takeReplayCheckpoint( UnsignedInt frame )+{+ const DWORD startMs = timeGetTime();+ CreateDirectoryA( TheGameState->getSaveDirectory().str(), NULL );+ CreateDirectoryA( TheGameState->getFilePathInSaveDirectory( REPLAY_CHECKPOINT_FOLDER ).str(), NULL );+ const AsciiString folder = replayCheckpointFolder();+ CreateDirectoryA( folder.str(), NULL );++ ReplayCheckpoint &checkpoint = TheReplayCheckpoints[ frame ];+ checkpoint.path.format( "%s\\%u.sav", folder.str(), frame );+ checkpoint.cursor = TheRecorder->getPlaybackCursor();+ checkpoint.random = GetGameLogicRandomState();+ // the command list first: what it holds reaches the logic ahead of what the stream still holds+ collectPostedCRCs( TheCommandList, checkpoint.postedCRCs );+ collectPostedCRCs( TheMessageStream, checkpoint.postedCRCs );+ TheGameState->saveCheckpoint( checkpoint.path );+ DEBUG_LOG(( "REPLAY CHECKPOINT frame %u in %u ms\n", frame, (UnsignedInt)( timeGetTime() - startMs ) ));+}++/** Load the last checkpoint at or before the frame, or the first one if the frame is before it. The+ * camera, the speed and the observer's view stay as they were: the checkpoint carries the camera it+ * was taken with, which is not where the person watching is looking now. */+static void rewindReplay( UnsignedInt target )+{+ std::map< UnsignedInt, ReplayCheckpoint >::const_iterator at = TheReplayCheckpoints.upper_bound( target );+ if( at != TheReplayCheckpoints.begin() )+ --at;+ const ReplayCheckpoint &checkpoint = at->second;++ const AsciiString replayFile = TheRecorder->getCurrentReplayFilename();+ Coord3D lookingAt;+ TheTacticalView->getPosition( &lookingAt );+ const Real angle = TheTacticalView->getAngle();+ const Real pitch = TheTacticalView->getPitch();+ const Real zoom = TheTacticalView->getZoom();+ const Int framesPerSecond = TheGameEngine->getFramesPerSecondLimit();+ const DWORD startMs = timeGetTime();++ TheGameState->loadCheckpoint( checkpoint.path,+ [ & ]() { TheRecorder->resumePlayback( replayFile, checkpoint.cursor ); } );+ SetGameLogicRandomState( checkpoint.random );++ for( size_t each = 0; each < checkpoint.postedCRCs.size(); each++ )+ {+ GameMessage *crc = TheMessageStream->appendMessage( GameMessage::MSG_LOGIC_CRC );+ crc->appendIntegerArgument( checkpoint.postedCRCs[ each ].first );+ crc->appendBooleanArgument( checkpoint.postedCRCs[ each ].second );+ }++ TheTacticalView->lookAt( &lookingAt );+ TheTacticalView->setAngle( angle );+ TheTacticalView->setPitch( pitch );+ TheTacticalView->setZoom( zoom );+ TheGameEngine->setFramesPerSecondLimit( framesPerSecond );+ DEBUG_LOG(( "REPLAY REWIND to frame %u from the checkpoint at %u, loaded in %u ms\n",+ target, at->first, (UnsignedInt)( timeGetTime() - startMs ) ));+}++/** Every client pass, between two logic frames: the checkpoints are taken here, a seek back is carried+ * out here, and a seek stops on its frame rather than on the next picture drawn. */static void updateReplaySeek( void ){- if( TheReplaySeekFrame == 0 || !TheGameLogic->isInGame() || TheGameLogic->isLoadingMap() )+ if( !TheGameLogic->isInGame() || TheGameLogic->isLoadingMap() )return;+ if( !TheGameLogic->isInReplayGame() )+ {+ TheReplaySeekFrame = 0;+ TheReplayRewindWaiting = FALSE;+ if( TheReplayCheckpointsOf.isNotEmpty() )+ {+ forgetReplayCheckpoints();+ TheReplayCheckpointsOf.clear();+ }+ return;+ }++ if( TheReplayCheckpointsOf != TheRecorder->getCurrentReplayFilename() )+ {+ forgetReplayCheckpoints();+ TheReplayCheckpointsOf = TheRecorder->getCurrentReplayFilename();+ }- const Bool seeking = TheGameLogic->isInReplayGame() && TheGameLogic->getFrame() < TheReplaySeekFrame;+ if( TheReplayRewindWaiting )+ {+ TheReplayRewindWaiting = FALSE;+ rewindReplay( TheReplaySeekFrame );+ }++ const UnsignedInt frame = TheGameLogic->getFrame();+ if( TheRecorder->hasPlaybackLeft() && frame > 0+ && ( TheReplayCheckpoints.empty() || frame >= TheReplayCheckpoints.rbegin()->first + REPLAY_CHECKPOINT_FRAMES ) )+ takeReplayCheckpoint( frame );++ if( TheReplaySeekFrame == 0 )+ return;+ const Bool seeking = frame < TheReplaySeekFrame;TheWritableGlobalData->m_TiVOFastMode = seeking;if( !seeking )TheReplaySeekFrame = 0;@@ -2480,6 +2626,9 @@ void InGameUI::runSpectatorAction( const std::string &action )// the pause key's own message, so the key and the button are one pathelse if( action == REPLAY_PAUSE && TheGameLogic->isInReplayGame() )TheMessageStream->appendMessage( GameMessage::MSG_META_TOGGLE_PAUSE );+ // replay:seek:N, a frame to jump to, for a script that has no pointer to put on the timeline+ else if( action.compare( 0, REPLAY_SEEK_TO.size(), REPLAY_SEEK_TO ) == 0 && TheGameLogic->isInReplayGame() )+ seekReplay( (UnsignedInt)atoi( action.substr( REPLAY_SEEK_TO.size() ).c_str() ) );else if( action.compare( 0, REPLAY_SPEED.size(), REPLAY_SPEED ) == 0 && TheGameLogic->isInReplayGame() )TheGameEngine->setFramesPerSecondLimit( atoi( action.substr( REPLAY_SPEED.size() ).c_str() ) * replayNormalFramesPerSecond() / PERCENT );}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cppindex 8ebd0c7df..0b3f4076f 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp@@ -251,6 +251,7 @@ GameLogic::GameLogic( void )m_loadingMap = FALSE;m_loadingSave = FALSE;+ m_loadingWithoutScreen = FALSE;m_clearingGameData = FALSE;}@@ -617,7 +618,10 @@ static void placeNetworkBuildingsForPlayer(Int slotNum, const GameSlot *pSlot, P// ------------------------------------------------------------------------------------------------LoadScreen *GameLogic::getLoadScreen( Bool loadingSaveGame ){- switch (m_gameMode)+ if( m_loadingWithoutScreen )+ return NULL;++ switch (m_gameMode){case GAME_SHELL:return NEW ShellGameLoadScreen;@@ -1073,7 +1077,7 @@ static void populateRandomStartPosition( GameInfo *game )// ------------------------------------------------------------------------------------------------void GameLogic::updateLoadProgress( Int progress ){-+if( m_loadScreen )m_loadScreen->update( progress );@@ -1583,7 +1587,7 @@ void GameLogic::startNewGame( Bool loadingSaveGame )// update the player list to match the new map.TheTeamFactory->reset();ThePlayerList->newGame();-+// update the loadscreenupdateLoadProgress(LOAD_PROGRESS_POST_PLAYER_LIST_RESET);@@ -2111,9 +2115,11 @@ void GameLogic::startNewGame( Bool loadingSaveGame )// a unit's models on whichever logic frame the first one of its kind appeared: 18ms of a 33ms// frame for the first Ranger out of a barracks, and the opening of a match is nothing but// first appearances. It is not a flag any more. The shell map is the one exception - it- // builds none of this and would only pay the loading second for nothing.+ // builds none of this and would only pay the loading second for nothing. Nor does a replay's+ // rewind, which reloads the map it was just drawing: the models are all still in memory, and+ // the walk over them held the picture for three quarters of a second.//- if( !isInShellGame() )+ if( !isInShellGame() && !m_loadingWithoutScreen ){if (TheGlobalData->m_preloadEverything){