Skip to content

tweak(fps): Decouple logic time step from render update #1451

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
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
2 changes: 2 additions & 0 deletions Core/GameEngine/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ set(GAMEENGINE_SRC
# Include/Common/Errors.h
Include/Common/file.h
Include/Common/FileSystem.h
Include/Common/FrameRateLimit.h
# Include/Common/FunctionLexicon.h
Include/Common/GameAudio.h
# Include/Common/GameCommon.h
Expand Down Expand Up @@ -569,6 +570,7 @@ set(GAMEENGINE_SRC
# Source/Common/DamageFX.cpp
# Source/Common/Dict.cpp
# Source/Common/DiscreteCircle.cpp
Source/Common/FrameRateLimit.cpp
# Source/Common/GameEngine.cpp
# Source/Common/GameLOD.cpp
# Source/Common/GameMain.cpp
Expand Down
70 changes: 70 additions & 0 deletions Core/GameEngine/Include/Common/FrameRateLimit.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
** Command & Conquer Generals Zero Hour(tm)
** Copyright 2025 TheSuperHackers
**
** 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/>.
*/

#pragma once

class FrameRateLimit
{
public:
FrameRateLimit();

Real wait(UnsignedInt maxFps);

private:
LARGE_INTEGER m_freq;
LARGE_INTEGER m_start;
};


enum FpsValueChange
{
FpsValueChange_Increase,
FpsValueChange_Decrease,
};


class RenderFpsPreset
{
public:
enum CPP_11(: UnsignedInt)
{
UncappedFpsValue = 1000,
};

static UnsignedInt getNextFpsValue(UnsignedInt value);
static UnsignedInt getPrevFpsValue(UnsignedInt value);
static UnsignedInt changeFpsValue(UnsignedInt value, FpsValueChange change);

private:
static const UnsignedInt s_fpsValues[];
};


class LogicTimeScaleFpsPreset
{
public:
enum CPP_11(: UnsignedInt)
{
StepFpsValue = 5,
};

static UnsignedInt getNextFpsValue(UnsignedInt value);
static UnsignedInt getPrevFpsValue(UnsignedInt value);
static UnsignedInt changeFpsValue(UnsignedInt value, FpsValueChange change);
};

126 changes: 126 additions & 0 deletions Core/GameEngine/Source/Common/FrameRateLimit.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/*
** Command & Conquer Generals Zero Hour(tm)
** Copyright 2025 TheSuperHackers
**
** 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/>.
*/

#include "PreRTS.h"
#include "Common/FrameRateLimit.h"


FrameRateLimit::FrameRateLimit()
{
QueryPerformanceFrequency(&m_freq);
QueryPerformanceCounter(&m_start);
}

Real FrameRateLimit::wait(UnsignedInt maxFps)
{
LARGE_INTEGER tick;
QueryPerformanceCounter(&tick);
double elapsedSeconds = static_cast<double>(tick.QuadPart - m_start.QuadPart) / m_freq.QuadPart;
const double targetSeconds = 1.0 / maxFps;
const double sleepSeconds = targetSeconds - elapsedSeconds - 0.002; // leave ~2ms for spin wait

if (sleepSeconds > 0.0)
{
// Non busy wait with Munkee sleep
DWORD dwMilliseconds = static_cast<DWORD>(sleepSeconds * 1000);
Sleep(dwMilliseconds);
}

// Busy wait for remaining time
do
{
QueryPerformanceCounter(&tick);
elapsedSeconds = static_cast<double>(tick.QuadPart - m_start.QuadPart) / m_freq.QuadPart;
}
while (elapsedSeconds < targetSeconds);

m_start = tick;
return (Real)elapsedSeconds;
}


const UnsignedInt RenderFpsPreset::s_fpsValues[] = {
30, 50, 56, 60, 65, 70, 72, 75, 80, 85, 90, 100, 110, 120, 144, 240, 480, UncappedFpsValue };

static_assert(LOGICFRAMES_PER_SECOND <= 30, "Min FPS values need to be revisited!");

UnsignedInt RenderFpsPreset::getNextFpsValue(UnsignedInt value)
{
const Int first = 0;
const Int last = ARRAY_SIZE(s_fpsValues) - 1;
for (Int i = first; i < last; ++i)
{
if (value >= s_fpsValues[i] && value < s_fpsValues[i + 1])
{
return s_fpsValues[i + 1];
}
}
return s_fpsValues[last];
}

UnsignedInt RenderFpsPreset::getPrevFpsValue(UnsignedInt value)
{
const Int first = 0;
const Int last = ARRAY_SIZE(s_fpsValues) - 1;
for (Int i = last; i > first; --i)
{
if (value <= s_fpsValues[i] && value > s_fpsValues[i - 1])
{
return s_fpsValues[i - 1];
}
}
return s_fpsValues[first];
}

UnsignedInt RenderFpsPreset::changeFpsValue(UnsignedInt value, FpsValueChange change)
{
switch (change)
{
default:
case FpsValueChange_Increase: return getNextFpsValue(value);
case FpsValueChange_Decrease: return getPrevFpsValue(value);
}
}


UnsignedInt LogicTimeScaleFpsPreset::getNextFpsValue(UnsignedInt value)
{
return value + StepFpsValue;
}

UnsignedInt LogicTimeScaleFpsPreset::getPrevFpsValue(UnsignedInt value)
{
if (value - StepFpsValue < LOGICFRAMES_PER_SECOND)
{
return LOGICFRAMES_PER_SECOND;
}
else
{
return value - StepFpsValue;
}
}

UnsignedInt LogicTimeScaleFpsPreset::changeFpsValue(UnsignedInt value, FpsValueChange change)
{
switch (change)
{
default:
case FpsValueChange_Increase: return getNextFpsValue(value);
case FpsValueChange_Decrease: return getPrevFpsValue(value);
}
}
1 change: 1 addition & 0 deletions GeneralsMD/Code/GameEngine/Include/Common/GameCommon.h
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
// ----------------------------------------------------------------------------------------------
enum
{
BaseFps = 30, // The historic base frame rate for this game. This value must never change.
LOGICFRAMES_PER_SECOND = 30,
MSEC_PER_SECOND = 1000
};
Expand Down
26 changes: 21 additions & 5 deletions GeneralsMD/Code/GameEngine/Include/Common/GameEngine.h
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@
#include "Common/SubsystemInterface.h"
#include "Common/GameType.h"

#define DEFAULT_MAX_FPS 45

// forward declarations
class AudioManager;
class GameLogic;
Expand Down Expand Up @@ -72,8 +70,20 @@ class GameEngine : public SubsystemInterface

virtual void execute( void ); /**< The "main loop" of the game engine.
It will not return until the game exits. */
virtual void setFramesPerSecondLimit( Int fps ); ///< Set the maximum rate engine updates are allowed to occur
virtual Int getFramesPerSecondLimit( void ); ///< Get maxFPS. Not inline since it is called from another lib.

virtual void setFramesPerSecondLimit( Int fps ); ///< Set the max render and engine update fps.
virtual Int getFramesPerSecondLimit( void ); ///< Get the max render and engine update fps.
Real getUpdateTime(); ///< Get the last engine update delta time.
Real getUpdateFps(); ///< Get the last engine update fps.

virtual void setLogicTimeScaleFps( Int fps ); ///< Set the logic time scale fps and therefore scale the simulation time. Is capped by the max render fps and does not apply to network matches.
virtual Int getLogicTimeScaleFps(); ///< Get the raw logic time scale fps value.
virtual void enableLogicTimeScale( Bool enable ); ///< Enable the logic time scale setup. If disabled, the simulation time scale is bound to the render frame time or network update time.
virtual Bool isLogicTimeScaleEnabled(); ///< Check whether the logic time scale setup is enabled.
Int getActualLogicTimeScaleFps(); ///< Get the real logic time scale fps, depending on the max render fps, network state and enabled state.
Real getActualLogicTimeScaleRatio(); ///< Get the real logic time scale ratio, depending on the max render fps, network state and enabled state.
Real getActualLogicTimeScaleOverFpsRatio(); ///< Get the real logic time scale over render fps ratio, used to scale down steps in render updates to match logic updates.

virtual void setQuitting( Bool quitting ); ///< set quitting status
virtual Bool getQuitting(void); ///< is app getting ready to quit.

Expand All @@ -100,9 +110,15 @@ class GameEngine : public SubsystemInterface
virtual ParticleSystemManager* createParticleSystemManager( void ) = 0;
virtual AudioManager *createAudioManager( void ) = 0; ///< Factory for Audio Manager

Int m_maxFPS; ///< Maximum frames per second allowed
Int m_maxFPS; ///< Maximum frames per second for rendering
Int m_logicTimeScaleFPS; ///< Maximum frames per second for logic time scale
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be better to rename m_maxFPS to make it more relevant to the rendering FPS.

m_maxRenderFPS for example.

For the logic one, it would be better to have the naming match the rendering.

m_maxLogicFPS etc.

Copy link
Author

@xezon xezon Aug 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did not intent to rename m_maxFPS for this change to have a bit less diff.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

m_maxLogicFPS is not the correct terminology for this. Logic FPS is what we currently refer to as enum LOGICFRAMES_PER_SECOND=30.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

m_maxLogicFPS is not the correct terminology for this. Logic FPS is what we currently refer to as enum LOGICFRAMES_PER_SECOND=30.

It's the currently set max logic frame rate, LOGICFRAMES_PER_SECOND is the default maximum value. But since we can / need to be able to vary the current max logic frame rate, it makes sense to call it that for the variable.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

m_logicTimeScaleFPS is conceptually not equivalent to LOGICFRAMES_PER_SECOND or m_maxLogicFPS. It effectively is a ratio that scales the logic fps.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I expect it will be possible to change LOGICFRAMES_PER_SECOND at runtime to any value above 0.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

m_logicTickRate might be a better name for these instead of using logicTimeScale since time scale implies a period of time instead of a rate of action.

Copy link
Author

@xezon xezon Aug 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do not see that logic tick rate is a better name. Logic time scale is accurate, because time scale 2 means that the game runs twice as fast. If we can avoid changing the name, then that would be good, because it will take a while to rename everything.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But this is never set to a value that acts as a multiplier, it's set to a specific Tick rate / frames per second. That is then used to cap the update of the game logic.

Which is why the naming does not look correct to me on the surface compared to what you might have in mind.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The value Int m_logicTimeScaleFPS is a multiplier in disguise. It is synonymous to Real m_logicTimeScaleRatio, just with a different unit. As we can see in the GameEngine class interface, the time scale ratio can be inferred from the fps value.


Real m_updateTime; ///< Last engine update delta time
Real m_logicTimeAccumulator; ///< Frame time accumulated towards submitting a new logic frame

Bool m_quitting; ///< true when we need to quit the game
Bool m_isActive; ///< app has OS focus.
Bool m_enableLogicTimeScale;

};
inline void GameEngine::setQuitting( Bool quitting ) { m_quitting = quitting; }
Expand Down
4 changes: 4 additions & 0 deletions GeneralsMD/Code/GameEngine/Include/Common/MessageStream.h
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,10 @@ class GameMessage : public MemoryPoolObject
MSG_META_HELP, ///< bring up help screen
#endif

MSG_META_INCREASE_MAX_RENDER_FPS, ///< TheSuperHackers @feature Increase the max render fps
MSG_META_DECREASE_MAX_RENDER_FPS, ///< TheSuperHackers @feature Decrease the max render fps
MSG_META_INCREASE_LOGIC_TIME_SCALE, ///< TheSuperHackers @feature Increase the logic time scale
MSG_META_DECREASE_LOGIC_TIME_SCALE, ///< TheSuperHackers @feature Decrease the logic time scale
MSG_META_TOGGLE_LOWER_DETAILS, ///< toggles graphics options to crappy mode instantly
MSG_META_TOGGLE_CONTROL_BAR, ///< show/hide controlbar

Expand Down
2 changes: 2 additions & 0 deletions GeneralsMD/Code/GameEngine/Include/GameClient/Display.h
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ class Display : public SubsystemInterface

virtual void drawViews( void ); ///< Render all views of the world
virtual void updateViews ( void ); ///< Updates state of world views
virtual void stepViews(); ///< Update views for every fixed time step

virtual VideoBuffer* createVideoBuffer( void ) = 0; ///< Create a video buffer that can be used for this display

Expand All @@ -118,6 +119,7 @@ class Display : public SubsystemInterface
virtual Bool isClippingEnabled( void ) = 0;
virtual void enableClipping( Bool onoff ) = 0;

virtual void step() {}; ///< Do one fixed time step
virtual void draw( void ); ///< Redraw the entire display
virtual void setTimeOfDay( TimeOfDay tod ) = 0; ///< Set the time of day for this display
virtual void createLightPulse( const Coord3D *pos, const RGBColor *color, Real innerRadius,Real attenuationWidth,
Expand Down
2 changes: 2 additions & 0 deletions GeneralsMD/Code/GameEngine/Include/GameClient/GameClient.h
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ class GameClient : public SubsystemInterface,
virtual void setFrame( UnsignedInt frame ) { m_frame = frame; } ///< Set the GameClient's internal frame number
virtual void registerDrawable( Drawable *draw ); ///< Given a drawable, register it with the GameClient and give it a unique ID

void step(); ///< Do one fixed time step

void updateHeadless();

void addDrawableToLookupTable( Drawable *draw ); ///< add drawable ID to hash lookup table
Expand Down
Loading
Loading