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
perf(gamelogic): cheaper game crc, path claims and collision pairs
Olcay Seyganc7d002b45f80
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7c36a1f67..763183340 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -472,6 +472,7 @@ found and fixed, EA's own, not port damage.**- The main menu surf rolls at its proper pace, not ten times too fast.- And it is there at all again. The waves breaking on the main menu's beach had been worked out every frame and then drawn nowhere since v1.0.0, so the shore behind the menu was flat water.- Less work per picture in a big battle. Infantry and other bending models are shaped on every core at once instead of one, the shadow blobs and markers on the ground go to the graphics card in one batch instead of two uploads each, and a material or light identical to the one already set is no longer sent again. What is drawn does not change.+- A network match costs less to work out. Every step, each machine adds up a checksum of the whole game to compare with the others, and late in a four-player match that took 1.26ms; it takes 0.87ms now and comes out with the same number. With 410 units fighting in a two-player network match, the step went from 4.09ms to 3.99ms on average and from 7.9ms to 7.5ms at the slowest one in a hundred. Units in a big battle also spend about a fifth less time marking the ground they are about to cross. Recorded matches play back to the same checksum, and both machines of a network match end on the same one.## The computer opponent builds a base nowdiff --git a/GeneralsMD/Code/GameEngine/Include/Common/Overridable.h b/GeneralsMD/Code/GameEngine/Include/Common/Overridable.hindex deaba5960..5ea42ae0f 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/Overridable.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/Overridable.h@@ -57,12 +57,13 @@ class Overridable : public MemoryPoolObjectreturn m_nextOverride;}- // recursively ask if there is a next override, and if not, return this.+ // follow the chain to its last override, or return this if there is none.const Overridable *getFinalOverride( void ) const{- if (m_nextOverride)- return m_nextOverride->getFinalOverride();- return this;+ const Overridable *last = this;+ while (last->m_nextOverride)+ last = last->m_nextOverride;+ return last;}// set the next override on this object. This currently makes no attempt to prevent leaks.diff --git a/GeneralsMD/Code/GameEngine/Include/Common/XferCRC.h b/GeneralsMD/Code/GameEngine/Include/Common/XferCRC.hindex 5c07d5bc4..06169f306 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/XferCRC.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/XferCRC.h@@ -64,8 +64,6 @@ protected:virtual void xferImplementation( void *data, Int dataSize );- void addCRC( UnsignedInt val ); ///< CRC a 4-byte block-UnsignedInt m_crc;};diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/XferCRC.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/XferCRC.cppindex ebfe24620..c3be34d67 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/XferCRC.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/XferCRC.cpp@@ -36,11 +36,26 @@#include "Common/XferDeepCRC.h"#include "Common/crc.h"#include "Common/Snapshot.h"-#if defined(_WIN32)-#include "winsock2.h" // for htonl+#include <stdlib.h>++/* The CRC is defined on words in network byte order, which every target this builds for (x64 and+ ARM64, little-endian all) reaches with one byte swap. It used to be Winsock's htonl, an imported+ call per word that also made the compiler store m_crc back after each one; a whole game CRC late+ in a 4-player Twilight Flame match took 1.26 ms that way and takes 0.87 ms now. */+static inline UnsignedInt crcSwap( UnsignedInt v )+{+#if defined(_MSC_VER)+ return _byteswap_ulong( v );#else-#include <arpa/inet.h> // htonl, which winsock2.h supplies on Windows+ return __builtin_bswap32( v );#endif+}++// One 4-byte step: the running CRC rotated left a bit, plus the word in network byte order.+static inline UnsignedInt crcFold( UnsignedInt crc, UnsignedInt word )+{+ return (crc << 1) + crcSwap( word ) + (crc >> 31);+}//-------------------------------------------------------------------------------------------------//-------------------------------------------------------------------------------------------------@@ -99,29 +114,6 @@ void XferCRC::endBlock( void )} // end endBlock-//--------------------------------------------------------------------------------------------------//--------------------------------------------------------------------------------------------------void XferCRC::addCRC( UnsignedInt val )-{- int hibit;-- val = htonl(val);-- if (m_crc & 0x80000000)- {- hibit = 1;- }- else- {- hibit = 0;- }-- m_crc <<= 1;- m_crc += val;- m_crc += hibit;--} // end addCRC-// ------------------------------------------------------------------------------------------------/** Entry point for xfering a snapshot */// ------------------------------------------------------------------------------------------------@@ -153,9 +145,11 @@ void XferCRC::xferImplementation( void *data, Int dataSize )const UnsignedInt *uintPtr = (const UnsignedInt *) (data);+ // a local, so the compiler keeps it in a register instead of storing m_crc after every word+ UnsignedInt crc = m_crc;for (Int i=0 ; i<dataSize/4 ; i++){- addCRC (*uintPtr++);+ crc = crcFold( crc, *uintPtr++ );}int leftover = dataSize & 3;@@ -167,10 +161,11 @@ void XferCRC::xferImplementation( void *data, Int dataSize ){val += (c[i] << (i*8));}- val = htonl(val);- addCRC (val);+ // swapped here and again in the fold, as EA did, so the tail goes in unswapped+ crc = crcFold( crc, crcSwap( val ) );}-+ m_crc = crc;+} // end xferImplementation//-------------------------------------------------------------------------------------------------@@ -185,7 +180,7 @@ void XferCRC::skip( Int dataSize )UnsignedInt XferCRC::getCRC( void ){- return htonl(m_crc);+ return crcSwap( m_crc );} // end skipdiff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cppindex a44a08e86..79244bf55 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp@@ -4921,34 +4921,51 @@ void Pathfinder::resetClaims( void )}}-/* Two passes over the probe window on purpose. Reusing the first dead slot as soon as one turns- up would let the same (cell, bucket) exist twice - the live copy further along the window would- never be found again - and the weight the search reads would then depend on which of the two- the probe happened to reach first. */-void Pathfinder::addClaim( Int cell, UnsignedInt bucket, Int weight )+/* A hint that a cache line is about to be read, as PM_PREFETCH in PartitionManager.cpp. It decides+ nothing, so no claim can depend on it. */+#if defined(__GNUC__) || defined(__clang__)+ #define PF_PREFETCH(addr) __builtin_prefetch(addr)+#elif defined(_M_X64) || defined(_M_IX86)+ #include <xmmintrin.h>+ #define PF_PREFETCH(addr) _mm_prefetch((const char *)(addr), _MM_HINT_T0)+#elif defined(_M_ARM64)+ #include <intrin.h>+ #define PF_PREFETCH(addr) __prefetch(addr)+#else+ #define PF_PREFETCH(addr) ((void)0)+#endif++/* The dead slot is only remembered during the walk and written after it. Reusing the first dead+ slot as soon as one turns up would let the same (cell, bucket) exist twice - the live copy further+ along the window would never be found again - and the weight the search reads would then depend+ on which of the two the probe happened to reach first. Walking once and writing at the end gives+ exactly what the old two passes gave: a live match anywhere wins, else the first dead slot. */+static inline void claimInto( PathClaim *claims, Int cell, UnsignedInt bucket, Int weight, UnsignedInt nowBucket ){- if (m_claims == NULL || weight <= 0) return;const Int base = claimSlotOf(cell, bucket);- const UnsignedInt nowBucket = TheGameLogic->getFrame() / PF_CLAIM_BUCKET_FRAMES;- Int p;- for (p = 0; p < PF_CLAIM_PROBES; p++) {- PathClaim& e = m_claims[(base + p) & (PF_CLAIM_TABLE_SIZE - 1)];+ PathClaim *dead = NULL;+ for (Int p = 0; p < PF_CLAIM_PROBES; p++) {+ PathClaim& e = claims[(base + p) & (PF_CLAIM_TABLE_SIZE - 1)];if (e.m_cell == cell && e.m_bucket == bucket && e.m_weight > 0) {Int w = (Int)e.m_weight + weight;e.m_weight = (UnsignedShort)(w > 0xFFFF ? 0xFFFF : w);return;}- }- for (p = 0; p < PF_CLAIM_PROBES; p++) {- PathClaim& e = m_claims[(base + p) & (PF_CLAIM_TABLE_SIZE - 1)];- if (e.m_cell >= 0 && e.m_weight > 0 && e.m_bucket >= nowBucket) continue; // still live- e.m_cell = cell;- e.m_bucket = bucket;- e.m_weight = (UnsignedShort)weight;- return;+ if (dead == NULL && !(e.m_cell >= 0 && e.m_weight > 0 && e.m_bucket >= nowBucket)) // not still live+ dead = &e;}// the window is full of live claims: this one is simply not recorded. Dropping it costs the// search a penalty it will not see, which is the harmless direction to fail in.+ if (dead == NULL) return;+ dead->m_cell = cell;+ dead->m_bucket = bucket;+ dead->m_weight = (UnsignedShort)weight;+}++void Pathfinder::addClaim( Int cell, UnsignedInt bucket, Int weight )+{+ if (m_claims == NULL || weight <= 0) return;+ claimInto(m_claims, cell, bucket, weight, TheGameLogic->getFrame() / PF_CLAIM_BUCKET_FRAMES);}Int Pathfinder::getClaims( Int x, Int y, UnsignedInt frame ) const@@ -4977,7 +4994,21 @@ void Pathfinder::stampClaimAt( const Coord3D *pos, UnsignedInt frame, Int dilatiICoord2D c;worldToCell(pos, &c);const UnsignedInt bucket = frame / PF_CLAIM_BUCKET_FRAMES;+ const UnsignedInt nowBucket = TheGameLogic->getFrame() / PF_CLAIM_BUCKET_FRAMES;const Int h = m_extent.hi.y + 1;+ // the probe windows sit all over a 384 KB table: ask for every one first, so the misses overlap+ for (Int dx = -dilation; dx <= dilation; dx++) {+ Int x = c.x + dx;+ if (x < m_extent.lo.x || x > m_extent.hi.x) continue;+ for (Int dy = -dilation; dy <= dilation; dy++) {+ Int y = c.y + dy;+ if (y < m_extent.lo.y || y > m_extent.hi.y) continue;+ Int cell = x*h + y;+ PF_PREFETCH(&m_claims[claimSlotOf(cell, bucket)]);+ if (bucket > 0) PF_PREFETCH(&m_claims[claimSlotOf(cell, bucket-1)]);+ PF_PREFETCH(&m_claims[claimSlotOf(cell, bucket+1)]);+ }+ }for (Int dx = -dilation; dx <= dilation; dx++) {Int x = c.x + dx;if (x < m_extent.lo.x || x > m_extent.hi.x) continue;@@ -4985,9 +5016,9 @@ void Pathfinder::stampClaimAt( const Coord3D *pos, UnsignedInt frame, Int dilatiInt y = c.y + dy;if (y < m_extent.lo.y || y > m_extent.hi.y) continue;Int cell = x*h + y;- addClaim(cell, bucket, 2);- if (bucket > 0) addClaim(cell, bucket-1, 1);- addClaim(cell, bucket+1, 1);+ claimInto(m_claims, cell, bucket, 2, nowBucket);+ if (bucket > 0) claimInto(m_claims, cell, bucket-1, 1, nowBucket);+ claimInto(m_claims, cell, bucket+1, 1, nowBucket);UnsignedShort touch = (UnsignedShort)(bucket + 1);if (m_claimTouch[cell] < touch) m_claimTouch[cell] = touch;}@@ -6584,6 +6615,11 @@ Bool Pathfinder::checkForMovement(const Object *obj, TCheckMovementInfo &info)Optimising the empty case optimised the half that was already free. */Int numCellsAbove = info.radius;if (info.centerInCell) numCellsAbove++;+ const ObjectID myId = obj->getID();+ /* A four-entry memo of the units already met in this window (object, relationship, crush answer)+ was tried here on 2026-10-27 and taken out: on the 530-unit crowd it halved the time spent in+ those three calls and added the same back in its own lookups, so the function cost what it did+ before. Each cell asks once instead, and a moving unit's relationship is not asked twice. */Int i, j;// Bool isInfantry = obj->isKindOf(KINDOF_INFANTRY);for (i=info.cell.x-info.radius; i<info.cell.x+numCellsAbove; i++) {@@ -6591,24 +6627,33 @@ Bool Pathfinder::checkForMovement(const Object *obj, TCheckMovementInfo &info)PathfindCell *cell = getCell(info.layer,i, j);if (cell) {enum PathfindCell::CellFlags flags = cell->getFlags();- ObjectID posUnit = cell->getPosUnit();if ((flags == PathfindCell::UNIT_GOAL) || (flags == PathfindCell::UNIT_GOAL_OTHER_MOVING)) {info.allyGoal = true;}if (flags == PathfindCell::NO_UNITS) {continue; // Nobody is here, so it's ok.- } else if (posUnit==obj->getID()) {+ }+ // read only past the empty test: it goes through the cell's info, which every cell the running+ // search has visited carries, and an empty cell never needed it+ ObjectID posUnit = cell->getPosUnit();+ if (posUnit==myId) {continue; // we got it.} else if (posUnit==ignoreId) {- continue; // we are ignoring this one.+ // we are ignoring this one. EA asked again further down whether the unit's own id was+ // the ignored obstacle; that id is posUnit, so the second ask never fired and is gone.+ continue;} else {Bool check = false;Object *unit = NULL;+ Int rel = -1; // asked at most once a cellif (flags==PathfindCell::UNIT_PRESENT_MOVING || flags==PathfindCell::UNIT_GOAL_OTHER_MOVING) {unit = TheGameLogic->findObjectByID(posUnit);// order matters: we want to know if I consider it to be an ally, not vice versa- if (unit && obj->getRelationship(unit) == ALLIES) {- info.allyMoving = true;+ if (unit) {+ rel = obj->getRelationship(unit);+ if (rel == ALLIES) {+ info.allyMoving = true;+ }}if (info.considerTransient) {check = true;@@ -6618,22 +6663,17 @@ Bool Pathfinder::checkForMovement(const Object *obj, TCheckMovementInfo &info)check = true;unit = TheGameLogic->findObjectByID(posUnit);}- if (check && unit!=NULL) {- if (obj->getAIUpdateInterface() && obj->getAIUpdateInterface()->getIgnoredObstacleID()==unit->getID()) {- // Don't check if it's the ignored obstacle.- check = false;- }- }if (check && unit) {#ifdef INFANTRY_MOVES_THROUGH_INFANTRYif (obj->isKindOf(KINDOF_INFANTRY) && unit->isKindOf(KINDOF_INFANTRY)) {// Infantry can run through infantry.- continue; //+ continue; //}#endif// See if it is an ally.// order matters: we want to know if I consider it to be an ally, not vice versa- if (obj->getRelationship(unit) == ALLIES) {+ if (rel < 0) rel = obj->getRelationship(unit);+ if (rel == ALLIES) {if (!unit->getAIUpdateInterface()) {return false; // can't path through not-idle units.}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cppindex 732991951..e95f70ff3 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp@@ -1764,8 +1764,9 @@ ObjectShroudStatus PartitionData::getShroudedStatus(Int playerIndex)// answered before the cache, so no snapshot is taken and the site is not marked as seen: the// building that goes up there later is news to this player like any other. Only a plan nobody- // has started can be hidden, so the relationship lookup waits until the Object is one.- if (m_object && Object_isAwaitingBuilder(m_object->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION),+ // has started can be hidden, so the relationship lookup waits until the Object is one. The+ // status bit goes first: Object_isAwaitingBuilder is false without it, and lives in another file.+ if (m_object && m_object->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION) && Object_isAwaitingBuilder(m_object->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION),m_object->getConstructionPercent()) &&Object_isPlanHiddenFrom(m_object->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION),m_object->getConstructionPercent(),@@ -1790,9 +1791,10 @@ ObjectShroudStatus PartitionData::getShroudedStatus(Int playerIndex){if( inTheAir && coi->getCell()->isAirSeenByPlayer(playerIndex) )continue;- if( coi->getCell()->getShroudStatusForPlayer(playerIndex) == CELLSHROUD_SHROUDED )+ const CellShroudStatus cellStatus = coi->getCell()->getShroudStatusForPlayer(playerIndex);+ if( cellStatus == CELLSHROUD_SHROUDED )++shroudedCells;- else if( coi->getCell()->getShroudStatusForPlayer(playerIndex) == CELLSHROUD_FOGGED )+ else if( cellStatus == CELLSHROUD_FOGGED )++foggedCells;}@@ -2129,6 +2131,11 @@ void PartitionData::addPossibleCollisions(PartitionContactList *ctList)//DEBUG_LOG(("adding possible collision for %s\n",getObject()->getTemplate()->getName().str()));+ // collidesWith turns down any pair with a NO_COLLIDE side before it looks at anything else, so+ // such a pair is never listed: the rest keep their found order and their first orientation.+ if (m_noCollide)+ return;+CellAndObjectIntersection *myCoi = m_coiArray;for (Int i = m_coiInUseCount; i > 0; --i, ++myCoi){@@ -2139,7 +2146,7 @@ void PartitionData::addPossibleCollisions(PartitionContactList *ctList)for (CellAndObjectIntersection *coi = cell->getFirstCoiInCell(); coi; coi = coi->getNextCoi()){PartitionData *that = coi->getModule();- if (this != that)+ if (this != that && !that->m_noCollide){ctList->addToContactList(this, that);}@@ -2692,7 +2699,7 @@ void PartitionContactList::processContactList()if (cd->m_obj == NULL || cd->m_other == NULL)continue;- // we know that their partitions overlap; determine if they REALLY collide+ // we know that their partitions overlap; determine if they REALLY collide// before proceeding...CollideLocAndNormal cinfo;if (!cd->m_obj->friend_collidesWith(cd->m_other, &cinfo))@@ -2700,7 +2707,7 @@ void PartitionContactList::processContactList()Object* obj = cd->m_obj->getObject();Object* other = cd->m_other->getObject();-+if( obj->getStatusBits().test( OBJECT_STATUS_NO_COLLISIONS ) ||other->getStatusBits().test( OBJECT_STATUS_NO_COLLISIONS ) )continue;@@ -2936,7 +2943,7 @@ void PartitionManager::update()#ifdef INTENSE_DEBUGInt cc = 0;#endif- if (!m_updatedSinceLastReset)+ if (!m_updatedSinceLastReset){m_updatedSinceLastReset = true;}diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex ca26cc834..0c3480f3b 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -7684,6 +7684,73 @@ TEST(bitflags_crc_covers_every_word_of_the_flag_set)CHECK_NE( crcOfStatusMask( full ), crcOfStatusMask( fullMinusOne ) );}+/* The game's CRC as EA wrote it, byte by byte: each whole word read in network order (htonl of a+ little-endian load), the running value shifted left with its top bit added back, a 1-3 byte+ tail added as a little-endian number (htonl twice), and the result handed out through htonl.+ XferCRC folds with an inline byte swap now; every CRC a replay or a joiner checks has to stay+ exactly this. */+static void eaCRCAdd( UnsignedInt &crc, UnsignedInt val )+{+ UnsignedInt hibit = (crc & 0x80000000) ? 1 : 0;+ crc <<= 1;+ crc += val;+ crc += hibit;+}++static UnsignedInt eaCRCOfBuffers( const std::vector< std::vector<UnsignedByte> > &buffers )+{+ UnsignedInt crc = 0;+ for( size_t b = 0; b < buffers.size(); ++b )+ {+ const std::vector<UnsignedByte> &p = buffers[b];+ Int n = (Int)p.size();+ Int i = 0;+ for( ; i + 4 <= n; i += 4 )+ eaCRCAdd( crc, ((UnsignedInt)p[i] << 24) | ((UnsignedInt)p[i+1] << 16) | ((UnsignedInt)p[i+2] << 8) | p[i+3] );+ if( i < n )+ {+ UnsignedInt val = 0;+ for( Int k = 0; i + k < n; ++k )+ val += (UnsignedInt)p[i+k] << (k*8);+ eaCRCAdd( crc, val );+ }+ }+ return (crc >> 24) | ((crc >> 8) & 0xFF00) | ((crc << 8) & 0xFF0000) | (crc << 24);+}++TEST(xfer_crc_inline_byte_swap_gives_eas_htonl_numbers)+{+ // pinned by hand: word 01 02 03 04 gives 0x01020304, the tail 05 makes it 0x0204060D, swapped out+ UnsignedByte five[5] = { 1, 2, 3, 4, 5 };+ XferCRC pinned;+ pinned.open( "test" );+ pinned.xferUser( five, 5 );+ pinned.close();+ CHECK_EQ( pinned.getCRC(), 0x0D060402u );++ // random buffers of every length from 1 to 66, several to a session so the running value carries+ UnsignedInt seed = 0x2545F491u;+ for( Int round = 0; round < 300; ++round )+ {+ std::vector< std::vector<UnsignedByte> > buffers;+ XferCRC xfer;+ xfer.open( "test" );+ for( Int call = 0; call < 1 + round % 5; ++call )+ {+ std::vector<UnsignedByte> p( 1 + (round * 5 + call * 3) % 66 );+ for( size_t k = 0; k < p.size(); ++k )+ {+ seed = seed * 1664525u + 1013904223u;+ p[k] = (UnsignedByte)(seed >> 24);+ }+ xfer.xferUser( &p[0], (Int)p.size() );+ buffers.push_back( p );+ }+ xfer.close();+ CHECK_EQ( xfer.getCRC(), eaCRCOfBuffers( buffers ) );+ }+}+// A lobby or replay string carrying C=0 used to reach GameLogic's m_frame % interval and crash.extern Int NET_CRC_INTERVAL;TEST(crc_interval_is_held_between_1_and_100)