Skip to content

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.

10.0 KB
Raw Blame
/*
**	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 2025-2026 by Olcay Seygan for Zero Hour Reforged; see the git history.
// Modified 2026 by İlyas Akın for the macOS/Linux port; see NOTICE.md and the git history.

////////////////////////////////////////////////////////////////////////////////
//																																						//
//  (c) 2001-2003 Electronic Arts Inc.																				//
//																																						//
////////////////////////////////////////////////////////////////////////////////


#pragma once

#include <list>
#include "Common/MessageStream.h"
#include "GameNetwork/GameInfo.h"
#include "Common/WallClock.h"

/**
  * The ReplayGameInfo class holds information about the replay game and
	* the contents of its slot list for reconstructing multiplayer games.
	*/
class ReplayGameInfo : public GameInfo
{
private:
	GameSlot m_ReplaySlot[MAX_SLOTS];

public:
	ReplayGameInfo()
	{
		for (Int i = 0; i< MAX_SLOTS; ++i)
			setSlotPointer(i, &m_ReplaySlot[i]);
	}
};

enum RecorderModeType {
	RECORDERMODETYPE_RECORD,
	RECORDERMODETYPE_PLAYBACK,
	RECORDERMODETYPE_NONE // this is a valid state to be in on the shell map, or in saved games
};

/**
  * The CRCs of a replay.  Playback recomputes the logic CRC on every interval frame and pushes
	* it here; every CRC that comes back out of the replay file is compared against the front of
	* the queue.  The two streams therefore have to line up entry for entry.
	*/
class CRCInfo
{
public:
	CRCInfo();
	void addCRC(UnsignedInt val);
	UnsignedInt readCRC(void);

	void setLocalPlayer(UnsignedInt index) { m_localPlayer = index; }
	UnsignedInt getLocalPlayer(void) { return m_localPlayer; }

	void setSawCRCMismatch(void) { m_sawCRCMismatch = TRUE; }
	Bool sawCRCMismatch(void) { return m_sawCRCMismatch; }

	/// the first recorded CRC may be frame 0's or frame 1's - see replayMayLackFirstCRC()
	void allowMissingFirstCRC(void) { m_alignment = ALIGN_PENDING; }

	/**
	 * The computed CRC to compare `recorded` with, taken off the queue.  Once only, when armed by
	 * allowMissingFirstCRC: if the queue's head is `recorded` the recording has its frame 0 CRC and
	 * nothing moves; if the next one is, the recording lacks it and the head is dropped; if neither is,
	 * the head is compared, and reported, as it is.
	 */
	UnsignedInt readCRCFor(UnsignedInt recorded);

	enum Alignment
	{
		ALIGN_NONE,							///< not a network replay: compared one for one from frame 0
		ALIGN_PENDING,					///< a network replay whose first comparison has not happened yet
		ALIGN_FROM_FRAME_0,			///< its CRCs are recorded from frame 0
		ALIGN_FRAME_0_MISSING,	///< legacy: its frame 0 CRC was never recorded, and one was dropped
		ALIGN_UNDECIDED					///< neither fitted: the first comparison was a real mismatch
	};
	Alignment getAlignment(void) const { return m_alignment; }

protected:

	Bool m_sawCRCMismatch;
	Alignment m_alignment;
	std::list<UnsignedInt> m_data;
	UnsignedInt m_localPlayer;
};

/**
  * TRUE if a replay recorded in this game mode may lack its frame 0 CRC.  A network game's CRCs travel
	* as commands, and a command is only sent once the network has left its pregame state, which it
	* does when the logic reaches frame 1.  Until d9eccdda (2026-09-22) that happened after frame 0's
	* CRC had been taken off the command list and deleted, so the CRC was never sent, executed or
	* recorded: every retail replay and every one recorded before then starts at frame 1.  Since then
	* Network::update notes the new frame first, so frame 0's CRC goes out and is recorded.  Playback
	* makes a frame 0 CRC either way, so for these modes CRCInfo decides at the first comparison which
	* kind of recording it has (allowMissingFirstCRC).  Games recorded off the network - solo and
	* skirmish - always have their frame 0 CRC and are compared one for one.
	*/
Bool replayMayLackFirstCRC( Int originalGameMode );

