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.

perf(gamelogic): resume pathfinder searches across frames

Olcay Seygan27ae1f54d9a3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1b56f61f6..4b81a622f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -29,6 +29,10 @@ found and fixed, EA's own, not port damage.**
- You pick for your own seat and the host picks for the computer seats, the way colour and team already work. The pick is in the replay and the saved game, and a room that leaves the column at 100% plays and replays as it did.
- Promotions and armour research still come on top, at the seat's share: an Elite Paladin with Composite Armor reads 364 at 50% against 728 at 100%. A vehicle stolen from a handicapped player moves to its new owner's column and keeps its share of health, so a Humvee at 80 of 120 becomes 160 of 240 with no damage dealt and no repair given.
+## Long routes in big computer matches
+
+- A unit looking for a long way across a crowded map no longer stops mid-search and gives up, and a big match no longer stalls the frame while a few units work out where to go. A search that runs out of its share of a step waits for the next one and carries on, and the limit on how much ground one search can cover is doubled. In eight Hard computer players on Twilight Flame, six matches a side, the pathfinding cost 34.9 seconds a match where it cost 42.8, with 28% fewer cells searched, and fewer units sat wedged. Replays recorded before this change play out differently.
+
## Computer players earn double
- A computer player in a skirmish or a network match now earns double, on every difficulty. A truckload worth 75 banks 150, and the 1000 for capturing an oil derrick is 2000. It counts everything the computer makes by playing: supply docks, oil derricks and other tech buildings, black markets, drop zones, hackers, bounties, crates, salvage and stolen cash. On one generated map, two Easy computers earned 25,800 and 28,200 in six minutes and forty seconds and now earn 51,600 and 56,400. Two Hard ones on the same seed went from 22,800 and 24,825 to 74,800 and 81,090, because Hard spends the extra money on more income: one of them built four supply centers and two drop zones where it used to build two and one.
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
index 409a22cfb..cf80efa3e 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
@@ -959,6 +959,8 @@ public:
static void bumpCrowdRepath( void ); ///< a unit gave up on its route rather than steer round
static void bumpDither( void ); ///< a unit was caught driving a long way and gaining nothing
void processPathfindQueue(void); ///< Process some or all of the queued pathfinds.
+ /// this unit's search ran out of the frame's cells and carries on at its next turn in the queue
+ Bool isSearchSuspended( ObjectID id ) const { return id != INVALID_ID && m_search.owner == id && !m_search.done; }
void forceMapRecalculation( ); ///< Force pathfind map recomputation. If region is given, only that area is recomputed
/** Returns an aircraft path to the goal. */
@@ -1102,6 +1104,10 @@ public:
protected:
virtual Path *internalFindPath( Object *obj, const LocomotorSet& locomotorSet, const Coord3D *from, const Coord3D *to); ///< Find a short, valid path between given locations
+ Path *continueFindPath( Object *obj, const LocomotorSet& locomotorSet, Bool mayStop ); ///< internalFindPath's cell search, from wherever it last stopped
+ void settleSuspendedSearch( void ); ///< finish a stopped search before another search takes the lists
+ void dropSuspendedSearch( void ); ///< throw a stopped search away
+ void closeSearch( void ); ///< hand back the lists of the main search that just ended
Path *findHierarchicalPath( Bool isHuman, const LocomotorSet& locomotorSet, const Coord3D *from, const Coord3D *to, Bool crusher);
Path *findClosestHierarchicalPath( Bool isHuman, const LocomotorSet& locomotorSet, const Coord3D *from, const Coord3D *to, Bool crusher);
Path *internal_findHierarchicalPath( Bool isHuman, const LocomotorSurfaceTypeMask locomotorSurface, const Coord3D *from, const Coord3D *to, Bool crusher, Bool closestOK);
@@ -1294,6 +1300,36 @@ private:
std::vector<bool> m_isQueuedForPath;
Int m_cumulativeCellsAllocated;
+ /* The main cell search's state, kept here rather than on the stack so a search that runs out of
+ the queue's cells for the frame can stop and carry on from the same cell next frame. At most
+ one is ever stopped: it belongs to the unit at the head of the queue, which keeps that place
+ until the search ends, so requests are still answered in the order they came. Its cells stay
+ on m_openList and m_closedList, so any other search first finishes it (settleSuspendedSearch)
+ and keeps the answer for the unit's next turn. Never saved: a loaded game starts that unit's
+ search over. */
+ struct ResumableSearch
+ {
+ ObjectID owner; ///< the unit a stopped search belongs to, INVALID_ID when none
+ Bool done; ///< another search finished it, and result is the answer
+ Bool claimed; ///< the owner's turn in the queue carried it on or took the answer
+ Path *result;
+ Coord3D from, rawTo, to;
+ PathfindCell *goalCell, *parentCell, *closestCell;
+ Real closestDistanceSqr;
+ ICoord2D startCellNdx, goalCellNdx;
+ Int radius;
+ Bool centerInCell, isHuman;
+ Int cellCount; ///< cells taken so far, all frames together
+ Int credited; ///< of those, already charged to earlier frames' budgets
+ Bool isTunneling, ignoreUnderConstruction, restricted;
+ ObjectID ignoreObstacleID;
+ UnsignedInt flowNow, flowNowBucket; ///< the flow clock starts when the search did, not when it resumed
+ Real startDirX, startDirY;
+ Bool startDirValid;
+ };
+ ResumableSearch m_search;
+ ObjectID m_queueOwnerID; ///< the unit whose turn in the queue is running, INVALID_ID outside it
+
/* diagnostics only - never read by the simulation, so it stays out of xfer(). Records
whether the cell search now running was fenced into a hierarchical corridor or was let
loose on the whole map, so the slow-search log can say which of the two is costing the
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
index abf9a6e5f..d1ac21088 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
@@ -772,8 +772,8 @@ public:
TunnelTripEnd getTunnelTripEnd() const { return m_tunnelTripEnd; } ///< how the leg from the far mouth is walked
void startGarrisonSearch(); ///< the auto garrison key: into the nearest free seat around here, and on to the next while a building turns the unit away
Bool isSeekingGarrison() const { return m_isSeekingGarrison; } ///< on an auto garrison search, so a building lost on the way is no target
-#if defined(_DEBUG) || defined(_INTERNAL)
inline const Coord3D *friend_getRequestedDestination() const { return &m_requestedDestination; }
+#if defined(_DEBUG) || defined(_INTERNAL)
inline const Coord3D *friend_getRequestedDestination2() const { return &m_requestedDestination2; }
#endif
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
index d62e69a4c..e62973a85 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
@@ -1792,8 +1792,14 @@ Bool PathfindCell::allocateInfo( const ICoord2D &pos )
/**
* Releases an info record for a cell.
*/
-void PathfindCell::releaseInfo( void )
-{
+void PathfindCell::releaseInfo( void )
+{
+ // still on a search's open or closed list: a unit left the cell while a search stopped by the
+ // queue's budget holds it. The parent link is that search's route, and the search hands the
+ // info back itself when it ends.
+ if (m_info && (m_info->m_prevOpen || m_info->m_nextOpen || m_info->m_open || m_info->m_closed)) {
+ return;
+ }
// 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) {
@@ -1810,14 +1816,8 @@ void PathfindCell::releaseInfo( void )
}
if (m_info) {
- DEBUG_ASSERTCRASH(m_info->m_prevOpen==NULL && m_info->m_nextOpen==NULL, ("Shouldn't be linked."));
- DEBUG_ASSERTCRASH(m_info->m_open==NULL && m_info->m_closed==NULL, ("Shouldn't be linked."));
DEBUG_ASSERTCRASH(m_info->m_goalUnitID==INVALID_ID && m_info->m_posUnitID==INVALID_ID, ("Shouldn't be occupied."));
DEBUG_ASSERTCRASH(m_info->m_goalAircraftID==INVALID_ID , ("Shouldn't be occupied by aircraft."));
- if (m_info->m_prevOpen || m_info->m_nextOpen || m_info->m_open || m_info->m_closed) {
- // Bad release. Skip for now, better leak than crash. jba.
- return;
- }
PathfindCellInfo::releaseACellInfo(m_info);
m_info = NULL;
}
@@ -4604,9 +4604,14 @@ Pathfinder::Pathfinder( void ) :m_map(NULL),
m_clearance(NULL), m_clearanceDirty(true), m_clearanceFrame(0),
m_traffic(NULL), m_trafficCells(NULL), m_numTrafficCells(0), m_trafficDecayFrame(0),
m_claims(NULL), m_claimTouch(NULL),
- m_flowCosts(false), m_flowSpeed(0), m_flowNow(0), m_flowNowBucket(0)
+ m_flowCosts(false), m_flowSpeed(0), m_flowNow(0), m_flowNowBucket(0),
+ m_queueOwnerID(INVALID_ID)
{
debugPath = NULL;
+ m_search.owner = INVALID_ID;
+ m_search.done = FALSE;
+ m_search.claimed = FALSE;
+ m_search.result = NULL;
PathfindCellInfo::allocateCellInfos();
reset();
}
@@ -5365,6 +5370,8 @@ const char *Pathfinder::getProfileReport( void )
void Pathfinder::reset( void )
{
+ dropSuspendedSearch(); // while its cells still exist
+ m_queueOwnerID = INVALID_ID;
m_probeBestDistSqr = 0x7FFFFFFF;
frameToShowObstacles = 0;
DEBUG_LOG(("Pathfind cell is %d bytes, PathfindCellInfo is %d bytes\n", sizeof(PathfindCell), sizeof(PathfindCellInfo)));
@@ -5713,6 +5720,7 @@ void Pathfinder::classifyObjectFootprint( Object *obj, Bool insert )
}
}
// recalc the wall.
+ dropSuspendedSearch(); // its cells are reset, infos and all
m_layers[LAYER_WALL].classifyWallCells(m_wallPieces, m_numWallPieces);
}
}
@@ -6083,6 +6091,7 @@ void Pathfinder::classifyMapCell( Int i, Int j , PathfindCell *cell)
*/
void Pathfinder::newMap( void )
{
+ dropSuspendedSearch();
m_wallHeight = TheAI->getAiData()->m_wallHeight; // may be updated by map.ini.
Region3D terrainExtent;
TheTerrainLogic->getMaximumPathfindExtent( &terrainExtent );
@@ -6146,6 +6155,7 @@ void Pathfinder::newMap( void )
*/
void Pathfinder::classifyMap(void)
{
+ dropSuspendedSearch(); // cell->reset() below takes the infos out from under its lists
Int i, j;
// for now, sample cell corners and classify cell accordingly
@@ -6393,6 +6403,63 @@ void Pathfinder::cleanOpenAndClosedLists(void) {
}
+/// the main search ended: its lists go back, and the cells it charged to earlier frames are not
+/// charged again to this one
+void Pathfinder::closeSearch( void )
+{
+ cleanOpenAndClosedLists();
+ m_cumulativeCellsAllocated -= m_search.credited;
+ m_search.credited = 0;
+ m_search.owner = INVALID_ID;
+}
+
+/// a stopped search nobody is going to want, or one whose cells are about to be reclassified
+void Pathfinder::dropSuspendedSearch( void )
+{
+ if (m_search.owner == INVALID_ID)
+ return;
+ if (m_search.done) {
+ if (m_search.result)
+ m_search.result->deleteInstance();
+ m_search.result = NULL;
+ m_search.done = FALSE;
+ m_search.owner = INVALID_ID;
+ return;
+ }
+ m_isTunneling = false;
+ closeSearch();
+ m_search.goalCell->releaseInfo();
+}
+
+/** Another search is about to use the open and closed lists while a stopped one still has its
+ * cells on them. So the stopped one is finished now, past the frame's budget, and the answer is
+ * kept for its unit's next turn in the queue. A unit that no longer wants that answer - gone,
+ * asking for somewhere else, or itself the one asking now - just loses the search. */
+void Pathfinder::settleSuspendedSearch( void )
+{
+ if (m_search.owner == INVALID_ID || m_search.done)
+ return;
+ Object *obj = TheGameLogic->findObjectByID( m_search.owner );
+ AIUpdateInterface *ai = obj ? obj->getAIUpdateInterface() : NULL;
+ const Coord3D *wanted = ai ? ai->friend_getRequestedDestination() : NULL;
+ if (ai == NULL || !ai->isWaitingForPath() || m_search.owner == m_queueOwnerID ||
+ wanted->x != m_search.rawTo.x || wanted->y != m_search.rawTo.y) {
+ dropSuspendedSearch();
+ return;
+ }
+ const ObjectID owner = m_search.owner;
+ const ObjectID ignoreID = m_ignoreObstacleID;
+ const Bool ignoreSites = m_ignoreUnderConstruction;
+ const Bool restricted = m_lastSearchRestricted;
+ Path *path = continueFindPath( obj, ai->getLocomotorSet(), FALSE );
+ m_ignoreObstacleID = ignoreID;
+ m_ignoreUnderConstruction = ignoreSites;
+ m_lastSearchRestricted = restricted;
+ m_search.owner = owner;
+ m_search.done = TRUE;
+ m_search.result = path;
+}
+
//-------------------------------------------------------------------------------------------------
/** Is this obstacle cell one the builder now searching is allowed to walk over - a structure that
@@ -7721,8 +7788,9 @@ void Pathfinder::processPathfindQueue(void)
#pragma message("AHHHH!, forced calls to pathzonerefresh still in code... notify M Lorenzen")
s_stopForceCalling==FALSE ||
#endif
- m_zoneManager.needToCalculateZones())
+ m_zoneManager.needToCalculateZones())
{
+ dropSuspendedSearch(); // its corridor is in the old zone numbers; the unit starts over
m_zoneManager.calculateZones(m_map, m_layers, m_extent);
return;
}
@@ -7768,18 +7836,33 @@ void Pathfinder::processPathfindQueue(void)
requestsThisFrame < PATHFIND_REQUESTS_PER_FRAME &&
m_queuePRTail!=m_queuePRHead) {
++requestsThisFrame;
- Object *obj = TheGameLogic->findObjectByID(m_queuedPathfindRequests[m_queuePRHead]);
- m_isQueuedForPath[m_queuedPathfindRequests[m_queuePRHead]] = false;
+ const ObjectID id = m_queuedPathfindRequests[m_queuePRHead];
+ Object *obj = TheGameLogic->findObjectByID(id);
+ m_isQueuedForPath[id] = false;
m_queuedPathfindRequests[m_queuePRHead] = INVALID_ID;
+ m_search.claimed = FALSE;
if (obj) {
AIUpdateInterface *ai = obj->getAIUpdateInterface();
if (ai) {
+ m_queueOwnerID = id;
ai->doPathfind(this);
+ m_queueOwnerID = INVALID_ID;
#ifdef DEBUG_QPF
pathsFound++;
#endif
}
}
+ // a stopped search its unit did not come back for: gone, or asking something else now
+ if (m_search.owner != INVALID_ID && !m_search.claimed) {
+ dropSuspendedSearch();
+ }
+ if (m_search.owner != INVALID_ID) {
+ // the frame's cells ran out inside this unit's search: it keeps the head of the queue and
+ // carries on from the same cell next frame, so nobody behind it is answered first
+ m_queuedPathfindRequests[m_queuePRHead] = id;
+ m_isQueuedForPath[id] = true;
+ break;
+ }
m_queuePRHead = m_queuePRHead+1;
if (m_queuePRHead >= PATHFIND_QUEUE_LEN) {
m_queuePRHead = 0;
@@ -8287,6 +8370,24 @@ Path *Pathfinder::findPath( Object *obj, const LocomotorSet& locomotorSet, const
const Coord3D *rawTo)
{
PathProfile pfProfile( PF_FIND );
+ // the unit whose search the budget stopped, at the head of the queue again for the same goal:
+ // carry on from the cell it stopped on, in the corridor it was laid in, or take the answer
+ // another search finished for it in the meantime
+ if (obj && obj->getID() == m_search.owner && m_search.owner == m_queueOwnerID &&
+ rawTo->x == m_search.rawTo.x && rawTo->y == m_search.rawTo.y) {
+ m_search.claimed = TRUE;
+ if (m_search.done) {
+ Path *path = m_search.result;
+ m_search.result = NULL;
+ m_search.done = FALSE;
+ m_search.owner = INVALID_ID;
+ return path;
+ }
+ return continueFindPath(obj, locomotorSet, TRUE);
+ }
+ // the main search's state is about to be laid out again; only the queue asks for it, so whatever
+ // is held is the head unit's and it has just asked for something else
+ dropSuspendedSearch();
if (!clientSafeQuickDoesPathExist(locomotorSet, from, rawTo)) {
return NULL;
}
@@ -8373,14 +8474,6 @@ Path *Pathfinder::internalFindPath( Object *obj, const LocomotorSet& locomotorSe
DEBUG_LOG(("internal find path...\n"));
#endif
-#if defined _DEBUG || defined _INTERNAL
- Int startTimeMS = Clock_Milliseconds_Coarse();
-#endif
- // release-visible timing (DebugLogFile.txt) for searches that cost a visible frame: how
- // much was the A* itself and how much the path build/optimize after it
- Int64 fpFreq64 = 0, fpT0 = 0;
- fpFreq64 = Clock_Ticks_Per_Second();
- fpT0 = Clock_Ticks();
Bool centerInCell = true;
Int radius = 0;
if (obj) {
@@ -8523,7 +8616,75 @@ Path *Pathfinder::internalFindPath( Object *obj, const LocomotorSet& locomotorSe
// "closed" list is initially empty
m_closedList = NULL;
- Int cellCount = 0;
+ // what the cell search needs from here on, kept where it can be picked up again next frame
+ ResumableSearch &s = m_search;
+ s.from = *from;
+ s.rawTo = *rawTo;
+ s.to = adjustTo;
+ s.goalCell = goalCell;
+ s.parentCell = parentCell;
+ s.closestCell = NULL;
+ s.closestDistanceSqr = FLT_MAX;
+ s.startCellNdx = startCellNdx;
+ s.goalCellNdx = cell;
+ s.radius = radius;
+ s.centerInCell = centerInCell;
+ s.isHuman = isHuman;
+ s.cellCount = 0;
+ s.credited = 0;
+ // only the request at the head of the queue has a budget to run out of
+ return continueFindPath(obj, locomotorSet, obj != NULL && obj->getID() == m_queueOwnerID);
+}
+
+/**
+ * The A* loop of internalFindPath, from wherever the search last stopped. With mayStop it stops
+ * again once the queue's cells for this frame are spent: the lists stay as they are, the answer is
+ * NULL and isSearchSuspended() says why. The budget is a count of cells, so every machine stops
+ * on the same one.
+ */
+Path *Pathfinder::continueFindPath( Object *obj, const LocomotorSet& locomotorSet, Bool mayStop )
+{
+ ResumableSearch &s = m_search;
+ if (s.owner != INVALID_ID) {
+ // a search stopped on an earlier frame: put back what it was searching with
+ beginFlowSearch(obj);
+ m_flowNow = s.flowNow;
+ m_flowNowBucket = s.flowNowBucket;
+ thePathStartDirX = s.startDirX;
+ thePathStartDirY = s.startDirY;
+ thePathStartDirValid = s.startDirValid;
+ m_isTunneling = s.isTunneling;
+ m_ignoreObstacleID = s.ignoreObstacleID;
+ m_ignoreUnderConstruction = s.ignoreUnderConstruction;
+ m_lastSearchRestricted = s.restricted;
+ /* Every cell the search owns is on its lists, which releaseInfo leaves alone - except the
+ goal, which holds an info from the start and joins a list only once it is reached. A unit
+ clearing its goal or position there in between hands that info back, so it is fetched
+ again; nothing points at it, since the goal is nobody's parent yet. */
+ if (!s.goalCell->allocateInfo(s.goalCellNdx)) {
+ dropSuspendedSearch();
+ return NULL;
+ }
+ }
+#if defined _DEBUG || defined _INTERNAL
+ Int startTimeMS = Clock_Milliseconds_Coarse();
+#endif
+ // release-visible timing (DebugLogFile.txt) for searches that cost a visible frame: how
+ // much was the A* itself and how much the path build/optimize after it
+ Int64 fpFreq64 = 0, fpT0 = 0;
+ fpFreq64 = Clock_Ticks_Per_Second();
+ fpT0 = Clock_Ticks();
+ const Coord3D *from = &s.from;
+ const Coord3D *rawTo = &s.rawTo;
+ const Coord3D *to = &s.to;
+ PathfindCell *goalCell = s.goalCell;
+ PathfindCell *parentCell = s.parentCell;
+ const Bool isHuman = s.isHuman;
+ const Bool centerInCell = s.centerInCell;
+ const Int radius = s.radius;
+ const ICoord2D startCellNdx = s.startCellNdx;
+ Int cellCount = s.cellCount;
+ const Int cellsBefore = cellCount;
/* Every other search in this file caps the cells it will look at - findClosestPath has
MAX_CELL_COUNT, patchPath has CELL_LIMIT, findAttackPath has ATTACK_CELL_LIMIT - and this
@@ -8546,9 +8707,11 @@ Path *Pathfinder::internalFindPath( Object *obj, const LocomotorSet& locomotorSe
A truncated route is a unit walking at a wall it cannot see round, and it pays for that with
another search a second later. Three separate attempts to buy the tail with search capacity
(this, twice, and the queue's cell budget) all bought it with movement instead. */
- enum { MAX_INTERNAL_CELL_COUNT = 20000 };
- PathfindCell *closestCell = NULL;
- Real closestDistanceSqr = FLT_MAX;
+ /* Since the search stops at the queue's cell budget and carries on next frame, this no longer
+ bounds a frame, so it is no longer the 20000 it was for that. What is left for it to bound is
+ how long one request holds the head of the queue - 40000 cells is 16 frames at 2500 a frame -
+ and the cell-info pool, so a goal that cannot be reached still ends. */
+ enum { MAX_INTERNAL_CELL_COUNT = 40000 };
Bool hitCellCap = false;
//
@@ -8608,7 +8771,7 @@ Path *Pathfinder::internalFindPath( Object *obj, const LocomotorSet& locomotorSe
cellCount, searchMs, buildMs, nodes, from->x, from->y, rawTo->x, rawTo->y));
}
}
- cleanOpenAndClosedLists();
+ closeSearch();
parentCell->releaseInfo();
return path;
}
@@ -8623,9 +8786,9 @@ Path *Pathfinder::internalFindPath( Object *obj, const LocomotorSet& locomotorSe
Int dx = IABS(goalCell->getXIndex()-parentCell->getXIndex());
Int dy = IABS(goalCell->getYIndex()-parentCell->getYIndex());
Real distSqr = (Real)(dx*dx+dy*dy);
- if (distSqr < closestDistanceSqr) {
- closestDistanceSqr = distSqr;
- closestCell = parentCell;
+ if (distSqr < s.closestDistanceSqr) {
+ s.closestDistanceSqr = distSqr;
+ s.closestCell = parentCell;
}
}
@@ -8634,14 +8797,37 @@ Path *Pathfinder::internalFindPath( Object *obj, const LocomotorSet& locomotorSe
cellCount += examineNeighboringCells(parentCell, goalCell, locomotorSet, isHuman, centerInCell, radius, startCellNdx, obj, NO_ATTACK);
+ if (mayStop && m_openList != NULL &&
+ m_cumulativeCellsAllocated + (cellCount - cellsBefore) >= PATHFIND_CELLS_PER_FRAME) {
+ // the frame's cells are spent: keep the lists and carry on from here next frame, charging
+ // this frame for the part it did
+ m_cumulativeCellsAllocated += cellCount - cellsBefore;
+ s.credited += cellCount - cellsBefore;
+ s.cellCount = cellCount;
+ s.parentCell = parentCell;
+ s.owner = obj->getID();
+ s.done = FALSE;
+ s.claimed = TRUE;
+ s.flowNow = m_flowNow;
+ s.flowNowBucket = m_flowNowBucket;
+ s.startDirX = thePathStartDirX;
+ s.startDirY = thePathStartDirY;
+ s.startDirValid = thePathStartDirValid;
+ s.isTunneling = m_isTunneling;
+ s.ignoreObstacleID = m_ignoreObstacleID;
+ s.ignoreUnderConstruction = m_ignoreUnderConstruction;
+ s.restricted = m_lastSearchRestricted;
+ m_isTunneling = false;
+ return NULL;
+ }
}
/* the cap stopped the search - return the best partial route rather than nothing, so the unit
closes on the goal and the next request picks up from there. The partial path is built the
same way a complete one is, so the caller cannot tell the difference and nothing downstream
needs to learn about capped searches. */
- if (hitCellCap && closestCell && closestCell != parentCell) {
- Path *partial = buildActualPath( obj, locomotorSet.getValidSurfaces(), from, closestCell, centerInCell, false );
+ if (hitCellCap && s.closestCell && s.closestCell != parentCell) {
+ Path *partial = buildActualPath( obj, locomotorSet.getValidSurfaces(), from, s.closestCell, centerInCell, false );
if (partial) {
if (fpFreq64 > 0) {
Int64 fpTCap = 0;
@@ -8650,10 +8836,10 @@ Path *Pathfinder::internalFindPath( Object *obj, const LocomotorSet& locomotorSe
TheGameLogic->getFrame(), obj ? obj->getTemplate()->getName().str() : "?",
m_lastSearchRestricted ? "corridor" : "openmap",
cellCount, 1000.0f * (Real)(fpTCap - fpT0) / (Real)fpFreq64,
- (Int)sqrt(closestDistanceSqr), from->x, from->y, rawTo->x, rawTo->y));
+ (Int)sqrt(s.closestDistanceSqr), from->x, from->y, rawTo->x, rawTo->y));
}
m_isTunneling = false;
- cleanOpenAndClosedLists();
+ closeSearch();
parentCell->releaseInfo();
goalCell->releaseInfo();
return partial;
@@ -8699,6 +8885,7 @@ Path *Pathfinder::internalFindPath( Object *obj, const LocomotorSet& locomotorSe
if (obj) {
Bool valid;
+ const Bool isCrusher = obj->getCrusherLevel() > 0;
valid = validMovementPosition( isCrusher, obj->getLayer(), locomotorSet, to ) ;
DEBUG_LOG(("%d ", TheGameLogic->getFrame()));
@@ -8728,7 +8915,7 @@ Path *Pathfinder::internalFindPath( Object *obj, const LocomotorSet& locomotorSe
from->x, from->y, to->x, to->y, cellCount, failMs));
}
m_isTunneling = false;
- cleanOpenAndClosedLists();
+ closeSearch();
parentCell->releaseInfo();
goalCell->releaseInfo();
return NULL;
@@ -9033,6 +9220,7 @@ Path *Pathfinder::findGroundPath( const Coord3D *from,
DEBUG_LOG(("Find ground path..."));
#endif
Bool centerInCell = false;
+ settleSuspendedSearch();
beginFlowSearch(NULL); // the group corridor is terrain, and every member rides it
m_zoneManager.clearPassableFlags();
@@ -9527,6 +9715,7 @@ Path *Pathfinder::internal_findHierarchicalPath( Bool isHuman, const LocomotorSu
#if defined _DEBUG || defined _INTERNAL
Int startTimeMS = Clock_Milliseconds_Coarse();
#endif
+ settleSuspendedSearch();
beginFlowSearch(NULL); // "is there a way at all" must not be talked out of it by traffic
if (rawTo->x == 0.0f && rawTo->y == 0.0f) {
@@ -10281,6 +10470,7 @@ Bool Pathfinder::pathDestination( Object *obj, const LocomotorSet& locomotorSet
{
//CRCDEBUG_LOG(("Pathfinder::pathDestination()\n"));
if (m_isMapReady == false) return NULL;
+ settleSuspendedSearch();
beginFlowSearch(NULL);
if (!obj) return false;
@@ -10568,6 +10758,7 @@ Int Pathfinder::checkPathCost(Object *obj, const LocomotorSet& locomotorSet, con
{
//CRCDEBUG_LOG(("Pathfinder::checkPathCost()\n"));
if (m_isMapReady == false) return NULL;
+ settleSuspendedSearch();
beginFlowSearch(NULL); // this is a yardstick between two points, not a route anybody drives
enum {MAX_COST = 0x7fff0000};
if (!obj) return MAX_COST;
@@ -10777,6 +10968,7 @@ Path *Pathfinder::findClosestPath( Object *obj, const LocomotorSet& locomotorSet
Coord3D *rawTo, Bool blocked, Real pathCostMultiplier, Bool moveAllies)
{
PathProfile pfProfile( PF_CLOSEST );
+ settleSuspendedSearch();
beginFlowSearch(obj);
//CRCDEBUG_LOG(("Pathfinder::findClosestPath()\n"));
#if defined _DEBUG || defined _INTERNAL
@@ -11855,7 +12047,8 @@ Bool Pathfinder::isGroundPathPassable( Bool isCrusher, const Coord3D& startWorld
*/
void Pathfinder::changeBridgeState( PathfindLayerEnum layer, Bool repaired)
{
- if (m_layers[layer].isUnused()) return;
+ if (m_layers[layer].isUnused()) return;
+ dropSuspendedSearch(); // the bridge's cells are reset, infos and all
if (m_layers[layer].setDestroyed(!repaired)) {
m_zoneManager.markZonesDirty( repaired );
}
@@ -12383,6 +12576,7 @@ Path *Pathfinder::getMoveAwayFromPath(Object* obj, Object *otherObj,
Path *pathToAvoid, Object *otherObj2, Path *pathToAvoid2)
{
PathProfile pfProfile( PF_MOVEAWAY );
+ settleSuspendedSearch();
beginFlowSearch(NULL);
if (m_isMapReady == false) return NULL; // Should always be ok.
#if defined _DEBUG || defined _INTERNAL
@@ -12560,6 +12754,7 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSet
Path *originalPath, Bool blocked )
{
PathProfile pfProfile( PF_PATCH );
+ settleSuspendedSearch();
beginFlowSearch(obj);
//CRCDEBUG_LOG(("Pathfinder::patchPath()\n"));
#if defined _DEBUG || defined _INTERNAL
@@ -12747,6 +12942,7 @@ Path *Pathfinder::findAttackPath( const Object *obj, const LocomotorSet& locomot
const Object *victim, const Coord3D* victimPos, const Weapon *weapon )
{
PathProfile pfProfile( PF_ATTACK );
+ settleSuspendedSearch();
beginFlowSearch(NULL); // "where can I shoot from" is not a movement route
/*
CRCDEBUG_LOG(("Pathfinder::findAttackPath() for object %d (%s)\n", obj->getID(), obj->getTemplate()->getName().str()));
@@ -13106,6 +13302,7 @@ Path *Pathfinder::findSafePath( const Object *obj, const LocomotorSet& locomotor
const Coord3D *from, const Coord3D* repulsorPos1, const Coord3D* repulsorPos2, Real repulsorRadius)
{
PathProfile pfProfile( PF_SAFE );
+ settleSuspendedSearch();
beginFlowSearch(NULL); // running away prices danger, not traffic
//CRCDEBUG_LOG(("Pathfinder::findSafePath()\n"));
if (m_isMapReady == false) return NULL; // Should always be ok.
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
index e51764d36..a7b51e0ef 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
@@ -2249,8 +2249,16 @@ Bool AIUpdateInterface::computePath( PathfindServicesInterface *pathServices, Co
theNewPath = pathServices->patchPath( getObject(), m_locomotorSet,
getPath(), m_isBlockedAndStuck);
} else {
- theNewPath = pathServices->findPath( getObject(), m_locomotorSet, getObject()->getPosition(),
+ theNewPath = pathServices->findPath( getObject(), m_locomotorSet, getObject()->getPosition(),
destination);
+ if (theNewPath == NULL && TheAI->pathfinder()->isSearchSuspended( getObject()->getID() )) {
+ // the queue's cells for this frame ran out inside the search: still waiting, still at
+ // the head of the queue, and the search carries on from where it stopped next frame
+ TheAI->pathfinder()->setIgnoreObstacleID( INVALID_ID );
+ TheAI->pathfinder()->setIgnoreUnderConstruction( FALSE );
+ m_waitingForPath = TRUE;
+ return FALSE;
+ }
}
}
if (theNewPath==NULL && m_path==NULL) {