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.

feat(gameengine): let a unit stuck in a queue repath round it

Olcay Seygan3380080cc15f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e14106daa..288d7cb9d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -442,6 +442,7 @@ found and fixed — EA's own, not port damage.**
- The coarse route is widened along its whole length, not just at the start.
- The main search stops after 20,000 squares and hands back a partial route.
- Units heading the same way take the lane beside the traffic instead of joining the back of it. Ground another unit is already driving over costs a little to plan through, so a column spreads into parallel lanes at the gate it forms at. Over twenty-four full matches the time units spend standing behind each other dropped by a third, and the searches to do it cost 6% more squares - the price is capped, or a crowded route would be worth walking around the map to avoid.
+- A unit that has stood behind another one for a second and a half stops waiting and plans its own way round it. For that one route, ground somebody else is parked on costs real money, so the tank at the back pulls out of the line, drives past the ones standing in it and rejoins in front, instead of idling until the line decides to move. Two things had been holding it there. The engine only counted you as blocked while you were actually touching the unit ahead, and a tank in a queue does not touch every frame - it creeps up, nudges, backs off its speed, drifts apart, touches again - so the count kept resetting to zero and the two-second rule that asks for a new route never fired at all; it now decays instead of resetting, so touching more often than you clear still gets you there. And a unit approaching something to shoot refused to re-plan for as long as its target stood still, which is precisely the case where a dozen tanks arrive at the same building and stack up behind each other. Over forty-eight full matches the time units spend standing behind each other fell on both halves of the batch, and the worst jam in it was halved; the searches that do it never once came back with no route.
- A group you send across the map travels abreast instead of nose to tail. Up to forty units it is given one corridor wide enough for the whole group and split into columns, so it crosses a gap side by side and the outside of the column takes the wider way round. Where the ground is too tight for a full-width corridor - a bridge, a ramp, a gap between two cliffs - the group is given the widest corridor that fits instead of being dropped back to every unit for itself, which is what used to turn exactly those crossings into a single queue. The columns then close up to whatever width the ground allows and open out again on the far side, and a unit whose place in the column would put it in a cliff or a wall takes the middle of the road instead of driving into the rock and stopping. The gap between columns is measured off the units you actually selected rather than fixed at a guess that was narrower than a tank, so a group of tanks spreads wider than a group of scout cars and side by side means side by side instead of a trip spent shoving. Two units sharing a column drive one line, in file, which is what a column is for, and they arrive on that same spacing rather than piling onto one spot. The route itself is straightened as it is handed out: a corner is only driven if it is a real corner, so a group crossing open ground goes in long straight runs rather than nodding left and right the whole way, which is both faster and how a column of tanks is supposed to look. That corridor is only skipped for selections larger than any hand ever drags a box around.
- Routes now look ahead in time, not just in space. Every unit on the move leaves a note of *when* it expects to be on each square and which way it will be facing, and a route that would put you on a square somebody else wants at that same moment, coming the other way, costs extra to plan. Traffic going your way is free - the unit in front of you is about to not be there, and a queue along one road is what a road is for. So two groups sent through each other pick their gaps before they meet instead of grinding to a halt nose to nose in the middle. In the model of this movement code, sixteen units crossing each other on open ground cut the time spent standing still by a quarter, arrived sooner, and the planning itself cost under one percent more.
- Long turns went from 513 to 201, and the worst from 2,976ms to 243ms.
@@ -489,6 +490,8 @@ found and fixed — EA's own, not port damage.**
- The opponent's decisions are argued with a number: 20 headless matches per change, same seeds, win rate and match length before and after.
- That caught two changes that looked right and measured catastrophic - a wave that waited jammed the whole production line, and a retreat rule that counted buildings as gunfire sent every attack home. Both showed up as twenty matches with zero kills.
- Massing an army before attacking is written and measured but switched off: it needs somewhere to wait that is not the production queue.
+- The self-play harness cannot see a traffic jam. Leaving a queue was measured over ninety-six matches and thirty-three of the forty-eight maps came out bit-identical, because a computer opponent moves five units at a time and never forms the queue a human makes by dragging a box round fifteen tanks. Where a jam did occur it got better, and nothing regressed, but the honest statement is that the number is thin: the rule fires about twice a match against the machine, and the case it was written for is one a person creates. Each unit that takes the way round says so in the log.
+- Then it was asked to swing wider, and four ways of doing that were tried and thrown away. Charging more than double for driving over somebody gave the same routes to one square in fifty-six thousand, and so did looking half again as far ahead: past the point where going round is cheaper than going through, paying more does not move the line further out. Planning a lane's clearance around the traffic, and giving up on the queue half a second sooner, both did change the routes, and both made units wait longer than doing nothing at all - spread them harder and they park across each other, which is the same wall the lane-picking above ran into. A unit that leaves a queue has to leave it late and by the shortest way round, or it is not saving anyone time.
- Bugs deliberately left alone are pinned by a test documenting the behaviour.
- Infantry shadows were fixed in the wrong place first, and nobody has eyeballed them yet.
- The shade under smoke vanished between builds and was rewritten from these notes.
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
index b5eb9e338..2da685c82 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
@@ -776,6 +776,7 @@ public:
static const char *getMatchProfileReport( void );
static void bumpNoPath( void ); ///< a path request came back empty
static void bumpBlockedFrame( Bool stuck ); ///< one unit-frame spent blocked by another unit
+ static void bumpQueueDetour( void ); ///< a unit gave up on its queue and repathed round it
void processPathfindQueue(void); ///< Process some or all of the queued pathfinds.
void forceMapRecalculation( ); ///< Force pathfind map recomputation. If region is given, only that area is recomputed
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
index 5403115f4..8b4d8ee7d 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
@@ -478,6 +478,16 @@ public:
Bool isQuickPathAvailable( const Coord3D *destination ) const; ///< does a path (using quick pathfind) exist between us and the destination
Int getNumFramesBlocked(void) const {return m_blockedFrames;}
Bool isBlockedAndStuck(void) const {return m_isBlockedAndStuck;}
+ //
+ // m_blockedFrames is zeroed by a single frame without a collision, and a unit queued behind
+ // another one does not collide every frame - it creeps, touches, backs off its speed and
+ // touches again - so the counter almost never reaches the two seconds that force a repath,
+ // and the queue stands there. m_queueFrames counts the same collisions and decays instead
+ // of resetting, so a unit that touches more often than it clears climbs to the threshold.
+ // That is what says "I am in a line, not in traffic".
+ //
+ Bool isQueuedBehindUnits(void) const;
+ void spendQueueCredit(void); ///< a path was computed; the detour has had its chance
Bool canComputeQuickPath(void); ///< Returns true if we can quickly comput a path. Usually missiles & the like that just move straight to the destination.
Bool computeQuickPath(const Coord3D *destination); ///< Computes a quick path to the destination.
@@ -730,6 +740,7 @@ private:
ICoord2D m_pathfindGoalCell; ///< Cell we are moving towards.
ICoord2D m_pathfindCurCell; ///< Cell we are currently occupying.
Int m_blockedFrames; ///< Number of frames we've been blocked.
+ Int m_queueFrames; ///< blocked frames, decayed rather than reset - see isQueuedBehindUnits
Real m_curMaxBlockedSpeed; ///< Max speed we can have and not run into blocking things.
Real m_bumpSpeedLimit; ///< Max speed after bumping a unit.
UnsignedInt m_ignoreCollisionsUntil; ///< Timer to cheat if we get stuck.
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
index 2ccbc2049..00b655650 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
@@ -146,6 +146,7 @@ static Int thePFOutOfCells = 0; ///< a search ran the shared cell-info pool dr
static Int thePFNoPath = 0; ///< a unit asked for a path and got nothing back
static Int thePFBlockedFrames = 0; ///< unit-frames spent standing behind another unit
static Int thePFStuckFrames = 0; ///< of those, the ones where the blocker was not moving either
+static Int thePFQueueDetours = 0; ///< units that gave up on a queue and repathed round it
inline void pfBump( Int slot ) { thePFCalls[ slot ]++; }
@@ -1974,6 +1975,48 @@ const Int PATH_CONGESTION_COST = 5;
const Int PATH_CONGESTION_RANGE = 30; ///< cells from the start within which other paths cost anything
const Int PATH_CONGESTION_MAX_PATHS = 4; ///< the penalty stops growing past this many paths in a footprint
+/* The cost above is about where other units are *going*. This one is about where they are
+ standing right now, and it is only paid by a unit that has already given up on the queue it is
+ in (AIUpdateInterface::isQueuedBehindUnits). Every other search keeps the retail flat cost.
+
+ A cell holding another unit costs 3*COST_DIAGONAL = 42 in retail, which is four cells of ground.
+ That is enough to prefer the lane beside a single parked tank and nowhere near enough to walk
+ round a column of six: driving through them is 42 a cell, but the way round is a hundred cells
+ of open ground the search has to be paid to take. For the one search that gets it, occupied
+ ground costs 162 instead, which buys about sixteen cells of detour per unit in the way - a tank
+ pulls out of the line, drives right round the ones standing in it and comes back in front.
+
+ Bounded to the cells near the start for the reason the congestion comment gives: the A*
+ heuristic cannot see this cost, so an unbounded version of it floods the search. The window
+ has to hold the whole queue, though, or the unit plans around the tank in front of it and
+ rejoins the same line two cells later: sixteen cells is a hundred and sixty world units, which
+ is a column of five tanks plus the room to swing round it.
+
+ These two numbers are where the sweep stopped, and it is worth saying what is on the other side
+ of them, because "swing wider" sounds free and is not. Four ways to widen it, same 24 seeds,
+ blocked unit-frames per 1000 logic frames and cell expansions per match - retail, with none of
+ this, is 34,2:
+ 50 over 10 cells (this) 28,8 56.784
+ cost 50 -> 120 28,4 56.783
+ range 10 -> 16 28,6 56.763
+ a cell of clearance around
+ the traffic, not just the
+ cells it stands on 33,6 56.661
+ threshold 40 -> 25 frames 40,6 64.383
+
+ One cell of difference in 56.784 is the same routes to within rounding, twice over: the cost
+ saturates the way the crossing cost saturates at 60, because past the point where going round
+ is cheaper than going through, paying more does not move the line further out - the route is
+ already the widest the ground offers. The range is inert for the same reason.
+
+ The two that do change something both make it worse, and in the same way the congestion cost
+ does at 10: spread them harder and they park across each other. A cell of clearance sends the
+ detour wide enough to meet the next lane's traffic, and firing sooner pulls units out of lines
+ that were about to clear - that one is worse than doing nothing at all. A unit that leaves a
+ queue has to leave it late and by the shortest way round, or it is not saving anyone time. */
+const Int PATH_QUEUE_COST = 5*COST_ORTHOGONAL;
+const Int PATH_QUEUE_RANGE = 10; ///< cells from the start within which standing units cost extra
+
/* Split out of examineNeighboringCells so the cap is testable: the cap is the only thing keeping
this cost from flooding the search, since the heuristic cannot see it. */
Int Pathfinder_congestionPenalty( Int usage, Int costPerPath )
@@ -4266,6 +4309,7 @@ void Pathfinder::resetMatchProfile( void )
thePFNoPath = 0;
thePFBlockedFrames = 0;
thePFStuckFrames = 0;
+ thePFQueueDetours = 0;
}
void Pathfinder::bumpNoPath( void )
@@ -4280,6 +4324,11 @@ void Pathfinder::bumpBlockedFrame( Bool stuck )
thePFStuckFrames++;
}
+void Pathfinder::bumpQueueDetour( void )
+{
+ thePFQueueDetours++;
+}
+
const char *Pathfinder::getMatchProfileReport( void )
{
__int64 freq = 0;
@@ -4303,8 +4352,8 @@ const char *Pathfinder::getMatchProfileReport( void )
len += oneLen;
}
if( len < (Int)sizeof( thePFMatchReport ) - 64 )
- sprintf( thePFMatchReport + len, "| nopath %d outofcells %d blocked %d stuck %d",
- thePFNoPath, thePFOutOfCells, thePFBlockedFrames, thePFStuckFrames );
+ sprintf( thePFMatchReport + len, "| nopath %d outofcells %d blocked %d stuck %d queuedetour %d",
+ thePFNoPath, thePFOutOfCells, thePFBlockedFrames, thePFStuckFrames, thePFQueueDetours );
return thePFMatchReport;
}
@@ -6894,7 +6943,12 @@ Int Pathfinder::examineNeighboringCells(PathfindCell *parentCell, PathfindCell *
// world units per frame, for turning a distance travelled into the frame we get there.
// Zero switches the crossing cost off for this search: without a speed there is no clock.
Real crossingSpeed = 0.0f;
+ // nonzero only for a unit that has decided to leave the queue it is standing in; see
+ // PATH_QUEUE_COST
+ Int queueCost = 0;
if (obj && obj->getAIUpdateInterface()) {
+ if (obj->getAIUpdateInterface()->isQueuedBehindUnits())
+ queueCost = PATH_QUEUE_COST;
canPathThroughUnits = obj->getAIUpdateInterface()->canPathThroughUnits();
// Our own current path must not repel us while we repath (the caller only destroys it
// once the new one is built). O(1) after the first neighbour expansion of a search.
@@ -7083,6 +7137,12 @@ Int Pathfinder::examineNeighboringCells(PathfindCell *parentCell, PathfindCell *
if (info.allyMoving && dx<10 && dy<10) {
newCostSoFar += 3*COST_DIAGONAL;
}
+ // leaving the queue: the ground the units in front of us are standing on is worth
+ // going round, for this search only
+ if (queueCost && dx<PATH_QUEUE_RANGE && dy<PATH_QUEUE_RANGE
+ && (info.allyMoving || info.allyFixedCount>0)) {
+ newCostSoFar += queueCost;
+ }
if (m_pathUsage && dx < PATH_CONGESTION_RANGE && dy < PATH_CONGESTION_RANGE) {
// Other units' live paths through our footprint: pay per path so we pick a parallel
// lane. Capped, because the heuristic does not know about this cost and an uncapped
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
index 1c1efc6bd..90cb85eec 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
@@ -1819,7 +1819,14 @@ StateReturnType AIInternalMoveToState::update()
forceRecompute = true;
}
Bool blocked=false;
- if (ai->isBlockedAndStuck() || ai->getNumFramesBlocked()>2*LOGICFRAMES_PER_SECOND) {
+ // isQueuedBehindUnits is the intermittent case the two-second rule misses: a unit shuffling
+ // along at the back of a column touches the one in front every few frames, never for two
+ // seconds together, and used to stay in the line for as long as the line existed. Throttled
+ // to once a second because not every state answers a forced recompute by actually computing
+ // one - the ones that decline (tightening, pursuing) would otherwise be asked every frame.
+ Bool queued = ai->isQueuedBehindUnits()
+ && TheGameLogic->getFrame() - m_blockedRepathTimestamp > LOGICFRAMES_PER_SECOND;
+ if (ai->isBlockedAndStuck() || ai->getNumFramesBlocked()>2*LOGICFRAMES_PER_SECOND || queued) {
forceRecompute = true;
blocked = true;
m_blockedRepathTimestamp = TheGameLogic->getFrame();
@@ -2420,12 +2427,23 @@ Bool AIAttackApproachTargetState::computePath()
AIUpdateInterface *ai = getMachineOwner()->getAI();
- if (ai->isBlockedAndStuck())
+ if (ai->isBlockedAndStuck())
{
forceRepath = true;
// Intense logging. jba
//CRCDEBUG_LOG(("AIAttackApproachTargetState::computePath - stuck, recomputing for object %d\n", getMachineOwner()->getID()));
}
+ //
+ // This state is where a group of tanks piles up nose to tail, and it is the one state that
+ // could not get itself out. The base move state asks for a repath after two seconds of being
+ // blocked; this override ignored that, and the "victim has not moved, so do not re-path" bail
+ // below then held every tank behind the ones in front for as long as the target stood still.
+ // A unit that has given up on its queue repaths whatever the victim is doing.
+ //
+ if (ai->isQueuedBehindUnits())
+ {
+ forceRepath = true;
+ }
if (m_waitingForPath) return true;
if (!forceRepath && ai->getPath()==NULL && !ai->isWaitingForPath())
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
index 2d012a56e..c5586e1da 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
@@ -73,6 +73,41 @@
#define SLEEPY_AI
+//
+// Leaving a queue. A unit standing behind another one collides, backs its speed off, drifts
+// apart, and collides again a few frames later, so m_blockedFrames - which a single clean frame
+// zeroes - rarely reaches the two seconds that force a repath. The column therefore sits.
+// m_queueFrames counts the same collisions but decays by one per clear frame instead of resetting,
+// so a unit touching more often than it clears climbs; one that is genuinely moving falls to zero.
+// Past the threshold the unit repaths once, and that search prices the traffic beside it (see
+// PATH_QUEUE_COST in AIPathfind.cpp) so the route it gets back leaves the line instead of
+// rejoining it.
+//
+// The threshold is under the two-second rule on purpose: a unit that is being reliably crushed
+// against a blocker every frame still hits the old rule first, and this only catches the
+// intermittent case the old rule misses. The ceiling stops a unit wedged for a minute from
+// carrying a minute of credit into open ground.
+//
+enum
+{
+ QUEUE_FRAMES_THRESHOLD = 40, ///< about 1.3 seconds of mostly-blocked frames
+ QUEUE_FRAMES_CEILING = 80
+};
+
+/* Split out so the climb-and-decay can be checked on its own: it is the whole of the "am I in a
+ line" decision, and a version that gets it wrong either never fires or fires on open ground. */
+Int AIUpdate_queueFrameStep( Int queueFrames, Bool blocked )
+{
+ if (blocked)
+ return queueFrames < QUEUE_FRAMES_CEILING ? queueFrames + 1 : QUEUE_FRAMES_CEILING;
+ return queueFrames > 0 ? queueFrames - 1 : 0;
+}
+
+Bool AIUpdate_isQueued( Int queueFrames )
+{
+ return queueFrames >= QUEUE_FRAMES_THRESHOLD;
+}
+
#ifdef _INTERNAL
// for occasional debugging...
//#pragma optimize("", off)
@@ -240,6 +275,7 @@ AIUpdateInterface::AIUpdateInterface( Thing *thing, const ModuleData* moduleData
m_pathfindGoalCell.x = m_pathfindGoalCell.y = -1;
m_pathfindCurCell.x = m_pathfindCurCell.y = -1;
m_blockedFrames = 0;
+ m_queueFrames = 0;
m_curMaxBlockedSpeed = 0;
m_bumpSpeedLimit = FAST_AS_POSSIBLE;
m_ignoreCollisionsUntil = 0;
@@ -1443,7 +1479,34 @@ Bool AIUpdateInterface::needToRotate(void)
//-------------------------------------------------------------------------------------------------
-/* Returns TRUE if the physics collide should apply the force. Normally not.
+/* Returns TRUE if this unit has spent long enough standing behind other units to call it a queue
+ rather than a moment of traffic. See QUEUE_FRAMES_THRESHOLD at the top of this file. */
+Bool AIUpdateInterface::isQueuedBehindUnits(void) const
+{
+ return AIUpdate_isQueued( m_queueFrames );
+}
+
+//-------------------------------------------------------------------------------------------------
+/* Called at the end of every path computation. The search that just ran is the detour, so the
+ credit is spent and the unit counts again from zero to decide whether it worked - without this
+ a queued unit asks for a new path on every frame for as long as it is queued. It is also where
+ the headless run's "queuedetour" count comes from: how often a unit gave up on the line it was
+ standing in, which is the number that says whether a change to the threshold did anything. */
+void AIUpdateInterface::spendQueueCredit(void)
+{
+ if (isQueuedBehindUnits())
+ {
+ Pathfinder::bumpQueueDetour();
+ // the headless counter only prints at the end of an unattended run, and this behaviour is
+ // something you watch happen in a real game - so say it in the log too, once per detour
+ DEBUG_LOG(("QUEUE DETOUR: frame %d, '%s' %d leaving a queue\n", TheGameLogic->getFrame(),
+ getObject()->getTemplate()->getName().str(), getObject()->getID()));
+ }
+ m_queueFrames = 0;
+}
+
+//-------------------------------------------------------------------------------------------------
+/* Returns TRUE if the physics collide should apply the force. Normally not.
Also determines whether objects are blocked, and if so, if they are stuck. jba.*/
Bool AIUpdateInterface::processCollision(PhysicsBehavior *physics, Object *other)
{
@@ -1683,6 +1746,7 @@ Bool AIUpdateInterface::computeQuickPath( const Coord3D *destination )
m_pathTimestamp = TheGameLogic->getFrame();
m_blockedFrames = 0;
+ spendQueueCredit();
m_isBlockedAndStuck = FALSE;
return TRUE;
}
@@ -1693,7 +1757,6 @@ Bool AIUpdateInterface::computeQuickPath( const Coord3D *destination )
*/
Bool AIUpdateInterface::computePath( PathfindServicesInterface *pathServices, Coord3D *destination )
{
-
if (!m_isBlockedAndStuck) {
destroyPath();
}
@@ -1804,6 +1867,7 @@ Bool AIUpdateInterface::computePath( PathfindServicesInterface *pathServices, Co
m_pathTimestamp = TheGameLogic->getFrame();
m_blockedFrames = 0;
+ spendQueueCredit();
m_isBlockedAndStuck = FALSE;
if (m_path)
return TRUE;
@@ -1823,10 +1887,11 @@ Bool AIUpdateInterface::computeAttackPath( PathfindServicesInterface *pathServic
{
// jba intense debug
//CRCDEBUG_LOG(("Info - RePathing very quickly %d, %d.\n", m_pathTimestamp, TheGameLogic->getFrame()));
- if (m_path && m_isBlockedAndStuck)
+ if (m_path && m_isBlockedAndStuck)
{
setIgnoreCollisionTime(2*LOGICFRAMES_PER_SECOND);
m_blockedFrames = 0;
+ spendQueueCredit();
m_isBlocked = FALSE;
m_isBlockedAndStuck = FALSE;
return TRUE;
@@ -2039,6 +2104,7 @@ Bool AIUpdateInterface::computeAttackPath( PathfindServicesInterface *pathServic
m_pathTimestamp = TheGameLogic->getFrame();
m_blockedFrames = 0;
+ spendQueueCredit();
m_isBlockedAndStuck = FALSE;
//CRCDEBUG_LOG(("AIUpdateInterface::computeAttackPath() done\n"));
if (m_path)
@@ -2166,6 +2232,7 @@ UpdateSleepTime AIUpdateInterface::doLocomotor( void )
chooseGoodLocomotorFromCurrentSet();
+ m_queueFrames = AIUpdate_queueFrameStep( m_queueFrames, m_isBlocked );
if (m_isBlocked)
{
++m_blockedFrames;
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 77a56659f..1784b8fba 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -6266,6 +6266,65 @@ TEST(congestion_cost_is_charged_per_path_and_capped)
CHECK( Pathfinder_congestionPenalty( 255, 20 ) <= 8*10 );
}
+extern Int AIUpdate_queueFrameStep( Int queueFrames, Bool blocked );
+extern Bool AIUpdate_isQueued( Int queueFrames );
+
+TEST(a_queue_is_blocked_frames_that_decay_rather_than_reset)
+{
+ /* The counter this replaces was zeroed by a single frame without a collision, and a unit at
+ the back of a column does not collide every frame - it creeps up, touches, backs its speed
+ off, drifts apart and touches again - so it never reached the two seconds that force a
+ repath and the column just stood there. This one decays. */
+
+ /* Blocked every frame it climbs, and crosses the threshold inside a second or so. The exact
+ frame is a tuning constant and this test does not pin it: it pins that the threshold is
+ reached at all, that it takes long enough not to fire on a passing nudge, and that it comes
+ in under the two-second rule it exists to get in front of. */
+ Int q = 0;
+ Int framesToFire = 0;
+ while( !AIUpdate_isQueued( q ) && framesToFire < 1000 )
+ {
+ q = AIUpdate_queueFrameStep( q, true );
+ framesToFire++;
+ }
+ CHECK( AIUpdate_isQueued( q ) );
+ CHECK( framesToFire > 10 ); // a shove in traffic is not a queue
+ CHECK( framesToFire < 60 ); // 2*LOGICFRAMES_PER_SECOND: the rule this gets in front of
+
+ // and it stops climbing, so a unit wedged for a minute carries no credit into open ground
+ for( Int i = 0; i < 1000; i++ )
+ q = AIUpdate_queueFrameStep( q, true );
+ CHECK_EQ( 80, q );
+
+ // clear ground walks it back down to nothing, and no further
+ for( Int i = 0; i < 1000; i++ )
+ q = AIUpdate_queueFrameStep( q, false );
+ CHECK_EQ( 0, q );
+ CHECK( !AIUpdate_isQueued( q ) );
+
+ /* The case that matters: touching two frames in three still gets there, where the old
+ reset-on-clear counter never left 1. Three frames a cycle, net +1. */
+ q = 0;
+ for( Int cycle = 0; cycle < 40; cycle++ )
+ {
+ q = AIUpdate_queueFrameStep( q, true );
+ q = AIUpdate_queueFrameStep( q, true );
+ q = AIUpdate_queueFrameStep( q, false );
+ }
+ CHECK( AIUpdate_isQueued( q ) );
+
+ // but a unit that is merely nudged now and then - one frame in three - never fires
+ q = 0;
+ for( Int cycle = 0; cycle < 1000; cycle++ )
+ {
+ q = AIUpdate_queueFrameStep( q, true );
+ q = AIUpdate_queueFrameStep( q, false );
+ q = AIUpdate_queueFrameStep( q, false );
+ }
+ CHECK( !AIUpdate_isQueued( q ) );
+ CHECK_EQ( 0, q );
+}
+
extern Int Pathfinder_crossingPenalty( Int conflicts );
TEST(crossing_cost_is_charged_per_conflict_and_capped)
diff --git a/ai-batch.ps1 b/ai-batch.ps1
index b0c5b2ef7..148704fc7 100644
--- a/ai-batch.ps1
+++ b/ai-batch.ps1
@@ -133,7 +133,7 @@ for ($i = 0; $i -lt $Runs; $i++) {
# what the pathfinder did over the whole match, for comparing a pathing change against its
# baseline: search time and count say what it cost, nopath/outofcells say whether it broke,
# blocked/stuck say whether the traffic jams it was aimed at actually got shorter
- $pf = [pscustomobject]@{ FindMs = 0.0; Finds = 0; Expands = 0; NoPath = 0; OutOfCells = 0; Blocked = 0; Stuck = 0 }
+ $pf = [pscustomobject]@{ FindMs = 0.0; Finds = 0; Expands = 0; NoPath = 0; OutOfCells = 0; Blocked = 0; Stuck = 0; QueueDetour = 0 }
# THREADING-ROADMAP.md section 0: the per-scope frame cost, present only in a PERF_TIMERS
# build (-Exe generals_perf.exe), and the job pool's own report, present in every build.
$perf = @{}
@@ -183,6 +183,7 @@ for ($i = 0; $i -lt $Runs; $i++) {
if ($report -match "outofcells (\d+)") { $pf.OutOfCells = [int]$Matches[1] }
if ($report -match "blocked (\d+)") { $pf.Blocked = [int]$Matches[1] }
if ($report -match "stuck (\d+)") { $pf.Stuck = [int]$Matches[1] }
+ if ($report -match "queuedetour (\d+)") { $pf.QueueDetour = [int]$Matches[1] }
}
elseif ($line -match "HEADLESS PLAYER (\d+) '(.*?)': (\w+) \| score (\d+) \| money (\d+) earned (\d+) spent \| units (\d+) built (\d+) lost (\d+) killed peak (\d+)") {
$slots[[int]$Matches[1]] = [pscustomobject]@{
@@ -254,6 +255,10 @@ if ($pfRows.Count -gt 0) {
$totFrames = ($pfRows | Measure-Object Frames -Sum).Sum
$totBlocked = ($pfRows | ForEach-Object { $_.Pf.Blocked } | Measure-Object -Sum).Sum
Write-Host ("blocked unit-frames per 1000 logic frames: {0:n1}" -f (1000.0 * $totBlocked / $totFrames))
+ # how often a unit gave up on the line it was standing in and repathed round it. Zero here and
+ # a change to the queue detour cannot have done anything, good or bad.
+ $totDetour = ($pfRows | ForEach-Object { $_.Pf.QueueDetour } | Measure-Object -Sum).Sum
+ Write-Host ("queue detours per 1000 logic frames: {0:n1}" -f (1000.0 * $totDetour / $totFrames))
}
# Stability. A mean frame time is the statistic that hides a stutter, so this reports the tail: