Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Core/GameEngine/Include/GameNetwork/FileTransfer.h
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,7 @@ AsciiString GetReadmeFromMap( AsciiString path );

// The meat of file (map) transfers
Bool DoAnyMapTransfers(GameInfo *game);

// Resume-from-replay: the host pushes the resume source
// (a replay file) to every human guest over the same transfer path at game start.
Bool DoResumeReplayTransfer(GameInfo *game, AsciiString path);
10 changes: 10 additions & 0 deletions Core/GameEngine/Include/GameNetwork/GameInfo.h
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,13 @@ class GameInfo
void setCRCInterval( Int val ) { m_crcInterval = (val > 0 && val < 100) ? val : 100; }
Int getCRCInterval() const { return m_crcInterval; }

// Resume-from-replay arming. When non-zero, every client
// replays its copy of the resume source (Resume.rep, pushed from the host) in lockstep
// up to this frame on game start before live control resumes (see ResumeFromReplay).
void setResumeHandoffFrame( UnsignedInt f ) { m_resumeHandoffFrame = f; }
UnsignedInt getResumeHandoffFrame() const { return m_resumeHandoffFrame; }
Bool isResumeArmed() const { return m_resumeHandoffFrame != 0; }

Bool haveWeSurrendered() { return m_surrendered; }
void markAsSurrendered() { m_surrendered = TRUE; }

Expand Down Expand Up @@ -254,6 +261,9 @@ class GameInfo
Money m_startingCash;
UnsignedShort m_superweaponRestriction;
Bool m_oldFactionsOnly; // Only USA, China, GLA -- not USA Air Force General, GLA Toxic General, et al

// resume-from-replay arming (appended last so existing member offsets are untouched)
UnsignedInt m_resumeHandoffFrame;
};

extern GameInfo *TheGameInfo;
Expand Down
6 changes: 6 additions & 0 deletions Core/GameEngine/Include/GameNetwork/NetworkDefs.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ static Int MIN_RUNAHEAD = 6;
static constexpr const Int MIN_RUNAHEAD = 4;
#endif

// Resume-from-replay catchup pins the run-ahead and the
// logic frame rate that ConnectionManager::updateRunAhead negotiates, so every
// peer derives the same short packet send interval while fast-forwarding.
static constexpr const Int CATCHUP_RUNAHEAD = 32;
static constexpr const Int CATCHUP_FRAME_RATE = 1000;

// FRAME_DATA_LENGTH needs to be MAX_FRAMES_AHEAD+1 because a player on a different
// computer can send commands for a frame that is one beyond twice the max runahead.
static constexpr const Int FRAME_DATA_LENGTH = (MAX_FRAMES_AHEAD + 1) * 2;
Expand Down
9 changes: 9 additions & 0 deletions Core/GameEngine/Source/Common/FramePacer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include "GameLogic/GameLogic.h"
#include "GameLogic/ScriptEngine.h"

#include "Common/Recorder.h"
#include "GameNetwork/NetworkDefs.h"
#include "GameNetwork/NetworkInterface.h"

Expand Down Expand Up @@ -109,6 +110,14 @@ Bool FramePacer::isActualFramesPerSecondLimitEnabled() const
#endif
}

// Resume-from-replay catchup runs one logic frame per
// render frame and fast-forwards many times faster than realtime, so the render
// cap has to get out of the way until the lead-in.
if (TheRecorder != nullptr && TheRecorder->isResumeCatchupMode() && !TheRecorder->isResumeCatchupLeadIn())
{
allowFpsLimit = false;
}

