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): retransmit on the link's own round trip, not a flat 2s
Olcay Seygana371e077f6bb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 16e362b36..8f8f9e5f3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -177,6 +177,14 @@ map. Ctrl+A is still everything at once.deliver their orders in, and stalled on almost every frame — and the game's response to oneplayer stalling is to slow everyone down. It measures the simulation now.+- **One lost packet no longer freezes the game for two seconds.** Nobody's next frame can happen+ until everyone's orders for it have arrived, so a single dropped packet stalls the whole match+ until it is sent again — and the game always waited a flat two seconds before trying. It now+ measures the round trip to each player and waits about that long instead, which on a normal+ connection is under a fifth of a second. It keeps a little extra room for connections that swing+ around, backs off when a link is genuinely down rather than hammering it, and never waits longer+ than the two seconds it used to, so nobody ends up worse off than before.+## Sharper textures, for freeZero Hour shipped downscaled copies of a lot of the base game's textures, and because of the orderdiff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/Connection.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/Connection.hindex 5d79de709..3d0009d97 100644--- a/GeneralsMD/Code/GameEngine/Include/GameNetwork/Connection.h+++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/Connection.h@@ -45,6 +45,39 @@#define CONNECTION_LATENCY_HISTORY_LENGTH 200+/**+ * Retransmit timeout bounds, in milliseconds.+ *+ * EA shipped a flat 2000ms retry (Connection::Connection), so on a 40ms link one lost command+ * packet cost every player in the game a two-second stall before it was even tried again. Their+ * own intent is commented out in doRetryMetrics(): "m_retryTime = m_averageLatency * 1.5". It+ * could not be switched on as written - m_averageLatency is a 200-slot rolling mean over an array+ * that starts full of zeroes, so early in a game it reads near zero and a 1.5x multiple of that is+ * a packet storm. What is used instead is the standard Jacobson/Karels estimator, which carries+ * its own variance term and therefore widens on a jittery link instead of hugging the mean.+ *+ * The floor keeps a LAN game from retransmitting faster than the ack can physically come back.+ * The ceiling is EA's old constant, so no link is ever served worse than the shipped behaviour.+ */+#define CONNECTION_MIN_RETRY_TIME 150+#define CONNECTION_MAX_RETRY_TIME 2000++/**+ * Fold one round-trip sample into the smoothed estimate and rewrite the timeout. Jacobson/Karels:+ * srtt tracks the mean, rttvar the mean deviation, and the timeout sits four deviations out so+ * ordinary jitter does not trigger a retransmit. srtt < 0 means "no samples yet" and seeds both.+ * Free function (not a member, not static) so test_gameengine can link straight to it.+ */+void Connection_updateRetryTimeout( Real sampleMS, Real &srtt, Real &rttvar, time_t &retryMS );++/**+ * How long to wait before sending this particular command again, given the connection's current+ * timeout and how many times the command has already gone out. Repeated failures back off+ * exponentially up to the ceiling, so a link that is genuinely down is not hammered.+ * Free function (not a member, not static) so test_gameengine can link straight to it.+ */+time_t Connection_retryDelayFor( time_t baseRetryMS, Int numTimesSent );+class Connection : public MemoryPoolObject{MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(Connection, "Connection")@@ -93,8 +126,10 @@ protected:User *m_user;NetCommandList *m_netCommandList;- time_t m_retryTime; ///< The time between sending retry packets for this connection. Time is in milliseconds.- Real m_averageLatency; ///< The average time between sending a command and receiving an ACK.+ time_t m_retryTime; ///< The time between sending retry packets for this connection. Time is in milliseconds. Derived from the two estimators below, never a constant.+ Real m_smoothedLatency; ///< Jacobson/Karels srtt, in milliseconds. Negative until the first untainted round-trip sample arrives.+ Real m_latencyVariance; ///< Jacobson/Karels rttvar (mean deviation), in milliseconds.+ Real m_averageLatency; ///< The average time between sending a command and receiving an ACK. Reporting only - the timeout is driven by m_smoothedLatency.Real m_latencies[CONNECTION_LATENCY_HISTORY_LENGTH]; ///< List of the last 100 latencies.time_t m_frameGrouping; ///< The minimum time between packet sends.diff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetCommandRef.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetCommandRef.hindex 7865dc5b3..90671e05c 100644--- a/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetCommandRef.h+++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetCommandRef.h@@ -65,12 +65,16 @@ public:time_t getTimeLastSent() const;void setTimeLastSent(time_t timeLastSent);+ Int getNumTimesSent() const;+ void markSent(time_t when);+protected:NetCommandMsg *m_msg;NetCommandRef *m_next;NetCommandRef *m_prev;UnsignedByte m_relay; ///< Need this in the command reference since the relay value will be different depending on where this particular reference is being sent.time_t m_timeLastSent;+ Int m_numTimesSent; ///< How many times this reference has gone out. An ack for a command sent more than once cannot be timed (which send is it acking?), so it is not used as a latency sample - Karn's rule.#ifdef DEBUG_NETCOMMANDREFUnsignedInt m_id;@@ -133,6 +137,24 @@ inline void NetCommandRef::setTimeLastSent(time_t timeLastSent)m_timeLastSent = timeLastSent;}+/**+ * How many times this reference has been put on the wire. 1 is a first transmission, more is a+ * retransmission and its ack is ambiguous.+ */+inline Int NetCommandRef::getNumTimesSent() const+{+ return m_numTimesSent;+}++/**+ * Record a send: stamp the time and count it.+ */+inline void NetCommandRef::markSent(time_t when)+{+ m_timeLastSent = when;+ ++m_numTimesSent;+}+/*** Set the send relay for this reference of the command.*/diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Connection.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Connection.cppindex 1c229195a..e7c744f29 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Connection.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Connection.cpp@@ -31,6 +31,62 @@enum { MaxQuitFlushTime = 30000 }; // wait this many milliseconds at most to retry things before quitting+/**+ * Jacobson/Karels. See the comment on CONNECTION_MIN_RETRY_TIME in Connection.h for why the flat+ * 2000ms it replaces had to go, and why EA's own commented-out mean-times-1.5 could not be it.+ */+void Connection_updateRetryTimeout( Real sampleMS, Real &srtt, Real &rttvar, time_t &retryMS )+{+ if (sampleMS < 0.0f) {+ sampleMS = 0.0f;+ }++ if (srtt < 0.0f) {+ // First sample: the mean is the sample and the deviation is half of it, which is the+ // conventional seed and keeps the first timeout from being absurdly tight.+ srtt = sampleMS;+ rttvar = sampleMS / 2.0f;+ } else {+ Real deviation = srtt - sampleMS;+ if (deviation < 0.0f) {+ deviation = -deviation;+ }+ rttvar = (0.75f * rttvar) + (0.25f * deviation);+ srtt = (0.875f * srtt) + (0.125f * sampleMS);+ }++ Real timeout = srtt + (4.0f * rttvar);+ if (timeout < (Real)CONNECTION_MIN_RETRY_TIME) {+ timeout = (Real)CONNECTION_MIN_RETRY_TIME;+ }+ if (timeout > (Real)CONNECTION_MAX_RETRY_TIME) {+ timeout = (Real)CONNECTION_MAX_RETRY_TIME;+ }+ retryMS = (time_t)timeout;+}++/**+ * Exponential backoff on top of the connection's timeout, capped at the ceiling. numTimesSent is+ * how many times the command has already gone out, so 1 (a single transmission awaiting its first+ * retry) is the un-backed-off case.+ */+time_t Connection_retryDelayFor( time_t baseRetryMS, Int numTimesSent )+{+ Int backoff = numTimesSent - 1;+ if (backoff < 0) {+ backoff = 0;+ }+ if (backoff > 4) {+ backoff = 4;+ }++ time_t delay = baseRetryMS << backoff;+ if (delay > CONNECTION_MAX_RETRY_TIME) {+ delay = CONNECTION_MAX_RETRY_TIME;+ }+ return delay;+}+/*** The constructor.*/@@ -38,7 +94,12 @@ Connection::Connection() {m_transport = NULL;m_user = NULL;m_netCommandList = NULL;- m_retryTime = 2000; // set retry time to 2 seconds.+ // Start at the ceiling - EA's old flat constant - and let the first acks pull it down to what+ // the link actually is. Starting low would mean retransmitting before the very first ack of+ // the game had a chance to arrive.+ m_retryTime = CONNECTION_MAX_RETRY_TIME;+ m_smoothedLatency = -1.0f;+ m_latencyVariance = 0.0f;m_lastTimeSent = 0;m_frameGrouping = 1;m_isQuitting = false;@@ -91,6 +152,11 @@ void Connection::init() {m_numRetries = 0;m_retryMetricsTime = 0;+ // A reset connection knows nothing about the link again: back to the ceiling, no samples.+ m_retryTime = CONNECTION_MAX_RETRY_TIME;+ m_smoothedLatency = -1.0f;+ m_latencyVariance = 0.0f;+for (Int i = 0; i < CONNECTION_LATENCY_HISTORY_LENGTH; ++i) {m_latencies[i] = 0;}@@ -293,7 +359,9 @@ UnsignedInt Connection::doSend() {time_t timeLastSent = msg->getTimeLastSent();- if (((curtime - timeLastSent) > m_retryTime) || (timeLastSent == -1)) {+ time_t retryDelay = Connection_retryDelayFor(m_retryTime, msg->getNumTimesSent());++ if (((curtime - timeLastSent) > retryDelay) || (timeLastSent == -1)) {notDone = packet->addCommand(msg);if (notDone) {// the msg command was added to the packet.@@ -302,7 +370,7 @@ UnsignedInt Connection::doSend() {++m_numRetries;}doRetryMetrics();- msg->setTimeLastSent(curtime);+ msg->markSent(curtime);} else {m_netCommandList->removeMessage(msg);msg->deleteInstance();@@ -384,6 +452,13 @@ NetCommandRef * Connection::processAck(UnsignedShort commandID, UnsignedByte orim_averageLatency += lat / CONNECTION_LATENCY_HISTORY_LENGTH;m_latencies[index] = lat;+ // Karn's rule: an ack for a command that went out more than once cannot be timed, because+ // there is no way to tell which of the sends it is acking. Timing it against the last send+ // reads far too short and would drag the timeout down exactly when the link is losing packets.+ if (temp->getNumTimesSent() <= 1) {+ Connection_updateRetryTimeout(lat, m_smoothedLatency, m_latencyVariance, m_retryTime);+ }+#if defined(_DEBUG) || defined(_INTERNAL)if (doDebug == TRUE) {DEBUG_LOG(("Connection::processAck - disconnect frame command %d found, removing from command list.\n", commandID));@@ -395,7 +470,8 @@ NetCommandRef * Connection::processAck(UnsignedShort commandID, UnsignedByte orivoid Connection::setFrameGrouping(time_t frameGrouping) {m_frameGrouping = frameGrouping;-// m_retryTime = frameGrouping * 4;+ // (EA had "m_retryTime = frameGrouping * 4" here. The timeout is measured from acks now -+ // see Connection_updateRetryTimeout - so the send cadence no longer dictates it.)}void Connection::doRetryMetrics() {@@ -405,9 +481,9 @@ void Connection::doRetryMetrics() {if ((curTime - m_retryMetricsTime) > 10000) {m_retryMetricsTime = curTime;++numSeconds;-// DEBUG_LOG(("Retries in the last 10 seconds = %d, average latency = %fms\n", m_numRetries, m_averageLatency));+ DEBUG_LOG(("Connection::doRetryMetrics - retries in the last 10s = %d, average latency = %.1fms, srtt = %.1fms, rttvar = %.1fms, retry timeout = %dms\n",+ m_numRetries, m_averageLatency, m_smoothedLatency, m_latencyVariance, (Int)m_retryTime));m_numRetries = 0;-// m_retryTime = m_averageLatency * 1.5;}}diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/NetCommandRef.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/NetCommandRef.cppindex 0044d0d44..abd1e80d9 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/NetCommandRef.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/NetCommandRef.cpp@@ -45,6 +45,7 @@ NetCommandRef::NetCommandRef(NetCommandMsg *msg)m_prev = NULL;m_msg->attach();m_timeLastSent = -1;+ m_numTimesSent = 0;#ifdef DEBUG_NETCOMMANDREFm_id = ++refNum;diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex 4e1ea3d1a..c5015ba3a 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -27,6 +27,7 @@#include "Common/INIException.h"#include "Common/STLTypedefs.h"#include "Common/StackDump.h"+#include "GameNetwork/Connection.h"#include "GameClient/Water.h"#include "GameLogic/Module/PhysicsUpdate.h"#include "GameClient/ParticleSys.h"@@ -1847,3 +1848,85 @@ TEST(network_fps_metric_measures_logic_frames_not_rendered_ones)and must read zero rather than wrapping the unsigned subtraction. */CHECK_NEAR( FrameMetrics_logicFpsSample( 1000, 1000, 1000 ), 0.0f, 0.001f );}++/* ---------------------------------------------------------------------------------------------+ Adaptive retransmit. EA shipped a flat 2000ms retry, so on a fast link one lost command packet+ cost the whole room a two-second stall. Their own commented-out intent (average latency * 1.5)+ could not be switched on as written - the average is a rolling mean over an array that starts+ full of zeroes - so this is Jacobson/Karels instead, which carries a variance term and widens on+ a jittery link rather than hugging the mean.+ --------------------------------------------------------------------------------------------- */+extern void Connection_updateRetryTimeout( Real sampleMS, Real &srtt, Real &rttvar, time_t &retryMS );+extern time_t Connection_retryDelayFor( time_t baseRetryMS, Int numTimesSent );++TEST(connection_retry_timeout_follows_the_link_and_never_leaves_its_bounds)+{+ /* A steady 40ms LAN link: the first sample seeds srtt=40, rttvar=20, so the timeout starts at+ 40+80=120 and is lifted to the 150ms floor. Feeding the same number repeatedly drives the+ deviation to zero, so it settles on the floor - which is the whole point: a lost packet on+ this link is retried in 150ms, not 2000. */+ Real srtt = -1.0f, rttvar = 0.0f;+ time_t retry = CONNECTION_MAX_RETRY_TIME;+ Connection_updateRetryTimeout( 40.0f, srtt, rttvar, retry );+ CHECK_EQ( (Int)retry, CONNECTION_MIN_RETRY_TIME );+ for( Int i = 0; i < 100; ++i )+ Connection_updateRetryTimeout( 40.0f, srtt, rttvar, retry );+ CHECK_NEAR( srtt, 40.0f, 0.5f );+ CHECK( rttvar < 1.0f );+ CHECK_EQ( (Int)retry, CONNECTION_MIN_RETRY_TIME );++ /* A steady 300ms link settles above the floor, at about the mean, because the deviation+ collapses. It must not sit at EA's ceiling. */+ srtt = -1.0f; rttvar = 0.0f; retry = CONNECTION_MAX_RETRY_TIME;+ for( Int i = 0; i < 200; ++i )+ Connection_updateRetryTimeout( 300.0f, srtt, rttvar, retry );+ CHECK( retry > CONNECTION_MIN_RETRY_TIME );+ CHECK( retry < CONNECTION_MAX_RETRY_TIME );+ CHECK_NEAR( (Real)retry, 300.0f, 30.0f );++ /* The reason the variance term exists: a link whose mean is 100ms but which swings between+ 40 and 160 must be given more room than a rock-steady 100ms link, or every swing is read as+ a loss and retransmitted. */+ Real steadySrtt = -1.0f, steadyVar = 0.0f;+ time_t steadyRetry = CONNECTION_MAX_RETRY_TIME;+ Real jumpySrtt = -1.0f, jumpyVar = 0.0f;+ time_t jumpyRetry = CONNECTION_MAX_RETRY_TIME;+ for( Int i = 0; i < 200; ++i )+ {+ Connection_updateRetryTimeout( 100.0f, steadySrtt, steadyVar, steadyRetry );+ Connection_updateRetryTimeout( (i & 1) ? 160.0f : 40.0f, jumpySrtt, jumpyVar, jumpyRetry );+ }+ CHECK( jumpyRetry > steadyRetry );++ /* Neither bound can be crossed: a satellite link is capped at EA's old constant so nobody is+ served worse than the shipped behaviour, and a zero-latency loopback still waits the floor. */+ srtt = -1.0f; rttvar = 0.0f; retry = 0;+ for( Int i = 0; i < 50; ++i )+ Connection_updateRetryTimeout( 5000.0f, srtt, rttvar, retry );+ CHECK_EQ( (Int)retry, CONNECTION_MAX_RETRY_TIME );++ srtt = -1.0f; rttvar = 0.0f; retry = 0;+ for( Int i = 0; i < 50; ++i )+ Connection_updateRetryTimeout( 0.0f, srtt, rttvar, retry );+ CHECK_EQ( (Int)retry, CONNECTION_MIN_RETRY_TIME );+}++TEST(connection_retry_backs_off_when_a_command_keeps_going_unacked)+{+ /* A command that has gone out once waits the connection's plain timeout. */+ CHECK_EQ( (Int)Connection_retryDelayFor( 200, 1 ), 200 );++ /* Each further attempt doubles, so a link that is genuinely down is not hammered at the+ floor rate for as long as the disconnect timer runs. */+ CHECK_EQ( (Int)Connection_retryDelayFor( 200, 2 ), 400 );+ CHECK_EQ( (Int)Connection_retryDelayFor( 200, 3 ), 800 );+ CHECK_EQ( (Int)Connection_retryDelayFor( 200, 4 ), 1600 );++ /* ...but never past the ceiling, however long it stays down. */+ CHECK_EQ( (Int)Connection_retryDelayFor( 200, 5 ), CONNECTION_MAX_RETRY_TIME );+ CHECK_EQ( (Int)Connection_retryDelayFor( 200, 50 ), CONNECTION_MAX_RETRY_TIME );+ CHECK_EQ( (Int)Connection_retryDelayFor( CONNECTION_MAX_RETRY_TIME, 3 ), CONNECTION_MAX_RETRY_TIME );++ /* A command that has never been sent is not a retry, and must not read as a negative shift. */+ CHECK_EQ( (Int)Connection_retryDelayFor( 200, 0 ), 200 );+}