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.

feat(gameengine): uncap rendering, pace game logic by wall clock

Olcay Seygan161d205d99ce
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
index bdec745d4..c34cc48ce 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
@@ -738,13 +738,35 @@ void GameEngine::reset( void )
/// -----------------------------------------------------------------------------------------------
DECLARE_PERF_TIMER(GameEngine_update)
+/** -----------------------------------------------------------------------------------------------
+ * Wall-clock pacing for the logic tick: update() may be called at any render rate, but a logic
+ * frame is only "due" every 1000/logicFps milliseconds. The elapsed time added per call is
+ * clamped to one logic frame, so a renderer slower than the logic rate runs one logic frame per
+ * render frame (the original slow-machine behavior) instead of a catch-up burst.
+ * Free function (not a member, not static) so test_gameengine can link straight to it.
+ */
+Bool GameEngine_isLogicFrameDue( Real& accumMs, Real elapsedMs, Int logicFps )
+{
+ if (logicFps <= 0)
+ return TRUE;
+ const Real msPerLogicFrame = 1000.0f / logicFps;
+ if (elapsedMs > msPerLogicFrame)
+ elapsedMs = msPerLogicFrame;
+ accumMs += elapsedMs;
+ if (accumMs < msPerLogicFrame)
+ return FALSE;
+ accumMs -= msPerLogicFrame;
+ return TRUE;
+}
+
/** -----------------------------------------------------------------------------------------------
* Update the game engine by updating the GameClient and GameLogic singletons.
- * @todo Allow the client to run as fast as possible, but limit the execution
- * of TheNetwork and TheGameLogic to a fixed framerate.
+ * The client runs as fast as possible; TheGameLogic is limited to a fixed wall-clock
+ * framerate (m_maxFPS, the game-speed setting), so game speed does not scale with the
+ * render framerate.
*/
void GameEngine::update( void )
-{
+{
USE_PERF_TIMER(GameEngine_update)
{
@@ -770,7 +792,34 @@ void GameEngine::update( void )
}
- if ((TheNetwork == NULL && !TheGameLogic->isGamePaused()) || (TheNetwork && TheNetwork->isFrameDataReady()))
+ // Fast-forward modes run a logic frame on every call; otherwise logic ticks at
+ // m_maxFPS Hz of wall clock, however fast the client/renderer above is running.
+#if defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE)
+ Bool fastMode = TheGlobalData->m_TiVOFastMode;
+#else
+ Bool fastMode = TheGlobalData->m_TiVOFastMode && TheGameLogic->isInReplayGame();
+#endif
+ fastMode = fastMode || TheTacticalView->getTimeMultiplier() > 1 || TheScriptEngine->isTimeFast();
+
+ static DWORD prevLogicTime = timeGetTime();
+ static Real logicAccumMs = 0.0f;
+ DWORD now = timeGetTime();
+ Real elapsedMs = (Real)(now - prevLogicTime);
+ prevLogicTime = now;
+
+ Bool logicFrameDue;
+ if (fastMode)
+ {
+ logicAccumMs = 0.0f;
+ logicFrameDue = TRUE;
+ }
+ else
+ {
+ logicFrameDue = GameEngine_isLogicFrameDue(logicAccumMs, elapsedMs, m_maxFPS);
+ }
+
+ if (logicFrameDue &&
+ ((TheNetwork == NULL && !TheGameLogic->isGamePaused()) || (TheNetwork && TheNetwork->isFrameDataReady())))
{
TheGameLogic->UPDATE();
}
@@ -788,8 +837,7 @@ extern HWND ApplicationHWnd;
*/
void GameEngine::execute( void )
{
-
- DWORD prevTime = timeGetTime();
+ DWORD prevLoopTime = timeGetTime();
#if defined(_DEBUG) || defined(_INTERNAL)
DWORD startTime = timeGetTime() / 1000;
#endif
@@ -859,39 +907,33 @@ void GameEngine::execute( void )
} // perf
{
-
- if (TheTacticalView->getTimeMultiplier()<=1 && !TheScriptEngine->isTimeFast())
+ // In a real game rendering runs uncapped - game speed stays constant because
+ // the logic tick is paced by wall clock inside update(). The menus/shell keep
+ // the original coupled cadence: their window animations step once per loop
+ // iteration and were tuned for m_maxFPS, and capping here also keeps the
+ // present queue short so the cursor stays responsive.
+ // Unconditional in menus - the window animations move a fixed step per loop
+ // iteration, so an uncapped menu makes them finish instantly after their
+ // wall-clock start delay ("wait, then pop") whatever m_useFpsLimit says.
+ Bool inMenus = !TheGameLogic->isInGame() || TheGameLogic->isInShellGame();
+ if (inMenus && m_maxFPS > 0)
{
+ DWORD limit = (DWORD)(1000.0f/m_maxFPS)-1;
+ DWORD now = timeGetTime();
+ while ((now - prevLoopTime) < limit)
+ {
+ ::Sleep(1);
+ now = timeGetTime();
+ }
+ }
+ prevLoopTime = timeGetTime();
- // I'm disabling this in internal because many people need alt-tab capability. If you happen to be
- // doing performance tuning, please just change this on your local system. -MDC
#if defined(_DEBUG) || defined(_INTERNAL)
+ // I'm disabling this in internal because many people need alt-tab capability. If you happen to be
+ // doing performance tuning, please just change this on your local system. -MDC
+ if (TheTacticalView->getTimeMultiplier()<=1 && !TheScriptEngine->isTimeFast())
::Sleep(1); // give everyone else a tiny time slice.
#endif
-
-
- #if defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE)
- if ( ! TheGlobalData->m_TiVOFastMode )
- #else //always allow this cheatkey if we're in a replaygame.
- if ( ! (TheGlobalData->m_TiVOFastMode && TheGameLogic->isInReplayGame()))
- #endif
- {
- // limit the framerate
- DWORD now = timeGetTime();
- DWORD limit = (1000.0f/m_maxFPS)-1;
- while (TheGlobalData->m_useFpsLimit && (now - prevTime) < limit)
- {
- ::Sleep(0);
- now = timeGetTime();
- }
- //Int slept = now - prevTime;
- //DEBUG_LOG(("delayed %d\n",slept));
-
- prevTime = now;
-
- }
-
- }
}
} // perfgather for execute_loop
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp
index 2583124f1..4193a3e6b 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp
@@ -184,7 +184,11 @@ static GameWindow *dropDownWindows[DROPDOWN_COUNT];
static Bool buttonPushed = FALSE;
static Bool isShuttingDown = FALSE;
static Bool startGame = FALSE;
-static Int initialGadgetDelay = 210;
+// Was 210 client frames (7s at the menu's 30Hz cadence) of staring at the shell map
+// before the menu UI fades in. Retail hid most of that behind the Bink intro movies,
+// which this port stubs out, so the wait read as "the menu never comes". One second
+// keeps the fade choreography without the dead air.
+static Int initialGadgetDelay = 30;
enum
{
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
index e44a8b085..eda4371ca 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
@@ -1758,6 +1758,15 @@ AGAIN:
//
//PredictiveLODOptimizerClass::Optimize_LODs( 5000 );
+ // Only a scripted frozen-time camera pan may hold us inside the render do-loop
+ // below. The "client outran logic" case (lastFrame == getFrame()) must NOT: with
+ // rendering decoupled from the logic tick that is the common case, and looping on
+ // it kept draw() spinning - message pump dead - until the shell map's camera
+ // movement of the moment finished.
+ Bool loopForCameraMovement = TheTacticalView->isTimeFrozen() && !TheTacticalView->isCameraMovementFinished()
+ && !TheScriptEngine->isTimeFrozenDebug() && !TheScriptEngine->isTimeFrozenScript()
+ && !TheGameLogic->isGamePaused();
+
Bool freezeTime = TheTacticalView->isTimeFrozen() && !TheTacticalView->isCameraMovementFinished();
freezeTime = freezeTime || TheScriptEngine->isTimeFrozenDebug() || TheScriptEngine->isTimeFrozenScript();
freezeTime = freezeTime || TheGameLogic->isGamePaused();
@@ -1841,6 +1850,7 @@ AGAIN:
// limit the framerate
while(TheGlobalData->m_useFpsLimit && (now - prevTime) < minTime-1)
{
+ ::Sleep(1); // was a pure spin; this loop can run for whole camera pans
now = timeGetTime();
}
prevTime = now;
@@ -1997,12 +2007,17 @@ AGAIN:
}
}
- if (TheScriptEngine->isTimeFrozenDebug() || TheScriptEngine->isTimeFrozenScript() || TheGameLogic->isGamePaused())
+ if (TheScriptEngine->isTimeFrozenDebug() || TheScriptEngine->isTimeFrozenScript() || TheGameLogic->isGamePaused())
{
freezeTime = false; // We're frozen for debug or for pause, and need to continue out of the loop.
}
- } while (freezeTime && !TheTacticalView->isCameraMovementFinished());
+ // A scripted pan holds us in here for seconds - keep the window responsive
+ // (same pattern as LoadScreen::update).
+ if (loopForCameraMovement)
+ TheGameEngine->serviceWindowsOS();
+
+ } while (loopForCameraMovement && !TheTacticalView->isCameraMovementFinished());
#ifdef EXTENDED_STATS
if (DX8Wrapper::stats.m_disableOverhead) {
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp
index 8bedecde6..0c89fa10b 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp
@@ -417,8 +417,16 @@ void W3DView::buildCameraTransform( Matrix3D *transform )
transform->Make_Identity();
transform->Look_At( sourcePos, targetPos, 0 );
- //WST 11/12/2002 New camera shaker system
- CameraShakerSystem.Timestep(1.0f/30.0f);
+ //WST 11/12/2002 New camera shaker system
+ // This runs once per render frame (and again on every scrollBy), not once per 30Hz
+ // tick, so step the shaker by real elapsed time to keep shakes framerate-independent.
+ static DWORD prevShakeTime = timeGetTime();
+ DWORD nowShakeTime = timeGetTime();
+ Real shakeDt = (nowShakeTime - prevShakeTime) * 0.001f;
+ prevShakeTime = nowShakeTime;
+ if (shakeDt > 1.0f/30.0f)
+ shakeDt = 1.0f/30.0f;
+ CameraShakerSystem.Timestep(shakeDt);
CameraShakerSystem.Update_Camera_Shaker(sourcePos, &m_shakerAngles);
transform->Rotate_X(m_shakerAngles.X);
transform->Rotate_Y(m_shakerAngles.Y);
@@ -1105,6 +1113,20 @@ void W3DView::update(void)
// Int elapsedTimeMs = TheW3DFrameLengthInMsec; // Assume a constant time flow. It just works out better. jba.
+ // The camera smoothing and scripted one-frame movements below were tuned for one
+ // call per 30Hz engine tick; update() now runs once per render frame. Step them on
+ // the original wall-clock cadence so camera motion speed is framerate-independent,
+ // while the camera transform itself still updates every render frame.
+ static DWORD prevCameraStepTime = 0;
+ DWORD nowCameraStepTime = timeGetTime();
+ Bool stepTime = (nowCameraStepTime - prevCameraStepTime) >= (DWORD)TheW3DFrameLengthInMsec;
+ // During a scripted frozen-time pan, W3DDisplay::draw's inner loop calls us and
+ // paces itself to ~30fps already; gating on top of that ran the pan at half speed.
+ if (isTimeFrozen() && !isCameraMovementFinished())
+ stepTime = TRUE;
+ if (stepTime)
+ prevCameraStepTime = nowCameraStepTime;
+
if (TheTerrainRenderObject->doesNeedFullUpdate()) {
RefRenderObjListIterator *it = W3DDisplay::m_3DScene->createLightsIterator();
TheTerrainRenderObject->updateCenter(m_3DCamera, it);
@@ -1121,7 +1143,7 @@ void W3DView::update(void)
{
followFactor = -1;
}
- if (cameraLock != INVALID_ID)
+ if (stepTime && cameraLock != INVALID_ID)
{
m_doingMoveCameraOnWaypointPath = false;
m_CameraArrivedAtWaypointOnPathFlag = false;
@@ -1284,7 +1306,7 @@ void W3DView::update(void)
}
}
- if (!(TheScriptEngine->isTimeFrozenDebug()/* || TheScriptEngine->isTimeFrozenScript()*/) && !TheGameLogic->isGamePaused()) {
+ if (stepTime && !(TheScriptEngine->isTimeFrozenDebug()/* || TheScriptEngine->isTimeFrozenScript()*/) && !TheGameLogic->isGamePaused()) {
// If we aren't frozen for debug, allow the camera to follow scripted movements.
if (updateCameraMovements()) {
didScriptedMovement = true;
@@ -1299,26 +1321,29 @@ void W3DView::update(void)
// Process camera shake
/// @todo Make this framerate-independent
//
- if (m_shakeIntensity > 0.01f)
+ if (stepTime)
{
- m_shakeOffset.x = m_shakeIntensity * m_shakeAngleCos;
- m_shakeOffset.y = m_shakeIntensity * m_shakeAngleSin;
+ if (m_shakeIntensity > 0.01f)
+ {
+ m_shakeOffset.x = m_shakeIntensity * m_shakeAngleCos;
+ m_shakeOffset.y = m_shakeIntensity * m_shakeAngleSin;
- // fake a stiff spring/damper
- const Real dampingCoeff = 0.75f;
- m_shakeIntensity *= dampingCoeff;
+ // fake a stiff spring/damper
+ const Real dampingCoeff = 0.75f;
+ m_shakeIntensity *= dampingCoeff;
- // spring is so "stiff", it pulls 180 degrees opposite each frame
- m_shakeAngleCos = -m_shakeAngleCos;
- m_shakeAngleSin = -m_shakeAngleSin;
+ // spring is so "stiff", it pulls 180 degrees opposite each frame
+ m_shakeAngleCos = -m_shakeAngleCos;
+ m_shakeAngleSin = -m_shakeAngleSin;
- recalcCamera = true;
- }
- else
- {
- m_shakeIntensity = 0.0f;
- m_shakeOffset.x = 0.0f;
- m_shakeOffset.y = 0.0f;
+ recalcCamera = true;
+ }
+ else
+ {
+ m_shakeIntensity = 0.0f;
+ m_shakeOffset.x = 0.0f;
+ m_shakeOffset.y = 0.0f;
+ }
}
//Process New C3 Camera Shaker system
@@ -1336,7 +1361,7 @@ void W3DView::update(void)
*/
m_terrainHeightUnderCamera = getHeightAroundPos(m_pos.x, m_pos.y);
m_currentHeightAboveGround = m_cameraOffset.z * m_zoom - m_terrainHeightUnderCamera;
- if (TheTerrainLogic && TheGlobalData && TheInGameUI && m_okToAdjustHeight && !TheGameLogic->isGamePaused())
+ if (stepTime && TheTerrainLogic && TheGlobalData && TheInGameUI && m_okToAdjustHeight && !TheGameLogic->isGamePaused())
{
Real desiredHeight = (m_terrainHeightUnderCamera + m_heightAboveGround);
Real desiredZoom = desiredHeight / m_cameraOffset.z;
@@ -1812,6 +1837,17 @@ void W3DView::scrollBy( Coord2D *delta )
{
const Real SCROLL_RESOLUTION = 250.0f;
+ // The scroll offsets are tuned as per-30Hz-tick amounts but arrive once per render
+ // frame, so scale the applied movement by real elapsed time to keep scroll speed
+ // framerate-independent. m_scrollAmount stays unscaled - the height-adjust cutoff
+ // in update() compares it against per-tick thresholds.
+ static DWORD prevScrollTime = timeGetTime();
+ DWORD nowScrollTime = timeGetTime();
+ Real scrollDtFactor = (nowScrollTime - prevScrollTime) / (Real)TheW3DFrameLengthInMsec;
+ prevScrollTime = nowScrollTime;
+ if (scrollDtFactor > 3.0f)
+ scrollDtFactor = 3.0f; // after a hitch or idle, don't teleport the camera
+
Vector3 world, worldStart, worldEnd;
Vector2 screen, start, end;
@@ -1829,9 +1865,9 @@ void W3DView::scrollBy( Coord2D *delta )
m_3DCamera->Device_To_World_Space( start, &worldStart );
m_3DCamera->Device_To_World_Space( end, &worldEnd );
- world.X = worldEnd.X - worldStart.X;
- world.Y = worldEnd.Y - worldStart.Y;
- world.Z = worldEnd.Z - worldStart.Z;
+ world.X = (worldEnd.X - worldStart.X) * scrollDtFactor;
+ world.Y = (worldEnd.Y - worldStart.Y) * scrollDtFactor;
+ world.Z = (worldEnd.Z - worldStart.Z) * scrollDtFactor;
// scroll by delta
Coord3D pos = *getPosition();
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index bcd346065..18a1d61f4 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -443,3 +443,29 @@ TEST(are_music_files_on_cd_accepts_the_local_no_cd_layout)
CHECK_EQ( TheFileSystem->areMusicFilesOnCD(), TRUE );
remove( "genseczh.big" );
}
+
+/* GameEngine.cpp: rendering is uncapped and the logic tick is paced by wall
+ clock instead of by render frames, so game speed must not scale with fps.
+ This is the pacing decision function; the statics live in update(). */
+extern Bool GameEngine_isLogicFrameDue( Real& accumMs, Real elapsedMs, Int logicFps );
+
+TEST(logic_tick_is_wall_clock_paced_not_render_paced)
+{
+ /* A 300fps renderer (3.33ms/frame) at 30fps logic: 900 render frames span
+ 3 seconds, which must yield 90 logic frames, not 900. */
+ Real accum = 0.0f;
+ Int due = 0;
+ for( Int i = 0; i < 900; ++i )
+ if( GameEngine_isLogicFrameDue( accum, 1000.0f / 300.0f, 30 ) )
+ ++due;
+ CHECK( due >= 89 && due <= 91 );
+
+ /* A renderer slower than the logic rate runs exactly one logic frame per
+ render frame (elapsed time is clamped) - never a catch-up burst. */
+ accum = 0.0f;
+ for( Int i = 0; i < 50; ++i )
+ CHECK( GameEngine_isLogicFrameDue( accum, 100.0f, 30 ) );
+
+ /* A non-positive fps never throttles (the -noFPSLimit style dev mode). */
+ CHECK( GameEngine_isLogicFrameDue( accum, 0.0f, 0 ) );
+}