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.

fix(gamelogic): two loads of one save play out the same game

Olcay Seygan559016aeb998
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c06483ab0..d7dad1efe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -54,6 +54,7 @@ found and fixed — EA's own, not port damage.**
- Picking USA, GLA or China now opens a list of that campaign's missions, every one of them open. Pick a mission, then the difficulty, and it starts with its briefing and movie as it always did; win it and the campaign carries on to the next one. Every campaign mission starts at the same rank however you reach it, so starting at the fourth is the same game as playing through to it.
- The "Mission Start" saves the campaign makes after each victory load again, from the original game and from every earlier version of Reforged. They hold only the campaign, the mission and the difficulty, none of which the 60-step battle changed. A game saved in the middle of a mission on an earlier version still does not load, and the message that refuses it now says which saves do.
- A mission with moving water (China's third, GLA's first, America's sixth) loads from a save with its water still running and at the height the mission had raised it to. A load used to freeze the water until the next wave came through and drop it back to the level the map started at, and saving while a script was raising it tore the game down.
+- Load the same save twice and the same battle plays out both times. The dice, the paths units were waiting for and the computer players' calls to each other are saved now, so two loads no longer drift apart within a minute. A load also stopped switching a powered player's radar off, stopped forgetting which targets a mission's computer player was told to go after, and no longer counts every unit's sight twice for the first seconds. Saves from earlier versions still load; a save from this version does not load in an earlier one.
## Health bars you can read at a glance
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
index f797f5de1..bf78ae4d7 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
@@ -168,7 +168,10 @@ public:
/// given a node, append to this node
void append( PathNode *list );
-
+
+ /// Path::xfer puts back the direction and distance to the next optimized node exactly as saved
+ void friend_setNextOptimizedCache( const Coord2D &dir, Real dist ) { m_nextOptiDirNorm2D = dir; m_nextOptiDist2D = dist; }
+
public:
mutable Int m_id; // Used in Path::xfer() to save & recreate the path list.
@@ -920,6 +923,7 @@ public:
void crc( Xfer *xfer );
void xfer( Xfer *xfer );
void loadPostProcess( void );
+ void xferFlowState( Xfer *xfer ); ///< the request queue and the flow maps, which GameLogic saves after the objects
Bool clientSafeQuickDoesPathExist( const LocomotorSet& locomotorSet, const Coord3D *from, const Coord3D *to ); ///< Can we build any path at all between the locations (terrain & buildings check - fast)
Bool clientSafeQuickDoesPathExistForUI( const LocomotorSet& locomotorSet, const Coord3D *from, const Coord3D *to ); ///< Can we build any path at all between the locations (terrain onlyk - fast)
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
index a7f494d7b..3691391c1 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
@@ -569,7 +569,7 @@ protected:
void answerTeamRequests(void); ///< Air, Attacker and Rusher answer an ally's call for help
const AITeamRequest *freshRequest(AITeamRequestKind kind, UnsignedInt within) const; ///< the request of that kind posted inside within frames, NULL for none
void coopChat(const char *trigger); ///< one line to the team when answering, GUI:AICoop<trigger>
- AITeamRequest m_inbox[ AIREQ_COUNT ]; ///< the latest request of each kind from an ally; not saved
+ AITeamRequest m_inbox[ AIREQ_COUNT ]; ///< the latest request of each kind from an ally
UnsignedInt m_answeredFrame; ///< the frame of the last call answerTeamRequests answered
void shareSurplusWithAllies(Int bank, Int target); ///< Economist: who gets what out of the bank (the hook only)
AsciiString sneakyLane(const Coord3D *from, const AsciiString &requested, Int pathSuffix); ///< Sneaky: the back door or the flank
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h
index b158af141..1484984d2 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h
@@ -40,6 +40,7 @@
#include "Common/Snapshot.h"
#include "Common/STLTypedefs.h"
#include "Common/ObjectStatusTypes.h"
+#include "Common/RandomValue.h"
#include "GameNetwork/NetworkDefs.h"
#include "GameLogic/CRCSnapshotRing.h"
#include "Common/STLTypedefs.h"
@@ -313,6 +314,11 @@ public:
and carried by a save. */
Int getSupplyPileLimit( void ) const { return m_supplyPileLimit; }
+ /** A save carries the logic random stream as it stood, but the load itself draws from the stream
+ and the engine reset before it reseeded from the clock. GameState calls this after every
+ block's post-process, the last thing a load does, so play goes on from the saved stream. */
+ void restoreLoadedRandomState( void );
+
#ifdef DUMP_PERF_STATS
void getAIMetricsStatistics( UnsignedInt *numAI, UnsignedInt *numMoving, UnsignedInt *numAttacking, UnsignedInt *numWaitingForPath, UnsignedInt *overallFailedPathfinds );
void resetOverallFailedPathfinds() { m_overallFailedPathfinds = 0; }
@@ -458,6 +464,14 @@ private:
};
std::vector<PendingTechBuilding> m_pendingTechBuildings; ///< in the order they died, which every machine agrees on
void techRespawnTick( void );
+
+ /// the logic random stream a save carried, put back once the whole load is done (restoreLoadedRandomState)
+ GameLogicRandomState m_loadedRandomState;
+ Bool m_loadedRandomPending;
+
+ /// the sleepy update heap as a save wrote it, object and behavior module index per entry, for loadPostProcess
+ std::vector< std::pair< ObjectID, Int > > m_loadedSleepyOrder;
+ Bool m_loadedSleepyPending;
LoadScreen *getLoadScreen( Bool loadSaveGame );
LoadScreen *m_loadScreen;
Bool m_gamePaused;
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
index 5f021504c..c0d850f14 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
@@ -869,6 +869,7 @@ private:
// Attack Info --------------------------------------------------------------------------------------------
const AttackPriorityInfo* m_attackInfo;
+ AsciiString m_attackInfoToLoad; ///< the set a save named: the script engine that holds it loads after the objects
// "Planning Mode" -----------------------------------------------------------------------------------------
enum { MAX_WAYPOINTS = 16 };
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h
index 328977335..d79f6fa9b 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h
@@ -1313,6 +1313,7 @@ private:
PartitionCell* m_cells; ///< array of cells
PartitionData* m_dirtyModules;
Bool m_updatedSinceLastReset; ///< Used to force a return of OBJECTSHROUD_INVALID before update has been called.
+ Bool m_cellsFromSave; ///< see isKeepingCellsFromSave
std::queue<SightingInfo *> m_pendingUndoShroudReveals; ///< Anything can queue up an Undo to happen later. This is a queue, because "later" is a constant
@@ -1411,6 +1412,15 @@ public:
void processEntirePendingUndoShroudRevealQueue(); ///< process every pending one regardless of timestamp
+ /** A load of a save from version 3 on has every cell's shroud, air sight, threat and value as
+ saved, each object's last look, shroud, threat and value with them, and the undo queue. The
+ first update after it only notes the cell each object stands in: the cell change it sees for
+ every object would otherwise undo each sighting late, through the queue, and do it again at
+ once, so every looker counted twice for a few seconds and a look the save did not have was
+ added. GameState clears it again after that update. */
+ Bool isKeepingCellsFromSave( void ) const { return m_cellsFromSave; }
+ void stopKeepingCellsFromSave( void ) { m_cellsFromSave = FALSE; }
+
/// return the number of PartitionCells in the x-dimension.
Int getCellCountX() { DEBUG_ASSERTCRASH(m_cellCountX != 0, ("partition not inited")); return m_cellCountX; }
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp
index 43594f722..00601ee49 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp
@@ -3936,6 +3936,12 @@ static void doPowerDisable( Object *obj, void *userData )
//-------------------------------------------------------------------------------------------------
void Player::onPowerBrownOutChange( Bool brownOut )
{
+ // A load puts every building's power back one by one, and each step would brown the player out
+ // or in again: the radar flag and every powered object's disabled state, which the save already
+ // holds as they were, came out as the last step left them.
+ if( TheGameState->isInLoadGame() )
+ return;
+
// Everything that changes due to Player's power supply goes in here.
if( brownOut )
disableRadar();
@@ -4769,7 +4775,11 @@ void Player::xfer( Xfer *xfer )
if( xfer->getXferMode() == XFER_SAVE )
{
- for( upgrade = m_upgradeList; upgrade; upgrade = upgrade->friend_getNext() )
+ // back to front: loading prepends each one (addUpgrade), which puts them back in this order
+ Upgrade *last = m_upgradeList;
+ while( last && last->friend_getNext() )
+ last = last->friend_getNext();
+ for( upgrade = last; upgrade; upgrade = upgrade->friend_getPrev() )
{
// write upgrade name
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ResourceGatheringManager.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ResourceGatheringManager.cpp
index b48698443..b7e4f6cdc 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ResourceGatheringManager.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ResourceGatheringManager.cpp
@@ -33,6 +33,7 @@
#include "Common/ResourceGatheringManager.h"
#include "Common/ActionManager.h"
+#include "Common/GameState.h"
#include "Common/PlayerList.h"
#include "Common/Xfer.h"
#include "GameLogic/GameLogic.h"
@@ -63,9 +64,12 @@ ResourceGatheringManager::~ResourceGatheringManager()
m_supplyCenters.erase( m_supplyCenters.begin(), m_supplyCenters.end() );
}
+/* A load makes every object afresh, and a warehouse or a center registers on creation under the ID
+ newObject gave it before the save's own ID is put back. The lists were loaded already, with the
+ real IDs, so whatever registers during a load is a stale ID that a later object gets again. */
void ResourceGatheringManager::addSupplyCenter( Object *newCenter )
{
- if( newCenter == NULL )
+ if( newCenter == NULL || TheGameState->isInLoadGame() )
return;
m_supplyCenters.push_back( newCenter->getID() );
@@ -92,7 +96,7 @@ void ResourceGatheringManager::removeSupplyCenter( Object *oldCenter )
void ResourceGatheringManager::addSupplyWarehouse( Object *newWarehouse )
{
- if( newWarehouse == NULL )
+ if( newWarehouse == NULL || TheGameState->isInLoadGame() ) // see addSupplyCenter
return;
m_supplyWarehouses.push_back( newWarehouse->getID() );
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp
index 9e6091058..b1813e1f8 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp
@@ -1664,6 +1664,10 @@ void GameState::gameStatePostProcessLoad( void )
// evil... must ensure this is updated prior to the script engine running the first time.
ThePartitionManager->update();
+ ThePartitionManager->stopKeepingCellsFromSave();
+
+ // last, so nothing the load did can draw from the stream after it is put back
+ TheGameLogic->restoreLoadedRandomState();
} // end loadPostProcess
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
index f00479772..a44a08e86 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
@@ -35,6 +35,7 @@
#include "Common/PerfTimer.h"
#include "Common/Player.h"
#include "Common/CRCDebug.h"
+#include "Common/GameState.h"
#include "Common/GlobalData.h"
#include "Common/LatchRestore.h"
#include "Common/ThingTemplate.h"
@@ -397,7 +398,9 @@ void Path::xfer( Xfer *xfer )
{
// version
// 2: the cached point on the path
- XferVersion currentVersion = 2;
+ // 3: each node's direction and distance to its next optimized node, as cached. A node moved
+ // after its link was set keeps the old values, and computePointOnPath reads them.
+ XferVersion currentVersion = 3;
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
@@ -421,11 +424,16 @@ void Path::xfer( Xfer *xfer )
Bool canOpt = node->getCanOptimize();
xfer->xferBool(&canOpt);
Int id = -1;
- if (node->getNextOptimized()) {
+ Coord2D optDir;
+ Real optDist;
+ if (node->getNextOptimized(&optDir, &optDist)) {
id = node->getNextOptimized()->m_id;
}
xfer->xferInt(&id);
- count--;
+ xfer->xferReal(&optDir.x);
+ xfer->xferReal(&optDir.y);
+ xfer->xferReal(&optDist);
+ count--;
node = node->getPrevious();
}
DEBUG_ASSERTCRASH(count==0, ("Wrong data count"));
@@ -443,6 +451,13 @@ void Path::xfer( Xfer *xfer )
xfer->xferBool(&canOpt);
Int optID = -1;
xfer->xferInt(&optID);
+ Coord2D optDir = { 0.0f, 0.0f };
+ Real optDist = 0.0f;
+ if (version >= 3) {
+ xfer->xferReal(&optDir.x);
+ xfer->xferReal(&optDir.y);
+ xfer->xferReal(&optDist);
+ }
PathNode *node = newInstance(PathNode);
node->m_id = nodeId;
node->setPosition(&pos);
@@ -461,6 +476,8 @@ void Path::xfer( Xfer *xfer )
m_pathTail = node;
if (optNode) {
node->setNextOptimized(optNode);
+ if (version >= 3)
+ node->friend_setNextOptimizedCache(optDir, optDist);
}
count--;
}
@@ -469,7 +486,7 @@ void Path::xfer( Xfer *xfer )
xfer->xferBool(&m_isOptimized);
Int obsolete1 = 0;
xfer->xferInt(&obsolete1);
- UnsignedInt obsolete2;
+ UnsignedInt obsolete2 = 0; // was written uninitialised: two saves of one path differed by stack garbage
xfer->xferUnsignedInt(&obsolete2);
xfer->xferBool(&m_blockedByAlly);
@@ -6076,10 +6093,14 @@ void Pathfinder::newMap( void )
}
allocateFlowMaps();
classifyMap();
- // Add existing objects.
+ // Add existing objects. Not a plan still waiting for its builder: it goes down with the first
+ // percent of work (Object::setConstructionPercent), and a loaded game, which comes through here,
+ // walled its builder out of a site the game that was saved still walked across.
Object *obj;
for( obj = TheGameLogic->getFirstObject(); obj; obj = obj->getNextObject() )
{
+ if( Object_isAwaitingBuilder( obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ), obj->getConstructionPercent() ) )
+ continue;
classifyObjectFootprint(obj, true);
}
@@ -13236,18 +13257,57 @@ void Pathfinder::xfer( Xfer *xfer )
//-----------------------------------------------------------------------------
void Pathfinder::loadPostProcess( void )
{
- /* None of the three flow maps is saved, and only one of them needs to be. Clearance is a
- measure of the map, so it is simply recomputed from the map that has just been loaded and
- comes out identical to the one the save was taken from. Traffic and claims are a few
- seconds of history that the game rebuilds by playing: a loaded game starts with nobody
- jammed and nobody's plan on the map, and is back to the same state within a second or two.
- The cost of that is a unit or two picking a marginally different route just after a load,
- which is a single-player concern - Generals has no mid-game save in a network match, so
- there is no second machine to disagree with. */
- buildClearance();
- resetClaims();
- m_numTrafficCells = 0;
- if (m_traffic)
- memset(m_traffic, 0, (m_extent.hi.x+1)*(m_extent.hi.y+1)*sizeof(UnsignedByte));
} // end loadPostProcess
+
+//-----------------------------------------------------------------------------
+/** What the pathfinder carries from one frame to the next beyond the map itself: the queue of
+ * units waiting for a path, and the three flow maps. The map loads with the save and the objects
+ * put themselves back on it, but these are history, and a loaded game that rebuilt them from
+ * nothing chose other routes for the first seconds than the game that was saved. GameLogic
+ * writes this after the objects, since loading them touches the same maps. */
+void Pathfinder::xferFlowState( Xfer *xfer )
+{
+ xfer->xferUser( m_queuedPathfindRequests, sizeof( ObjectID ) * PATHFIND_QUEUE_LEN );
+ xfer->xferInt( &m_queuePRHead );
+ xfer->xferInt( &m_queuePRTail );
+ xfer->xferInt( &m_cumulativeCellsAllocated );
+ if( xfer->getXferMode() == XFER_LOAD )
+ {
+ // queueForPath turns away a unit already waiting by this, so it has to say who is
+ m_isQueuedForPath.assign( m_isQueuedForPath.size(), false );
+ for( Int slot = m_queuePRHead; slot != m_queuePRTail; slot = ( slot + 1 ) % PATHFIND_QUEUE_LEN )
+ {
+ const size_t id = (size_t)m_queuedPathfindRequests[ slot ];
+ if( id >= m_isQueuedForPath.size() )
+ m_isQueuedForPath.resize( id + 1024, false );
+ m_isQueuedForPath[ id ] = true;
+ }
+ }
+
+ const Int cells = (m_extent.hi.x+1) * (m_extent.hi.y+1);
+ Int savedCells = cells;
+ xfer->xferInt( &savedCells );
+ if( savedCells != cells )
+ throw SC_INVALID_DATA;
+
+ xfer->xferUser( m_clearance, cells * sizeof( UnsignedByte ) );
+ xfer->xferBool( &m_clearanceDirty );
+ xfer->xferUnsignedInt( &m_clearanceFrame );
+
+ xfer->xferUser( m_traffic, cells * sizeof( UnsignedByte ) );
+ xfer->xferInt( &m_numTrafficCells );
+ if( m_numTrafficCells < 0 || m_numTrafficCells > PF_TRAFFIC_CELLS )
+ throw SC_INVALID_DATA;
+ if( m_numTrafficCells > 0 )
+ xfer->xferUser( m_trafficCells, m_numTrafficCells * sizeof( Int ) );
+ xfer->xferUnsignedInt( &m_trafficDecayFrame );
+
+ for( Int i = 0; i < PF_CLAIM_TABLE_SIZE; ++i )
+ {
+ xfer->xferInt( &m_claims[ i ].m_cell );
+ xfer->xferUnsignedInt( &m_claims[ i ].m_bucket );
+ xfer->xferUnsignedShort( &m_claims[ i ].m_weight );
+ }
+ xfer->xferUser( m_claimTouch, cells * sizeof( UnsignedShort ) );
+}
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
index 0e825b3f8..031079257 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
@@ -16515,7 +16515,7 @@ void AIPlayer::xfer( Xfer *xfer )
{
// version
- XferVersion currentVersion = 26; // 2: scout 3: rung and role 4: scouting stamps 5: the capturer 6: parked waves 7: superweapon aims 8: the hijacker 9: tactical steps 10: the ferry and dropped riders 11: the outward placement ring 12: the pressure level 13: falling back 14: gunship Chinooks and the boarding wait 15: transport Chinooks and the lent one 16: healer and raider Helixes 17: the seen-enemy ledger 18: the fist 19: the Ambulances 20: the last Ambulance lost 21: the purchase queue's reservation 22: the measured income 23: the Ambulances bought 24: the starting fortune 25: the factory backlog clocks 26: the personality
+ XferVersion currentVersion = 27; // 2: scout 3: rung and role 4: scouting stamps 5: the capturer 6: parked waves 7: superweapon aims 8: the hijacker 9: tactical steps 10: the ferry and dropped riders 11: the outward placement ring 12: the pressure level 13: falling back 14: gunship Chinooks and the boarding wait 15: transport Chinooks and the lent one 16: healer and raider Helixes 17: the seen-enemy ledger 18: the fist 19: the Ambulances 20: the last Ambulance lost 21: the purchase queue's reservation 22: the measured income 23: the Ambulances bought 24: the starting fortune 25: the factory backlog clocks 26: the personality 27: the team request inbox
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
@@ -16954,6 +16954,19 @@ void AIPlayer::xfer( Xfer *xfer )
xfer->xferBool( &m_dozerIsRepairing );
xfer->xferInt( &m_bridgeTimer );
+ // an ally's calls for help, which an Air, Attacker or Rusher AI answers for a while after
+ if( version >= 27 )
+ {
+ for( Int k = 0; k < AIREQ_COUNT; ++k )
+ {
+ xfer->xferInt( &m_inbox[ k ].from );
+ xfer->xferInt( &m_inbox[ k ].enemy );
+ xfer->xferCoord3D( &m_inbox[ k ].pos );
+ xfer->xferUnsignedInt( &m_inbox[ k ].frame );
+ }
+ xfer->xferUnsignedInt( &m_answeredFrame );
+ }
+
} // end xfer
// ------------------------------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp
index d1b28b08b..a19215f66 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp
@@ -4438,13 +4438,14 @@ void Object::crc( Xfer *xfer )
* 9: Extra sighting for reveal to all with different range units
* 10: each player's memory of it while it is out of their sight
* 11: the cached angle, which the matrix does not give back bit for bit
+ * 12: the last threat and value sightings
*/
//-------------------------------------------------------------------------------------------------
void Object::xfer( Xfer *xfer )
{
// version
- const XferVersion currentVersion = 11;
+ const XferVersion currentVersion = 12;
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
@@ -4883,10 +4884,28 @@ void Object::xfer( Xfer *xfer )
if (version >= 5)
{
xfer->xferBool(&m_isReceivingDifficultyBonus);
- }
+ }
else
m_isReceivingDifficultyBonus = FALSE;
+ // The partition's threat and value maps are not saved, they are the sum of what every object last
+ // put on them. So each object carries its own part and puts it back, and the load no longer
+ // has every object take its old part off and add a new one where it stands (PartitionManager::xfer).
+ if (version >= 12)
+ {
+ xfer->xferSnapshot( m_partitionLastThreat );
+ xfer->xferSnapshot( m_partitionLastValue );
+ if (xfer->getXferMode() == XFER_LOAD)
+ {
+ if (!m_partitionLastThreat->isInvalid())
+ ThePartitionManager->doThreatAffect( m_partitionLastThreat->m_where.x, m_partitionLastThreat->m_where.y,
+ m_partitionLastThreat->m_howFar, m_partitionLastThreat->m_data, m_partitionLastThreat->m_forWhom );
+ if (!m_partitionLastValue->isInvalid())
+ ThePartitionManager->doValueAffect( m_partitionLastValue->m_where.x, m_partitionLastValue->m_where.y,
+ m_partitionLastValue->m_howFar, m_partitionLastValue->m_data, m_partitionLastValue->m_forWhom );
+ }
+ }
+
} // end xfer
//-------------------------------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
index 255b992ad..50645d1fa 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
@@ -2276,10 +2276,11 @@ void PartitionData::updateCellsTouched()
const PartitionCell *currentCell = ThePartitionManager->getCellAt( currentCellIndexX, currentCellIndexY );
if(obj && currentCell != m_lastCell )
{
- // To not expose PartitionCells, he will think in terms of points. He will
- // unlook at a point and look at the new point. We do the rounding and the
+ // To not expose PartitionCells, he will think in terms of points. He will
+ // unlook at a point and look at the new point. We do the rounding and the
// changing into PartitionCells
- obj->onPartitionCellChange();
+ if( !ThePartitionManager->isKeepingCellsFromSave() )
+ obj->onPartitionCellChange();
m_lastCell = currentCell;
}
@@ -2770,6 +2771,7 @@ PartitionManager::PartitionManager()
m_worldExtents.hi.zero();
m_dirtyModules = NULL;
m_updatedSinceLastReset = false;
+ m_cellsFromSave = FALSE;
#ifdef FASTER_GCO
m_maxGcoRadius = 0;
#endif
@@ -2899,6 +2901,7 @@ void PartitionManager::reset()
void PartitionManager::shutdown()
{
m_updatedSinceLastReset = false;
+ m_cellsFromSave = FALSE;
ThePartitionManager->removeAllDirtyModules();
#ifdef _DEBUG
@@ -2970,19 +2973,22 @@ void PartitionManager::update()
dirty->friend_updateCellsTouched();
}
- if (collideEm && !dirty->getObject()->isKindOf(KINDOF_IMMOBILE))
+ // the update a load ends with only puts every object back in its cells: the collisions
+ // and the queued unlooks were the saved frame's, and the next frame does its own
+ if (collideEm && !dirty->getObject()->isKindOf(KINDOF_IMMOBILE) && !m_cellsFromSave)
{
dirty->addPossibleCollisions(&ctList);
}
}
-
+
ctList.processContactList();
#ifdef INTENSE_DEBUG
DEBUG_ASSERTLOG(cc==0,("updated partition info for %d objects\n",cc));
#endif
TheContactList = NULL;
- processPendingUndoShroudRevealQueue();
+ if (!m_cellsFromSave)
+ processPendingUndoShroudRevealQueue();
}
#if defined(_DEBUG) || defined(_INTERNAL)
@@ -5175,16 +5181,21 @@ void PartitionManager::crc( Xfer *xfer )
* Version Info:
* 1: Initial version
* 2: m_pendingUndoShroudReveals stores Unlooks waiting to happen.
+ * 3: the cells are kept as saved through the update that ends the load
*/
// ------------------------------------------------------------------------------------------------
void PartitionManager::xfer( Xfer *xfer )
{
// version
- XferVersion currentVersion = 2;
+ XferVersion currentVersion = 3;
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
+ // version 3 writes nothing new: it says the objects carry their threat and value (Object 12)
+ if( xfer->getXferMode() == XFER_LOAD )
+ m_cellsFromSave = version >= 3;
+
// cell size information
Real cellSize = m_cellSize;
xfer->xferReal( &cellSize );
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
index f0fed2ef5..77ed56d9e 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
@@ -7539,11 +7539,7 @@ void AIUpdateInterface::xfer( Xfer *xfer )
if (m_attackInfo) attackName = m_attackInfo->getName();
xfer->xferAsciiString(&attackName);
if (xfer->getXferMode() == XFER_LOAD)
- {
- if (attackName.isNotEmpty()) {
- m_attackInfo = TheScriptEngine->getAttackInfo(attackName);
- }
- }
+ m_attackInfoToLoad = attackName; // looked up in loadPostProcess, once the script engine has its sets back
xfer->xferInt(&m_waypointCount);
if (m_waypointCount<0 || m_waypointCount>MAX_WAYPOINTS) {
@@ -7853,7 +7849,13 @@ void AIUpdateInterface::loadPostProcess( void )
{
UpdateModule::loadPostProcess();
- if (m_fixLocoInPostProcess && m_curLocomotorSet!=LOCOMOTORSET_INVALID)
+ if (m_attackInfoToLoad.isNotEmpty())
+ {
+ m_attackInfo = TheScriptEngine->getAttackInfo(m_attackInfoToLoad);
+ m_attackInfoToLoad.clear();
+ }
+
+ if (m_fixLocoInPostProcess && m_curLocomotorSet!=LOCOMOTORSET_INVALID)
{
m_fixLocoInPostProcess = FALSE;
@@ -7874,18 +7876,21 @@ void AIUpdateInterface::loadPostProcess( void )
TheAI->pathfinder()->updatePos(getObject(), getObject()->getPosition());
} else {
if (m_pathfindGoalCell.x >= 0 && m_pathfindGoalCell.y >= 0) {
+ // a quarter cell in: updateGoal floors the position for a unit that centres in a cell and
+ // rounds it for one that does not, and from the middle of the cell rounding went one over
Coord3D goalPos;
- goalPos.x = m_pathfindGoalCell.x * PATHFIND_CELL_SIZE_F + PATHFIND_CELL_SIZE_F*0.5f;
- goalPos.y = m_pathfindGoalCell.y * PATHFIND_CELL_SIZE_F + PATHFIND_CELL_SIZE_F*0.5f;
+ goalPos.x = m_pathfindGoalCell.x * PATHFIND_CELL_SIZE_F + PATHFIND_CELL_SIZE_F*0.25f;
+ goalPos.y = m_pathfindGoalCell.y * PATHFIND_CELL_SIZE_F + PATHFIND_CELL_SIZE_F*0.25f;
m_pathfindGoalCell.x = -1;
m_pathfindGoalCell.y = -1;
TheAI->pathfinder()->updateGoal(getObject(), &goalPos, getObject()->getLayer());
}
}
- // The pathfinder's queue is not saved, so a unit that was in it when the game was saved comes
- // back waiting for a path nobody is going to look for, and stands for the rest of the match.
- // One waiting on the retry timer is asked for again by update() and needs nothing here.
+ // A save before GameLogic 18 has no pathfinder queue, so a unit that was in it when the game was
+ // saved comes back waiting for a path nobody is going to look for, and stands for the rest of the
+ // match. From 18 on it is still in the queue and queueForPath turns it away. One waiting on the
+ // retry timer is asked for again by update() and needs nothing here.
if (m_waitingForPath && m_queueForPathFrame == 0)
queueForPathOrRetry();
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
index eb48296d4..4bbb8158e 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
@@ -268,6 +268,8 @@ GameLogic::GameLogic( void )
m_incomeSharing = INCOME_SHARING_OFF;
m_techRespawnDelay = 0;
m_supplyPileLimit = 0;
+ m_loadedRandomPending = FALSE;
+ m_loadedSleepyPending = FALSE;
m_gamePaused = FALSE;
m_inputEnabledMemory = TRUE;
m_mouseVisibleMemory = TRUE;
@@ -459,6 +461,11 @@ void GameLogic::reset( void )
m_thingTemplateBuildableOverrides.clear();
m_controlBarOverrides.clear();
+ // a load that failed part way must not hand its stream or heap order to the next one
+ m_loadedRandomPending = FALSE;
+ m_loadedSleepyPending = FALSE;
+ m_loadedSleepyOrder.clear();
+
// set the hash to be rather large. We need to optimize this value later.
// m_objHash.clear();
// m_objHash.resize(OBJ_HASH_SIZE);
@@ -5974,13 +5981,14 @@ void GameLogic::prepareLogicForObjectLoad( void )
* 15: xfer m_incomeSharing
* 16: xfer m_techRespawnDelay and m_pendingTechBuildings
* 17: xfer m_supplyPileLimit
+ * 18: xfer the logic random stream and the pathfinder's request queue and flow maps
*/
// ------------------------------------------------------------------------------------------------
void GameLogic::xfer( Xfer *xfer )
{
// version
- const XferVersion currentVersion = 17;
+ const XferVersion currentVersion = 18;
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
@@ -6404,8 +6412,67 @@ void GameLogic::xfer( Xfer *xfer )
{
m_supplyPileLimit = 0;
}
+
+ // Without the stream two loads of one save go on differently: the engine reset before the load
+ // seeded it from the clock. A save older than 18 keeps that.
+ if ( version >= 18 )
+ {
+ GameLogicRandomState state = GetGameLogicRandomState();
+ for ( Int i = 0; i < 6; ++i )
+ xfer->xferUnsignedInt( &state.seed[ i ] );
+ xfer->xferUnsignedInt( &state.baseSeed );
+ if ( xfer->getXferMode() == XFER_LOAD )
+ {
+ m_loadedRandomState = state;
+ m_loadedRandomPending = TRUE;
+ }
+
+ TheAI->pathfinder()->xferFlowState( xfer );
+
+ // The sleepy update heap as it stands. Modules due on the same frame and phase run in the order
+ // the heap gives them up, which depends on how it was built; a heap rebuilt from the object list
+ // on load runs them in another order than the game that was saved.
+ UnsignedInt sleepyCount = (UnsignedInt)m_sleepyUpdates.size();
+ xfer->xferUnsignedInt( &sleepyCount );
+ if ( xfer->getXferMode() == XFER_SAVE )
+ {
+ std::map< UpdateModulePtr, std::pair< ObjectID, Int > > where;
+ for ( Object *owner = getFirstObject(); owner; owner = owner->getNextObject() )
+ {
+ Int moduleIndex = 0;
+ for ( BehaviorModule **b = owner->getBehaviorModules(); *b; ++b, ++moduleIndex )
+ if ( (*b)->getUpdate() )
+ where[ (UpdateModulePtr)( (*b)->getUpdate() ) ] = std::make_pair( owner->getID(), moduleIndex );
+ }
+ for ( UnsignedInt i = 0; i < sleepyCount; ++i )
+ {
+ std::pair< ObjectID, Int > entry = where[ m_sleepyUpdates[ i ].module ];
+ xfer->xferObjectID( &entry.first );
+ xfer->xferInt( &entry.second );
+ }
+ }
+ else
+ {
+ m_loadedSleepyOrder.resize( sleepyCount );
+ for ( UnsignedInt i = 0; i < sleepyCount; ++i )
+ {
+ xfer->xferObjectID( &m_loadedSleepyOrder[ i ].first );
+ xfer->xferInt( &m_loadedSleepyOrder[ i ].second );
+ }
+ m_loadedSleepyPending = TRUE;
+ }
+ }
} // end xfer
+// ------------------------------------------------------------------------------------------------
+void GameLogic::restoreLoadedRandomState( void )
+{
+ if ( !m_loadedRandomPending )
+ return;
+ SetGameLogicRandomState( m_loadedRandomState );
+ m_loadedRandomPending = FALSE;
+}
+
// ------------------------------------------------------------------------------------------------
/** Load post process entry point */
// ------------------------------------------------------------------------------------------------
@@ -6440,6 +6507,24 @@ void GameLogic::loadPostProcess( void )
now = 1;
#endif
+ // a save from version 18 on gives the heap entry by entry, which is a heap already
+ const Bool sleepyFromSave = m_loadedSleepyPending;
+ if( sleepyFromSave )
+ {
+ for( std::vector< std::pair< ObjectID, Int > >::const_iterator it = m_loadedSleepyOrder.begin(); it != m_loadedSleepyOrder.end(); ++it )
+ {
+ Object *owner = findObjectByID( it->first );
+ if( owner == NULL )
+ throw SC_INVALID_DATA;
+ UpdateModulePtr u = (UpdateModulePtr)( owner->getBehaviorModules()[ it->second ]->getUpdate() );
+ SleepyEntry e = { u->friend_getPriority(), u };
+ m_sleepyUpdates.push_back( e );
+ u->friend_setIndexInLogic( m_sleepyUpdates.size() - 1 );
+ }
+ m_loadedSleepyOrder.clear();
+ m_loadedSleepyPending = FALSE;
+ }
+
// go through all objects, examine each update module and put it on the appropriate update list
for( obj = getFirstObject(); obj; obj = obj->getNextObject() )
{
@@ -6455,7 +6540,11 @@ void GameLogic::loadPostProcess( void )
#endif
if (!u)
continue;
-
+
+ // already on the heap the save gave
+ if (sleepyFromSave && u->friend_getIndexInLogic() != -1)
+ continue;
+
DEBUG_ASSERTCRASH(u->friend_getIndexInLogic() == -1, ("Hmm, expected index to be -1 here"));
// check each update module
@@ -6473,17 +6562,23 @@ void GameLogic::loadPostProcess( void )
u->friend_setNextCallFrame(now);
#endif
{
+ if (sleepyFromSave)
+ {
+ pushSleepyUpdate(u);
+ continue;
+ }
SleepyEntry e = { u->friend_getPriority(), u };
m_sleepyUpdates.push_back(e);
u->friend_setIndexInLogic(m_sleepyUpdates.size() - 1);
}
-
+
} // end for, u
} // end for, obj
// re-sort the priority queue all at once now that all modules are on it
- remakeSleepyUpdate();
+ if (!sleepyFromSave)
+ remakeSleepyUpdate();
} // end loadPostProcess