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(gamelogic): plug pathfinder record leaks and log slow logic frames
Olcay Seygan21d3791aa0b2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1663e6699..1eeb1ed44 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,6 +25,12 @@ explosion flashes, tree sway, water, menu transitions, camera drift, screen fadeand all of it starts racing. Each one now has a clock of its own, so **you get a smooth, modernpicture and the game still plays like Zero Hour**.+Two more that only show up once the picture is fast: the subtitles under the mission briefings and+cutscenes used to hold each line for a number of frames rather than for a length of time, so on a+modern machine they flicked past faster than anyone reads. And the red pulse the radar gives you when+your base is being attacked was counting frames too — it strobed instead of throbbing, and it timed+itself out early. Both run on the clock now.+The surf on the beach behind the main menu is the clearest example of how deep this went. Theoriginal code measured how much real time had passed, and then ignored the answer and moved everywave forward by a thirty-third of a second — correct, and only correct, while the picture was pinned@@ -49,6 +55,11 @@ Fixed. And with it:a second of damage, in a check meant to cover ten seconds.- One AI decision was made from leftover memory, so **two identical matches did not play outidentically** — the same class of fault that desyncs a multiplayer game.+- **The difficulty settings for build speed did nothing.** Every build order the AI placed was+ pinned to the same three-second wait, whatever the map, the difficulty or the AI's own money.+ Those numbers are read again: a rich AI presses its advantage, a broke one slows down, and a+ mission script that asks for a thirty-second pause between buildings finally gets one. The+ average pace is unchanged, so a skirmish still feels like Zero Hour.## Attack-move actually attacks@@ -122,6 +133,20 @@ Around it, the whole production loop got tightened:every barracks you own and the upgrade button used to grey out the moment the first one in thegroup had bought it, leaving you to hunt the rest down one at a time. The button now lights if*any* of them can still buy it, and the click goes to one that can.+- **One right click cancels one thing.** Cancelling a queued unit or upgrade used to take three or+ four tries: the click was only counted if the mouse had not drifted a single pixel off the+ picture between pressing and releasing. It counts the moment you press now. And the upgrade being+ researched — the one thing you most want to take back — was the one button that refused+ clicks at all while it was running.+- **Buy an upgrade for a group and it spreads.** Select four barracks, click the upgrade, and all+ four start it, as far as your money goes. It used to buy exactly one and quietly throw the other+ three clicks away.+- **The progress clock stopped flickering.** The filling circle over a picture was drawn once per+ game tick but the picture is redrawn far more often than that, so most frames showed no progress+ at all and the whole thing strobed. It is steady at any frame rate now.+- **A group's upgrade shows its progress.** With several buildings selected, the one actually paying+ for the upgrade is rarely the one the command bar happens to be reading, so the button showed+ nothing while the research ran.- **Select several factories, click a unit, and it goes to whichever has the shortest queue.**Shift-click queues five, spread the same way.- **The nearest free worker takes a new job** — and a worker already halfway through a building does@@ -140,6 +165,22 @@ Around it, the whole production loop got tightened:- **Aircraft always show how many attack runs they have left**, selected or not. That is the numberthat decides whether you commit them or send them home.+**Placing buildings.** The grid you place on is drawn on the ground now instead of over the top of+everything — it follows the slope, your units and buildings stand on it rather than under it, and+ground you cannot build on is a soft red wash instead of a scribble. Three more:++- **Running out of money no longer strands the building you were placing.** Shift-hold a row of+ bunkers, run dry halfway, and the ghost used to freeze on the map: it could not be placed, could+ not be turned, and the click that failed went through to the ground as a move order for whatever+ you had selected. Now it simply keeps following the cursor until the money comes in.+- **The range ring appears for GLA defences too.** A stinger site has no gun of its own — it keeps+ three soldiers alive beside it and they carry the missiles — so the game called it unarmed and+ drew nothing while you sited it. The faction whose defences most need placing was the one faction+ that got no help placing them.+- **A click clears a half-typed building shortcut.** With the structure grid armed and waiting for+ its second key, a click could leave it armed, and the next A or S you pressed became a building to+ place instead of an attack-move or a stop — which cancelled your selection.+**Health bars are in the owner's colour.** They used to run green to red by how damaged somethingwas — which is what the length of the bar was already telling you — and told you nothing about whoseit was. In the middle of a fight that is the question you actually have. They now match the colour@@ -328,6 +369,24 @@ looks right to you.- The window used to go grey and *Not Responding* during the scripted camera moves on the menu.- Half a dozen rarer crashes in combat — poison clouds, mine clearing, killing a garrisoned building,crew-killing weapons — all traced and fixed.+- **Blowing up a full transport was a coin flip.** Kill a Technical, a Battle Bus or a tunnel with+ Terrorists inside and the passengers explode, and their explosion kills the vehicle that is+ already in the middle of killing them. The game was walking a list of passengers that the second+ death had just thrown away. EA patched two versions of this by hand in 2003, one per patch, as+ players kept finding new ways to trigger it; every remaining version is closed now. Neutron+ Shells on a loaded Technical, a bunker buster on a tunnel network, a half-damaged Battle Bus —+ all survivable.+- **A unit could be loaded into a vehicle that no longer exists**, or a vehicle destroyed on the+ same frame could still spawn its crew. Both left something in the game holding a pointer to a+ corpse.+- **A unit that killed itself took the game with it, sometimes.** Every unit runs on a little+ machine that decides what it is doing this instant — and that machine belongs to the unit. A+ Terrorist reaching a truck, a suicide bomber, anything that dies to its own attack, destroyed the+ machine in the middle of the machine's own turn, and the next few instructions were reading a unit+ that had already been cleared away. It survives its own death now and finishes the turn properly.+- **Ordering a Jarmen Kell to snipe an empty bike** — one whose rider you already shot — was a+ crash rather than a refusal. So was a formation move that included something which cannot drive+ itself, and telling a hacker to step out of the way at the exact moment it stood up.And when something does go wrong, it now writes a readable crash report instead of the windowsilently vanishing.@@ -347,6 +406,25 @@ Measured on a real map, a destination 23 cells away across a ridge:**Ten times faster.** That is what removes the hitch when you send a large army somewhere far.+The pathfinder has a fixed number of scratch records to search with, and three separate faults were+handing them out and never taking them back:++- **Every wall, fence and building on the map permanently held one.** They were being used to+ remember which structure sits on a cell — something that has nothing to do with searching. Build+ up a base over half an hour and the search runs out of room to think in, and units simply stop+ taking orders. That state now lives on the map cell itself, where it belongs, and the search keeps+ everything it started with. The same fault had a second face: with the records gone, a finished+ building could end up standing on ground the game still believed was clear.+- **Every abandoned search leaked one**, and an abandoned search is the normal case — a blocked+ route, an unreachable target, a unit that gets a new order mid-move.+- **A recycled record could still point at the last unit that used it**, which is how a unit+ occasionally set off along someone else's route.++Two more long-standing ones from the same pass: a single unit told to move no longer gets nudged to+the middle of the nearest square — a lone Chinook lands where you clicked, while a group still gets+the tidy formation. And a footprint change around a structure could permanently mark the ground+beside it as unbuildable and unwalkable, for the rest of the match.+## Sound, video, and getting it to start at all- **Audio is real**, through the game's own audio library. The sound SDK was stripped from the sourcediff --git a/GeneralsMD/Code/GameEngine/Include/Common/StateMachine.h b/GeneralsMD/Code/GameEngine/Include/Common/StateMachine.hindex 403c1540b..e95de4b66 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/StateMachine.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/StateMachine.h@@ -37,6 +37,8 @@#include "Common/Snapshot.h"#include "Common/Xfer.h"+#include "refcount.h"+//-----------------------------------------------------------------------------//-----------------------------------------------------------------------------//-----------------------------------------------------------------------------@@ -237,7 +239,7 @@ inline State::~State() { }/*** A finite state machine.*/-class StateMachine : public MemoryPoolObject, public Snapshot+class StateMachine : public MemoryPoolObject, public Snapshot, public RefCountClass{MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( StateMachine, "StateMachinePool" );@@ -342,6 +344,24 @@ protected:virtual void xfer( Xfer *xfer );virtual void loadPostProcess();+public:+ /**+ The machine is reference counted, so that it can survive its own owner being destroyed+ while one of its states is updating (see updateStateMachine). deleteInstance() is the+ only way this class was ever destroyed, so it becomes "drop the owner's reference"+ instead, and the pooled memory is handed back from Delete_This when the last one goes.+ */+ void deleteInstance()+ {+ if (this)+ Release_Ref();+ }++ virtual void Delete_This()+ {+ MemoryPoolObject::deleteInstance();+ }+protected:/**diff --git a/GeneralsMD/Code/GameEngine/Include/Common/TunnelTracker.h b/GeneralsMD/Code/GameEngine/Include/Common/TunnelTracker.hindex cde04a1f8..f16b790e5 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/TunnelTracker.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/TunnelTracker.h@@ -49,6 +49,7 @@ public:UnsignedInt getContainCount() const { return m_containListSize; }Int getContainMax() const;const ContainedItemsList* getContainedItemsList() const { return &m_containList; }+ void swapContainedItemsList( ContainedItemsList& newList );Bool isValidContainerFor(const Object* obj, Bool checkCapacity) const;void addToContainList( Object *obj ); ///< add 'obj' to contain listdiff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.hindex 9fbd8094f..596024607 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h@@ -250,6 +250,13 @@ public:virtual void update( void ); ///< do one frame of AI computationinline Pathfinder *pathfinder( void ) { return m_pathfinder; } ///< public access to the pathfind system++ /** How long the last AI frame spent in the pathfinder's queue and in the players' own updates,+ * in milliseconds. GameLogic's slow frame log reads these: with several AI players a hitch is+ * either pathfinding or the AIs themselves, and guessing which has been the expensive way to+ * find out. */+ static Real getLastPathfindMS( void ) { return s_lastPathfindMS; }+ static Real getLastPlayerUpdateMS( void ) { return s_lastPlayerUpdateMS; }enum{CAN_SEE = 1 << 0,@@ -280,6 +287,9 @@ public:enum FormationID getNextFormationID(void);static void parseAiDataDefinition( INI* ini );++ static Real s_lastPathfindMS; ///< see getLastPathfindMS+ static Real s_lastPlayerUpdateMS; ///< see getLastPlayerUpdateMSconst TAiData *getAiData() {return m_aiData;}// Note: Does not work for things that do not have AI. (This is in AI.h, after all)diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.hindex 0e0ba0afe..f5bbd3bbe 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h@@ -239,12 +239,7 @@ protected:ObjectID m_posUnitID; ///< The objectID of the ground unit that is occupying this cell.ObjectID m_goalAircraftID; ///< The objectID of the aircraft whose goal this is.- ObjectID m_obstacleID; ///< the object ID who overlaps this cell-UnsignedInt m_isFree:1;- UnsignedInt m_blockedByAlly:1;///< True if this cell is blocked by an allied unit.- UnsignedInt m_obstacleIsFence:1;///< True if occupied by a fence.- UnsignedInt m_obstacleIsTransparent:1;///< True if obstacle is transparent (undefined if obstacleid is invalid)/// @todo Do we need both mark values in this cell? Can't store a single value and compare it?UnsignedInt m_open:1; ///< place for marking this cell as on the open listUnsignedInt m_closed:1; ///< place for marking this cell as on the closed list@@ -295,9 +290,9 @@ public:Bool isObstaclePresent( ObjectID objID ) const; ///< return true if the given object ID is registered as an obstacle in this cell- Bool isObstacleTransparent( ) const{return m_info?m_info->m_obstacleIsTransparent:false; } ///< return true if the obstacle in the cell is KINDOF_CAN_SEE_THROUGHT_STRUCTURE+ Bool isObstacleTransparent( ) const{return m_obstacleIsTransparent; } ///< return true if the obstacle in the cell is KINDOF_CAN_SEE_THROUGHT_STRUCTURE- Bool isObstacleFence( void ) const {return m_info?m_info->m_obstacleIsFence:false; }///< return true if the given obstacle in the cell is a fence.+ Bool isObstacleFence( void ) const {return m_obstacleIsFence; }///< return true if the given obstacle in the cell is a fence./// Return estimated cost from given cell to reach goal cellUnsignedInt costToGoal( PathfindCell *goal );@@ -329,8 +324,8 @@ public:inline UnsignedShort getXIndex(void) const {return m_info->m_pos.x;}inline UnsignedShort getYIndex(void) const {return m_info->m_pos.y;}- inline Bool isBlockedByAlly(void) const {return m_info->m_blockedByAlly;}- inline void setBlockedByAlly(Bool blocked) {m_info->m_blockedByAlly = (blocked!=0);}+ inline Bool isBlockedByAlly(void) const {return m_blockedByAlly;}+ inline void setBlockedByAlly(Bool blocked) {m_blockedByAlly = (blocked!=0);}inline Bool getOpen(void) const {return m_info->m_open;}inline Bool getClosed(void) const {return m_info->m_closed;}@@ -361,7 +356,7 @@ public:inline ObjectID getGoalAircraft(void) const {ObjectID id = m_info?m_info->m_goalAircraftID:INVALID_ID; return id;}inline ObjectID getPosUnit(void) const {ObjectID id = m_info?m_info->m_posUnitID:INVALID_ID; return id;}- inline ObjectID getObstacleID(void) const {ObjectID id = m_info?m_info->m_obstacleID:INVALID_ID; return id;}+ inline ObjectID getObstacleID(void) const {return m_obstacleID;}void setLayer( PathfindLayerEnum layer ) { m_layer = layer; } ///< set the cell layerPathfindLayerEnum getLayer( void ) const { return (PathfindLayerEnum)m_layer; } ///< get the cell layer@@ -371,6 +366,17 @@ public:private:PathfindCellInfo *m_info;+ //+ // A cell that holds an obstacle used to keep a pooled PathfindCellInfo alive for as long as+ // the obstacle stood there, and releaseInfo() refuses to reclaim an obstacle cell - so every+ // wall, fence and building on the map permanently ate records the A* search needs. The four+ // fields below are what the record was being held open for, so they live here instead and+ // the pool is left to the search.+ //+ ObjectID m_obstacleID; ///< the object ID who overlaps this cell+ UnsignedInt m_blockedByAlly:1; ///< True if this cell is blocked by an allied unit.+ UnsignedInt m_obstacleIsFence:1; ///< True if occupied by a fence.+ UnsignedInt m_obstacleIsTransparent:1;///< True if obstacle is transparent (undefined if obstacleid is invalid)zoneStorageType m_zone:14; ///< Zone. Each zone is a set of adjacent terrain type. If from & to in the same zone, you can successfully pathfind. If not,// you still may be able to if you can cross multiple terrain types.UnsignedShort m_aircraftGoal:1; //< This is an aircraft goal cell.@@ -989,8 +995,7 @@ inline Bool PathfindCell::isObstaclePresent( ObjectID objID ) const{if (objID != INVALID_ID && (getType() == PathfindCell::CELL_OBSTACLE)){- DEBUG_ASSERTCRASH(m_info, ("Should have info to be obstacle."));- return (m_info && m_info->m_obstacleID == objID);+ return (m_obstacleID == objID);}return false;diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.hindex 5c433a614..d42f00ac3 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h@@ -37,6 +37,8 @@enum { INVALID_SKILLSET_SELECTION = -1 };class BuildListInfo;+// this header used to compile only behind whoever happened to include Team.h first+class TeamPrototype;/*** When a team is selected for training, a list of these@@ -245,6 +247,22 @@ protected:MAKE_DLINK_HEAD(TeamInQueue, TeamReadyQueue); ///< List of teams built, waiting to reach rally point.protected:+ Int computeStructureDelay( void ); ///< frames to wait before trying the next structure+ Int computeTeamDelay( void ); ///< frames to wait before trying the next team++public:+ /// the arithmetic behind the two above, free of the Player so a test can reach it+ static Int computeBuildDelay( Real seconds, Int money, Int poorAt, Int wealthyAt,+ Real poorMod, Real wealthyMod, Real rateScale );+protected:++ /**+ How much faster than the AIData delays this AI works. 1 = exactly as the data says.+ The skirmish AI overrides it: it is meant to react faster than a scripted campaign AI,+ and used to get that by clamping its own timers, which threw the data away.+ */+ virtual Real getBuildRateScale( void ) { return 1.0f; }+Bool isPossibleToBuildTeam( TeamPrototype *proto, Bool requireIdleFactory, Bool &needMoney ); ///< return true if team can be considered for buildingObject *buildStructureNow(const ThingTemplate *bldgPlan, BuildListInfo *info ); ///< Build a base buiding.Object *buildStructureWithDozer(const ThingTemplate *bldgPlan, BuildListInfo *info ); ///< Build a base buiding.diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AISkirmishPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AISkirmishPlayer.hindex 3f93cc973..3d7277f8e 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AISkirmishPlayer.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AISkirmishPlayer.h@@ -82,6 +82,7 @@ protected:virtual void xfer( Xfer *xfer );virtual void loadPostProcess( void );+ virtual Real getBuildRateScale( void );virtual void doBaseBuilding(void);virtual void checkReadyTeams(void);virtual void checkQueuedTeams(void);diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/TunnelContain.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/TunnelContain.hindex cdb15252b..81753edcf 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/TunnelContain.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/TunnelContain.h@@ -40,6 +40,7 @@#include "GameLogic/Module/CreateModule.h"#include "Common/GameMemory.h"class Team;+class TunnelTracker;//-------------------------------------------------------------------------------------------------class TunnelContainModuleData : public OpenContainModuleData@@ -102,6 +103,9 @@ public:virtual void onSelling();///< Container is being sold. Tunnel responds by kicking people out if this is the last tunnel.virtual void onCapture( Player *oldOwner, Player *newOwner ); // Need to change who we are registered with.+ virtual void orderAllPassengersToExit( CommandSourceType commandSource, Bool instantly );+ virtual void orderAllPassengersToIdle( CommandSourceType commandSource );+virtual Bool isValidContainerFor(const Object* obj, Bool checkCapacity) const;virtual void addToContainList( Object *obj ); ///< The part of AddToContain that inheritors can override (Can't do whole thing because of all the private stuff involved)virtual void removeFromContain( Object *obj, Bool exposeStealthUnits = FALSE ); ///< remove 'obj' from contain list@@ -131,6 +135,14 @@ public:protected:+ //+ // A tunnel keeps nothing of its own - the whole contain list belongs to the owning player's+ // TunnelTracker, and a Player that has been init'ed but not yet handed a dict does not have one+ // (Player::init leaves it NULL, Player::initFromDict allocates it). Every path below that+ // reaches for the tracker goes through this.+ //+ TunnelTracker *getTunnelTracker( void ) const;+void scatterToNearbyPosition(Object* obj);Bool m_needToRunOnBuildComplete;Bool m_isCurrentlyRegistered; ///< Keeps track if this is registered with the player, so we don't double remove and mess updiff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cppindex eb27ba747..3c89d8a0b 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp@@ -1436,6 +1436,16 @@ Bool ActionManager::canSnipeVehicle( const Object *obj, const Object *objectToSnreturn FALSE;}+ //+ // A bike whose rider was already sniped or dismounted is not marked unmanned, but there is+ // nobody left on it to shoot.+ //+ ContainModuleInterface *contain = objectToSnipe->getContain();+ if( contain && contain->isRiderChangeContain() && contain->getContainedItemsList()->empty() )+ {+ return FALSE;+ }+return TRUE;}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Energy.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Energy.cppindex 53ec36292..f09022e75 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Energy.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Energy.cpp@@ -193,6 +193,14 @@ void Energy::addPowerBonus( Object *obj )if( obj == NULL )return;+ //+ // The mirror of removePowerBonus: a disabled producer contributes nothing, and the bonus of an+ // upgrade completed while it is disabled is added by onDisabledEdge when it comes back. Adding+ // it here as well counts it twice.+ //+ if( obj->isDisabled() )+ return;+addProduction(obj->getTemplate()->getEnergyBonus());// sanity@@ -212,6 +220,14 @@ void Energy::removePowerBonus( Object *obj )if( obj == NULL )return;+ //+ // A disabled producer contributes nothing: onDisabledEdge already took its production and its+ // bonus out of the pool. Taking the bonus away a second time here drives the pool below what+ // the player actually has and fakes a brownout.+ //+ if( obj->isDisabled() )+ return;+addProduction( -obj->getTemplate()->getEnergyBonus() );// sanitydiff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/TunnelTracker.cppindex 1a4a21415..05b392be2 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp@@ -107,6 +107,13 @@ Int TunnelTracker::getContainMax() constreturn TheGlobalData->m_maxTunnelCapacity;}+// ------------------------------------------------------------------------+void TunnelTracker::swapContainedItemsList( ContainedItemsList& newList )+{+ m_containList.swap( newList );+ m_containListSize = (Int)m_containList.size();+}+// ------------------------------------------------------------------------void TunnelTracker::updateNemesis(const Object *target){diff --git a/GeneralsMD/Code/GameEngine/Source/Common/StateMachine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/StateMachine.cppindex 17b631fb9..8ae0b7f86 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/StateMachine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/StateMachine.cpp@@ -412,6 +412,19 @@ StateReturnType StateMachine::resetToDefaultState()}+//-----------------------------------------------------------------------------+/**+ * Holds a reference on a state machine for the length of a scope.+ */+class StateMachineRefHolder+{+public:+ StateMachineRefHolder( StateMachine *machine ) : m_machine(machine) { m_machine->Add_Ref(); }+ ~StateMachineRefHolder() { m_machine->Release_Ref(); }+private:+ StateMachine *m_machine;+};+//-----------------------------------------------------------------------------/*** Run one step of the machine@@ -433,6 +446,11 @@ StateReturnType StateMachine::updateStateMachine()if (m_currentState){+ // The state update below can destroy this machine's owner - a state that kills its own+ // object, for instance - which drops the owner's reference to us. Hold one of our own+ // for the rest of this function so the machine outlives the update that ended it.+ StateMachineRefHolder refThis( this );+// update() can change m_currentState, so save it for a moment...State* stateBeforeUpdate = m_currentState;diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cppindex 353b29792..4fcf36feb 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp@@ -353,16 +353,38 @@ void AI::reset( void )/*** Update the AI system*/+Real AI::s_lastPathfindMS = 0.0f;+Real AI::s_lastPlayerUpdateMS = 0.0f;++/** Milliseconds between two performance counter readings. */+static Real aiElapsedMS( const Int64 &from, const Int64 &to )+{+ static Int64 freq = 0;+ if( freq == 0 )+ QueryPerformanceFrequency( (LARGE_INTEGER *)&freq );+ if( freq == 0 )+ return 0.0f;+ return (Real)( (double)(to - from) * 1000.0 / (double)freq );+}+void AI::update( void ){+ Int64 start, afterPathfind, end;+ QueryPerformanceCounter( (LARGE_INTEGER *)&start );+// Do pathfinding.m_pathfinder->processPathfindQueue();+ QueryPerformanceCounter( (LARGE_INTEGER *)&afterPathfind );+// run player updates{ThePlayerList->UPDATE();}+ QueryPerformanceCounter( (LARGE_INTEGER *)&end );+ s_lastPathfindMS = aiElapsedMS( start, afterPathfind );+ s_lastPlayerUpdateMS = aiElapsedMS( afterPathfind, end );}/**diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cppindex 1773a8a34..b8c86d7e2 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp@@ -1094,6 +1094,12 @@ void AIGroup::friend_moveFormationToPos( const Coord3D *pos, CommandSourceType c}Object *theUnit = (*i);AIUpdateInterface *ai = theUnit->getAIUpdateInterface();+ // a group can hold things that do not steer themselves - a formation move means nothing to them+ if (ai == NULL)+ {+ continue;+ }+Bool isDifferentFormation = false;Coord2D offset;if (isDifferentFormation) {diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cppindex 8ac53e7d4..5e4e3c970 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp@@ -1173,13 +1173,9 @@ PathfindCellInfo *PathfindCellInfo::getACellInfo(PathfindCell *cell,const ICoordinfo->m_totalCost = 0;info->m_open = 0;info->m_closed = 0;- info->m_obstacleID = INVALID_ID;info->m_goalUnitID = INVALID_ID;info->m_posUnitID = INVALID_ID;info->m_goalAircraftID = INVALID_ID;- info->m_obstacleIsFence = false;- info->m_obstacleIsTransparent = false;- info->m_blockedByAlly = false;}return info;}@@ -1190,8 +1186,6 @@ PathfindCellInfo *PathfindCellInfo::getACellInfo(PathfindCell *cell,const ICoordvoid PathfindCellInfo::releaseACellInfo(PathfindCellInfo *theInfo){DEBUG_ASSERTCRASH(!theInfo->m_isFree, ("Shouldn't be free."));- //@ todo -fix this assert on usa04. jba.- //DEBUG_ASSERTCRASH(theInfo->m_obstacleID==0, ("Shouldn't be obstacle."));theInfo->m_pathParent = s_firstFree;s_firstFree = theInfo;s_firstFree->m_isFree = true;@@ -1231,8 +1225,11 @@ void PathfindCell::reset( )m_zone = 0;m_aircraftGoal = false;m_pinched = false;+ m_obstacleID = INVALID_ID;+ m_blockedByAlly = false;+ m_obstacleIsFence = false;+ m_obstacleIsTransparent = false;if (m_info) {- m_info->m_obstacleID = INVALID_ID;PathfindCellInfo::releaseACellInfo(m_info);m_info = NULL;}@@ -1255,7 +1252,9 @@ Bool PathfindCell::startPathfind( PathfindCell *goalCell )if (goalCell) {m_info->m_totalCost = costToGoal( goalCell );}- m_info->m_open = TRUE;+ // the caller assigns this cell to m_openList by hand rather than linking it in, so it+ // is not really on a list; saying it is only makes releaseInfo() refuse to free it+ m_info->m_open = FALSE;m_info->m_closed = FALSE;return true;}@@ -1309,6 +1308,11 @@ Bool PathfindCell::allocateInfo( const ICoord2D &pos )*/void PathfindCell::releaseInfo( void ){+ // a cell that did not make it onto the final path keeps its parent link, and the info+ // that link points at gets recycled under it - clear it before any of the early outs+ if (m_info) {+ m_info->m_pathParent = NULL;+ }if (m_type==PathfindCell::CELL_OBSTACLE) {return;}@@ -1469,24 +1473,22 @@ Bool PathfindCell::setTypeAsObstacle( Object *obstacle, Bool isFence, const ICooif (isRubble) {m_type = PathfindCell::CELL_RUBBLE;- if (m_info) {- m_info->m_obstacleID = INVALID_ID;- releaseInfo();- }+ m_obstacleID = INVALID_ID;+ m_obstacleIsFence = false;+ m_obstacleIsTransparent = false;+ releaseInfo();return true;}+ //+ // This used to reach into the search pool for a record to hold the three values below, and+ // hand back false - "no obstacle here" - when the pool was empty. The obstacle then stood+ // on the map with the cell still marked clear.+ //m_type = PathfindCell::CELL_OBSTACLE ;- if (!m_info) {- m_info = PathfindCellInfo::getACellInfo(this, pos);- if (!m_info) {- DEBUG_CRASH(("Not enough PathFindCellInfos in pool."));- return false;- }- }- m_info->m_obstacleID = obstacle->getID();- m_info->m_obstacleIsFence = isFence;- m_info->m_obstacleIsTransparent = obstacle->isKindOf(KINDOF_CAN_SEE_THROUGH_STRUCTURE);+ m_obstacleID = obstacle->getID();+ m_obstacleIsFence = isFence;+ m_obstacleIsTransparent = obstacle->isKindOf(KINDOF_CAN_SEE_THROUGH_STRUCTURE);return true;}@@ -1495,7 +1497,7 @@ Bool PathfindCell::setTypeAsObstacle( Object *obstacle, Bool isFence, const ICoo*/void PathfindCell::setType( CellType type ){- if (m_info && (m_info->m_obstacleID != INVALID_ID)) {+ if (m_obstacleID != INVALID_ID) {DEBUG_ASSERTCRASH(type==PathfindCell::CELL_OBSTACLE, ("Wrong type."));m_type = PathfindCell::CELL_OBSTACLE;return;@@ -1512,10 +1514,11 @@ Bool PathfindCell::removeObstacle( Object *obstacle )if (m_type == PathfindCell::CELL_RUBBLE) {m_type = PathfindCell::CELL_CLEAR;}- if (!m_info) return false;- if (m_info->m_obstacleID != obstacle->getID()) return false;+ if (m_obstacleID != obstacle->getID()) return false;m_type = PathfindCell::CELL_CLEAR;- m_info->m_obstacleID = INVALID_ID;+ m_obstacleID = INVALID_ID;+ m_obstacleIsFence = false;+ m_obstacleIsTransparent = false;releaseInfo();return true;}@@ -4055,6 +4058,10 @@ void Pathfinder::classifyFence( Object *obj, Bool insert )IRegion2D cellBounds;cellBounds.lo.x = REAL_TO_INT_FLOOR((pos->x + 0.5f)/PATHFIND_CELL_SIZE_F);cellBounds.lo.y = REAL_TO_INT_FLOOR((pos->y + 0.5f)/PATHFIND_CELL_SIZE_F);+ // hi was left holding whatever was on the stack, and the loop below only ever raises+ // it - so the zone update below covered a random rectangle+ cellBounds.hi.x = REAL_TO_INT_CEIL((pos->x + 0.5f)/PATHFIND_CELL_SIZE_F);+ cellBounds.hi.y = REAL_TO_INT_CEIL((pos->y + 0.5f)/PATHFIND_CELL_SIZE_F);Bool didAnything = false;for (Int iy = 0; iy < numStepsY; ++iy, tl_x += ydx, tl_y += ydy)@@ -4478,16 +4485,12 @@ void Pathfinder::internal_classifyObjectFootprint( Object *obj, Bool insert )}}- for( j=cellBounds.lo.y; j<=cellBounds.hi.y; j++ )- {- for( i=cellBounds.lo.x; i<=cellBounds.hi.x; i++ )- {- if (m_map[i][j].getPinched() && (m_map[i][j].getType() == PathfindCell::CELL_CLEAR)) {- m_map[i][j].setType(PathfindCell::CELL_IMPASSABLE);- m_map[i][j].setPinched(false);- }- }- }+ //+ // A pass here used to promote every pinched-but-clear cell to CELL_IMPASSABLE. Pinched+ // cells already cannot be pathed through, so the promotion bought nothing - but it is+ // permanent, and it also blocks building, so a footprint change could quietly wall off+ // the ground around a structure for the rest of the match.+ //// Expand building bounds 1 cell.#define MARK_BORDER_PINCHED@@ -5439,12 +5442,12 @@ Bool Pathfinder::adjustDestination(Object *obj, const LocomotorSet& locomotorSetBool center;getRadiusAndCenter(obj, iRadius, center);ICoord2D cell;- Coord3D adjustDest = *dest;+ Coord3D cellDest = *dest;if (!center) {- adjustDest.x += PATHFIND_CELL_SIZE_F/2;- adjustDest.y += PATHFIND_CELL_SIZE_F/2;+ cellDest.x += PATHFIND_CELL_SIZE_F/2;+ cellDest.y += PATHFIND_CELL_SIZE_F/2;}- worldToCell( &adjustDest, &cell );+ worldToCell( &cellDest, &cell );PathfindLayerEnum layer = TheTerrainLogic->getLayerForDestination(dest);if (groupDest) {layer = TheTerrainLogic->getLayerForDestination(groupDest);@@ -5455,7 +5458,18 @@ Bool Pathfinder::adjustDestination(Object *obj, const LocomotorSet& locomotorSetInt i, j;i = cell.x;j = cell.y;- if (checkForAdjust(obj, locomotorSet, isHuman, i,j, layer, iRadius, center, dest, groupDest)) {+ //+ // The centre cell is checked first, and it snapped the order to the middle of that cell+ // even when nothing was in the way - which is why a lone Chinook never landed where you+ // clicked. Keep the click for a single unit; a group still gets the tidy grid, because+ // without it the formation smears.+ //+ Coord3D adjustDest = *dest;+ if (checkForAdjust(obj, locomotorSet, isHuman, i,j, layer, iRadius, center, &adjustDest, groupDest)) {+ const Bool singleUnit = obj->getGroup() && obj->getGroup()->getCount() == 1;+ if (!(isHuman && singleUnit)) {+ *dest = adjustDest;+ }return true;}@@ -6668,10 +6682,14 @@ Path *Pathfinder::internalFindPath( Object *obj, const LocomotorSet& locomotorSezone2 = m_zoneManager.getEffectiveZone(locomotorSet.getValidSurfaces(), isCrusher, goalCell->getZone());if (layer==LAYER_WALL && zone1 == 0) {+ goalCell->releaseInfo();+ parentCell->releaseInfo();return NULL;}if (destinationLayer==LAYER_WALL && zone2 == 0) {+ goalCell->releaseInfo();+ parentCell->releaseInfo();return NULL;}@@ -6767,8 +6785,8 @@ Path *Pathfinder::internalFindPath( Object *obj, const LocomotorSet& locomotorSecellCount, searchMs, buildMs, nodes, from->x, from->y, rawTo->x, rawTo->y));}}- parentCell->releaseInfo();cleanOpenAndClosedLists();+ parentCell->releaseInfo();return path;}@@ -6844,8 +6862,9 @@ Path *Pathfinder::internalFindPath( Object *obj, const LocomotorSet& locomotorSeTheGameLogic->getFrame(), obj ? obj->getTemplate()->getName().str() : "?",from->x, from->y, to->x, to->y, cellCount));m_isTunneling = false;- goalCell->releaseInfo();cleanOpenAndClosedLists();+ parentCell->releaseInfo();+ goalCell->releaseInfo();return NULL;}@@ -7220,6 +7239,7 @@ Path *Pathfinder::findGroundPath( const Coord3D *from,PathfindLayerEnum layer = TheTerrainLogic->getLayerForDestination(from);PathfindCell *parentCell = getClippedCell( layer,&clipFrom );if (parentCell == NULL) {+ goalCell->releaseInfo();return NULL;}if (parentCell!=goalCell) {@@ -7277,8 +7297,8 @@ Path *Pathfinder::findGroundPath( const Coord3D *from,m_isTunneling = false;// construct and return pathPath *path = buildGroundPath(crusher, from, goalCell, centerInCell, pathDiameter );- parentCell->releaseInfo();cleanOpenAndClosedLists();+ parentCell->releaseInfo();return path;}@@ -7466,8 +7486,9 @@ Path *Pathfinder::findGroundPath( const Coord3D *from,TheGameLogic->incrementOverallFailedPathfinds();#endifm_isTunneling = false;- goalCell->releaseInfo();cleanOpenAndClosedLists();+ parentCell->releaseInfo();+ goalCell->releaseInfo();return NULL;}@@ -7711,7 +7732,14 @@ Path *Pathfinder::internal_findHierarchicalPath( Bool isHuman, const LocomotorSu// Close parent cell;m_openList = parentCell->removeFromOpenList(m_openList);m_closedList = parentCell->putOnClosedList(m_closedList);- startCell->allocateInfo(ndx);+ if (!startCell->allocateInfo(ndx)) {+ // out of cell infos - anything already linked into the lists has to come off+ // them before the start and goal cells hand their own records back+ cleanOpenAndClosedLists();+ parentCell->releaseInfo();+ goalCell->releaseInfo();+ return NULL;+ }startCell->setParentCellHierarchical(parentCell);cellCount++;Int curCost = startCell->costToHierGoal(parentCell);@@ -7723,7 +7751,14 @@ Path *Pathfinder::internal_findHierarchicalPath( Bool isHuman, const LocomotorSum_openList = startCell->putOnSortedOpenList( m_openList );cellCount++;- cell->allocateInfo(toNdx);+ if (!cell->allocateInfo(toNdx)) {+ // out of cell infos - anything already linked into the lists has to come off+ // them before the start and goal cells hand their own records back+ cleanOpenAndClosedLists();+ parentCell->releaseInfo();+ goalCell->releaseInfo();+ return NULL;+ }curCost = cell->costToHierGoal(parentCell);remCost = cell->costToHierGoal(goalCell);cell->setCostSoFar(curCost);@@ -7807,13 +7842,23 @@ Path *Pathfinder::internal_findHierarchicalPath( Bool isHuman, const LocomotorSuPathfindCell *startCell = getCell(LAYER_GROUND, ndx.x, ndx.y);if (startCell==NULL) continue;if (startCell != parentCell) {- startCell->allocateInfo(ndx);+ if (!startCell->allocateInfo(ndx)) {+ cleanOpenAndClosedLists();+ parentCell->releaseInfo();+ goalCell->releaseInfo();+ return NULL;+ }startCell->setParentCellHierarchical(parentCell);if (!startCell->getClosed() && !startCell->getOpen()) {m_closedList = startCell->putOnClosedList(m_closedList);}}- cell->allocateInfo(toNdx);+ if (!cell->allocateInfo(toNdx)) {+ cleanOpenAndClosedLists();+ parentCell->releaseInfo();+ goalCell->releaseInfo();+ return NULL;+ }cell->setParentCellHierarchical(startCell);cellCount++;@@ -7867,11 +7912,9 @@ Path *Pathfinder::internal_findHierarchicalPath( Bool isHuman, const LocomotorSu#endif}#endif- if (goalCell->hasInfo() && !goalCell->getClosed() && !goalCell->getOpen()) {- goalCell->releaseInfo();- }- parentCell->releaseInfo();cleanOpenAndClosedLists();+ parentCell->releaseInfo();+ goalCell->releaseInfo();return path;}@@ -8068,10 +8111,9 @@ Path *Pathfinder::internal_findHierarchicalPath( Bool isHuman, const LocomotorSu}#endif#endif- if (goalCell->hasInfo() && !goalCell->getClosed() && !goalCell->getOpen()) {- goalCell->releaseInfo();- }cleanOpenAndClosedLists();+ parentCell->releaseInfo();+ goalCell->releaseInfo();return path;}@@ -8117,8 +8159,9 @@ Path *Pathfinder::internal_findHierarchicalPath( Bool isHuman, const LocomotorSuTheGameLogic->incrementOverallFailedPathfinds();#endifm_isTunneling = false;- goalCell->releaseInfo();cleanOpenAndClosedLists();+ parentCell->releaseInfo();+ goalCell->releaseInfo();return NULL;}@@ -8382,7 +8425,6 @@ Bool Pathfinder::pathDestination( Object *obj, const LocomotorSet& locomotorSetif (parentCell!=goalCell) {if (!parentCell->allocateInfo(startCellNdx)) {- desiredCell->releaseInfo();goalCell->releaseInfo();return FALSE;}@@ -8496,7 +8538,10 @@ Bool Pathfinder::pathDestination( Object *obj, const LocomotorSet& locomotorSetneighborFlags[i] = true;if (!newCell->allocateInfo(newCellCoord)) {- // Out of cells for pathing...+ // Out of cells for pathing - unwind the lists before walking out, or every+ // cell already linked into them keeps its record for good+ cleanOpenAndClosedLists();+ goalCell->releaseInfo();return cellCount;}cellCount++;@@ -8554,6 +8599,7 @@ Bool Pathfinder::pathDestination( Object *obj, const LocomotorSet& locomotorSet#endifm_isTunneling = false;cleanOpenAndClosedLists();+ parentCell->releaseInfo();goalCell->releaseInfo();return false;}@@ -8565,8 +8611,9 @@ struct TightenPathStructPathfindLayerEnum layer;Int radius;Bool center;- Bool foundDest;- Coord3D destPos;+ Bool foundNewDest;+ Coord3D orgDestPos;+ Coord3D newDestPos;};@@ -8577,13 +8624,15 @@ struct TightenPathStructif (d->layer != to->getLayer()) {return 0; // abort.}- Coord3D pos;+ // checkForAdjust reads pos as well as writing it, so it has to start from the+ // destination we are tightening towards rather than from stack litter+ Coord3D pos = d->orgDestPos;if (!TheAI->pathfinder()->checkForAdjust(d->obj, *d->locomotorSet, true, to_x, to_y, to->getLayer(), d->radius, d->center, &pos, NULL)){return 0; // bail early}- d->foundDest = true;- d->destPos = pos;+ d->foundNewDest = true;+ d->newDestPos = pos;return 0; // keep going}@@ -8598,10 +8647,11 @@ void Pathfinder::tightenPath(Object *obj, const LocomotorSet& locomotorSet, Coorinfo.layer = TheTerrainLogic->getLayerForDestination(from);info.obj = obj;info.locomotorSet = &locomotorSet;- info.foundDest = false;+ info.foundNewDest = false;+ info.orgDestPos = *to;iterateCellsAlongLine(*from, *to, info.layer, tightenPathCallback, &info);- if (info.foundDest) {- *from = info.destPos;+ if (info.foundNewDest) {+ *from = info.newDestPos;}}@@ -8680,16 +8730,17 @@ Int Pathfinder::checkPathCost(Object *obj, const LocomotorSet& locomotorSet, conparentCell = m_openList;m_openList = parentCell->removeFromOpenList(m_openList);- // put parent cell onto closed list - its evaluation is finished- m_closedList = parentCell->putOnClosedList( m_closedList );-if (parentCell==goalCell) {Int cost = parentCell->getTotalCost();m_isTunneling = false;cleanOpenAndClosedLists();+ parentCell->releaseInfo();return cost;}+ // put parent cell onto closed list - its evaluation is finished+ m_closedList = parentCell->putOnClosedList( m_closedList );+if (cellCount > MAX_CELL_COUNT) {continue;}@@ -8749,7 +8800,10 @@ Int Pathfinder::checkPathCost(Object *obj, const LocomotorSet& locomotorSet, conneighborFlags[i] = true;if (!newCell->allocateInfo(newCellCoord)) {- // Out of cells for pathing...+ // Out of cells for pathing - unwind the lists before walking out+ cleanOpenAndClosedLists();+ parentCell->releaseInfo();+ goalCell->releaseInfo();return cellCount;}cellCount++;@@ -8798,10 +8852,9 @@ Int Pathfinder::checkPathCost(Object *obj, const LocomotorSet& locomotorSet, con}m_isTunneling = false;- if (goalCell->hasInfo() && !goalCell->getClosed() && !goalCell->getOpen()) {- goalCell->releaseInfo();- }cleanOpenAndClosedLists();+ parentCell->releaseInfo();+ goalCell->releaseInfo();return MAX_COST;}@@ -8942,6 +8995,7 @@ Path *Pathfinder::findClosestPath( Object *obj, const LocomotorSet& locomotorSetif (parentCell!=goalCell) {worldToCell(&clipFrom, &pos2d);if (!parentCell->allocateInfo(pos2d)) {+ goalCell->releaseInfo();return NULL;}}@@ -9007,9 +9061,9 @@ Path *Pathfinder::findClosestPath( Object *obj, const LocomotorSet& locomotorSetm_isTunneling = false;// construct and return pathPath *path = buildActualPath( obj, locomotorSet.getValidSurfaces(), from, goalCell, centerInCell, blocked);+ cleanOpenAndClosedLists();parentCell->releaseInfo();goalCell->releaseInfo();- cleanOpenAndClosedLists();return path;}// put parent cell onto closed list - its evaluation is finished@@ -9089,8 +9143,9 @@ Path *Pathfinder::findClosestPath( Object *obj, const LocomotorSet& locomotorSetrawTo->y = closesetCell->getYIndex()*PATHFIND_CELL_SIZE_F + PATHFIND_CELL_SIZE_F/2.0f;// construct and return pathPath *path = buildActualPath( obj, locomotorSet.getValidSurfaces(), from, closesetCell, centerInCell, blocked );- goalCell->releaseInfo();cleanOpenAndClosedLists();+ parentCell->releaseInfo();+ goalCell->releaseInfo();return path;}@@ -9109,8 +9164,9 @@ Path *Pathfinder::findClosestPath( Object *obj, const LocomotorSet& locomotorSetTheGameLogic->incrementOverallFailedPathfinds();#endifm_isTunneling = false;- goalCell->releaseInfo();cleanOpenAndClosedLists();+ parentCell->releaseInfo();+ goalCell->releaseInfo();return NULL;}@@ -10496,8 +10552,8 @@ Path *Pathfinder::getMoveAwayFromPath(Object* obj, Object *otherObj,m_isTunneling = false;// construct and return pathPath *newPath = buildActualPath( obj, locomotorSet.getValidSurfaces(), obj->getPosition(), parentCell, centerInCell, false);- parentCell->releaseInfo();cleanOpenAndClosedLists();+ parentCell->releaseInfo();return newPath;}// put parent cell onto closed list - its evaluation is finished@@ -10518,6 +10574,7 @@ Path *Pathfinder::getMoveAwayFromPath(Object* obj, Object *otherObj,#endifm_isTunneling = false;cleanOpenAndClosedLists();+ parentCell->releaseInfo();return NULL;}@@ -10633,7 +10690,7 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSet}if (startNode == originalPath->getLastNode()) {- cleanOpenAndClosedLists();+ parentCell->releaseInfo();return NULL; // no open nodes.}PathfindCell *candidateGoal;@@ -10641,6 +10698,7 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSetICoord2D goalCellNdx;worldToCell(&goalPos, &goalCellNdx);if (!candidateGoal->allocateInfo(goalCellNdx)) {+ parentCell->releaseInfo();return NULL;}@@ -10676,8 +10734,8 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSet// cleanup the path by checking line of sightpath->optimize(obj, locomotorSet.getValidSurfaces(), blocked);registerPathUsage(path);- parentCell->releaseInfo();cleanOpenAndClosedLists();+ parentCell->releaseInfo();candidateGoal->releaseInfo();return path;@@ -10701,12 +10759,9 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSet}#endifm_isTunneling = false;- if (!candidateGoal->getOpen() && !candidateGoal->getClosed())- {- // Not on one of the lists- candidateGoal->releaseInfo();- }cleanOpenAndClosedLists();+ parentCell->releaseInfo();+ candidateGoal->releaseInfo();return false;}@@ -10852,6 +10907,7 @@ Path *Pathfinder::findAttackPath( const Object *obj, const LocomotorSet& locomotreturn NULL;if (!goalCell->allocateInfo(victimCellNdx)) {+ parentCell->releaseInfo();return false;}@@ -11001,10 +11057,9 @@ Path *Pathfinder::findAttackPath( const Object *obj, const LocomotorSet& locomot}}Path *path = buildActualPath( obj, locomotorSet.getValidSurfaces(), obj->getPosition(), parentCell, centerInCell, false);- if (goalCell->hasInfo() && !goalCell->getClosed() && !goalCell->getOpen()) {- goalCell->releaseInfo();- }cleanOpenAndClosedLists();+ parentCell->releaseInfo();+ goalCell->releaseInfo();return path;}}@@ -11061,10 +11116,9 @@ Path *Pathfinder::findAttackPath( const Object *obj, const LocomotorSet& locomotTheGameLogic->incrementOverallFailedPathfinds();#endifm_isTunneling = false;- if (goalCell->hasInfo() && !goalCell->getClosed() && !goalCell->getOpen()) {- goalCell->releaseInfo();- }cleanOpenAndClosedLists();+ parentCell->releaseInfo();+ goalCell->releaseInfo();return false;}@@ -11186,8 +11240,8 @@ Path *Pathfinder::findSafePath( const Object *obj, const LocomotorSet& locomotor#endif// construct and return pathPath *path = buildActualPath( obj, locomotorSet.getValidSurfaces(), obj->getPosition(), parentCell, centerInCell, false);- parentCell->releaseInfo();cleanOpenAndClosedLists();+ parentCell->releaseInfo();return path;}@@ -11223,6 +11277,7 @@ Path *Pathfinder::findSafePath( const Object *obj, const LocomotorSet& locomotor#endifm_isTunneling = false;cleanOpenAndClosedLists();+ parentCell->releaseInfo();return false;}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cppindex df77cdea4..c780d32ad 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp@@ -800,12 +800,7 @@ void AIPlayer::processBaseBuilding( void )info->decrementNumRebuilds();m_readyToBuildStructure = false;- m_structureTimer = TheAI->getAiData()->m_structureSeconds*LOGICFRAMES_PER_SECOND;- if (m_player->getMoney()->countMoney() < TheAI->getAiData()->m_resourcesPoor) {- m_structureTimer = m_structureTimer/TheAI->getAiData()->m_structuresPoorMod;- } else if (m_player->getMoney()->countMoney() > TheAI->getAiData()->m_resourcesWealthy) {- m_structureTimer = m_structureTimer/TheAI->getAiData()->m_structuresWealthyMod;- }+ m_structureTimer = computeStructureDelay();m_frameLastBuildingBuilt = TheGameLogic->getFrame();// only build one building per delay loopbreak;@@ -835,12 +830,7 @@ void AIPlayer::processBaseBuilding( void )info->decrementNumRebuilds();m_readyToBuildStructure = false;- m_structureTimer = TheAI->getAiData()->m_structureSeconds*LOGICFRAMES_PER_SECOND;- if (m_player->getMoney()->countMoney() < TheAI->getAiData()->m_resourcesPoor) {- m_structureTimer = m_structureTimer/TheAI->getAiData()->m_structuresPoorMod;- } else if (m_player->getMoney()->countMoney() > TheAI->getAiData()->m_resourcesWealthy) {- m_structureTimer = m_structureTimer/TheAI->getAiData()->m_structuresWealthyMod;- }+ m_structureTimer = computeStructureDelay();m_frameLastBuildingBuilt = TheGameLogic->getFrame();// only build one building per delay loopbreak;@@ -1738,12 +1728,7 @@ Bool AIPlayer::selectTeamToBuild( void )// Build it at low priority, as we have selected it automagically.buildSpecificAITeam(teamProto, false);m_readyToBuildTeam = false;- m_teamTimer = m_teamSeconds*LOGICFRAMES_PER_SECOND;- if (m_player->getMoney()->countMoney() < TheAI->getAiData()->m_resourcesPoor) {- m_teamTimer = m_teamTimer/TheAI->getAiData()->m_teamPoorMod;- } else if (m_player->getMoney()->countMoney() > TheAI->getAiData()->m_resourcesWealthy) {- m_teamTimer = m_teamTimer/TheAI->getAiData()->m_teamWealthyMod;- }+ m_teamTimer = computeTeamDelay();return true;}return false;@@ -2736,6 +2721,57 @@ void AIPlayer::queueUnits( void )}}++//----------------------------------------------------------------------------------------------------------+/**+ * Frames to wait before trying the next structure, from AIData's StructureSeconds with the+ * rate modifier for a poor or a wealthy player applied. This was four copies of the same+ * five lines; the skirmish AI needs to bend the result, so it lives in one place now.+ */+Int AIPlayer::computeStructureDelay( void )+{+ return computeBuildDelay( TheAI->getAiData()->m_structureSeconds,+ m_player->getMoney()->countMoney(),+ TheAI->getAiData()->m_resourcesPoor,+ TheAI->getAiData()->m_resourcesWealthy,+ TheAI->getAiData()->m_structuresPoorMod,+ TheAI->getAiData()->m_structuresWealthyMod,+ getBuildRateScale() );+}++//----------------------------------------------------------------------------------------------------------+/**+ * The delay arithmetic, with nothing of the Player in it so a test can drive it: the written+ * delay, bent by whichever rate modifier the player's bank account selects, then divided by+ * how much faster than the data this kind of AI is meant to work.+ */+Int AIPlayer::computeBuildDelay( Real seconds, Int money, Int poorAt, Int wealthyAt,+ Real poorMod, Real wealthyMod, Real rateScale )+{+ if (money < poorAt) {+ seconds = seconds/poorMod;+ } else if (money > wealthyAt) {+ seconds = seconds/wealthyMod;+ }+ return (Int)(seconds*LOGICFRAMES_PER_SECOND/rateScale);+}++//----------------------------------------------------------------------------------------------------------+/**+ * Frames to wait before trying the next team. Same as computeStructureDelay, except the+ * base delay is m_teamSeconds, which the SET_BASE_CONSTRUCTION_SPEED script action writes.+ */+Int AIPlayer::computeTeamDelay( void )+{+ return computeBuildDelay( (Real)m_teamSeconds,+ m_player->getMoney()->countMoney(),+ TheAI->getAiData()->m_resourcesPoor,+ TheAI->getAiData()->m_resourcesWealthy,+ TheAI->getAiData()->m_teamPoorMod,+ TheAI->getAiData()->m_teamWealthyMod,+ getBuildRateScale() );+}+//----------------------------------------------------------------------------------------------------------/*** See if it's time to build another base building.diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cppindex bcd3d601a..927a2919b 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp@@ -266,12 +266,7 @@ void AISkirmishPlayer::processBaseBuilding( void )bldgInfo->decrementNumRebuilds();m_readyToBuildStructure = false;- m_structureTimer = TheAI->getAiData()->m_structureSeconds*LOGICFRAMES_PER_SECOND;- if (m_player->getMoney()->countMoney() < TheAI->getAiData()->m_resourcesPoor) {- m_structureTimer = m_structureTimer/TheAI->getAiData()->m_structuresPoorMod;- } else if (m_player->getMoney()->countMoney() > TheAI->getAiData()->m_resourcesWealthy) {- m_structureTimer = m_structureTimer/TheAI->getAiData()->m_structuresWealthyMod;- }+ m_structureTimer = computeStructureDelay();m_frameLastBuildingBuilt = TheGameLogic->getFrame();// only build one building per delay loop} // bldg built@@ -300,12 +295,7 @@ void AISkirmishPlayer::processBaseBuilding( void )info->decrementNumRebuilds();m_readyToBuildStructure = false;- m_structureTimer = TheAI->getAiData()->m_structureSeconds*LOGICFRAMES_PER_SECOND;- if (m_player->getMoney()->countMoney() < TheAI->getAiData()->m_resourcesPoor) {- m_structureTimer = m_structureTimer/TheAI->getAiData()->m_structuresPoorMod;- } else if (m_player->getMoney()->countMoney() > TheAI->getAiData()->m_resourcesWealthy) {- m_structureTimer = m_structureTimer/TheAI->getAiData()->m_structuresWealthyMod;- }+ m_structureTimer = computeStructureDelay();m_frameLastBuildingBuilt = TheGameLogic->getFrame();// only build one building per delay loopbreak;@@ -871,6 +861,25 @@ void AISkirmishPlayer::processTeamBuilding( void )}}+//----------------------------------------------------------------------------------------------------------+/**+ * How much faster than AIData's written delays the skirmish AI works.+ *+ * EA got the same effect by clamping m_structureTimer and m_teamTimer to a flat 3 seconds on+ * every frame they counted down. That did make the skirmish AI brisk, but it also silently+ * threw away everything the data said: with the shipped TeamSeconds of 10 the clamp fired for+ * every player, so TeamsWealthyRate and TeamsPoorRate changed nothing, a rich AI and a broke+ * AI queued teams at exactly the same 3 second beat, and the SET_BASE_CONSTRUCTION_SPEED+ * script action could only ever slow an AI down to 3 seconds too. Expressed as a rate+ * instead, the shipped values land on the same 3 seconds they do today, and the modifiers+ * work again around it: a wealthy skirmish AI presses at 1.5 seconds, a poor one drops to 5.+ * See FINDINGS.md 4.+ */+Real AISkirmishPlayer::getBuildRateScale( void )+{+ return 10.0f/3.0f;+}+//----------------------------------------------------------------------------------------------------------/*** See if it's time to build another base building.@@ -885,9 +894,6 @@ void AISkirmishPlayer::doBaseBuilding( void )m_readyToBuildStructure = true;m_buildDelay = 0;}- if (m_structureTimer > 3*LOGICFRAMES_PER_SECOND) {- m_structureTimer = 3*LOGICFRAMES_PER_SECOND;- }}// This timer is to keep from banging on the logic each frame. If something interesting// happens, like a building is added or a unit finished, the timers are shortcut.@@ -937,9 +943,6 @@ void AISkirmishPlayer::doTeamBuilding( void )m_readyToBuildTeam = true;m_teamDelay = 0;}- if (m_teamTimer > 3*LOGICFRAMES_PER_SECOND) {- m_teamTimer = 3*LOGICFRAMES_PER_SECOND;- }}// This timer is to keep from banging on the logic each frame. If something interestingdiff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cppindex 422c1fdbf..9f5568cec 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp@@ -6833,6 +6833,10 @@ StateReturnType AIExitState::update()if( goalExitInterface == NULL )return STATE_FAILURE;+ // The container died while we were queued to leave it - we are already out, stop asking.+ if( goal->isEffectivelyDead() )+ return STATE_FAILURE;+if( goalExitInterface->isExitBusy() )return STATE_CONTINUE;// Just wait a sec.diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cppindex 0c7356540..5f66c70aa 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp@@ -299,6 +299,14 @@ void OpenContain::addToContain( Object *rider )if( rider == NULL )return;+ //+ // Neither side of this may already be destroyed. A destroyed container is about to be deleted+ // and the rider would be left pointing at freed memory; a destroyed rider leaves the container+ // holding a record for an object the logic is about to delete.+ //+ if( getObject()->isDestroyed() || rider->isDestroyed() )+ return;+Drawable *riderDraw = rider->getDrawable();Bool wasSelected = FALSE;if( riderDraw && riderDraw->isSelected() )@@ -434,17 +442,26 @@ void OpenContain::removeAllContained( Bool exposeStealthUnits )//-------------------------------------------------------------------------------------------------void OpenContain::killAllContained( void ){- ContainedItemsList::iterator it = m_containList.begin();+ //+ // Empty the contain list up front rather than walking the live one. A rider that deals fatal+ // damage as it dies can kill the container itself, and the container's own death then re-enters+ // this function and walks the same list the outer call is still erasing from. Shooting a GLA+ // Technical full of Terrorists with Neutron Shells does exactly that.+ //+ ContainedItemsList list;+ list.swap( m_containList );+ m_containListSize = 0;- while ( it != m_containList.end() )+ ContainedItemsList::iterator it = list.begin();++ while ( it != list.end() ){Object *rider = *it;-+ DEBUG_ASSERTCRASH( rider, ("Contain list must not contain NULL element") );if ( rider ){- it = m_containList.erase(it);- m_containListSize--;+ it = list.erase(it);onRemoving( rider );rider->onRemovedFrom( getObject() );@@ -459,7 +476,7 @@ void OpenContain::killAllContained( void )DEBUG_ASSERTCRASH( m_containListSize == 0, ("killallcontain just made a booboo, list size != zero.") );-} // end removeAllContained+} // end killAllContained//--------------------------------------------------------------------------------------------------------/** Force all contained objects in the contained list to exit, and kick them in the pants on the way out*/@@ -1442,35 +1459,55 @@ void OpenContain::processDamageToContained(Real percentDamage){const OpenContainModuleData *data = getOpenContainModuleData();- const ContainedItemsList* items = getContainedItemsList();- if( items )+ //+ // Hold the contain list off to one side while the damage goes out. Advancing the iterator first+ // (the comment below is EA's) is not enough: a rider that explodes on death can kill the+ // container, and the container's death then walks the very list this loop is standing in. A GLA+ // Battle Bus with two half-dead Terrorists in it does exactly that.+ //+ // Caveat: while the list is parked here, damage a dying rider deals cannot reach the other+ // riders through the container. Nothing in the shipped data does that.+ //+ ContainedItemsList list;+ m_containList.swap( list );+ m_containListSize = 0;++ ContainedItemsList::iterator it = list.begin();++ while( it != list.end() ){- ContainedItemsList::const_iterator it;- it = items->begin();+ Object *object = *it;- while( it != items->end() ) // was while(*it), which dereferences end()- {- Object *object = *it;+ DEBUG_ASSERTCRASH( object, ("Contain list must not contain NULL element") );- //Advance to the next iterator before we apply the damage.- //It's possible that the damage will kill the unit and foobar- //the iterator list.- ++it;+ //Calculate the damage to be inflicted on each unit.+ Real damage = object->getBodyModule()->getMaxHealth() * percentDamage;- //Calculate the damage to be inflicted on each unit.- Real damage = object->getBodyModule()->getMaxHealth() * percentDamage;+ DamageInfo damageInfo;+ damageInfo.in.m_damageType = DAMAGE_UNRESISTABLE;+ damageInfo.in.m_deathType = data->m_isBurnedDeathToUnits ? DEATH_BURNED : DEATH_NORMAL;+ damageInfo.in.m_sourceID = getObject()->getID();+ damageInfo.in.m_amount = damage;+ object->attemptDamage( &damageInfo );- DamageInfo damageInfo;- damageInfo.in.m_damageType = DAMAGE_UNRESISTABLE;- damageInfo.in.m_deathType = data->m_isBurnedDeathToUnits ? DEATH_BURNED : DEATH_NORMAL;- damageInfo.in.m_sourceID = getObject()->getID();- damageInfo.in.m_amount = damage;- object->attemptDamage( &damageInfo );+ if( !object->isEffectivelyDead() && percentDamage == 1.0f )+ object->kill(); // in case we are carrying flame proof troops we have been asked to kill- if( !object->isEffectivelyDead() && percentDamage == 1.0f )- object->kill(); // in case we are carrying flame proof troops we have been asked to kill+ if( object->isEffectivelyDead() )+ {+ onRemoving( object );+ object->onRemovedFrom( getObject() );+ it = list.erase( it );+ }+ else+ {+ ++it;}}++ // and hand back whoever survived+ m_containList.swap( list );+ m_containListSize = (UnsignedInt)m_containList.size();}//-------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TransportContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TransportContain.cppindex 3766e4c75..e310e4de4 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TransportContain.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TransportContain.cpp@@ -479,7 +479,8 @@ UpdateSleepTime TransportContain::update(){const TransportContainModuleData *moduleData = getTransportContainModuleData();- if( m_payloadCreated == FALSE )+ // A transport that was destroyed this frame must not fill itself with a payload on the way out.+ if( m_payloadCreated == FALSE && !getObject()->isDestroyed() )createPayload();if( moduleData && moduleData->m_healthRegen )diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TunnelContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TunnelContain.cppindex 02d73af63..62d70d1ea 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TunnelContain.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TunnelContain.cpp@@ -67,10 +67,19 @@ TunnelContain::~TunnelContain(){}-void TunnelContain::addToContainList( Object *obj )+TunnelTracker *TunnelContain::getTunnelTracker( void ) const{Player *owningPlayer = getObject()->getControllingPlayer();- owningPlayer->getTunnelSystem()->addToContainList( obj );+ return owningPlayer ? owningPlayer->getTunnelSystem() : NULL;+}++void TunnelContain::addToContainList( Object *obj )+{+ TunnelTracker *tunnelTracker = getTunnelTracker();+ if( tunnelTracker == NULL )+ return;++ tunnelTracker->addToContainList( obj );}//-------------------------------------------------------------------------------------------------@@ -98,16 +107,16 @@ void TunnelContain::removeFromContain( Object *obj, Bool exposeStealthUnits )// we can only remove this object from the contains list of this module if// it is actually contained by this module//- Player *owningPlayer = getObject()->getControllingPlayer();- if( owningPlayer == NULL )+ TunnelTracker *tunnelTracker = getTunnelTracker();+ if( tunnelTracker == NULL )return; //game tear down. We do the onRemove* stuff first because this is allowed to fail but that still needs to be done- if( ! owningPlayer->getTunnelSystem()->isInContainer( obj ) )+ if( ! tunnelTracker->isInContainer( obj ) ){return;}- owningPlayer->getTunnelSystem()->removeFromContain( obj, exposeStealthUnits );+ tunnelTracker->removeFromContain( obj, exposeStealthUnits );}@@ -118,8 +127,11 @@ void TunnelContain::removeFromContain( Object *obj, Bool exposeStealthUnits )//--------------------------------------------------------------------------------------------------------void TunnelContain::harmAndForceExitAllContained( DamageInfo *info ){- Player *owningPlayer = getObject()->getControllingPlayer();- const ContainedItemsList *fullList = owningPlayer->getTunnelSystem()->getContainedItemsList();+ TunnelTracker *tunnelTracker = getTunnelTracker();+ if( tunnelTracker == NULL )+ return;++ const ContainedItemsList *fullList = tunnelTracker->getContainedItemsList();Object *obj;ContainedItemsList::const_iterator it;@@ -149,18 +161,26 @@ void TunnelContain::harmAndForceExitAllContained( DamageInfo *info )//-------------------------------------------------------------------------------------------------void TunnelContain::killAllContained( void ){- Player *owningPlayer = getObject()->getControllingPlayer();- const ContainedItemsList *fullList = owningPlayer->getTunnelSystem()->getContainedItemsList();+ //+ // Take the tunnel system's list away from it before killing anything: a rider that deals fatal+ // damage on death kills the tunnel, and the tunnel's death walks this same list again while the+ // outer call is still iterating it. Neutron Shells on a tunnel full of Terrorists does it.+ //+ TunnelTracker *tunnelTracker = getTunnelTracker();+ if( tunnelTracker == NULL )+ return;- Object *obj;- ContainedItemsList::const_iterator it;- it = (*fullList).begin();- while( it != (*fullList).end() )+ ContainedItemsList list;+ tunnelTracker->swapContainedItemsList( list );++ ContainedItemsList::iterator it = list.begin();+ while( it != list.end() ){- obj = *it;- it++;+ Object *obj = *it++;+ DEBUG_ASSERTCRASH( obj, ("Contain list must not contain NULL element") );+removeFromContain( obj, true );- obj->kill();+ obj->kill();}}//-------------------------------------------------------------------------------------------------@@ -168,8 +188,11 @@ void TunnelContain::killAllContained( void )//-------------------------------------------------------------------------------------------------void TunnelContain::removeAllContained( Bool exposeStealthUnits ){- Player *owningPlayer = getObject()->getControllingPlayer();- const ContainedItemsList *fullList = owningPlayer->getTunnelSystem()->getContainedItemsList();+ TunnelTracker *tunnelTracker = getTunnelTracker();+ if( tunnelTracker == NULL )+ return;++ const ContainedItemsList *fullList = tunnelTracker->getContainedItemsList();Object *obj;ContainedItemsList::const_iterator it;@@ -187,8 +210,11 @@ void TunnelContain::removeAllContained( Bool exposeStealthUnits )//-------------------------------------------------------------------------------------------------void TunnelContain::iterateContained( ContainIterateFunc func, void *userData, Bool reverse ){- Player *owningPlayer = getObject()->getControllingPlayer();- owningPlayer->getTunnelSystem()->iterateContained( func, userData, reverse );+ TunnelTracker *tunnelTracker = getTunnelTracker();+ if( tunnelTracker == NULL )+ return;++ tunnelTracker->iterateContained( func, userData, reverse );}//-------------------------------------------------------------------------------------------------@@ -260,30 +286,44 @@ void TunnelContain::onSelling()//-------------------------------------------------------------------------------------------------Bool TunnelContain::isValidContainerFor(const Object* obj, Bool checkCapacity) const{- Player *owningPlayer = getObject()->getControllingPlayer();- return owningPlayer->getTunnelSystem()->isValidContainerFor( obj, checkCapacity );+ TunnelTracker *tunnelTracker = getTunnelTracker();+ return tunnelTracker ? tunnelTracker->isValidContainerFor( obj, checkCapacity ) : FALSE;}UnsignedInt TunnelContain::getContainCount() const{- Player *owningPlayer = getObject()->getControllingPlayer();- if( owningPlayer && owningPlayer->getTunnelSystem() )- {- return owningPlayer->getTunnelSystem()->getContainCount();- }- return 0;+ TunnelTracker *tunnelTracker = getTunnelTracker();+ return tunnelTracker ? tunnelTracker->getContainCount() : 0;}Int TunnelContain::getContainMax( void ) const{- Player *owningPlayer = getObject()->getControllingPlayer();- return owningPlayer->getTunnelSystem()->getContainMax();+ TunnelTracker *tunnelTracker = getTunnelTracker();+ return tunnelTracker ? tunnelTracker->getContainMax() : 0;}const ContainedItemsList* TunnelContain::getContainedItemsList() const{- Player *owningPlayer = getObject()->getControllingPlayer();- return owningPlayer->getTunnelSystem()->getContainedItemsList();+ TunnelTracker *tunnelTracker = getTunnelTracker();+ return tunnelTracker ? tunnelTracker->getContainedItemsList() : NULL;+}++//-------------------------------------------------------------------------------------------------+void TunnelContain::orderAllPassengersToExit( CommandSourceType commandSource, Bool instantly )+{+ if( getTunnelTracker() == NULL )+ return;++ OpenContain::orderAllPassengersToExit( commandSource, instantly );+}++//-------------------------------------------------------------------------------------------------+void TunnelContain::orderAllPassengersToIdle( CommandSourceType commandSource )+{+ if( getTunnelTracker() == NULL )+ return;++ OpenContain::orderAllPassengersToIdle( commandSource );}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cppindex 1361aedcf..4c1fccfac 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp@@ -3899,7 +3899,12 @@ void Object::onDisabledEdge(Bool becomingDisabled)// We will need to adjust power ... somehow ...Int powerToAdjust = getTemplate()->getEnergyProduction();- if( powerToAdjust > 0 )+ //+ // A plant that is still under construction has never been counted (friend_adjustPowerForPlayer+ // runs when it is finished), so disabling or re-enabling a building site must not move the+ // player's power either way.+ //+ if( powerToAdjust > 0 && !testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ) ){// We can't affect something that consumes, or else we go low power which removes the consumption// which makes us not low power so we add the consumption so we go low power...@@ -4172,19 +4177,6 @@ void Object::xfer( Xfer *xfer )// private statusxfer->xferUnsignedByte( &m_privateStatus );- // OK, now that we have xferred our status bits, it's safe to set the team...- if( xfer->getXferMode() == XFER_LOAD )- {- Team *team = TheTeamFactory->findTeamByID( teamID );- if( team == NULL )- {- DEBUG_CRASH(( "Object::xfer - Unable to load team\n" ));- throw SC_INVALID_DATA;- }- const Bool restoring = true;- setOrRestoreTeam( team, restoring );- }-// geometry infoxfer->xferSnapshot( &m_geometryInfo );@@ -4236,6 +4228,24 @@ void Object::xfer( Xfer *xfer )// disabled till framexfer->xferUser( m_disabledTillFrame, sizeof( UnsignedInt ) * DISABLED_COUNT );+ //+ // OK, now that we have xferred our status bits AND our disabled data, it is safe to set the+ // team: joining one runs friend_adjustPowerForPlayer, which asks isDisabled() - and until the+ // disabled mask above has been read that answer is whatever the fresh object was built with,+ // so a saved game brought a disabled power plant back as a working one.+ //+ if( xfer->getXferMode() == XFER_LOAD )+ {+ Team *team = TheTeamFactory->findTeamByID( teamID );+ if( team == NULL )+ {+ DEBUG_CRASH(( "Object::xfer - Unable to load team\n" ));+ throw SC_INVALID_DATA;+ }+ const Bool restoring = true;+ setOrRestoreTeam( team, restoring );+ }+// special model condition untilxfer->xferUnsignedInt( &m_smcUntil );diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cppindex 2ff28acfd..ff76e6d4b 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp@@ -3239,6 +3239,15 @@ void AIUpdateInterface::privateMoveAwayFromUnit( Object *unit, CommandSourceType{return;}++ //+ // A queued AI command is re-issued a frame or more after it was made, and the object it names+ // can be gone by then - a hacker told to step aside while it is coming out of its hacking state+ // is the reproducible case.+ //+ if (unit == NULL)+ return;+ObjectID id = unit->getID();if (m_stateMachine->getTemporaryState() == AI_MOVE_OUT_OF_THE_WAY) {if (m_moveOutOfWay1 == id) {diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cppindex da1efd3c8..9404b4030 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp@@ -3590,6 +3590,17 @@ extern __int64 Total_Load_3D_Assets;/** Update all objects in the world by invoking their update() methods. */// ------------------------------------------------------------------------------------------------+/** Milliseconds between two performance counter readings. */+static Real logicElapsedMS( const Int64 &from, const Int64 &to )+{+ static Int64 freq = 0;+ if( freq == 0 )+ QueryPerformanceFrequency( (LARGE_INTEGER *)&freq );+ if( freq == 0 )+ return 0.0f;+ return (Real)( (double)(to - from) * 1000.0 / (double)freq );+}+void GameLogic::update( void ){USE_PERF_TIMER(GameLogic_update)@@ -3641,11 +3652,20 @@ void GameLogic::update( void )UnsignedInt now = TheGameLogic->getFrame();TheGameClient->setFrame(now);+ /* A logic frame that runs long is a hitch the player feels, and a release build has no+ profiler to ask about it. Time the frame's own phases and, when the frame runs over+ budget, write down where the time went - a handful of performance counter reads a frame+ costs nothing next to the 33ms the frame is allowed. */+ Int64 tFrameStart = 0, tScripts = 0, tObjects = 0, tAI = 0, tPartition = 0, tFrameEnd = 0;+ QueryPerformanceCounter( (LARGE_INTEGER *)&tFrameStart );+// update (execute) scripts{TheScriptEngine->UPDATE();}+ QueryPerformanceCounter( (LARGE_INTEGER *)&tScripts );+Bool freezeTime = TheTacticalView->isTimeFrozen() && !TheTacticalView->isCameraMovementFinished();freezeTime = freezeTime || TheScriptEngine->isTimeFrozenDebug() || TheScriptEngine->isTimeFrozenScript();@@ -3785,11 +3805,15 @@ void GameLogic::update( void )validateSleepyUpdate();+ QueryPerformanceCounter( (LARGE_INTEGER *)&tObjects );+// update the Artificial Intelligence system{TheAI->UPDATE();}+ QueryPerformanceCounter( (LARGE_INTEGER *)&tAI );+// production updates{TheBuildAssistant->UPDATE();@@ -3800,6 +3824,8 @@ void GameLogic::update( void )ThePartitionManager->UPDATE();}+ QueryPerformanceCounter( (LARGE_INTEGER *)&tPartition );+//// End of frame clean-up//@@ -3841,6 +3867,23 @@ void GameLogic::update( void )+ // how long did that take? only a frame that ran over budget is worth a line in the log+ QueryPerformanceCounter( (LARGE_INTEGER *)&tFrameEnd );+ {+ const Real SLOW_FRAME_MS = 20.0f; // the logic gets 1/30th of a second, 33ms, per frame+ const Real total = logicElapsedMS( tFrameStart, tFrameEnd );+ if( total > SLOW_FRAME_MS && now > 60 && getGameMode() != GAME_SHELL && getGameMode() != GAME_NONE )+ {+ const Real scripts = logicElapsedMS( tFrameStart, tScripts );+ const Real objects = logicElapsedMS( tScripts, tObjects );+ const Real ai = logicElapsedMS( tObjects, tAI );+ const Real partition = logicElapsedMS( tAI, tPartition );+ const Real rest = total - scripts - objects - ai - partition;+ DEBUG_LOG(("SLOW LOGIC FRAME %d: %.1fms | scripts %.1f | objects %.1f | ai %.1f (pathfind %.1f, players %.1f) | partition %.1f | rest %.1f\n",+ now, total, scripts, objects, ai, AI::getLastPathfindMS(), AI::getLastPlayerUpdateMS(), partition, rest));+ }+ }+// increment world timeif (!m_startNewGame){diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex 26d9e150c..88b726389 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -33,6 +33,10 @@#include "GameClient/ControlBar.h"#include "GameClient/InGameUI.h"#include "GameLogic/IncomingDamage.h"+#include "GameLogic/AIPlayer.h"+#include "GameLogic/AIPathfind.h"+#include "Common/TunnelTracker.h"+#include "Common/StateMachine.h"#include <stdio.h>#include <string.h>@@ -1183,3 +1187,271 @@ TEST(placement_grid_snap_puts_footprint_edges_on_cell_lines)/* a template with no footprint worth the name still lands on a whole cell, not on nothing */CHECK_NEAR(InGameUI::snapPlacementAxis(13.0f, 0.0f), 14.5f, 0.0001f);}+++/* The shipped AIData.ini values, so the numbers below are the ones a real game uses. */+static const Real AIDATA_TEAM_SECONDS = 10.0f;+static const Int AIDATA_POOR = 2000;+static const Int AIDATA_WEALTHY = 7000;+static const Real AIDATA_TEAM_POOR_MOD = 0.6f;+static const Real AIDATA_TEAM_RICH_MOD = 2.0f;+static const Real SKIRMISH_RATE = 10.0f/3.0f;++static Int teamDelay(Int money, Real rate)+{+ return AIPlayer::computeBuildDelay(AIDATA_TEAM_SECONDS, money, AIDATA_POOR, AIDATA_WEALTHY,+ AIDATA_TEAM_POOR_MOD, AIDATA_TEAM_RICH_MOD, rate);+}++TEST(ai_build_delay_follows_the_players_bank_account)+{+ /* A campaign AI runs at the rate the data literally says: 10 seconds flat, faster when it+ * is rich, slower when it is broke. */+ CHECK_EQ(teamDelay(4000, 1.0f), 10 * LOGICFRAMES_PER_SECOND);+ CHECK_EQ(teamDelay(9000, 1.0f), 5 * LOGICFRAMES_PER_SECOND);+ CHECK_EQ(teamDelay(1000, 1.0f), (Int)(10.0f / 0.6f * LOGICFRAMES_PER_SECOND));++ /* The thresholds are exclusive on both sides - sitting exactly on Poor or exactly on+ * Wealthy is neither. */+ CHECK_EQ(teamDelay(AIDATA_POOR, 1.0f), 10 * LOGICFRAMES_PER_SECOND);+ CHECK_EQ(teamDelay(AIDATA_WEALTHY, 1.0f), 10 * LOGICFRAMES_PER_SECOND);+}++TEST(skirmish_build_rate_keeps_the_old_pace_but_not_the_old_flat_clamp)+{+ /* The skirmish AI used to clamp both of its timers to a flat 3 seconds every frame they+ * counted down. With the shipped TeamSeconds of 10 that clamp fired for every player at+ * every wealth, so TeamsWealthyRate and TeamsPoorRate did nothing at all. As a rate the+ * neutral case still lands on the same 3 seconds... */+ CHECK_EQ(teamDelay(4000, SKIRMISH_RATE), 3 * LOGICFRAMES_PER_SECOND);++ /* ...and the modifiers around it are alive again: rich presses harder, broke backs off.+ * Under the clamp all three of these were 90. */+ CHECK_EQ(teamDelay(9000, SKIRMISH_RATE), (Int)(1.5f * LOGICFRAMES_PER_SECOND));+ CHECK_EQ(teamDelay(1000, SKIRMISH_RATE), (Int)(5.0f * LOGICFRAMES_PER_SECOND));+ CHECK(teamDelay(9000, SKIRMISH_RATE) < teamDelay(4000, SKIRMISH_RATE));+ CHECK(teamDelay(1000, SKIRMISH_RATE) > teamDelay(4000, SKIRMISH_RATE));++ /* The SET_BASE_CONSTRUCTION_SPEED script action writes the seconds this reads, and the+ * clamp is what used to eat anything it asked for above 3 seconds. */+ const Int scripted = AIPlayer::computeBuildDelay(30.0f, 4000, AIDATA_POOR, AIDATA_WEALTHY,+ AIDATA_TEAM_POOR_MOD, AIDATA_TEAM_RICH_MOD,+ SKIRMISH_RATE);+ CHECK_EQ(scripted, 9 * LOGICFRAMES_PER_SECOND);+ CHECK(scripted > 3 * LOGICFRAMES_PER_SECOND);++ /* StructureSeconds ships as 0, so structures stay on the "as soon as the build delay lets+ * you" path they are on today, whatever the rate is. */+ CHECK_EQ(AIPlayer::computeBuildDelay(0.0f, 9000, AIDATA_POOR, AIDATA_WEALTHY, 0.6f, 2.0f, SKIRMISH_RATE), 0);+}++//////////////////////////////////////////////////////////////////////////////+// Pathfinder cell info pool+//////////////////////////////////////////////////////////////////////////////++/* The A* open and closed lists are drawn from one fixed pool of PathfindCellInfo+ records. A search that walks away from a cell without handing its record back+ leaks one entry, every time it runs, for the rest of the match - and once the+ pool is dry every pathfind on the map fails and the units stop taking orders.+ The pool is private, so the only way to measure it is to drain it. */+enum { CELL_POOL_PROBE_CAP = 400000 };++static Int drainCellInfoPool( void )+{+ PathfindCell *cells = new PathfindCell[ CELL_POOL_PROBE_CAP ];+ Int count = 0;+ while( count < CELL_POOL_PROBE_CAP )+ {+ ICoord2D pos;+ pos.x = count & 0xff;+ pos.y = (count >> 8) & 0xff;+ if( !cells[ count ].allocateInfo( pos ) )+ break;+ count++;+ }+ for( Int i = 0; i < count; i++ )+ cells[ i ].releaseInfo();+ delete [] cells;+ return count;+}++TEST(pathfind_pool_comes_back_whole_after_a_search_is_started)+{+ CHECK(bootOnce());+ PathfindCellInfo::allocateCellInfos();++ const Int baseline = drainCellInfoPool();+ CHECK(baseline > 1000);+ CHECK(baseline < CELL_POOL_PROBE_CAP);++ {+ PathfindCell start, goal;+ ICoord2D sp, gp;+ sp.x = 10; sp.y = 10;+ gp.x = 20; gp.y = 30;+ CHECK(start.allocateInfo(sp));+ CHECK(goal.allocateInfo(gp));++ /* startPathfind used to mark the start cell as sitting on the open list. It is not:+ * the caller assigns it to m_openList by hand rather than linking it in. All the flag+ * did was make releaseInfo() refuse to hand the record back, so every search that gave+ * up early - wrong zone, no path, pool empty - leaked its start cell. */+ start.startPathfind(&goal);+ CHECK(!start.getOpen());+ CHECK(!start.getClosed());++ start.releaseInfo();+ CHECK(!start.hasInfo());+ goal.releaseInfo();+ CHECK(!goal.hasInfo());+ }++ CHECK_EQ(drainCellInfoPool(), baseline);+ PathfindCellInfo::releaseCellInfos();+}++TEST(pathfind_cell_drops_its_parent_link_even_when_it_keeps_its_record)+{+ CHECK(bootOnce());+ PathfindCellInfo::allocateCellInfos();++ const Int baseline = drainCellInfoPool();++ {+ PathfindCell keeper, parent;+ ICoord2D kp, pp;+ kp.x = 5; kp.y = 5;+ pp.x = 6; pp.y = 5;+ CHECK(keeper.allocateInfo(kp));+ CHECK(parent.allocateInfo(pp));+ keeper.setParentCell(&parent);+ CHECK(keeper.getParentCell() == &parent);++ /* An obstacle cell hangs on to its record - releaseInfo() returns early for it. It+ * used to return before clearing the parent link as well, so the cell went on pointing+ * at a record the very next search hands out to some other cell, and walking the path+ * backwards from there reads a stranger's data. */+ keeper.setType(PathfindCell::CELL_OBSTACLE);+ keeper.releaseInfo();+ CHECK(keeper.hasInfo());+ CHECK(keeper.getParentCell() == NULL);++ keeper.setType(PathfindCell::CELL_CLEAR);+ keeper.releaseInfo();+ CHECK(!keeper.hasInfo());+ parent.releaseInfo();+ CHECK(!parent.hasInfo());+ }++ CHECK_EQ(drainCellInfoPool(), baseline);+ PathfindCellInfo::releaseCellInfos();+}++TEST(pathfind_obstacle_state_no_longer_borrows_a_search_record)+{+ CHECK(bootOnce());+ PathfindCellInfo::allocateCellInfos();++ const Int baseline = drainCellInfoPool();++ {+ PathfindCell cell;+ CHECK(!cell.hasInfo());++ /* Which object stands on a cell, whether it is a fence, whether you can see through it+ * and whether an ally is in the way all used to be stored in a pooled search record, so+ * a cell had to hold one open for as long as the wall stood on it - and releaseInfo()+ * refuses to reclaim an obstacle cell, so every building and fence on the map was a+ * permanent bite out of the pool the search draws from. They are cell state now, and a+ * cell answers for them with no record at all. */+ cell.setBlockedByAlly(TRUE);+ CHECK(cell.isBlockedByAlly());+ cell.setBlockedByAlly(FALSE);+ CHECK(!cell.isBlockedByAlly());+ CHECK(cell.getObstacleID() == INVALID_ID);+ CHECK(!cell.isObstacleFence());+ CHECK(!cell.isObstacleTransparent());+ CHECK(!cell.isObstaclePresent((ObjectID)17));++ CHECK(!cell.hasInfo());+ }++ CHECK_EQ(drainCellInfoPool(), baseline);+ PathfindCellInfo::releaseCellInfos();+}+++/* The tunnel network keeps the contain list for every tunnel a player owns, and+ * TunnelContain::killAllContained has to take that whole list away from the tracker before it+ * kills anything: a Terrorist that explodes on death kills the tunnel, and the tunnel's own death+ * walks the same list the outer call is still standing in. Taking the list away is only half of+ * it - the tracker's cached size has to follow, or the game reads a count that no longer matches+ * the list. No Object is touched here, only the bookkeeping. */+TEST(tunneltracker_handing_the_contain_list_over_takes_the_count_with_it)+{+ CHECK(bootOnce());++ TunnelTracker *tracker = newInstance(TunnelTracker);+ CHECK_EQ((Int)tracker->getContainCount(), 0);++ ContainedItemsList seeded;+ seeded.push_back((Object *)0x100);+ seeded.push_back((Object *)0x200);+ seeded.push_back((Object *)0x300);++ tracker->swapContainedItemsList(seeded);+ CHECK(seeded.empty());+ CHECK_EQ((Int)tracker->getContainCount(), 3);+ CHECK_EQ((Int)tracker->getContainedItemsList()->size(), 3);++ /* what killAllContained does: take the list, leave the tracker empty and consistent */+ ContainedItemsList taken;+ tracker->swapContainedItemsList(taken);+ CHECK_EQ((Int)taken.size(), 3);+ CHECK_EQ((Int)tracker->getContainCount(), 0);+ CHECK(tracker->getContainedItemsList()->empty());++ taken.clear();+ tracker->deleteInstance();+}++/* StateMachine is reference counted so that a state update which destroys the+ machine's owner does not pull the machine out from under updateStateMachine.+ The owner's deleteInstance() is now just "drop my reference". */+static Bool s_witnessMachineDestroyed = FALSE;++class WitnessStateMachine : public StateMachine+{+ /* borrow the real machine's pool - same size, and MemoryInit.cpp knows the name */+ MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(WitnessStateMachine, "StateMachinePool")+public:+ WitnessStateMachine() : StateMachine(NULL, "witness") {}+};++WitnessStateMachine::~WitnessStateMachine() { s_witnessMachineDestroyed = TRUE; }++TEST(statemachine_outlives_the_owner_that_lets_go_of_it_mid_update)+{+ CHECK(bootOnce());++ s_witnessMachineDestroyed = FALSE;+ StateMachine *machine = newInstance(WitnessStateMachine);+ CHECK_EQ(machine->Num_Refs(), 1);++ /* what updateStateMachine holds while m_currentState->update() runs */+ machine->Add_Ref();+ CHECK_EQ(machine->Num_Refs(), 2);++ /* the state update kills the owning object, which deletes its machine */+ machine->deleteInstance();+ CHECK(!s_witnessMachineDestroyed);+ CHECK_EQ(machine->Num_Refs(), 1);++ /* update() returns, updateStateMachine drops its reference - now it goes */+ machine->Release_Ref();+ CHECK(s_witnessMachineDestroyed);++ /* and deleteInstance() still tolerates a NULL machine, the way the pool one did */+ machine = NULL;+ machine->deleteInstance();+}