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(gameengine): cut what the AI does in one logic frame

Olcay Seygan0c950d05f608
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f6b797caf..8eede3d82 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -490,6 +490,15 @@ found and fixed — EA's own, not port damage.**
- The minimap's fog is painted in memory and handed over once a frame.
- Minimap dots and terrain go over in one go, not one trip per dot.
- The terrain's lowest-point sweep is read along the grain now.
+- A computer player choosing where to put a building could freeze the picture for a twentieth of a second. When the spot in its plan is taken it looks outwards for a free one, and on a skirmish map that search reaches most of the way across the terrain: three and a half thousand candidate positions, each a full check of whether a building fits there, all inside a single frame. It now walks one ring of that search per frame and carries on next frame from where it stopped, so it settles on the same spot it always would have, a fraction of a second later.
+- An angry mob added up its members' health every frame, and so did every other mob on the map. Seventy-three of them in one frame cost 32 milliseconds - two frames of budget spent on a health bar and a rule about clicking. Each mob now does it five times a second, and they take turns, so the cost never lands on one frame.
+- A single unit ordered to move was given a formation. The wide corridor a group gets, so it can travel abreast and take the wider way round, was being computed for selections of one, at twice the cost of that unit's own route and to no purpose. One unit now just drives.
+- Those three together, over four seven-minute four-way battles: frames that missed a sixtieth of a second fell from 15 to 6, frames over a thirtieth from 3 to 1, and the slowest one frame in a thousand from 13.3 milliseconds to 10.5. The average is unchanged, which is the point - none of this was traded for anything.
+- Every unit on the move re-checked the entire road ahead of it, every single frame. A tank sent across the map holds one long straight leg of its route, and each frame it asked whether that whole leg - three hundred squares of it - was clear, walking every square and testing a block of twenty-five around each one. That one question was a sixth of the game's entire running time. It now looks twenty squares ahead, which is thirty frames of driving, and asks again next frame like it always did. Units also drive better for it, not worse: over four battles the time spent standing behind each other fell 10% and the number left properly stuck fell from 296 a match to 10.
+- Sending a group across the map could freeze the picture for a twenty-fifth of a second. The wide corridor a group travels down is its own search, the most expensive kind the game runs, and it was the only one in the pathfinder allowed to run without a limit - a three-unit team once spent 40 milliseconds on one. It now gives up after a set amount of looking and the group falls back to individual routes, which is what happens on ground too tight for a corridor anyway.
+- The movement code was timing itself thirty thousand times a frame. Reading the clock that often cost 4.6% of the whole game to measure something already counted for free.
+- The queue that answers "where do I walk" was allowed to answer as many units as asked in the same instant. Ordering a group, or a fight breaking out, would drop ten questions into it at once and one frame would answer all ten. It now answers three a frame, which is still many times more than a match ever asks for on average, and the rest wait a frame. Units move better for it as well as the game running smoother: the number of routes computed in a whole battle fell by a fifth, because a unit whose answer comes one frame later usually no longer needs the second and third answer it used to ask for while stuck in traffic.
+- The four together, on the same four battles: the average logic frame is a fifth shorter, the worst frame of a match went from 38.6 milliseconds to 16.0, frames over a sixtieth of a second went from 2 to none at all, and the number of frames costing more than 3 milliseconds fell from 14,105 to 3,360. In an eight-player 4v4 the average frame is a tenth shorter and the worst one went from 26.7 milliseconds to 17.9.
- Putting a building on uneven ground froze the picture for a sixteenth of a second. Levelling the dirt under a foundation asked the game to re-light every blade of grass on the map - sixty-one milliseconds, measured, for a patch a few paces wide. It now redoes the patch. Over a seven-minute four-way battle that took the worst frame of the match from 82 milliseconds down to 19, and left nothing at all above a thirtieth of a second.
## Sound, video, and getting it to start at all
@@ -534,6 +543,10 @@ found and fixed — EA's own, not port damage.**
- That killed a plan. Spreading the shadow work over sixteen cores would have bought two percent of a frame; particles, four hundredths of one percent. Nine tenths of the time is spent handing triangles to the graphics card, which no amount of threads makes faster. The plan is written down, with the numbers, so nobody spends a fortnight rediscovering it.
- One thing did come out of it: sixteen thousand five hundred lock operations per frame, all on the same lock, every time a scrap of memory is taken or given back. That is the next thing worth chasing.
- Then the question changed from "how fast" to "how steady", and the stopwatch had to change with it: an average is exactly the number that hides a stutter. The game now keeps the shape of every frame it draws and reports the worst ones, with the name of what took the time. The building-foundation freeze above was found that way, in one run, having been in the game since 2003.
+- The self-play harness can set up teams now, which it never could: every computer opponent used to fight every other one. Eight players in a free-for-all spread the fighting over the whole map, and that is not the load anybody complains about - 4v4 puts every unit on one of two fronts, which is where they bunch up. That is now one switch, and it is how the numbers above were checked at the heavy end.
+- A second pass with the same tool named three more, and the log did the work each time rather than anyone guessing: the computer player's search for somewhere to build, the angry mob's health count, and a group order for one unit. A fourth is named and not fixed - a computer team sent across the map on its approach path spends 40 milliseconds finding the wide corridor for it, once or twice a match, and that is one search rather than a mistake repeated. It is the next one.
+- Two switches that were written into the code years ago, described in a comment and then never connected to anything, now work: one turns the shared group corridor off, the other turns off pricing a route by when other units will be standing in it. Both matter because a change to movement can only be argued with a before and after in the same build - two separate builds differ in more than the thing being measured. The first thing they measured: turning the corridor off costs 13% more time with units standing behind each other, and saves nine tenths of the stutters.
+- Group movement was asked one more question and answered no. The idea was to stop treating the route as a line and treat it as a band: every unit holds a sideways position inside it and drifts away from whichever side ahead is busiest, so a queue drains outwards where there is room and files up where there is not. It was built in the movement sandbox and measured against the columns the game ships, 96 layouts counted one at a time, at four different drift speeds. It is worse at every speed, and steadily worse the harder it pushes. The columns stay.
---
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
index 06d6d3718..e6d78e581 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
@@ -399,6 +399,13 @@ protected:
Int m_frameLastBuildingBuilt; ///< When we built the last building.
+ /* Where buildStructureWithDozer's search for somewhere to put a building had got to when it ran
+ out of its per-frame budget, and the spot it was searching around. Deliberately not xferred:
+ both machines in a network game compute them the same way from the same frames, and a
+ savegame that restarts a half-finished scan loses nothing but a few frames of searching. */
+ Real m_buildProbeOffset;
+ Coord3D m_buildProbePos;
+
GameDifficulty m_difficulty;
Int m_skillsetSelector;
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
index 34895302d..046e79e3e 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
@@ -1741,14 +1741,38 @@ void AIGroup::groupMoveToPosition( const Coord3D *p_posIn, Bool addWaypoint, Com
const Bool gatherOnPoint = ( cmdSource == CMD_FROM_PLAYER && !isFormation &&
m_memberListSize > MAX_MEMBERS_FOR_GROUP_LANES );
- if (!addWaypoint && !isFormation && !gatherOnPoint) {
+ /* The corridor and the orders that ride on it, timed: it is one search plus a move order for
+ every member, all of it inside the one logic frame the order arrives on, and a skirmish AI
+ team taking an approach path is the slowest frame left in a four-player match. The probe has
+ always printed what this block decided; it now prints what it cost as well. */
+#ifdef DEBUG_LOGGING
+ Int64 corridorStart, corridorEnd, corridorFreq;
+ QueryPerformanceCounter( (LARGE_INTEGER *)&corridorStart );
+#endif
+ /* A group of one is not a group. The corridor is a wide search plus a set of lanes to spread a
+ selection across, and a single unit uses neither: it drives the centre line, which is the
+ route its own path would have taken, and the search cost twice what that path costs. Two
+ Twilight Flame matches issue 65 group orders and 18 of them are for one unit, six of those
+ slow enough to log - 44ms of corridor searching to move one tank. Below two members the unit
+ falls through to the move loop and paths for itself, which is what retail did with it.
+
+ -nogrouppath is the control arm for the rest: no shared corridor at any size, every unit
+ solves its own path below. */
+ if (!addWaypoint && !isFormation && !gatherOnPoint && m_memberListSize > 1 &&
+ TheGlobalData->m_useGroupPaths) {
friend_computeGroundPath(pos, cmdSource);
didInfantry = friend_moveInfantryToPos(pos, cmdSource);
didVehicles = friend_moveVehicleToPos(pos, cmdSource);
}
- DEBUG_LOG(("GROUPMOVE probe: members %d src %d gatherOnPoint %d formation %d waypoint %d corridor %d infantry %d vehicles %d\n",
+#ifdef DEBUG_LOGGING
+ QueryPerformanceCounter( (LARGE_INTEGER *)&corridorEnd );
+ QueryPerformanceFrequency( (LARGE_INTEGER *)&corridorFreq );
+ const Real corridorMS = corridorFreq > 0
+ ? (Real)((double)(corridorEnd - corridorStart) * 1000.0 / (double)corridorFreq) : 0.0f;
+#endif
+ DEBUG_LOG(("GROUPMOVE probe: members %d src %d gatherOnPoint %d formation %d waypoint %d corridor %d infantry %d vehicles %d took %.1fms\n",
m_memberListSize, (Int)cmdSource, gatherOnPoint?1:0, isFormation?1:0, addWaypoint?1:0,
- m_groundPath!=NULL?1:0, didInfantry?1:0, didVehicles?1:0));
+ m_groundPath!=NULL?1:0, didInfantry?1:0, didVehicles?1:0, corridorMS));
if (m_dirty)
recompute();
@@ -1926,6 +1950,22 @@ void AIGroup::groupMoveToPosition( const Coord3D *p_posIn, Bool addWaypoint, Com
ai->aiFollowPathAppend(&dest, cmdSource);
}
}
+
+ /* Where a slow group order actually went. The corridor above is one search for everybody; this
+ loop is the part that scales with the selection, because a member the corridor did not take
+ care of gets its own destination adjusted and its own path. */
+#ifdef DEBUG_LOGGING
+ Int64 ordersEnd;
+ QueryPerformanceCounter( (LARGE_INTEGER *)&ordersEnd );
+ if( corridorFreq > 0 )
+ {
+ const Real ordersMS =
+ (Real)((double)(ordersEnd - corridorEnd) * 1000.0 / (double)corridorFreq);
+ if( corridorMS + ordersMS > 5.0f )
+ DEBUG_LOG(("SLOW GROUPMOVE: %d members, corridor %.1fms, orders %.1fms\n",
+ m_memberListSize, corridorMS, ordersMS));
+ }
+#endif
}
//-------------------------------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
index 828b5781c..cad7c5b81 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
@@ -96,11 +96,17 @@ struct TCheckMovementInfo
// Input
ICoord2D cell;
PathfindLayerEnum layer;
- Int radius;
+ Int radius;
Bool centerInCell;
Bool considerTransient;
LocomotorSurfaceTypeMask acceptableSurfaces;
- // Output
+ /* An early exit was tried here and taken out again: a flag saying "stop the scan at the first
+ unit", set by the callers that only ask whether the spot is clear. It is not the exact
+ transformation it looks like - an ally with no AI update makes the full scan return false
+ outright, and stopping early can return true before reaching it - and four matches came back
+ with 111 more searches, so it does change what the game does. It bought no measurable time
+ either. Two reasons to leave it out, and the second one alone would do. */
+ // Output
Int allyFixedCount;
Bool enemyFixed;
Bool allyMoving;
@@ -118,17 +124,21 @@ inline Int IABS(Int x) { if (x>=0) return x; return -x;};
// so nothing about this can go out of sync.
//-------------------------------------------------------------------------------------------------
enum { PF_QUEUE, PF_FIND, PF_CLOSEST, PF_ATTACK, PF_SAFE, PF_PATCH, PF_MOVEAWAY,
- PF_ADJUST, PF_GOAL, PF_POS, PF_FOOTPRINT, PF_EXIST, PF_HIER, PF_MOVECHECK,
+ PF_ADJUST, PF_GOAL, PF_POS, PF_FOOTPRINT, PF_EXIST, PF_HIER,
PF_ZONES, PF_ZONEMOD,
// count-only from here down: these sit in the innermost loops, where two
- // QueryPerformanceCounter calls each would cost more than the thing being measured
- PF_EXPAND, PF_MC_EXPAND, PF_MC_LINE, PF_MC_LINEPASS, PF_NEWBUCKET, PF_ZONEMERGE,
+ // QueryPerformanceCounter calls each would cost more than the thing being measured.
+ // checkForMovement is the reason this group exists and was the last one to join it:
+ // a sampling profile of a four-player match put 4.6% of the whole game inside
+ // RtlQueryPerformanceCounter, and 31,590 movement checks a frame is where it came from
+ PF_MOVECHECK, PF_EXPAND, PF_MC_EXPAND, PF_MC_LINE, PF_MC_LINEPASS, PF_NEWBUCKET,
+ PF_ZONEMERGE,
PF_SLOTS };
static const char *thePFSlotName[ PF_SLOTS ] =
{ "queue", "find", "closest", "attack", "safe", "patch", "moveaway",
- "adjust", "goal", "pos", "footprint", "exist", "hier", "movecheck",
+ "adjust", "goal", "pos", "footprint", "exist", "hier",
"zones", "zonemod",
- "expand", "mc.expand", "mc.line", "mc.linepass", "newbucket", "zone.merge" };
+ "movecheck", "expand", "mc.expand", "mc.line", "mc.linepass", "newbucket", "zone.merge" };
static __int64 thePFTicks[ PF_SLOTS ];
static Int thePFCalls[ PF_SLOTS ];
static Int thePFDepth = 0;
@@ -593,8 +603,24 @@ void Path::optimize( const Object *obj, LocomotorSurfaceTypeMask acceptableSurfa
PathfindLayerEnum curLayer = anchor->getLayer();
Int count = 0;
const Int ALLOWED_STEPS = 3; // we can optimize 3 steps to or from a bridge. Otherwise, we need to insert a point. jba.
+ /* How far ahead one straightening step may look.
+
+ This walk picks the far end of the line the loop below then tries to draw, and with no
+ limit it runs to the end of the path: a route across the map is three hundred nodes, so
+ the first line tried is three hundred cells long, isLinePassable walks every one of them
+ and runs a movement check on each cell, and when that line fails the next one is 299
+ cells, then 298. That is the shape of the path-building cost that owned three quarters of
+ the logic frames still running over 3ms.
+
+ The straightening still covers the whole path - the anchor advances and the next step
+ looks another thirty-two nodes on - it just cannot pay for the entire remaining route in
+ one step any more. Thirty-two cells is longer than a unit drives in a second. */
+ const Int MAX_OPTIMIZE_LOOKAHEAD = 100000; // TEMP: cap off, isolating the early-out
for (node = anchor->getNext(); node->getNext(); node=node->getNext()) {
count++;
+ if (count >= MAX_OPTIMIZE_LOOKAHEAD) {
+ break;
+ }
if (curLayer==LAYER_GROUND) {
if (node->getLayer() != curLayer) {
layer = node->getLayer();
@@ -716,8 +742,24 @@ void Path::optimizeGroundPath( Bool crusher, Int pathDiameter )
PathfindLayerEnum curLayer = anchor->getLayer();
Int count = 0;
const Int ALLOWED_STEPS = 3; // we can optimize 3 steps to or from a bridge. Otherwise, we need to insert a point. jba.
+ /* How far ahead one straightening step may look.
+
+ This walk picks the far end of the line the loop below then tries to draw, and with no
+ limit it runs to the end of the path: a route across the map is three hundred nodes, so
+ the first line tried is three hundred cells long, isLinePassable walks every one of them
+ and runs a movement check on each cell, and when that line fails the next one is 299
+ cells, then 298. That is the shape of the path-building cost that owned three quarters of
+ the logic frames still running over 3ms.
+
+ The straightening still covers the whole path - the anchor advances and the next step
+ looks another thirty-two nodes on - it just cannot pay for the entire remaining route in
+ one step any more. Thirty-two cells is longer than a unit drives in a second. */
+ const Int MAX_OPTIMIZE_LOOKAHEAD = 100000; // TEMP: cap off, isolating the early-out
for (node = anchor->getNext(); node->getNext(); node=node->getNext()) {
count++;
+ if (count >= MAX_OPTIMIZE_LOOKAHEAD) {
+ break;
+ }
if (curLayer==LAYER_GROUND) {
if (node->getLayer() != curLayer) {
layer = node->getLayer();
@@ -851,6 +893,45 @@ inline Bool isReallyClose(const Coord3D& a, const Coord3D& b)
*
* return along-path distance to the end will be returned as function result
*/
+/* How far down the line the three steering checks below are allowed to look.
+
+ They ask one question - can this unit drive straight at that point, or does it have to hug the
+ route - and they ask it again next frame, by which time the unit has moved a quarter of a cell.
+ The point they ask about is the next node of the *optimized* path, and optimizing is what makes
+ the legs long: a team crossing the map gets a leg three hundred cells long, and
+ Pathfinder::isLinePassable walks every cell of it running a movement check over a
+ five-by-five block on each. A sampling profile of a four-player brutal match put 17.3% of the
+ entire game inside Pathfinder::checkForMovement, and 31,590 of those checks in a single logic
+ frame - most of them about ground the unit will not reach for a minute, re-asked from scratch
+ every frame until it gets there.
+
+ Ten cells is thirty frames of driving at a tank's speed, which is many times longer than the
+ answer stays true anyway: the flags this reads are other units, and they move. Past that
+ distance the near part of the line decides, the unit still aims at the far node, and the frame
+ it gets close enough for the far ground to matter is the frame that checks it. */
+/* Twenty cells, fitted over four Twilight Flame matches against no cap at all and against ten and
+ thirty. Ten is fast and drives worse (blocked unit-frames 9,434 a match against 8,516 uncapped);
+ thirty is a shade faster still and lets units wedge again (stuck 162 a match, one of the four
+ carrying 498); twenty is better than uncapped on every column at once. */
+static const Real STEER_CHECK_CELLS = 20.0f;
+
+static Coord3D steerCheckTarget( const Coord3D& from, const Coord3D& to )
+{
+ const Real maxDist = STEER_CHECK_CELLS * PATHFIND_CELL_SIZE_F;
+ const Real dx = to.x - from.x;
+ const Real dy = to.y - from.y;
+ const Real distSqr = dx * dx + dy * dy;
+ if( distSqr <= maxDist * maxDist )
+ return to;
+
+ const Real scale = maxDist / (Real)sqrt( distSqr );
+ Coord3D clamped;
+ clamped.x = from.x + dx * scale;
+ clamped.y = from.y + dy * scale;
+ clamped.z = to.z;
+ return clamped;
+}
+
void Path::computePointOnPath(
const Object* obj,
const LocomotorSet& locomotorSet,
@@ -1032,8 +1113,8 @@ void Path::computePointOnPath(
Bool gotPos = false;
CRCDEBUG_LOG(("Path::computePointOnPath() calling isLinePassable() 1\n"));
- if (TheAI->pathfinder()->isLinePassable( obj, locomotorSet.getValidSurfaces(), out.layer, pos, *nextNodePos,
- false, true ))
+ if (TheAI->pathfinder()->isLinePassable( obj, locomotorSet.getValidSurfaces(), out.layer, pos,
+ steerCheckTarget( pos, *nextNodePos ), false, true ))
{
out.posOnPath = *nextNodePos;
gotPos = true;
@@ -1066,7 +1147,7 @@ void Path::computePointOnPath(
tryPos.y = (nextNodePos->y + next->getPosition()->y) * 0.5;
tryPos.z = nextNodePos->z;
CRCDEBUG_LOG(("Path::computePointOnPath() calling isLinePassable() 2\n"));
- if (veryClose || TheAI->pathfinder()->isLinePassable( obj, locomotorSet.getValidSurfaces(), closeNext->getLayer(), pos, tryPos, false, true ))
+ if (veryClose || TheAI->pathfinder()->isLinePassable( obj, locomotorSet.getValidSurfaces(), closeNext->getLayer(), pos, steerCheckTarget( pos, tryPos ), false, true ))
{
gotPos = true;
out.posOnPath = tryPos;
@@ -1084,7 +1165,7 @@ void Path::computePointOnPath(
out.posOnPath.z = closeNodePos->z;
CRCDEBUG_LOG(("Path::computePointOnPath() calling isLinePassable() 3\n"));
- if (TheAI->pathfinder()->isLinePassable( obj, locomotorSet.getValidSurfaces(), out.layer, pos, out.posOnPath, false, true ))
+ if (TheAI->pathfinder()->isLinePassable( obj, locomotorSet.getValidSurfaces(), out.layer, pos, steerCheckTarget( pos, out.posOnPath ), false, true ))
{
k = 0.5f;
gotPos = true;
@@ -1201,6 +1282,20 @@ Real Path::computeFlightDistToGoal( const Coord3D *pos, Coord3D& goalPos )
}
//-----------------------------------------------------------------------------------
+/* How many cells the queued searches may look at in one logic frame. EA's 5000 is about 3.5ms of
+ searching on this machine, and the queue spends all of it whenever there is work: with every
+ other cost in the frame trimmed, the pathfind queue owned 3,798 of the 5,312 frames that still
+ ran over 3ms in a four-player match.
+
+ Halving it to 2500 was tried and is worse at everything except the very tail. Four matches:
+ mean frame 1.38ms to 1.47, blocked unit-frames 7,673 to 8,318, units left stuck 9.8 to 26.8,
+ and the total search work went UP - 7.56 million cell expansions to 9.79 million, 5,885ms of
+ pathfinding a match to 6,946. A unit whose answer is late does not wait quietly: it stands in
+ the way, gets shoved, and asks again.
+
+ Tried a second time next to the request cap below, in case the cap changed the arithmetic: it
+ does not. 2500 cells with three requests a frame gives mean 1.24ms to 1.30 and blocked 7,191 to
+ 9,837. Cells are the wrong knob on this queue; requests are the right one. */
enum { PATHFIND_CELLS_PER_FRAME=5000}; // Number of cells we will search pathfinding per frame.
// A* open+closed sets draw from this pool; running dry aborts the search (no path) after
// burning the time. Retail 30000 was sized for 2003 memory - a long detour around a
@@ -1438,8 +1533,8 @@ void PathfindCell::releaseInfo( void )
/**
* Sets the goal unit into the info record for a cell.
*/
-void PathfindCell::setGoalUnit(ObjectID unitID, const ICoord2D &pos )
-{
+void PathfindCell::setGoalUnit(ObjectID unitID, const ICoord2D &pos )
+{
if (unitID==INVALID_ID) {
// removing goal.
if (m_info) {
@@ -4377,7 +4472,7 @@ const char *Pathfinder::getMatchProfileReport( void )
continue;
const Real ms = freq ? (Real)(thePFMatchTicks[ i ] * 1000.0 / (double)freq) : 0.0f;
char one[ 64 ];
- if( i >= PF_EXPAND )
+ if( i >= PF_MOVECHECK ) // the count-only group starts here
sprintf( one, "%s %dx ", thePFSlotName[ i ], thePFMatchCalls[ i ] );
else
sprintf( one, "%s %dx/%.0f ", thePFSlotName[ i ], thePFMatchCalls[ i ], ms );
@@ -4405,7 +4500,7 @@ const char *Pathfinder::getProfileReport( void )
continue;
const Real ms = freq ? (Real)(thePFTicks[ i ] * 1000.0 / (double)freq) : 0.0f;
char one[ 64 ];
- if( i >= PF_EXPAND )
+ if( i >= PF_MOVECHECK ) // the count-only group starts here
sprintf( one, "%s %dx ", thePFSlotName[ i ], thePFCalls[ i ] );
else
sprintf( one, "%s %dx/%.1f ", thePFSlotName[ i ], thePFCalls[ i ], ms );
@@ -5645,7 +5740,7 @@ Bool Pathfinder::checkDestination(const Object *obj, Int cellX, Int cellY, Pathf
*/
Bool Pathfinder::checkForMovement(const Object *obj, TCheckMovementInfo &info)
{
- PathProfile pfProfile( PF_MOVECHECK );
+ pfBump( PF_MOVECHECK ); // counted, never timed: see the count-only group in the enum
info.allyFixedCount = 0;
info.allyMoving = false;
info.allyGoal = false;
@@ -5661,6 +5756,16 @@ Bool Pathfinder::checkForMovement(const Object *obj, TCheckMovementInfo &info)
ignoreId = obj->getAIUpdateInterface()->getIgnoredObstacleID();
}
+ /* An occupancy summary was built here and taken out again: one counter per four-by-four block of
+ cells, maintained on every transition between "nobody here" and "somebody here", so that this
+ function could answer for open ground with one read instead of twenty-five. It works - four
+ matches came back bit-identical, which is the proof the counters never drift - and it buys
+ nothing: the pathfinder's own time fell 2.5% and the mean logic frame did not move at all.
+
+ The reason is worth keeping. The twenty-five reads it skips are a contiguous walk of a small
+ array, which is the cheap case; what costs money in this function is the cells that DO hold a
+ unit, where it looks the object up, asks the relationship and asks whether it can be crushed.
+ Optimising the empty case optimised the half that was already free. */
Int numCellsAbove = info.radius;
if (info.centerInCell) numCellsAbove++;
Int i, j;
@@ -6832,8 +6937,24 @@ void Pathfinder::processPathfindQueue(void)
#ifdef DEBUG_QPF
Int pathsFound = 0;
#endif
- while (m_cumulativeCellsAllocated < PATHFIND_CELLS_PER_FRAME &&
+ /* The cell budget bounds how much *searching* a frame does and says nothing about how many
+ requests it starts, which is where the bursts come from: a match averages under two path
+ requests a logic frame, and the frames that run long are the ones where a group order or a
+ wave of repaths puts ten of them in the queue at once and the frame answers all ten. A cap on
+ requests never bites the average - the queue drains at this rate every frame, which is many
+ times the demand - and clips the burst onto the next frame or two. */
+ /* Three, fitted. Against no cap at all it is faster and drives better at the same time: mean
+ logic frame 1.37ms to 1.24, p99 5.13 to 4.69, blocked unit-frames 7,673 a match to 7,191, and
+ the searches themselves 25,202 to 21,995 - a unit whose request waits a frame often no longer
+ needs the second, third and fourth repath it used to make while jammed. Two is a shade faster
+ still and the movement gives way: blocked back up to 8,531, units left stuck 12 to 21. */
+ enum { PATHFIND_REQUESTS_PER_FRAME = 3 };
+ Int requestsThisFrame = 0;
+
+ while (m_cumulativeCellsAllocated < PATHFIND_CELLS_PER_FRAME &&
+ requestsThisFrame < PATHFIND_REQUESTS_PER_FRAME &&
m_queuePRTail!=m_queuePRHead) {
+ ++requestsThisFrame;
Object *obj = TheGameLogic->findObjectByID(m_queuedPathfindRequests[m_queuePRHead]);
m_queuedPathfindRequests[m_queuePRHead] = INVALID_ID;
if (obj) {
@@ -7048,7 +7169,8 @@ Int Pathfinder::examineNeighboringCells(PathfindCell *parentCell, PathfindCell *
unregisterPathUsage(obj->getAIUpdateInterface()->getPath());
// getCurLocomotor, not getCurLocomotorSpeed: the latter DEBUG_LOGs when there is none.
const Locomotor *loco = obj->getAIUpdateInterface()->getCurLocomotor();
- if (loco)
+ // -nocrosstime leaves the speed at zero, which is this search's switch for "no clock"
+ if (loco && TheGlobalData->m_useCrossingCost)
crossingSpeed = loco->getMaxSpeedForCondition(obj->getBodyModule()->getDamageState());
}
Bool isCrusher = obj ? obj->getCrusherLevel() > 0 : false;
@@ -7645,6 +7767,18 @@ Path *Pathfinder::internalFindPath( Object *obj, const LocomotorSet& locomotorSe
request could spend the whole frame: 140513 cells / 285 ms measured, against a budget of
5000. The cap is a fixed count, not a timer, so every machine and every replay stops the
search at the same cell. */
+ /* Lowering this was tried twice, to bound the tail rather than the throughput: a search that
+ hits the cap hands back the partial route it has and the unit asks again later, so most
+ searches never notice. Both times it pulls in two directions and the movement one loses.
+
+ At 5000: 4v4 p99 7.08ms to 6.67 and stuck 149 to 87, but four players go blocked unit-frames
+ 7,673 to 9,595, stuck 9.8 to 86.8, and a frame over 16.7ms where there had been none. At
+ 10000, with the request cap below already in place: the worst frame of four matches 16.0ms
+ to 11.4, and blocked 7,191 to 9,908 with the mean and p99 both worse.
+
+ 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;
@@ -8241,6 +8375,17 @@ Path *Pathfinder::findGroundPath( const Coord3D *from,
// "closed" list is initially empty
m_closedList = NULL;
+ /* The group corridor was the last search in this file with no ceiling on it, and it is the most
+ expensive one per cell: every neighbour it looks at runs clearCellForDiameter, which reads a
+ six-by-six block. A three-unit team crossing Twilight Flame cost 40.5ms in one logic frame,
+ measured, and that was the worst frame of a four-player match.
+
+ The cap is a fixed cell count, so it stops at the same cell on every machine and in every
+ replay. Hitting it means the group gets no corridor at that width: AIGroup then tries 4 and
+ 3 cells wide, and if none of them answers, every member paths for itself - which is what
+ -nogrouppath does deliberately, and what retail did whenever the ground was too tight. */
+ enum { MAX_GROUND_PATH_CELLS = 3000 };
+
//
// Continue search until "open" list is empty, or
// until goal is found.
@@ -8248,6 +8393,11 @@ Path *Pathfinder::findGroundPath( const Coord3D *from,
Int cellCount = 0;
while( m_openList != NULL )
{
+ if (cellCount > MAX_GROUND_PATH_CELLS) {
+ DEBUG_LOG(("GROUNDPATH probe: gave up at %d cells, diameter %d\n", cellCount, pathDiameter));
+ break;
+ }
+
// take head cell off of open list - it has lowest estimated total path cost
parentCell = m_openList;
m_openList = parentCell->removeFromOpenList(m_openList);
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
index 021064371..debbad728 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
@@ -256,6 +256,7 @@ m_supplySourceAttackCheckFrame(0),
m_attackedSupplyCenter(INVALID_ID),
m_teamSeconds(10),
m_curWarehouseID(INVALID_ID),
+m_buildProbeOffset(0.0f),
m_scoutTimer(1),
m_retreatTimer(1),
m_expandTimer(1),
@@ -284,6 +285,7 @@ m_role(AIROLE_AGGRESSIVE)
m_structuresToRepair[i] = INVALID_ID;
}
m_repairDozerOrigin.zero();
+ m_buildProbePos.zero();
m_baseCenter.zero();
m_baseCenterSet = false;
m_difficulty = TheScriptEngine->getGlobalDifficulty();
@@ -841,9 +843,54 @@ Object *AIPlayer::buildStructureWithDozer(const ThingTemplate *bldgPlan, BuildLi
Real limit = 10*PATHFIND_CELL_SIZE_F;
if (isSkirmishAI()) {
limit = 120*PATHFIND_CELL_SIZE_F;
- }
+ }
Coord3D newPos = pos;
- for (posOffset = 0; posOffset<limit; posOffset += 2*PATHFIND_CELL_SIZE_F) {
+
+ /* One ring of that wiggle per logic frame.
+
+ The spot in the build list is taken, so this walks a square ring outwards looking for
+ one that is not, and for a skirmish AI it walks it 120 pathfind cells out - most of a
+ generated map. Every position costs a call to isLocationLegalToBuild, which is a
+ partition query for overlapping objects and a zone check for a route to it, and the
+ rings get longer the further out they go: 3,720 of them by the outermost, 46ms in one
+ logic frame, measured, and the worst frame of a four-player Twilight Flame match.
+ It is rare - four such frames in 55,876 - and that is exactly what a stutter is.
+
+ So the scan gets a budget and remembers where it was. It stops at the end of whichever
+ ring takes it past BUILD_PROBES_PER_FRAME positions, asks to be called again next
+ frame, and carries on from that ring; the positions are tried in the same order they
+ always were, so the spot it settles on is the spot it would have found in one go. The
+ budget counts positions rather than milliseconds on purpose: a stopwatch would test a
+ different number of them on a slower machine, and the two would desync.
+
+ A ring is finished once started rather than resumed part way through, which keeps the
+ whole of the state in one number.
+
+ The budget is small because the positions are not equally expensive. The rings near
+ the base are the dear ones - the partition query there comes back full of the
+ player's own buildings, and a position that gets past it pays for the terrain
+ sampling as well - while the outer rings are mostly off the map and are rejected on
+ the first line. A budget of 100 left a 19.7ms frame made of about 120 inner
+ positions; at 32 the first frame walks three rings and the worst frame this can cost
+ is either those, or one whole outer ring of 240 cheap ones. */
+ const Int BUILD_PROBES_PER_FRAME = 32;
+ Int probes = 0;
+ Bool outOfBudget = false;
+ Real firstOffset = 0;
+ if (m_buildProbeOffset > 0 &&
+ m_buildProbePos.x == pos.x && m_buildProbePos.y == pos.y) {
+ firstOffset = m_buildProbeOffset; // same spot as last frame: carry on from there
+ }
+ m_buildProbePos = pos;
+ m_buildProbeOffset = 0;
+
+ for (posOffset = firstOffset; posOffset<limit; posOffset += 2*PATHFIND_CELL_SIZE_F) {
+ if (probes >= BUILD_PROBES_PER_FRAME) {
+ // out of budget with rings left to walk: pick this one up again next frame
+ m_buildProbeOffset = posOffset;
+ outOfBudget = true;
+ break;
+ }
if (isSkirmishAI()) {
posOffset += 2*PATHFIND_CELL_SIZE_F;
}
@@ -852,6 +899,7 @@ Object *AIPlayer::buildStructureWithDozer(const ThingTemplate *bldgPlan, BuildLi
yPos = pos.y-offset;
for (xPos = pos.x-offset; xPos <= pos.x+offset; xPos+=PATHFIND_CELL_SIZE_F) {
if (isSkirmishAI()) xPos += PATHFIND_CELL_SIZE_F;
+ probes += 2;
newPos.x = xPos;
newPos.y = yPos;
valid = TheBuildAssistant->isLocationLegalToBuild( &newPos, bldgPlan, angle,
@@ -871,6 +919,7 @@ Object *AIPlayer::buildStructureWithDozer(const ThingTemplate *bldgPlan, BuildLi
xPos = pos.x-offset;
for (yPos = pos.y-offset; yPos <= pos.y+offset; yPos+=PATHFIND_CELL_SIZE_F) {
if (isSkirmishAI()) yPos += PATHFIND_CELL_SIZE_F;
+ probes += 2;
newPos.x = xPos;
newPos.y = yPos;
valid = TheBuildAssistant->isLocationLegalToBuild( &newPos, bldgPlan, angle,
@@ -889,6 +938,14 @@ Object *AIPlayer::buildStructureWithDozer(const ThingTemplate *bldgPlan, BuildLi
if (valid) break;
}
if (valid) pos = newPos;
+ if (!valid && outOfBudget) {
+ /* Out of budget with the search unfinished. The fallback below settles for the
+ original spot, and taking it here would be answering a question this frame has not
+ finished asking. */
+ TheTerrainVisual->removeAllBibs(); // isLocationLegalToBuild adds bib feedback
+ m_buildDelay = 1; // try again next frame; doBaseBuilding leaves any value >= 1 alone
+ return NULL;
+ }
if (!valid) {
valid = TheBuildAssistant->isLocationLegalToBuild( &pos, bldgPlan, angle,
BuildAssistant::NO_ENEMY_OBJECT_OVERLAP,
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp
index 597c6b014..698e518eb 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp
@@ -201,10 +201,25 @@ UpdateSleepTime SpawnBehavior::update( void )
{
/// @todo srj use SLEEPY_UPDATE here
- //EVERY FRAME
- if ( m_aggregateHealth )
+ /* Not every frame, and not on the same frame as the mob next to it.
+
+ computeAggregateStates walks every member of the mob, reading each one's veterancy, weapon
+ bonus, health and selection state, and rolls them into the nexus. EA ran it every frame for
+ every spawner alive. On Twilight Flame with four brutal AI that is 73 of them in one logic
+ frame costing 32.4ms, measured, which is two frames' worth of budget spent on a health bar
+ and a selection rule.
+
+ It runs every AGGREGATE_STATE_RATE frames instead, offset by the nexus' own object id so the
+ mobs do not all land on the same frame - the same staggering the AI players got, for the
+ same reason. What it costs is up to a fifth of a second of lag on the mob's aggregate health
+ bar and on click-one-select-all, neither of which anybody can see. The offset is an object
+ id, which is assigned in creation order and is identical on every machine, so this stays
+ inside the CRC. */
+ const Int AGGREGATE_STATE_RATE = 6;
+ if ( m_aggregateHealth &&
+ ((TheGameLogic->getFrame() + (UnsignedInt)getObject()->getID()) % AGGREGATE_STATE_RATE) == 0 )
{
- computeAggregateStates();
+ computeAggregateStates();
}
const SpawnBehaviorModuleData* md = getSpawnBehaviorModuleData();
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SimpleObjectIterator.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SimpleObjectIterator.cpp
index 03229d64a..c27c524e0 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SimpleObjectIterator.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SimpleObjectIterator.cpp
@@ -70,6 +70,16 @@ SimpleObjectIterator::~SimpleObjectIterator()
}
//=============================================================================
+/* Recycling these through a free list instead of the pool was tried and measured at nothing.
+
+ A gathering range query keeps every object it finds in one of these and an eight-player match
+ makes 111 such queries a logic frame, so this is thousands of pool allocations and frees a
+ frame, every one of them taking the global memory lock that THREADING-ROADMAP section 1.1 is
+ about. Recycling removes all of them, comes back bit-identical over four matches, and moves the
+ mean logic frame from 1.24ms to 1.26 - which is to say it does nothing. The pool is a free list
+ already and the lock is uncontended in a single-threaded logic frame, so the 16,523
+ critical-section operations a frame are cheap operations. Worth knowing before anybody spends a
+ fortnight on the allocator. */
void SimpleObjectIterator::insert(Object *obj, Real numeric)
{
DEBUG_ASSERTCRASH(obj, ("sorry, no nulls allowed here"));
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
index ef55624c3..e6335f988 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
@@ -1162,7 +1162,19 @@ UpdateSleepTime AIUpdateInterface::update( void )
// assume we can sleep forever, unless the state machine (or turret, etc) demand otherwise
UpdateSleepTime subMachineSleep = UPDATE_SLEEP_FOREVER;
- StateReturnType stRet = getStateMachine()->updateStateMachine();
+ /* -aislice: think every n-th frame, drive every frame.
+
+ The state machine below is where a unit decides - what to attack, where the next waypoint is,
+ whether to give up and repath - and it is the expensive half of the object walk. The
+ locomotor at the bottom of this function is what actually moves it, and that is not skipped,
+ so a sliced-out frame is a frame the unit keeps driving along the route it already has
+ without asking any new questions. The stagger is the object id: creation order, identical on
+ every machine, so this stays inside the CRC. Off by default (n = 1). */
+ const Int aiSlice = TheGlobalData ? TheGlobalData->m_aiSliceFrames : 1;
+ const Bool thinkThisFrame = (aiSlice <= 1) ||
+ (((TheGameLogic->getFrame() + (UnsignedInt)getObject()->getID()) % (UnsignedInt)aiSlice) == 0);
+
+ StateReturnType stRet = thinkThisFrame ? getStateMachine()->updateStateMachine() : STATE_CONTINUE;
// A unit that was just built walks a short exit path out of its producer and then, if the player
// set a rally point, attack moves to it - so it stops and fights whatever it runs into on the way
@@ -1249,9 +1261,10 @@ UpdateSleepTime AIUpdateInterface::update( void )
! obj->isDisabledByType( DISABLED_HACKED ) )
{
// If we are dead, don't let the turrets do anything anymore, or else they will keep attacking
- for (int i = 0; i < MAX_TURRETS; ++i)
+ // (a turret is deciding too, so it waits with the rest of the unit's thinking under -aislice)
+ for (int i = 0; thinkThisFrame && i < MAX_TURRETS; ++i)
{
- if (m_turretAI[i])
+ if (m_turretAI[i])
{
UpdateSleepTime tmp = m_turretAI[i]->updateTurretAI();
if (tmp < subMachineSleep)
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp
index f39ff57e1..0466dc001 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp
@@ -1777,12 +1777,35 @@ void ScriptActions::doTeamMoveToSkirmishApproachPath(const AsciiString& teamName
AsciiString pathLabel;
pathLabel.format("%s%d", waypointPathLabel.str(), mpNdx);
+ /* This action is the slowest single thing left in a four-player skirmish frame - 40ms of a 45ms
+ logic frame, once or twice a match, on the frame a team is told to take its approach path.
+ The script engine already lets only one of these through per frame. The three parts are
+ timed apart so the next person does not have to guess which one it is. */
+#ifdef DEBUG_LOGGING
+ Int64 tStart, tWaypoint, tEnd, tFreq;
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tStart );
+#endif
Waypoint *way = TheTerrainLogic->getClosestWaypointOnPath( &pos, pathLabel );
if (!way) {
return;
}
DEBUG_ASSERTLOG(TheTerrainLogic->isPurposeOfPath(way, pathLabel), ("***Wrong waypoint purpose. Make jba fix this.\n"));
+#ifdef DEBUG_LOGGING
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tWaypoint );
+#endif
theGroup->groupMoveToPosition(way->getLocation(), false, CMD_FROM_SCRIPT);
+#ifdef DEBUG_LOGGING
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tEnd );
+ QueryPerformanceFrequency( (LARGE_INTEGER *)&tFreq );
+ if( tFreq > 0 )
+ {
+ const Real wayMS = (Real)((double)(tWaypoint - tStart) * 1000.0 / (double)tFreq);
+ const Real moveMS = (Real)((double)(tEnd - tWaypoint) * 1000.0 / (double)tFreq);
+ if( wayMS + moveMS > 5.0f )
+ DEBUG_LOG(("SLOW APPROACH PATH: team %s, %d members, waypoint search %.1fms, group move %.1fms\n",
+ teamName.str(), count, wayMS, moveMS));
+ }
+#endif
}
//-------------------------------------------------------------------------------------------------