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
fix(gamenetwork): measure the frame cushion signed, so the self-slug fires
Olcay Seyganee6aeb518b67
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ded3f2973..df3352a42 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -224,6 +224,13 @@ map. Ctrl+A is still everything at once.that the game printed at startup and then ignored. It is a real setting now, and it is kept insidethe range that actually keeps the door open — a game can ask for these packets more often on afussy connection, but nothing can set it so far apart that the connection lapses between them.+- **The brake that stops an online game freezing was being switched off by the very thing it+ watches for.** When your machine is running out of the margin it keeps between the network and+ the simulation, it eases off its own speed for a moment so everyone catches up smoothly instead+ of the game locking solid. That margin was measured with a subtraction that ran backwards+ whenever an order arrived for a moment that had already passed — and the answer it produced was+ read as the largest margin possible, so the brake stayed off at precisely the moment it was+ needed. It is measured properly now.## Sharper textures, for freediff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/ConnectionManager.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/ConnectionManager.hindex 145805740..e8892f00c 100644--- a/GeneralsMD/Code/GameEngine/Include/GameNetwork/ConnectionManager.h+++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/ConnectionManager.h@@ -116,7 +116,7 @@ public:Real getUnknownPacketsPerSecond( void );UnsignedInt getPacketArrivalCushion( void );- UnsignedInt getMinimumCushion();+ Int getMinimumCushion();void flushConnections();diff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/CushionMetrics.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/CushionMetrics.hnew file mode 100644index 000000000..d2578a173--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/CushionMetrics.h@@ -0,0 +1,45 @@+/*+** 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/>.+*/++// FILE: CushionMetrics.h /////////////////////////////////////////////////////////////////////////+// Desc: How many frames of margin we have left, and when to spend some slowing down.+///////////////////////////////////////////////////////////////////////////////////////////////////++#pragma once++#ifndef _CUSHION_METRICS_H_+#define _CUSHION_METRICS_H_++#include "Lib/BaseType.h"++/* The "cushion" is how many frames ahead of the simulation a command arrived: the margin between+ the network and the frame that needs it. When it runs low the machine deliberately slows its+ own logic rate - the self-slug - so the rest of the room can catch up before anybody stalls+ outright. That decision is worth getting right in both directions: slug when there is no+ margin left and the room stutters instead of stalling, slug when there is and every player+ pays for nothing. */++/** The margin, in frames, between the frame a command is for and the frame we are on. Never+ negative: a command whose frame has already gone by is no margin at all, not a negative one. */+Int frameCushion( UnsignedInt executionFrame, UnsignedInt currentFrame );++/** Whether to slow our own logic rate. A negative minimumCushion means no sample has been taken+ yet, which is not the same as no margin - see the sentinel note in CushionMetrics.cpp. */+Bool shouldSelfSlug( Int minimumCushion, Int runAhead, UnsignedInt slackPercent );++#endif // _CUSHION_METRICS_H_diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/ConnectionManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/ConnectionManager.cppindex e5bd4f91a..1072352dc 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/ConnectionManager.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/ConnectionManager.cpp@@ -44,6 +44,7 @@#include "GameNetwork/ConnectionManager.h"#include "GameNetwork/StallJudgement.h"#include "GameNetwork/KeepAliveSchedule.h"+#include "GameNetwork/CushionMetrics.h"#include "GameNetwork/LANAPICallbacks.h"#include "GameNetwork/NAT.h"#include "GameNetwork/NetCommandWrapperList.h"@@ -1165,8 +1166,8 @@ void ConnectionManager::sendRemoteCommand(NetCommandRef *msg) {if (IsCommandSynchronized(msg->getCommand()->getNetCommandType())) {// DEBUG_LOG(("ConnectionManager::sendRemoteCommand - about to call allCommandsReady\n"));if (allCommandsReady(msg->getCommand()->getExecutionFrame(), TRUE)) {- UnsignedInt cushion = msg->getCommand()->getExecutionFrame() - TheGameLogic->getFrame();- if ((cushion < m_smallestPacketArrivalCushion) || (m_smallestPacketArrivalCushion == -1)) {+ Int cushion = frameCushion(msg->getCommand()->getExecutionFrame(), TheGameLogic->getFrame());+ if (((UnsignedInt)cushion < m_smallestPacketArrivalCushion) || (m_smallestPacketArrivalCushion == -1)) {m_smallestPacketArrivalCushion = cushion;}m_frameMetrics.addCushion(cushion);@@ -1422,7 +1423,12 @@ void ConnectionManager::getMinimumFps(Int &minFps, Int &minFpsPlayer) {// DEBUG_LOG(("\n"));}-UnsignedInt ConnectionManager::getMinimumCushion() {+/**+ * The smallest cushion measured over the current window, or a negative number if nothing has been+ * measured yet. This used to return UnsignedInt while FrameMetrics returns Int, so the "no sample+ * yet" sentinel came out the other side as four billion frames of margin - see CushionMetrics.h.+ */+Int ConnectionManager::getMinimumCushion() {return m_frameMetrics.getMinimumCushion();}diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/CushionMetrics.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/CushionMetrics.cppnew file mode 100644index 000000000..df3bf31f4--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/CushionMetrics.cpp@@ -0,0 +1,58 @@+/*+** 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/>.+*/++// FILE: CushionMetrics.cpp ///////////////////////////////////////////////////////////////////////+// Desc: How many frames of margin we have left, and when to spend some slowing down.+///////////////////////////////////////////////////////////////////////////////////////////////////++#include "PreRTS.h"+#include "GameNetwork/CushionMetrics.h"++Int frameCushion( UnsignedInt executionFrame, UnsignedInt currentFrame )+{+ /* EA wrote this as `UnsignedInt cushion = executionFrame - TheGameLogic->getFrame()`, which is+ fine right up until a command arrives for a frame that has already run - a late relay, or a+ command caught up with after the run-ahead shrank. The subtraction then wraps to around+ four billion, and the caller hands that to FrameMetrics::addCushion, whose parameter is Int:+ 4294967295 arrives as -1, which is exactly that class's "no sample yet" sentinel. One late+ command therefore erased the minimum cushion for the window. */+ Int diff = (Int)(executionFrame - currentFrame); // signed difference, wraparound-safe+ if( diff < 0 )+ diff = 0;++ return diff;+}++Bool shouldSelfSlug( Int minimumCushion, Int runAhead, UnsignedInt slackPercent )+{+ /* Negative is FrameMetrics' "nothing measured yet", set by init() and never produced by a real+ sample once frameCushion clamps. It used to reach here as an UnsignedInt through+ ConnectionManager::getMinimumCushion's return type, so it read as four billion frames of+ margin - the largest cushion representable, from the state that knows the least. */+ if( minimumCushion < 0 )+ return FALSE;++ if( runAhead <= 0 )+ return FALSE;++ /* The threshold is the slack the run-ahead was given: once the margin has eaten into that, the+ next hiccup is a stall rather than a wobble. */+ Int threshold = (Int)((runAhead * (Int)slackPercent) / 100);++ return minimumCushion < threshold;+}diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/FrameMetrics.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/FrameMetrics.cppindex 27c3af0e2..4c744345b 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/FrameMetrics.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/FrameMetrics.cpp@@ -62,13 +62,14 @@ FrameMetrics::FrameMetrics()}FrameMetrics::~FrameMetrics() {+ // both are NEW Real[...]; EA freed them with scalar delete, which is a different operatorif (m_fpsList != NULL) {- delete m_fpsList;+ delete[] m_fpsList;m_fpsList = NULL;}if (m_latencyList != NULL) {- delete m_latencyList;+ delete[] m_latencyList;m_latencyList = NULL;}diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Network.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Network.cppindex 955dc3854..7bda4fad3 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Network.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Network.cpp@@ -37,6 +37,7 @@#include "Common/Player.h"#include "Common/PlayerList.h"#include "GameNetwork/NetworkInterface.h"+#include "GameNetwork/CushionMetrics.h"#include "GameNetwork/Udp.h"#include "GameNetwork/Transport.h"#include "strtok_r.h"@@ -771,9 +772,7 @@ Bool Network::timeForNewFrame() {* running too far behind us, so we need to slow down to let them catch up.*/if (m_conMgr != NULL) {- Real cushion = m_conMgr->getMinimumCushion();- Real runAheadPercentage = m_runAhead * (TheGlobalData->m_networkRunAheadSlack / (Real)100.0); // If we are at least 50% into our slack, we need to slow down.- if (cushion < runAheadPercentage) {+ if (shouldSelfSlug(m_conMgr->getMinimumCushion(), m_runAhead, TheGlobalData->m_networkRunAheadSlack)) {// DEBUG_LOG(("Average cushion = %f, run ahead percentage = %f. Adjusting frameDelay from %I64d to ", cushion, runAheadPercentage, frameDelay));frameDelay += frameDelay / 10; // temporarily decrease the frame rate by 20%.// DEBUG_LOG(("%I64d\n", frameDelay));diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex 30781cd06..577829d4e 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -33,6 +33,7 @@#include "GameLogic/FPUControl.h"#include "GameNetwork/StallJudgement.h"#include "GameNetwork/KeepAliveSchedule.h"+#include "GameNetwork/CushionMetrics.h"#include <float.h>#include "GameClient/Water.h"#include "GameLogic/Module/PhysicsUpdate.h"@@ -2310,3 +2311,73 @@ TEST(keepalive_every_player_gets_one_within_the_round)CHECK_EQ( keepAliveSlotsDue( roundMS - 1, roundMS, 8 ), 8 );CHECK( roundMS <= 15000 ); // under the shortest NAT UDP timeouts seen in the wild}++// ---------------------------------------------------------------------------------------------+// The cushion, and the self-slug it drives (MULTIPLAYER 3.3). Two type defects met in the+// middle here: an unsigned frame subtraction that could wrap, and an Int sentinel returned+// through an UnsignedInt.+// ---------------------------------------------------------------------------------------------++TEST(framecushion_is_the_margin_and_never_negative)+{+ CHECK_EQ( frameCushion( 100, 100 ), 0 );+ CHECK_EQ( frameCushion( 130, 100 ), 30 );+ CHECK_EQ( frameCushion( 100, 99 ), 1 );++ // the defect: a command for a frame that has already run. EA's unsigned subtraction made this+ // 4294967295, which arrives at FrameMetrics::addCushion(Int) as -1 - that class's "no sample+ // yet" sentinel - and wiped the minimum cushion for the window.+ CHECK_EQ( frameCushion( 99, 100 ), 0 );+ CHECK_EQ( frameCushion( 0, 1 ), 0 );+ CHECK_EQ( frameCushion( 100, 5000 ), 0 );++ // and the frame counter is unsigned, so the difference has to survive its wraparound too+ CHECK_EQ( frameCushion( 5, 0xFFFFFFFEu ), 7 );+ CHECK_EQ( frameCushion( 0xFFFFFFFEu, 5 ), 0 );+}++TEST(selfslug_does_not_fire_on_a_cushion_nobody_has_measured)+{+ // FrameMetrics::init leaves the minimum cushion at -1. ConnectionManager::getMinimumCushion+ // returned UnsignedInt, so that reached Network::timeForNewFrame as four billion frames of+ // margin: the largest cushion representable, produced by the state that knows the least.+ CHECK( !shouldSelfSlug( -1, 20, 10 ) );+ CHECK( !shouldSelfSlug( -100, 20, 10 ) );++ // nor on a run-ahead that has not been established+ CHECK( !shouldSelfSlug( 0, 0, 10 ) );+ CHECK( !shouldSelfSlug( 0, -1, 10 ) );+}++TEST(selfslug_fires_once_the_margin_eats_into_the_slack)+{+ // run-ahead 20, slack 10% -> the threshold is 2 frames of margin+ CHECK( shouldSelfSlug( 0, 20, 10 ) );+ CHECK( shouldSelfSlug( 1, 20, 10 ) );+ CHECK( !shouldSelfSlug( 2, 20, 10 ) );+ CHECK( !shouldSelfSlug( 19, 20, 10 ) );++ // a bigger run-ahead is given proportionally more margin before it worries+ CHECK( shouldSelfSlug( 5, 60, 10 ) );+ CHECK( !shouldSelfSlug( 6, 60, 10 ) );++ // and a run-ahead too small for the slack to round to a frame never slugs, which is right:+ // there is no margin to protect+ CHECK( !shouldSelfSlug( 0, 9, 10 ) );+ CHECK( shouldSelfSlug( 0, 10, 10 ) );+}++TEST(selfslug_is_monotonic_in_the_cushion)+{+ // once there is enough margin the answer must stay no, or the frame rate would oscillate+ Bool seenNo = FALSE;+ for( Int cushion = 0; cushion <= 200; ++cushion )+ {+ Bool slug = shouldSelfSlug( cushion, 60, 10 );+ if( !slug )+ seenNo = TRUE;+ else+ CHECK( !seenNo );+ }+ CHECK( seenNo );+}