class RecorderClass : public SubsystemInterface {
public:
	RecorderClass();																	///< Constructor.
	virtual ~RecorderClass();													///< Destructor.

	void init();																			///< Initialize TheRecorder.
	void reset();																			///< Reset the state of TheRecorder.
	void update();																		///< General purpose update function.

	// Methods dealing with recording.
	void updateRecord();															///< The update function for recording.

	// Methods dealing with playback.
	void updatePlayback();														///< The update function for playing back a file.
	Bool playbackFile(AsciiString filename);					///< Starts playback of the specified file.
	Bool testVersionPlayback(AsciiString filename);   ///< Returns if the playback is a valid playback file for this version or not.
	AsciiString getCurrentReplayFilename( void );			///< valid during playback only
	UnsignedInt 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 recorded
	void stopPlayback();															///< Stops playback.  Its fine to call this even if not playing back a file.
#if defined _DEBUG || defined _INTERNAL
	Bool analyzeReplay( AsciiString filename );
	Bool isAnalysisInProgress( void );
#endif

public:
	void handleCRCMessage(UnsignedInt newCRC, Int playerIndex, Bool fromPlayback);
protected:
	CRCInfo *m_crcInfo;
public:

	// read in info relating to a replay, conditionally setting up m_file for playback
	struct ReplayHeader
	{
		AsciiString filename;
		Bool forPlayback;
		UnicodeString replayName;
		WallClockTime timeVal;
		UnicodeString versionString;
		UnicodeString versionTimeString;
		UnsignedInt versionNumber;
		UnsignedInt exeCRC;
		UnsignedInt iniCRC;
		time_t startTime;
		time_t endTime;
		UnsignedInt frameDuration;
		Bool quitEarly;
		Bool desyncGame;
		Bool playerDiscons[MAX_SLOTS];
		AsciiString gameOptions;
		Int localPlayerIndex;
	};
	Bool readReplayHeader( ReplayHeader& header );

	RecorderModeType getMode();												///< Returns the current operating mode.
	void initControls();															///< Show or Hide the Replay controls

	AsciiString getReplayDir();												///< Returns the directory that holds the replay files.
	static AsciiString getReplayArchiveDir();					///< Returns the directory that holds the archived replay files.
	AsciiString getReplayExtention();									///< Returns the file extention for replay files.
	AsciiString getLastReplayFileName();							///< Returns the filename used for the default replay.

	GameInfo *getGameInfo( void ) { return &m_gameInfo; }	///< Returns the slot list for playback game start

	Bool isMultiplayer( void );												///< is this a multiplayer game (record OR playback)?

	Int getGameMode( void ) { return m_originalGameMode; }

	void logPlayerDisconnect(UnicodeString player, Int slot);
	void logCRCMismatch( void );
	void cleanUpReplayFile( void );										///< after a crash, send replay/debug info to a central repository

	void stopRecording();															///< Stop recording and close m_file.
protected:
	void startRecording(GameDifficulty diff, Int originalGameMode, Int rankPoints, Int maxFPS);					///< Start recording to m_file.
	void writeToFile(GameMessage *msg);								///< Write this GameMessage to m_file.
	void archiveReplay(const AsciiString& fileName);	///< Copy the given replay to the archive directory under a timestamped name.

	void logGameStart(AsciiString options);
	void logGameEnd( void );

	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);
	void readArgument(GameMessageArgumentDataType type, GameMessage *msg);

	void cullBadCommands();														///< prevent the user from giving mouse commands that he shouldn't be able to do during playback.

	FILE *m_file;
	AsciiString m_fileName;
	Int m_currentFilePosition;
	RecorderModeType m_mode;
	AsciiString m_currentReplayFilename;							///< valid during playback only
	UnsignedInt m_playbackFrameDuration;							///< valid during playback only
	Int m_playbackFramesPerSecond;										///< valid during playback only

	ReplayGameInfo m_gameInfo;
	Bool m_wasDesync;

	Bool m_doingAnalysis;

	Int m_originalGameMode; // valid in replays

	UnsignedInt m_nextFrame;												///< The Frame that the next message is to be executed on.  This can be -1.
};

extern RecorderClass *TheRecorder;
RecorderClass *createRecorder();