allowFpsLimit &= TheGlobalData->m_useFpsLimit;
allowFpsLimit &= isFramesPerSecondLimitEnabled();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
#include "Common/Money.h"
#include "Common/Player.h"
#include "Common/PlayerList.h"
#include "Common/Recorder.h"
#include "Common/Science.h"
#include "Common/SpecialPower.h"
#include "Common/ThingTemplate.h"
Expand Down Expand Up @@ -120,6 +121,11 @@ CBCommandStatus ControlBar::processCommandTransitionUI( GameWindow *control, Gad
CBCommandStatus ControlBar::processCommandUI( GameWindow *control,
GadgetGameMessage gadgetMessage )
{
// Resume-from-replay catchup: control bar buttons and
// their hotkeys (which re-dispatch into this path) are inert until control is handed back
if( TheRecorder && TheRecorder->isResumeInputBlocked() )
return CBC_COMMAND_NOT_USED;

// get the command pointer from the control user data we put in the button
const CommandButton *commandButton = (const CommandButton *)GadgetButtonGetData(control);
if( !commandButton )
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2550,8 +2550,12 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage
GameMessage::Type t = msg->getType();
GameMessageDisposition disp = KEEP_MESSAGE;
// We want to always be able to get to the options menu even during no input times and a clear game data message should always go through
// Resume-from-replay catchup blocks every command the
// same way disabled input does (camera scrolling lives in LookAtTranslator and
// stays available); the options menu stays reachable so a stuck catchup can be left.
const Bool resumeBlocked = TheRecorder && TheRecorder->isResumeInputBlocked();
if (t != GameMessage::MSG_META_OPTIONS && t != GameMessage::MSG_CLEAR_GAME_DATA &&
!TheInGameUI->getInputEnabled() && !isSystemMessage(msg))
(!TheInGameUI->getInputEnabled() || resumeBlocked) && !isSystemMessage(msg))
{
return DESTROY_MESSAGE;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
#include "GameClient/Keyboard.h"
#include "GameClient/SelectionInfo.h"
#include "GameClient/SelectionXlat.h"
#include "Common/Recorder.h"
#include "GameClient/TerrainVisual.h"


Expand Down Expand Up @@ -350,7 +351,8 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessa
{
GameMessageDisposition disp = KEEP_MESSAGE;

if( !TheInGameUI->getInputEnabled() )
// Resume-from-replay catchup: no selecting until control is handed back
if( !TheInGameUI->getInputEnabled() || (TheRecorder && TheRecorder->isResumeInputBlocked()) )
{
//Keep the message so the other translators (WindowXlat) can handle.
if( m_dragSelecting )
Expand Down
54 changes: 45 additions & 9 deletions Core/GameEngine/Source/GameNetwork/ConnectionManager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ static Bool hasValidTransferFileExtension(const AsciiString& filePath)
"str",
"wak",
"tga",
"txt"
"txt",
"rep" // The resume-from-replay source (see ResumeFromReplay)
};

const char* fileExt = strrchr(filePath.str(), '.');
Expand Down Expand Up @@ -99,6 +100,7 @@ enum TransferFileType
TransferFileType_Txt,
TransferFileType_Tga,
TransferFileType_Wak,
TransferFileType_Rep,
TransferFileType_Count
};

Expand All @@ -116,6 +118,7 @@ static const TransferFileRule transferFileRules[TransferFileType_Count] =
{ ".txt", 1 * 1024 * 1024 },
{ ".tga", 2 * 1024 * 1024 },
{ ".wak", 128 * 1024 },
{ ".rep", 16 * 1024 * 1024 },
};

static TransferFileType getTransferFileType(const char* extension)
Expand Down Expand Up @@ -173,6 +176,18 @@ static Bool hasValidTransferFileContent(const AsciiString& filePath, const Unsig
break;
}

case TransferFileType_Rep:
{
// a replay starts with the GENREP tag (see RecorderClass::startRecording)
static const char replayTag[] = "GENREP";
if (dataSize < sizeof(replayTag) - 1 || memcmp(data, replayTag, sizeof(replayTag) - 1) != 0)
{
DEBUG_LOG(("Replay file '%s' does not start with GENREP.", filePath.str()));
return false;
}
break;
}

case TransferFileType_Tga:
{
if (dataSize < sizeof(TGAHeader) + sizeof(TGA2Footer))
Expand Down Expand Up @@ -1510,6 +1525,24 @@ void ConnectionManager::updateRunAhead(Int oldRunAhead, Int frameRate, Bool didS

newRunAhead = clamp<Int>(minRunAheadForClamp, newRunAhead, MAX_FRAMES_AHEAD / 2);

// During resume-from-replay catchup Network::update()
// drops the realtime frame gate, so the only thing bounding how fast we
// replay is lockstep: a frame advances once every peer's commands for it have
// arrived. Throughput is (frames in flight) / (packet send interval), and
// processRunAheadCommand derives that interval from runAhead and frameRate.
// The values negotiated above are tuned for realtime play and are hostile
// here (a low-latency LAN bottoms out at MIN_RUNAHEAD, barely 2x realtime),
// so pin a deep pipeline and a short send interval instead. The lead-in
// (last seconds before handoff) falls through to the normal negotiation so
// run-ahead and frame rate re-converge before control is handed back.
const Bool pinCatchupRates = TheRecorder
&& TheRecorder->isResumeCatchupMode()
&& !TheRecorder->isResumeCatchupLeadIn();
if (pinCatchupRates) {
newRunAhead = CATCHUP_RUNAHEAD;
minFps = CATCHUP_FRAME_RATE;
}

NetRunAheadCommandMsg* msg = newInstance(NetRunAheadCommandMsg);
msg->setPlayerID(m_localSlot);
if (DoesCommandRequireACommandID(msg->getNetCommandType())) {
Expand Down Expand Up @@ -1582,14 +1615,17 @@ void ConnectionManager::updateRunAhead(Int oldRunAhead, Int frameRate, Bool didS

// Let the player with the slowest FPS run a little faster than the other computers...
// just in case they are able to. Then we might be able to run the game faster which would be good.
Int newMinFps = (minFps * 11) / 10;
if (newMinFps == minFps) {
newMinFps = minFps + 1;
}


if (newMinFps > TheNetwork->getFrameRate()) {
newMinFps = TheNetwork->getFrameRate(); // Cap FPS to network frame rate.
// During catchup every peer must derive the SAME packet send interval, so the
// slowest-player nudge and the network frame-rate cap are skipped.
Int newMinFps = minFps;
if (!pinCatchupRates) {
newMinFps = (minFps * 11) / 10;
if (newMinFps == minFps) {
newMinFps = minFps + 1;
}
if (newMinFps > TheNetwork->getFrameRate()) {
newMinFps = TheNetwork->getFrameRate(); // Cap FPS to network frame rate.
}
}
msg2->setRunAhead(newRunAhead);
msg2->setFrameRate(newMinFps);
Expand Down
6 changes: 6 additions & 0 deletions Core/GameEngine/Source/GameNetwork/DisconnectManager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,12 @@ void DisconnectManager::update(ConnectionManager *conMgr) {
m_lastFrameTime = timeGetTime();
}

// The resume-from-replay freeze deliberately holds the
// logic frame for a countdown; that is not a stalled peer.
if (TheRecorder && TheRecorder->isResumeFreezeActive()) {
m_lastFrameTime = timeGetTime();
}

// The game logic stalls on the frame we are currently waiting for commands on,
// so we have to check for the current logic frame being one higher than
// the last one we had the commands ready for.
Expand Down
39 changes: 38 additions & 1 deletion Core/GameEngine/Source/GameNetwork/FileTransfer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,9 @@ static Bool doFileTransfer( AsciiString filename, MapTransferLoadScreen *ls, Int
fileTransferPercent = 100;
for (i=1; i<MAX_SLOTS; ++i)
{
if (TheGameInfo->getConstSlot(i)->isHuman() && !TheGameInfo->getConstSlot(i)->hasMap())
// Wait on the slots in the mask (the callers build it
// from the slots that lack the file), so the same loop serves the resume-from-replay transfer.
if (TheGameInfo->getConstSlot(i)->isHuman() && (mask & (1<<i)))
{
Int slotTransferPercent = TheNetwork->getFileTransferProgress(i, filename);
fileTransferPercent = min(fileTransferPercent, slotTransferPercent);
Expand Down Expand Up @@ -281,3 +283,38 @@ Bool DoAnyMapTransfers(GameInfo *game)
TheShell->showShell();
return ok;
}

//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------

// Push the resume-from-replay source from the host to every
// human guest. Every guest needs it (there is no "has file" state for replays), so the mask is
// every human slot but the host's; the file lands in the guest's replay directory under the same
// name (see GameState::portableMapPathToRealMapPath).
Bool DoResumeReplayTransfer(GameInfo *game, AsciiString path)
{
TheGameInfo = game;
path.toLower(); // the transfer bookkeeping compares against the normalized (lower-case) real path
Int mask = 0;
Int i=0;
for (i=1; i<MAX_SLOTS; ++i)
{
if (TheGameInfo->getConstSlot(i)->isHuman())
{
DEBUG_LOG(("Adding player %d to resume replay transfer mask", i));
mask |= (1<<i);
}
}
if (!mask)
return TRUE;

TheShell->hideShell();
MapTransferLoadScreen *ls = NEW MapTransferLoadScreen;
ls->init(TheGameInfo);
Bool ok = doFileTransfer(path, ls, mask);
delete ls;
ls = nullptr;
if (!ok)
TheShell->showShell();
return ok;
}
26 changes: 16 additions & 10 deletions Core/GameEngine/Source/GameNetwork/FrameMetrics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@

#include "GameNetwork/FrameMetrics.h"
#include "GameClient/Display.h"
#include "Common/Recorder.h"
#include "GameNetwork/networkutil.h"
#include "../NGMP_include.h"
#include "../NetworkMesh.h"
Expand Down Expand Up @@ -145,16 +146,21 @@ void FrameMetrics::doPerFrameMetrics(UnsignedInt frame) {
// Do the measurement of the fps.
time_t curTime = timeGetTime();
if ((curTime - m_lastFpsTimeThing) >= 1000) {
// if ((m_fpsListIndex % 16) == 0) {
// DEBUG_LOG(("FrameMetrics::doPerFrameMetrics - adding %f to fps history. average before: %f ", m_fpsList[m_fpsListIndex], m_averageFps));
// }
m_averageFps -= ((m_fpsList[m_fpsListIndex])) / TheGlobalData->m_networkFPSHistoryLength; // subtract out the old value from the average.
m_fpsList[m_fpsListIndex] = TheDisplay->getAverageFPS();
// m_fpsList[m_fpsListIndex] = TheGameClient->getFrame() - m_fpsStartingFrame;
m_averageFps += ((Real)(m_fpsList[m_fpsListIndex])) / TheGlobalData->m_networkFPSHistoryLength; // add the new value to the average.
// DEBUG_LOG(("average after: %f", m_averageFps));
++m_fpsListIndex;
m_fpsListIndex %= TheGlobalData->m_networkFPSHistoryLength;
// This history is the input to
// ConnectionManager::updateRunAhead, i.e. how this machine tells the rest of
// the game how fast it can run. During resume-from-replay catchup the renderer
// is deliberately throttled while logic fast-forwards, so display FPS measures
// the throttle, not the machine; sampling it would collapse the run-ahead
// negotiation. Hold the history steady through catchup and resume sampling
// for real on handoff.
const Bool inCatchup = (TheRecorder != nullptr) && TheRecorder->isResumeCatchupMode();
if (!inCatchup) {
m_averageFps -= ((m_fpsList[m_fpsListIndex])) / TheGlobalData->m_networkFPSHistoryLength; // subtract out the old value from the average.
m_fpsList[m_fpsListIndex] = TheDisplay->getAverageFPS();
m_averageFps += ((Real)(m_fpsList[m_fpsListIndex])) / TheGlobalData->m_networkFPSHistoryLength; // add the new value to the average.
++m_fpsListIndex;
m_fpsListIndex %= TheGlobalData->m_networkFPSHistoryLength;
}
m_lastFpsTimeThing = curTime;
}

Expand Down
18 changes: 18 additions & 0 deletions Core/GameEngine/Source/GameNetwork/GameInfo.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,7 @@ void GameInfo::reset()
m_mapSize = 0;
m_superweaponRestriction = 0;
m_startingCash = TheGlobalData->m_defaultStartingCash;
m_resumeHandoffFrame = 0;

for (Int i=0; i<MAX_SLOTS; ++i)
{
Expand Down Expand Up @@ -937,6 +938,16 @@ AsciiString GameInfoToAsciiString( const GameInfo *game )
game->getStartingCash().countMoney(), game->oldFactionsOnly() ? 'Y' : 'N' );
#endif

// Resume-from-replay handoff frame. Only emitted when
// armed so unarmed games still round-trip bit-identically through the serializer, and
// emitted before the slot list so the slot-name truncation below accounts for it.
if (game->isResumeArmed())
{
AsciiString resume;
resume.format("RH=%u;", game->getResumeHandoffFrame());
optionsString.concat(resume);
}

//add player info for each slot
optionsString.concat(slotListID);
optionsString.concat('=');
Expand Down Expand Up @@ -1028,6 +1039,7 @@ Bool ParseAsciiStringToGameInfo(GameInfo *game, AsciiString options)
Int useStats = TRUE;
Money startingCash = TheGlobalData->m_defaultStartingCash;
UnsignedShort restriction = 0; // Always the default
UnsignedInt resumeHandoffFrame = 0;

Bool sawMap = FALSE;
Bool sawMapCRC = FALSE;
Expand Down Expand Up @@ -1147,6 +1159,11 @@ Bool ParseAsciiStringToGameInfo(GameInfo *game, AsciiString options)
oldFactionsOnly = ( val.compareNoCase( "Y" ) == 0 );
sawOldFactions = TRUE;
}
else if (key.compare("RH") == 0)
{
// resume-from-replay handoff frame (see GameInfoToAsciiString)
resumeHandoffFrame = (UnsignedInt)strtoul(val.str(), nullptr, 10);
}
else if (key.getLength() == 1 && *key.str() == slotListID)
{
sawSlotlist = true;
Expand Down Expand Up @@ -1515,6 +1532,7 @@ Bool ParseAsciiStringToGameInfo(GameInfo *game, AsciiString options)
game->setSuperweaponRestriction(restriction);
game->setStartingCash(startingCash);
game->setOldFactionsOnly(oldFactionsOnly);
game->setResumeHandoffFrame(resumeHandoffFrame);

return true;
}
Expand Down
Loading
Loading