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): cut the cost of a seven-AI skirmish logic frame

Olcay Seygan309ce2fab1bc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1e9c2fca7..45ca33cb5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -266,9 +266,32 @@ Around it, the whole production loop got tightened:
nothing while the research ran.
- **Select several factories, click a unit, and it goes to whichever has the shortest queue.**
Shift-click queues five, spread the same way.
+- **A general's upgrade goes to whichever selected building is free.** Some upgrades are bought once
+ for your whole army rather than per building, and those always went to the same one of the selected
+ buildings — click three of them with four barracks selected and one barracks did all three jobs in
+ a row while the other three stood idle. Each click now goes to the shortest queue, and the bar
+ counts the clicks you have already made this instant, so a fast run of three lands on three
+ different buildings.
+- **Clicking an upgrade shows immediately that you clicked it.** The picture is now covered when the
+ work starts and uncovers as it progresses, instead of filling up with a shadow. The old way drew
+ nothing at all until the first percent had gone by, so an upgrade you had just paid for looked
+ exactly like one you had never touched — and with a long upgrade in a queue behind other work, it
+ could look untouched for a while.
+- **The strip above the command bar dims the same way.** A cameo that has just joined the queue is
+ covered and uncovers as it is built, so a fresh order looks like a fresh order. Items waiting
+ behind the one being worked on stay covered.
+- **You can hand a half-built building to another worker.** Click a second worker onto a building
+ already going up and it takes over; the one that was on it goes back to being idle. The game used
+ to refuse the click outright — the cursor did not even offer it — on the grounds that two workers
+ cannot build one thing faster. True, but that is not what you were asking for.
- **The nearest free worker takes a new job** — and a worker already halfway through a building does
- not get yanked off it. An idle worker will pick up any half-finished building nobody is working on,
+ not get yanked off it, unless you say so. An idle worker will pick up any half-finished building nobody is working on,
including one whose builder died.
+- **A worker that is building something still offers you the whole build list.** Its buttons used to
+ grey out until it finished, so lining up the next structure meant waiting or hunting down another
+ worker by hand. Click anyway: the order goes to the nearest idle worker, and only falls back to
+ interrupting a busy one when every worker you own is busy. Same for the build list you get with
+ nothing selected — it stays usable when the whole crew is out working.
- **Workers go back to collecting supplies** after they finish, instead of standing there.
- **Timings everywhere**: seconds left on a building going up, the current unit and the whole queue
behind it, a charge bar on superweapons, a progress clock on upgrades being researched. A bar only
@@ -281,6 +304,15 @@ Around it, the whole production loop got tightened:
earned — so it does not swing wildly the moment you spend something.
- **Aircraft always show how many attack runs they have left**, selected or not. That is the number
that decides whether you commit them or send them home.
+- **The corner readout now tells you two different things instead of one confusing one.** It reads
+ `00:12:30(00:13:04) 30hz(144fps)`: game time and, in brackets, the real time you have been
+ sitting there; then the rate the battle is being simulated at and, in brackets, the rate your
+ screen is being drawn at. They are not the same number, and the difference is the interesting
+ part - the drawing rate can be in the hundreds while the simulation is struggling. When it
+ struggles the first number drops below 30 and the two clocks drift apart by exactly the time it
+ lost.
+ The drawing rate really is the drawing rate now: both figures used to be counted off the same
+ clock, so the number in brackets was a second copy of the simulation rate and moved with it.
**Placing buildings.** The grid you place on is drawn on the ground now instead of over the top of
everything — it follows the slope, your units and buildings stand on it rather than under it, and
@@ -297,10 +329,12 @@ ground you cannot build on is a soft red wash instead of a scribble. Three more:
- **A click clears a half-typed building shortcut.** With the structure grid armed and waiting for
its second key, a click could leave it armed, and the next A or S you pressed became a building to
place instead of an attack-move or a stop — which cancelled your selection.
-- **The building shortcut now waits the two seconds it promises.** It was counting drawn frames
- rather than time, so on a fast machine it gave up in a third of a second — press Q, take a breath,
- and the second key was an attack-move again. It waits two real seconds now, whatever your frame
- rate.
+- **The two-key building shortcut works.** It was being thrown away the instant it was armed: the
+ command bar redraws itself the moment you press Q, and the redraw wiped the half-typed shortcut,
+ so the second key never had one to finish — Q-Q did nothing and Q-A was an attack-move that
+ cancelled your selection. It now lives until you pick a cell, select something else, or two real
+ seconds pass. (It used to count drawn frames rather than time for that wait, which on a fast
+ machine was a third of a second.)
- **Escape takes back what you were doing before it opens the menu.** With a building on the cursor,
a targeting order armed, or a half-typed shortcut waiting, Escape drops that and nothing else.
Press it again with nothing pending and the pause menu comes up as always.
@@ -549,6 +583,95 @@ the middle of the nearest square — a lone Chinook lands where you clicked, whi
the tidy formation. And a footprint change around a structure could permanently mark the ground
beside it as unbuildable and unwalkable, for the rest of the match.
+**A seven-opponent skirmish was still stuttering, though**, and we went looking with a stopwatch
+built into the game. Over one match, 513 turns ran long, and on average **93 percent of that lost
+time was one thing: the pathfinder**. The worst single turn took **three seconds** - the game
+visibly stops while one unit works out where to walk.
+
+The cause was a rescue we had added ourselves. When the coarse route came out too narrow for a big
+vehicle, we let the search start over with the whole map open to it. Generous, and ruinous: the
+pathfinder is allowed 5,000 squares of thinking per turn, and one of those restarted searches was
+measured chewing through **140,513 squares in 285 milliseconds**. The rescue is gone. A route too
+narrow for a tank is a route to widen, not an excuse to search the whole map over again.
+
+So we widened it. The coarse route was being opened out by one square on each side around the
+**starting point only** — the developers' own note says it is there so a unit can get around friendly
+units standing next to it — and the rest of the route, all the way to the destination, stayed a
+single ribbon ten squares wide. Now the whole length of it is opened out. That is the same rescue,
+applied where it costs something proportional to how far you are walking, rather than to how big the
+map is.
+
+And the search itself now has a stopping point. Every other search in the pathfinder had one; the
+main one had none, so a search for a destination it could never reach kept going until it had visited
+every square it could get to. It now stops after 20,000 squares and hands back the best part of the
+route it did work out, so the unit sets off towards where you clicked and works out the rest as it
+goes — instead of the game stopping dead for three seconds and the unit then standing there anyway.
+The limit is a fixed count of squares, not a stopwatch, so a slow machine and a fast one still play
+the same match.
+
+Measured again on the same seven-opponent match, those three together:
+
+| | Long turns | Average | Worst turn | Turns over a second |
+|---|---|---|---|---|
+| Before | 513 | 144 ms | 2,976 ms | 8 |
+| After | 201 | 61 ms | 243 ms | none |
+
+**Then we found why it was still 61 milliseconds.** A pathfinder works by guessing how far it still
+has to go and walking towards the best guess. This one's guess was far too low — it priced every step
+as a straight step on open ground, while the route it actually charges for costs more for a diagonal,
+more again for every turn, and more still for squeezing between buildings. A guess that low stops
+steering: instead of heading for the destination, the search spreads out sideways and ends up looking
+at nearly every square it is allowed to touch. The log caught it in the act — a route about 315
+squares long visiting **17,578 squares**.
+
+The guess now accounts for what a step really costs. The route it finds can be slightly longer than
+the theoretical best, and in exchange the search visits a fraction of the squares. On a unit walking
+across a map that is a trade worth making every time.
+
+**And one more, the big one.** Whenever the pathfinder looked at a square, it also tried drawing a
+straight line from that square all the way to the destination, checking every square on the line for
+anything in the way — a good shortcut when the line is clear. It did that from *every* square it
+looked at. On an open map with seven computer opponents on the move, that came to **130 million**
+of those checks in ten seconds of stuttering, with a single turn hitting **1.4 million**. One
+infantryman crossing open ground burned 130 milliseconds by himself. The shortcut is still there,
+but it is now only drawn from a square that is genuinely closer to the destination than anything
+tried so far — which is the only time it has a new chance of getting through.
+
+That one change took the stuttering turns from 615 to 108 and the time the game spends finding
+routes from 11.8 seconds to 1.6. The worst single route went from 130 milliseconds to 12.
+
+**Then the queue itself.** A pathfinder keeps a list of squares still to look at, cheapest first.
+Adding one meant reading down that list from the cheapest end until the right place turned up —
+about four hundred steps every time, eight times for every square examined. The list runs both ways,
+so it now comes in from whichever end is closer, and the two ordinary cases — cheaper than
+everything, dearer than everything — take no steps at all. Same order out, same routes, less work.
+
+**And the ten-second hiccup.** Every ten seconds or so the game redraws its map of which areas
+connect to which — it has to, because you and seven opponents keep putting buildings in the way.
+Joining two areas together meant rewriting the entire table, once per join, and on a big map that
+table has thousands of entries. The whole redraw landed inside a single turn: thirty to forty
+milliseconds where nothing else happened, no matter what was on screen. Twenty-five turns in one
+match were nothing but this. Joining two areas is now a single operation instead of a full rewrite.
+The map is still redrawn on exactly the same turns, and comes out exactly the same — it just stops
+costing you a turn.
+
+**And seven opponents all thinking at once.** Every computer player asks itself the same questions on
+a fixed rhythm - what to build next, what squad to raise, which bridge to repair - and every one of
+them was handed the same stopwatch, started on the same turn. Seven opponents therefore did all of
+their thinking on the same turn, over and over, for the entire match, while the six turns in between
+had nothing to do. They now take it in turns: each opponent gets its own slot in the cycle. Nobody
+thinks any less often, and no opponent is any slower - the work is simply spread across the turns
+instead of piled onto one of them.
+
+**And their squads marching out at the same moment.** When a computer player finishes a squad and
+sends it off toward you, the game works out the whole route across the map right then and there,
+while everything else waits. One of those cost thirty milliseconds - a whole turn on its own - and in
+a seven-opponent match six of them arrived on the same turn: eighty milliseconds where the game did
+nothing but plan marches. Only one squad is sent on its way per turn now; the rest go on the next
+turn, and the one after. A squad that used to leave on turn 4,120 leaves on turn 4,121 instead, which
+is a thirtieth of a second - you cannot see it, and it was sitting still waiting for orders either
+way.
+
## Sound, video, and getting it to start at all
- **Audio is real**, through the game's own audio library. The sound SDK was stripped from the source
diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h
index a442cea7c..e582d0e62 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h
@@ -1002,9 +1002,25 @@ protected:
ObjectID m_buildPageObjectID; ///< builder the page belongs to; a new one starts at the menu
Int m_chordGroup; ///< -1, or the structure group (0 = Q, 1 = W) armed by the first chord key
UnsignedInt m_chordStartMs; ///< millisecond the chord was armed on, for CHORD_TIMEOUT_MS
+ DrawableID m_chordDrawableID; ///< builder the armed chord addresses; the chord dies if the bar moves to another one
DrawableID m_standInBuilderID; ///< with nothing selected, the builder whose command bar is shown (INVALID_DRAWABLE_ID otherwise)
Drawable *findStandInBuilder( Bool freeOnly ); ///< the local player's free builder (or, unless freeOnly, any builder) to stand in for an empty selection
+ /** A player upgrade is researched once, so it goes to exactly one of the selected buildings -
+ * and the bar cannot see the queue an earlier click in this same frame just filled, because
+ * the message only reaches the logic on the next one. Clicking three upgrades on four selected
+ * barracks therefore stacked all three on whichever building the bar was drawn from, and the
+ * other three sat idle. These remember what has been handed out this frame so the next click
+ * can pick a building that is genuinely free. */
+ enum { UPGRADE_SPREAD_MAX = 32 }; ///< selections past this fall back to the plain queue count
+ UnsignedInt m_upgradeSpreadFrame; ///< logic frame the tallies below describe; a new frame clears them
+ ObjectID m_upgradeSpreadID[ UPGRADE_SPREAD_MAX ]; ///< building handed an upgrade this frame
+ Int m_upgradeSpreadCount[ UPGRADE_SPREAD_MAX ]; ///< how many, since one building can take several
+ Int m_upgradeSpreadEntries; ///< used entries in the two arrays above
+ Int upgradesSpreadTo( ObjectID id ); ///< upgrades already sent to this building this frame
+ void noteUpgradeSpread( ObjectID id ); ///< record one more upgrade sent to this building
+ Object *pickUpgradeProducer( const UpgradeTemplate *upgradeT, Object *fallback ); ///< freest selected building that can research it
+
// removed from multiplayer branch
//GameWindow *m_commandMarkers[ MAX_COMMANDS_PER_SET ]; ///< When we don't have a command, they want to show an image
// removed from multiplayer branch
diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h b/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h
index c6e8be62f..2d65ba82a 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h
@@ -836,9 +836,13 @@ protected:
DisplayString * m_hudDisplayString; ///< the ShowHudOverlay line (fps / clock / income)
DisplayString * m_incomeDisplayString; ///< the "(+N/min)" drawn beside the money
Int m_lastIncomeDisplayed; ///< so that string is only rebuilt when the rate changes
- UnsignedInt m_hudLastSampleFrame; ///< client frame the fps sample was last refreshed on
+ UnsignedInt m_hudDrawCount; ///< rendered frames counted by drawHudOverlay itself
+ UnsignedInt m_hudLastSampleFrame; ///< m_hudDrawCount the fps sample was last refreshed on
UnsignedInt m_hudLastSampleMs; ///< wall clock of that sample
Real m_hudFps; ///< smoothed render rate
+ UnsignedInt m_hudLastSampleLogicFrame; ///< logic frame at that same sample
+ Real m_hudLogicHz; ///< logic frames actually simulated per real second
+ UnsignedInt m_hudRealClockBaseMs; ///< wall clock the two elapsed-time readouts were aligned at
// A script time freeze stops the logic clock, and the military subtitle's counters are
// logic frames, so they have to be stepped by hand while it lasts. These two turn the
// wall clock into that step without drift: every update works out how many 30Hz frames
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
index f5bbd3bbe..288464713 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
@@ -53,6 +53,60 @@ class PathfindZoneManager;
typedef UnsignedShort zoneStorageType;
+//----------------------------------------------------------------------------------------------------------
+// Zone equivalency sets.
+//
+// A zone equivalency array answers "which zone is this zone really the same as". EA stored it
+// flat - every entry already held its set's representative - and merged two sets by relabelling
+// *every* entry of the array, so one merge cost O(zones) and a whole-map rezone cost
+// O(cells x zones). On a big map with a few thousand zones that is tens of milliseconds, once
+// every ZONE_UPDATE_FREQUENCY frames, all inside one logic frame.
+//
+// The array is used as the parent forest of a union-find instead: pathfindZoneFind walks to the
+// root with path compression, pathfindZoneUnion links the higher root under the lower one, and
+// pathfindZoneFlatten collapses the forest back to the flat form every reader outside the merge
+// loops still expects. Linking the higher root under the lower one is exactly EA's "keep the
+// lower zone" rule, so a set's representative is still the smallest id in it and the flattened
+// array is identical to what the relabelling version produced - only the cost changes.
+//
+// Every link points from a higher id to a lower one, which is what lets the flatten be a single
+// ascending pass and what keeps pathfindZoneFind's walk terminating.
+//----------------------------------------------------------------------------------------------------------
+
+inline Int pathfindZoneFind( zoneStorageType *zoneEquivalency, Int zone )
+{
+ Int root = zone;
+ while (zoneEquivalency[root] != root) {
+ root = zoneEquivalency[root];
+ }
+ while (zoneEquivalency[zone] != root) {
+ Int next = zoneEquivalency[zone];
+ zoneEquivalency[zone] = (zoneStorageType)root;
+ zone = next;
+ }
+ return root;
+}
+
+inline void pathfindZoneUnion( zoneStorageType *zoneEquivalency, Int zoneA, Int zoneB )
+{
+ Int rootA = pathfindZoneFind( zoneEquivalency, zoneA );
+ Int rootB = pathfindZoneFind( zoneEquivalency, zoneB );
+ if (rootA == rootB) return;
+ if (rootB < rootA) {
+ zoneEquivalency[rootA] = (zoneStorageType)rootB; // keep the lower zone
+ } else {
+ zoneEquivalency[rootB] = (zoneStorageType)rootA;
+ }
+}
+
+inline void pathfindZoneFlatten( zoneStorageType *zoneEquivalency, Int numZones )
+{
+ for (Int i = 0; i < numZones; i++) {
+ zoneEquivalency[i] = zoneEquivalency[zoneEquivalency[i]];
+ }
+}
+
+
//----------------------------------------------------------------------------------------------------------
@@ -301,6 +355,9 @@ public:
UnsignedInt costSoFar( PathfindCell *parent );
+ /// tell the open list its single seed cell, so the tail pointer starts out right
+ static void setOpenListSeed( PathfindCell *cell );
+
/// put self on "open" list in ascending cost order, return new list
PathfindCell *putOnSortedOpenList( PathfindCell *list );
@@ -539,6 +596,8 @@ public:
Bool isPassable(Int cellX, Int cellY) const;
Bool clipIsPassable(Int cellX, Int cellY) const;
void setPassable(Int cellX, Int cellY, Bool passable);
+ /// mark this cell's block passable together with the eight blocks around it, clipped to the map
+ void setPassableWithNeighbors(Int cellX, Int cellY);
void setAllPassable(void);
@@ -642,6 +701,17 @@ public:
const Coord3D *to, ObjectID ignoreObject=INVALID_ID ); ///< Can we build any path at all between the locations (terrain, buildings & units check - slower)
Bool queueForPath(ObjectID id); ///< The object wants to request a pathfind, so put it on the list to process.
+
+ //
+ // Per-frame accounting of where pathfinder time actually goes. The slow-frame log used to
+ // charge all of it to `processPathfindQueue`, and most slow frames turned out to run no
+ // search large enough to log itself - so the cost is spread over the other entry points
+ // (patching, attack paths, goal and position updates, footprint reclassification) and there
+ // was no way to tell which. Reset at the top of each logic frame, printed when the frame runs
+ // over budget. Timing only, nothing the simulation reads.
+ //
+ static void resetProfile( void ); ///< start a new frame's tally
+ static const char *getProfileReport( void ); ///< "patch 12x/3.1 attack 4x/8.0", empty when idle
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
@@ -861,6 +931,7 @@ private:
PathfindCell *m_openList; ///< Cells ready to be explored
PathfindCell *m_closedList; ///< Cells already explored
+ Int m_probeBestDistSqr; ///< closest a straight-line-to-goal probe has been fired from, this search
Bool m_isMapReady; ///< True if all cells of map have been classified
Bool m_isTunneling; ///< True if path started in an obstacle
@@ -888,6 +959,12 @@ private:
Int m_queuePRHead;
Int m_queuePRTail;
Int m_cumulativeCellsAllocated;
+
+ /* 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
+ frame. */
+ Bool m_lastSearchRestricted;
};
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
index d42f00ac3..8119e36da 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
@@ -254,6 +254,15 @@ public:
/// the arithmetic behind the two above, free of the Player so a test can reach it
static Int computeBuildDelay( Real seconds, Int money, Int poorAt, Int wealthyAt,
Real poorMod, Real wealthyMod, Real rateScale );
+
+ /**
+ Where in a repeating check's cycle this player sits. Every AIPlayer arms the same timers
+ with the same constants on the same frame, so a lobby full of bots does its base building,
+ team building and bridge repair in lockstep for the whole match and the cost of all of them
+ lands on one logic frame. Spreading them over the cycle changes *when* each one runs, not
+ how often, and it is a function of the player index alone - the simulation stays deterministic.
+ */
+ static Int computeUpdatePhase( Int playerIndex, Int cycleFrames );
protected:
/**
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/ScriptEngine.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/ScriptEngine.h
index 1cc7602a8..49074b9d3 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/ScriptEngine.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/ScriptEngine.h
@@ -233,6 +233,23 @@ public:
virtual void reset( void ); ///< Reset
virtual void update( void ); ///< Update
+ //
+ // Every side's script list is walked every frame, so one expensive condition costs the logic
+ // frame 30 times a second. update() keeps the worst script of the frame (EA's own
+ // SPECIAL_SCRIPT_PROFILING already does the measuring - it just had nowhere to report to before
+ // the game ended) and this hands it to GameLogic's slow-frame line.
+ //
+ static const char *getProfileReport( void );
+
+ //
+ // True for the script actions that order a whole team somewhere. Every one of them lands in
+ // AIGroup::friend_computeGroundPath, which runs a full-map A* on the spot instead of queueing
+ // it, so a skirmish lobby where several AI teams reach their move instruction on the same frame
+ // pays for all of those searches at once. The sequential-script step lets one of them through
+ // per logic frame and makes the rest wait a frame; see evaluateAndProgressAllSequentialScripts.
+ //
+ static Bool isThrottledTeamMoveAction( Int actionType );
+
void appendSequentialScript(const SequentialScript *scriptToSequence);
void removeSequentialScript(SequentialScript *scriptToRemove);
void notifyOfTeamDestruction(Team *teamDestroyed);
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
index 0420835d6..e1143cb29 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
@@ -775,10 +775,36 @@ Bool GameEngine_isLogicFrameDue( Real& accumMs, Real elapsedMs, Int logicFps )
* framerate (m_maxFPS, the game-speed setting), so game speed does not scale with the
* render framerate.
*/
+#ifdef DEBUG_LOGGING
+//
+// Frame rate watchdog. A slow logic frame and a slow render both show up to the player as the same
+// stutter, and the logic-side slow-frame log cannot tell them apart because it never sees the client
+// half of the loop. So time both halves of every pass and, once a second, say what the rate was and
+// where the time went - but only when the rate actually dropped, so a smooth match logs nothing.
+//
+static Real engineElapsedMS( const Int64 &from, const Int64 &to )
+{
+ Int64 freq;
+ QueryPerformanceFrequency( (LARGE_INTEGER *)&freq );
+ if( freq < 1 )
+ return 0.0f;
+ return (Real)((double)(to - from) * 1000.0 / (double)freq);
+}
+#endif
+
void GameEngine::update( void )
{
USE_PERF_TIMER(GameEngine_update)
{
+#ifdef DEBUG_LOGGING
+ static Int fpsFrames = 0;
+ static Real fpsClientTotal = 0.0f, fpsClientMax = 0.0f;
+ static Real fpsLogicTotal = 0.0f, fpsLogicMax = 0.0f;
+ static DWORD fpsWindowStart = timeGetTime();
+ Int64 tClientStart, tClientEnd, tLogicStart, tLogicEnd;
+ Real clientMS = 0.0f, logicMS = 0.0f;
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tClientStart );
+#endif
{
@@ -800,6 +826,10 @@ void GameEngine::update( void )
TheCDManager->UPDATE();
}
+#ifdef DEBUG_LOGGING
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tClientEnd );
+ clientMS = engineElapsedMS( tClientStart, tClientEnd );
+#endif
// Fast-forward modes run a logic frame on every call; otherwise logic ticks at
@@ -831,9 +861,44 @@ void GameEngine::update( void )
if (logicFrameDue &&
((TheNetwork == NULL && !TheGameLogic->isGamePaused()) || (TheNetwork && TheNetwork->isFrameDataReady())))
{
+#ifdef DEBUG_LOGGING
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tLogicStart );
+#endif
TheGameLogic->UPDATE();
+#ifdef DEBUG_LOGGING
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tLogicEnd );
+ logicMS = engineElapsedMS( tLogicStart, tLogicEnd );
+#endif
}
+#ifdef DEBUG_LOGGING
+ fpsFrames++;
+ fpsClientTotal += clientMS;
+ fpsLogicTotal += logicMS;
+ if( clientMS > fpsClientMax ) fpsClientMax = clientMS;
+ if( logicMS > fpsLogicMax ) fpsLogicMax = logicMS;
+ {
+ const DWORD nowMS = timeGetTime();
+ const DWORD windowMS = nowMS - fpsWindowStart;
+ if( windowMS >= 1000 )
+ {
+ const Real fps = (Real)fpsFrames * 1000.0f / (Real)windowMS;
+ if( fps < 50.0f && TheGameLogic && TheGameLogic->isInGame() && !TheGameLogic->isInShellGame() )
+ {
+ DEBUG_LOG(("FPS %.0f over %dms (%d frames, logic frame %d) | client avg %.1f max %.1f | logic avg %.1f max %.1f | unaccounted %.1fms\n",
+ fps, (Int)windowMS, fpsFrames, TheGameLogic->getFrame(),
+ fpsClientTotal / fpsFrames, fpsClientMax,
+ fpsLogicTotal / fpsFrames, fpsLogicMax,
+ (Real)windowMS - fpsClientTotal - fpsLogicTotal));
+ }
+ fpsFrames = 0;
+ fpsClientTotal = fpsLogicTotal = 0.0f;
+ fpsClientMax = fpsLogicMax = 0.0f;
+ fpsWindowStart = nowMS;
+ }
+ }
+#endif
+
} // end perfGather
}
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp
index 3c89d8a0b..35aa2dccd 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp
@@ -484,7 +484,17 @@ Bool ActionManager::canResumeConstructionOf( const Object *obj,
// add more effectiveness to the construction so we'll say no (this might change for workers
// in the future)
//
+ // A player clicking one of their own builders onto the site is not "doubling up", though - it
+ // is a handover, and refusing it left the click doing nothing at all with no explanation. The
+ // engine already knows how to hand a site over: `DozerAIUpdate::newTask` makes the new builder
+ // the site's builder, and the old one's build state sees `getBuilderID() != dozer->getID()` on
+ // its next tick and drops the task. So the ban only needs to hold for orders the player did not
+ // give - the skirmish AI and scripts, where two builders trading a site back and forth would be
+ // a loop nobody asked for.
+ //
Object *builder = TheGameLogic->findObjectByID( objectBeingConstructed->getBuilderID() );
+ if( builder && builder != obj && commandSource == CMD_FROM_PLAYER )
+ builder = NULL;
if( builder )
{
AIUpdateInterface *ai = builder->getAI();
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp
index 5771cb6c2..413311da7 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp
@@ -174,6 +174,8 @@ void ControlBar::pressCommandButton( Int index )
{
m_chordGroup = ( index == CHORD_SLOT_Q ) ? 0 : 1;
m_chordStartMs = timeGetTime();
+ m_chordDrawableID = m_currentSelectedDrawable ? m_currentSelectedDrawable->getID()
+ : INVALID_DRAWABLE_ID;
markUIDirty(); // the group that is armed greys the other one out
return;
}
@@ -257,6 +259,7 @@ void ControlBar::dropChord( void )
return;
m_chordGroup = -1;
+ m_chordDrawableID = INVALID_DRAWABLE_ID;
markUIDirty(); // the greyed-out half of the structures comes back
} // end dropChord
@@ -1099,7 +1102,15 @@ ControlBar::ControlBar( void )
m_buildPageBackButton = NULL;
m_chordGroup = -1;
m_chordStartMs = 0;
+ m_chordDrawableID = INVALID_DRAWABLE_ID;
m_standInBuilderID = INVALID_DRAWABLE_ID;
+ m_upgradeSpreadFrame = 0;
+ m_upgradeSpreadEntries = 0;
+ for( i = 0; i < UPGRADE_SPREAD_MAX; i++ )
+ {
+ m_upgradeSpreadID[ i ] = INVALID_ID;
+ m_upgradeSpreadCount[ i ] = 0;
+ }
for( i = 0; i < MAX_MULTI_SELECT_GROUPS; i++ )
{
m_multiSelectGroupTemplate[ i ] = NULL;
@@ -1607,6 +1618,18 @@ void ControlBar::update( void )
{
dropChord();
}
+
+ //
+ // ... and neither does a chord whose builder is gone: the command bar is now showing
+ // something else, so the cell the second key would pick is not the one that was armed
+ //
+ if( m_chordGroup >= 0 )
+ {
+ const DrawableID nowShowing = m_currentSelectedDrawable ? m_currentSelectedDrawable->getID()
+ : INVALID_DRAWABLE_ID;
+ if( nowShowing != m_chordDrawableID )
+ dropChord();
+ }
if(m_controlBarSchemeManager)
m_controlBarSchemeManager->update();
@@ -1739,22 +1762,6 @@ void ControlBar::update( void )
m_currentSelectedDrawable = NULL;
markUIDirty();
}
- else
- {
- // the stand-in went to work - a builder with a job greys its structure buttons out -
- // so hand the bar to a free builder if there is one
- AIUpdateInterface *ai = standInObj->getAI();
- DozerAIInterface *dozer = ai ? ai->getDozerAIInterface() : NULL;
- if( dozer && !builderIsFree( ai, dozer ) )
- {
- Drawable *freeBuilder = findStandInBuilder( TRUE );
- if( freeBuilder && freeBuilder != standIn )
- {
- m_standInBuilderID = INVALID_DRAWABLE_ID;
- markUIDirty();
- }
- }
- }
}
//
@@ -2630,8 +2637,14 @@ void ControlBar::switchToContext( ControlBarContext context, Drawable *draw )
// save a pointer for the currently selected drawable
m_currentSelectedDrawable = draw;
- // a half-typed structure chord does not survive a context change
- dropChord();
+ //
+ // a half-typed structure chord used to be dropped here. It cannot be: evaluateContextUI
+ // erases the bar by switching to CB_CONTEXT_NONE before it rebuilds it, and arming the
+ // chord calls markUIDirty() itself to grey the other group out - so the chord killed
+ // itself on the very next frame and the second key never had a chord to resolve.
+ // ControlBar::update drops it instead, when the drawable driving the bar is no longer the
+ // one the chord was armed on.
+ //
if (IsInGameChatActive() == FALSE && TheGameLogic && !TheGameLogic->isInShellGame()) {
TheWindowManager->winSetFocus( NULL );
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp
index 794fc2ac1..40801ca15 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp
@@ -70,7 +70,15 @@
// PRIVATE DATA ///////////////////////////////////////////////////////////////////////////////////
static GameWindow *commandWindows[ MAX_COMMANDS_PER_SET ];
Bool commandWindowsInitialized = FALSE;
-static Color BuildClockColor = GameMakeColor(0,0,0,120); ///< translucent black radial fill drawn over the cameo as production progresses
+/** Translucent black scrim swept off the cameo as production progresses.
+ *
+ * It is drawn with the *inverse* clock - covered at 0%, fully uncovered at 100% - and that is the
+ * whole point. The forward clock (`W3DDisplay::drawRectClock`) early-outs on `percent < 1` and
+ * draws nothing at all, so an upgrade you had just clicked looked exactly like one you had not:
+ * the queue entry existed, the money was spent, and the button gave back no sign of it until the
+ * first percent ticked over. Starting covered means the click shows on screen the instant it
+ * lands, and the cameo reads as "uncovering" rather than "filling up with black". */
+static Color BuildClockColor = GameMakeColor(0,0,0,120);
//-------------------------------------------------------------------------------------------------
/** Is any selected building of the local player's researching or holding 'upgrade' in its queue?
@@ -772,7 +780,7 @@ void ControlBar::updateContextCommand( void )
const ProductionEntry *first = pu->firstProduction();
if( first && first->getProductionType() == PRODUCTION_UNIT &&
first->getProductionObject() == command->getThingTemplate() )
- GadgetButtonDrawClock( win, first->getPercentComplete(), BuildClockColor );
+ GadgetButtonDrawInverseClock( win, first->getPercentComplete(), BuildClockColor );
}
}
@@ -792,7 +800,11 @@ void ControlBar::updateContextCommand( void )
{
upgradeQueuedHere = TRUE;
if( entry )
- GadgetButtonDrawClock( win, entry->getPercentComplete(), BuildClockColor );
+ GadgetButtonDrawInverseClock( win, entry->getPercentComplete(), BuildClockColor );
+ else
+ /* queued but not started - no percentage to show, so show the full scrim. Without
+ it a waiting upgrade is indistinguishable from one that was never ordered. */
+ GadgetButtonDrawInverseClock( win, 0, BuildClockColor );
}
}
@@ -1225,10 +1237,13 @@ CommandAvailability ControlBar::getCommandAvailability( const CommandButton *com
if( dozerAI == NULL )
return COMMAND_RESTRICTED;
- // if building anything at all right now we can't build another
- if( dozerAI->isTaskPending( DOZER_TASK_BUILD ) == TRUE )
- return COMMAND_RESTRICTED;
-
+ //
+ // A builder already on a job used to grey out every structure button it had, so
+ // queueing the next building meant waiting for it or picking another dozer by hand.
+ // The button stays live: MSG_DOZER_CONSTRUCT hands the job to the idle builder
+ // nearest the site and only re-tasks a busy one when there is no idle one.
+ //
+
// return whether or not the player can build this thing
if( player->canBuild( whatToBuild ) == FALSE )
return COMMAND_RESTRICTED;
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp
index 042202e8a..51e6565c0 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp
@@ -100,6 +100,105 @@ void selectObjectOfType( Object* obj, void* selectObjectsInfo )
//-------------------------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------------------------
+/** How many upgrades this frame has already handed to this building.
+ *
+ * The tally is thrown away as soon as the logic frame changes, because from the next frame on the
+ * buildings' own production queues carry the same information and are the better source. */
+//-------------------------------------------------------------------------------------------------
+Int ControlBar::upgradesSpreadTo( ObjectID id )
+{
+ if( m_upgradeSpreadFrame != TheGameLogic->getFrame() )
+ {
+ m_upgradeSpreadFrame = TheGameLogic->getFrame();
+ m_upgradeSpreadEntries = 0;
+ }
+
+ for( Int i = 0; i < m_upgradeSpreadEntries; i++ )
+ if( m_upgradeSpreadID[ i ] == id )
+ return m_upgradeSpreadCount[ i ];
+
+ return 0;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Record that one more upgrade went to this building on this frame. */
+//-------------------------------------------------------------------------------------------------
+void ControlBar::noteUpgradeSpread( ObjectID id )
+{
+ upgradesSpreadTo( id ); // rolls the tally over if the frame changed
+
+ for( Int i = 0; i < m_upgradeSpreadEntries; i++ )
+ {
+ if( m_upgradeSpreadID[ i ] == id )
+ {
+ m_upgradeSpreadCount[ i ]++;
+ return;
+ }
+ }
+
+ if( m_upgradeSpreadEntries < UPGRADE_SPREAD_MAX )
+ {
+ m_upgradeSpreadID[ m_upgradeSpreadEntries ] = id;
+ m_upgradeSpreadCount[ m_upgradeSpreadEntries ] = 1;
+ m_upgradeSpreadEntries++;
+ }
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Of the selected buildings that can research this player upgrade, the one with the shortest
+ * queue - counting what earlier clicks on this same frame already sent it.
+ *
+ * A player upgrade is researched once for the whole player, so unlike an object upgrade it goes
+ * to exactly one building. The bar used to always name the object it was drawn from, so clicking
+ * three upgrades with four barracks selected stacked all three on one barracks while the other
+ * three stood idle. Ties keep selection order, so the same click on the same selection always
+ * picks the same building. */
+//-------------------------------------------------------------------------------------------------
+Object *ControlBar::pickUpgradeProducer( const UpgradeTemplate *upgradeT, Object *fallback )
+{
+ if( upgradeT == NULL )
+ return fallback;
+
+ Player *player = ThePlayerList->getLocalPlayer();
+ const DrawableList *selected = TheInGameUI->getAllSelectedDrawables();
+ if( selected == NULL )
+ return fallback;
+
+ Object *best = NULL;
+ Int bestLoad = 0;
+
+ for( DrawableListCIt it = selected->begin(); it != selected->end(); ++it )
+ {
+ Object *target = (*it)->getObject();
+ if( target == NULL || target->getControllingPlayer() != player )
+ continue;
+
+ ProductionUpdateInterface *tpu = target->getProductionUpdateInterface();
+ if( tpu == NULL || tpu->canQueueUpgrade( upgradeT ) != CANMAKE_OK )
+ continue;
+
+ if( target->canProduceUpgrade( upgradeT ) == FALSE || tpu->isUpgradeInQueue( upgradeT ) == TRUE )
+ continue;
+
+ Int load = tpu->getProductionCount() + upgradesSpreadTo( target->getID() );
+ DEBUG_LOG(("UpgradeSpread candidate obj %d '%s' queue %d + spread %d = %d\n",
+ (Int)target->getID(), target->getTemplate()->getName().str(),
+ (Int)tpu->getProductionCount(), upgradesSpreadTo( target->getID() ), load));
+ if( best == NULL || load < bestLoad )
+ {
+ best = target;
+ bestLoad = load;
+ }
+ }
+
+ DEBUG_LOG(("UpgradeSpread pick for '%s': obj %d (load %d), fallback obj %d\n",
+ upgradeT->getUpgradeName().str(), best ? (Int)best->getID() : 0, bestLoad,
+ fallback ? (Int)fallback->getID() : 0));
+
+ return best ? best : fallback;
+}
+
//-------------------------------------------------------------------------------------------------
/** Process a button transition message from the window system that should be for one of
* our GUI commands */
@@ -601,7 +700,23 @@ CBCommandStatus ControlBar::processCommandUI( GameWindow *control,
break;
}
- ProductionUpdateInterface* pu = obj ? obj->getProductionUpdateInterface() : NULL;
+ //
+ // A player upgrade is researched once for the whole player, so it goes to a single
+ // building - but with several selected there is no reason for that to be the same
+ // building every time. Send it to the one with the shortest queue instead, counting
+ // the upgrades earlier clicks on this frame already handed out, which is something
+ // the buildings' own queues cannot tell us yet because the messages have not reached
+ // the logic. Without this, clicking three upgrades with four barracks selected piled
+ // all three onto one barracks and left the other three idle.
+ //
+ Object *producer = obj;
+ DEBUG_LOG(("UpgradeSpread player upgrade '%s' ctx %d selCount %d rep obj %d\n",
+ upgradeT->getUpgradeName().str(), (Int)m_currContext,
+ TheInGameUI ? TheInGameUI->getSelectCount() : -1, (Int)obj->getID()));
+ if( m_currContext == CB_CONTEXT_MULTI_SELECT )
+ producer = pickUpgradeProducer( upgradeT, obj );
+
+ ProductionUpdateInterface* pu = producer ? producer->getProductionUpdateInterface() : NULL;
if (pu != NULL)
{
CanMakeType cmt = pu->canQueueUpgrade(upgradeT);
@@ -612,10 +727,14 @@ CBCommandStatus ControlBar::processCommandUI( GameWindow *control,
}
}
+ if( producer == NULL )
+ break;
+
// send the message
GameMessage *msg = TheMessageStream->appendMessage( GameMessage::MSG_QUEUE_UPGRADE );
- msg->appendObjectIDArgument( obj->getID() );
+ msg->appendObjectIDArgument( producer->getID() );
msg->appendIntegerArgument( upgradeT->getUpgradeNameKey() );
+ noteUpgradeSpread( producer->getID() );
break;
@@ -691,6 +810,8 @@ CBCommandStatus ControlBar::processCommandUI( GameWindow *control,
msg->appendObjectIDArgument( target->getID() );
msg->appendIntegerArgument( upgradeT->getUpgradeNameKey() );
sent++;
+ DEBUG_LOG(("UpgradeSpread object upgrade '%s' -> obj %d (purse left %d)\n",
+ upgradeT->getUpgradeName().str(), (Int)target->getID(), purse));
}
if( sent > 0 )
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
index c8f3b7963..0fcd0d73e 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
@@ -1049,12 +1049,16 @@ InGameUI::InGameUI()
m_hudDisplayString = NULL;
m_incomeDisplayString = NULL;
m_lastIncomeDisplayed = -1;
+ m_hudDrawCount = 0;
m_hudLastSampleFrame = 0;
m_hudLastSampleMs = 0;
m_cameraKeyLastMs = 0;
m_subtitleFreezeStartMs = 0;
m_subtitleFreezeSteps = 0;
m_hudFps = 0.0f;
+ m_hudLastSampleLogicFrame = 0;
+ m_hudLogicHz = 0.0f;
+ m_hudRealClockBaseMs = 0;
for( Int incomeBucket = 0; incomeBucket < INCOME_SAMPLES; incomeBucket++ )
m_incomeSamples[ incomeBucket ] = 0;
m_incomeSampleCount = 0;
@@ -5599,29 +5603,51 @@ void InGameUI::drawHudOverlay( void )
return;
//
- // Render rate, sampled over half a second of wall clock so the number is readable. This counts
- // client frames, which is the render rate - the logic rate is fixed by the game speed.
+ // Two rates, both sampled over half a second of wall clock so the numbers are readable, and
+ // they are not the same thing. Client frames are the render rate. Logic frames are the
+ // simulation, which is *supposed* to run at LOGICFRAMES_PER_SECOND and drops below it exactly
+ // when a frame overruns its budget - so a reading under the nominal rate is the stutter,
+ // measured, rather than something the render rate can be blamed for.
//
- const UnsignedInt clientFrame = TheGameClient->getFrame();
+ // NOT GameClient::getFrame() - that is the simulation frame number from the server, so the
+ // "fps" reading was a second copy of the logic rate and moved with it. postDraw runs once per
+ // rendered frame, so count the draws here instead.
+ ++m_hudDrawCount;
+ const UnsignedInt clientFrame = m_hudDrawCount;
+ const UnsignedInt logicFrame = TheGameLogic->getFrame();
UnsignedInt nowMs = timeGetTime();
if( m_hudLastSampleFrame == 0 )
{
m_hudLastSampleMs = nowMs;
m_hudLastSampleFrame = clientFrame;
+ m_hudLastSampleLogicFrame = logicFrame;
}
else if( nowMs - m_hudLastSampleMs >= 500 )
{
- m_hudFps = (clientFrame - m_hudLastSampleFrame) * 1000.0f / (Real)(nowMs - m_hudLastSampleMs);
+ const Real elapsed = (Real)(nowMs - m_hudLastSampleMs);
+ m_hudFps = (clientFrame - m_hudLastSampleFrame) * 1000.0f / elapsed;
+ m_hudLogicHz = (logicFrame - m_hudLastSampleLogicFrame) * 1000.0f / elapsed;
m_hudLastSampleMs = nowMs;
m_hudLastSampleFrame = clientFrame;
+ m_hudLastSampleLogicFrame = logicFrame;
}
- UnsignedInt totalSecs = TheGameLogic->getFrame() / LOGICFRAMES_PER_SECOND;
+ //
+ // Game time is logic frames; real time is the wall clock. They start together and drift apart
+ // by however much the simulation has fallen behind - which is the same stutter the two rates
+ // above show, totalled. The base is set the first time the overlay draws rather than at frame
+ // zero, so switching it on mid-game does not invent an hour of lag.
+ //
+ UnsignedInt gameSecs = logicFrame / LOGICFRAMES_PER_SECOND;
+ if( m_hudRealClockBaseMs == 0 )
+ m_hudRealClockBaseMs = nowMs - gameSecs * 1000;
+ UnsignedInt realSecs = (nowMs - m_hudRealClockBaseMs) / 1000;
UnicodeString text;
- text.format( L"%d:%02d:%02d %d fps",
- totalSecs / 3600, (totalSecs / 60) % 60, totalSecs % 60,
- REAL_TO_INT( m_hudFps ) );
+ text.format( L"%02d:%02d:%02d(%02d:%02d:%02d) %dhz(%dfps)",
+ gameSecs / 3600, (gameSecs / 60) % 60, gameSecs % 60,
+ realSecs / 3600, (realSecs / 60) % 60, realSecs % 60,
+ REAL_TO_INT( m_hudLogicHz + 0.5f ), REAL_TO_INT( m_hudFps + 0.5f ) );
if( m_hudDisplayString == NULL )
{
@@ -5802,11 +5828,18 @@ void InGameUI::drawProductionStripRow( Int row, Int y )
if( cameo )
TheDisplay->drawImage( cameo, x, y, x + PRODUCTION_STRIP_CAMEO, y + PRODUCTION_STRIP_CAMEO );
- // the head of a building's queue is the one being worked on, and only it has progress
- if( pu->firstProduction() == entry && entry->getPercentComplete() > 0.0f )
- TheDisplay->drawRectClock( x, y, PRODUCTION_STRIP_CAMEO, PRODUCTION_STRIP_CAMEO,
- REAL_TO_INT( entry->getPercentComplete() ),
- GameMakeColor( 0, 0, 0, 100 ) );
+ //
+ // The scrim starts covering the cameo and is swept off as the item is built, the same
+ // way round as the command bar's own clock. Going the other way - filling up with black
+ // as progress runs - meant a cameo that had just appeared was drawn clean, and
+ // `drawRectClock` refuses to draw at all below one percent, so a fresh order and a
+ // nearly finished one looked alike. Only the head of a building's queue has progress;
+ // everything behind it is waiting and wears the full scrim.
+ //
+ const Int percent = ( pu->firstProduction() == entry )
+ ? REAL_TO_INT( entry->getPercentComplete() ) : 0;
+ TheDisplay->drawRemainingRectClock( x, y, PRODUCTION_STRIP_CAMEO, PRODUCTION_STRIP_CAMEO,
+ percent, GameMakeColor( 0, 0, 0, 100 ) );
}
//
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
index 65fe95b5e..522b9063e 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
@@ -109,6 +109,83 @@ struct TCheckMovementInfo
inline Int IABS(Int x) { if (x>=0) return x; return -x;};
+//-------------------------------------------------------------------------------------------------
+// Where a logic frame's pathfinder time actually went. The slow-frame log charged all of it to
+// `processPathfindQueue`, and most slow frames run no search big enough to log itself - so the
+// cost sits in the other entry points and nothing said which. A scope object per public entry
+// charges the time to a slot; only the outermost one is timed, so a `findPath` that calls
+// `findHierarchicalPath` is not counted twice. Timing only; no simulation state is read here,
+// 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_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_OPENWALK, PF_ZONEMERGE,
+ PF_SLOTS };
+static const char *thePFSlotName[ PF_SLOTS ] =
+{ "queue", "find", "closest", "attack", "safe", "patch", "moveaway",
+ "adjust", "goal", "pos", "footprint", "exist", "hier", "movecheck",
+ "zones", "zonemod",
+ "expand", "mc.expand", "mc.line", "mc.linepass", "openwalk", "zone.merge" };
+static __int64 thePFTicks[ PF_SLOTS ];
+static Int thePFCalls[ PF_SLOTS ];
+static Int thePFDepth = 0;
+static char thePFReport[ 512 ];
+
+inline void pfBump( Int slot ) { thePFCalls[ slot ]++; }
+
+class PathProfile
+{
+public:
+ PathProfile( Int slot ) : m_slot( slot ), m_timed( thePFDepth == 0 )
+ {
+ thePFCalls[ slot ]++;
+ if( m_timed )
+ {
+ thePFDepth++;
+ QueryPerformanceCounter( (LARGE_INTEGER *)&m_start );
+ }
+ }
+ ~PathProfile()
+ {
+ if( m_timed )
+ {
+ __int64 end;
+ QueryPerformanceCounter( (LARGE_INTEGER *)&end );
+ thePFTicks[ m_slot ] += end - m_start;
+ thePFDepth--;
+ }
+ }
+private:
+ Int m_slot;
+ Bool m_timed;
+ __int64 m_start;
+};
+
+// Times unconditionally, even when nested inside a PathProfile scope - the enclosing slot's
+// total then includes this one. For costs that sit *inside* an already-timed entry point and
+// would otherwise be invisible.
+class PathProfileInner
+{
+public:
+ PathProfileInner( Int slot ) : m_slot( slot )
+ {
+ thePFCalls[ slot ]++;
+ QueryPerformanceCounter( (LARGE_INTEGER *)&m_start );
+ }
+ ~PathProfileInner()
+ {
+ __int64 end;
+ QueryPerformanceCounter( (LARGE_INTEGER *)&end );
+ thePFTicks[ m_slot ] += end - m_start;
+ }
+private:
+ Int m_slot;
+ __int64 m_start;
+};
+
//-----------------------------------------------------------------------------------
static Int frameToShowObstacles;
@@ -1524,6 +1601,21 @@ Bool PathfindCell::removeObstacle( Object *obstacle )
}
/// put self on "open" list in ascending cost order, return new list
+/* EA walked this list from the head on every insert and stopped only past the last cell of equal
+ cost, so a search with a wide frontier paid O(open list) per cell it expanded. Measured with the
+ `openwalk` counter on a 1-human / 7-AI skirmish: 62,490,219 walk steps over 108 slow frames, with
+ 8,871,712 of them in a single frame - about 400 steps per insert. The list is doubly linked, so
+ keep a tail pointer and walk in from whichever end is nearer the new cell's cost, taking the two
+ common cases (cheaper than everything, dearer than everything) in constant time. The insertion
+ point is unchanged - still after every cell of equal cost - so the search expands exactly the
+ cells it did before and lockstep holds. */
+static PathfindCellInfo *theOpenListTail = NULL;
+
+void PathfindCell::setOpenListSeed( PathfindCell *cell )
+{
+ theOpenListTail = cell ? cell->m_info : NULL;
+}
+
PathfindCell *PathfindCell::putOnSortedOpenList( PathfindCell *list )
{
DEBUG_ASSERTCRASH(m_info, ("Has to have info."));
@@ -1533,39 +1625,63 @@ PathfindCell *PathfindCell::putOnSortedOpenList( PathfindCell *list )
list = this;
m_info->m_prevOpen = NULL;
m_info->m_nextOpen = NULL;
+ theOpenListTail = m_info;
}
else
{
- // insertion sort
- PathfindCell *c, *lastCell = NULL;
- for( c = list; c; c = c->getNextOpen() )
- {
- if (c->m_info->m_totalCost > m_info->m_totalCost)
- break;
+ DEBUG_ASSERTCRASH(theOpenListTail && theOpenListTail->m_nextOpen==NULL, ("Open list tail is stale."));
+ const UnsignedInt cost = m_info->m_totalCost;
+ PathfindCellInfo *tail = theOpenListTail;
+ PathfindCellInfo *before; // insert after this one, NULL means at the head
- lastCell = c;
+ if (cost >= tail->m_totalCost)
+ {
+ before = tail; // dearer than everything - append
+ }
+ else if (cost < list->m_info->m_totalCost)
+ {
+ before = NULL; // cheaper than everything - prepend
+ }
+ else if (cost - list->m_info->m_totalCost <= tail->m_totalCost - cost)
+ {
+ // nearer the cheap end - walk forward to the first cell that costs more than us
+ PathfindCellInfo *c;
+ before = NULL;
+ for( c = list->m_info; c; c = c->m_nextOpen )
+ {
+ pfBump( PF_OPENWALK );
+ if (c->m_totalCost > cost)
+ break;
+ before = c;
+ }
+ }
+ else
+ {
+ // nearer the dear end - walk back to the last cell that does not cost more than us
+ before = tail;
+ while (before && before->m_totalCost > cost)
+ {
+ pfBump( PF_OPENWALK );
+ before = before->m_prevOpen;
+ }
}
- if (c)
+ if (before)
{
- // insert just before "c"
- if (c->m_info->m_prevOpen)
- c->m_info->m_prevOpen->m_nextOpen = this->m_info;
+ m_info->m_nextOpen = before->m_nextOpen;
+ m_info->m_prevOpen = before;
+ if (before->m_nextOpen)
+ before->m_nextOpen->m_prevOpen = m_info;
else
- list = this;
-
- m_info->m_prevOpen = c->m_info->m_prevOpen;
- c->m_info->m_prevOpen = this->m_info;
-
- m_info->m_nextOpen = c->m_info;
-
+ theOpenListTail = m_info;
+ before->m_nextOpen = m_info;
}
else
{
- // append after "lastCell" - end of list
- lastCell->m_info->m_nextOpen = this->m_info;
- m_info->m_prevOpen = lastCell->m_info;
- m_info->m_nextOpen = NULL;
+ m_info->m_prevOpen = NULL;
+ m_info->m_nextOpen = list->m_info;
+ list->m_info->m_prevOpen = m_info;
+ list = this;
}
}
@@ -1576,11 +1692,14 @@ PathfindCell *PathfindCell::putOnSortedOpenList( PathfindCell *list )
return list;
}
+
/// remove self from "open" list
PathfindCell *PathfindCell::removeFromOpenList( PathfindCell *list )
{
DEBUG_ASSERTCRASH(m_info, ("Has to have info."));
DEBUG_ASSERTCRASH(m_info->m_closed==FALSE && m_info->m_open==TRUE, ("Serious error - Invalid flags. jba"));
+ if (theOpenListTail == m_info)
+ theOpenListTail = m_info->m_prevOpen;
if (m_info->m_nextOpen)
m_info->m_nextOpen->m_prevOpen = m_info->m_prevOpen;
@@ -1599,6 +1718,7 @@ PathfindCell *PathfindCell::removeFromOpenList( PathfindCell *list )
/// remove all cells from "open" list
Int PathfindCell::releaseOpenList( PathfindCell *list )
{
+ theOpenListTail = NULL;
Int count = 0;
while (list) {
count++;
@@ -1718,6 +1838,22 @@ UnsignedInt PathfindCell::costToGoal( PathfindCell *goal )
#endif
+ /* The estimate above prices a step at COST_ORTHOGONAL, but costSoFar charges a real step far
+ more than that: COST_DIAGONAL for a diagonal, +4/+8/+16 for a 45/90/135 degree turn, another
+ COST_DIAGONAL for a pinched cell, and whatever the terrain adds. So the estimate is a long
+ way under the truth, and an A* whose estimate is too low stops steering: it fans out and
+ expands nearly every cell it is allowed to touch instead of walking towards the goal. That
+ is what the measurements showed - a 315-cell route expanding 17578 cells, essentially the
+ entire corridor, at 229 ms.
+
+ HEURISTIC_WEIGHT_NUM/DEN brings the estimate up towards what a step really costs. The search
+ is no longer guaranteed to find the *cheapest* route, only one within the weight factor of
+ it, which for a unit walking across a map is a trade worth making many times over: the
+ route is a few cells longer, the search is several times cheaper, and the frame does not
+ stall. It stays integer arithmetic and a fixed ratio, so every machine and every replay
+ expands the same cells in the same order. */
+ enum { HEURISTIC_WEIGHT_NUM = 3, HEURISTIC_WEIGHT_DEN = 2 };
+ cost = (cost * HEURISTIC_WEIGHT_NUM) / HEURISTIC_WEIGHT_DEN;
return cost;
}
@@ -1892,30 +2028,21 @@ static void __fastcall resolveBlockZones(Int srcZone, Int targetZone, zoneStorag
}
}
+// Merge two zone sets. This used to relabel the whole array (see the union-find comment in
+// AIPathfind.h); the array is now the union-find's parent forest and the merge is O(1) amortized.
+// The set representative is still the smallest id in it, so the flattened result is unchanged.
static void __fastcall resolveZones(Int srcZone, Int targetZone, zoneStorageType *zoneEquivalency, Int sizeOfZE)
{
- Int i;
// We have two zones being combined now. Keep the lower zone.
DEBUG_ASSERTCRASH(srcZone!=0 && targetZone!=0, ("Bad resolve zones ."));
DEBUG_ASSERTCRASH(srcZone<sizeOfZE && targetZone<sizeOfZE, ("Bad resolve zones ."));
- srcZone = zoneEquivalency[srcZone];
- targetZone = zoneEquivalency[targetZone];
- DEBUG_ASSERTCRASH(srcZone<sizeOfZE && targetZone<sizeOfZE, ("Bad resolve zones ."));
- zoneStorageType finalZone;
- if (targetZone<srcZone) {
- finalZone = zoneEquivalency[targetZone];
- } else {
- finalZone = zoneEquivalency[srcZone];
- }
- DEBUG_ASSERTCRASH(finalZone<sizeOfZE , ("Bad resolve zones ."));
- for (i=0; i<sizeOfZE; i++) {
- zoneStorageType ze = zoneEquivalency[i];
- if (ze == targetZone || ze == srcZone) {
- zoneEquivalency[i] = finalZone;
- }
- }
+ pfBump( PF_ZONEMERGE );
+ pathfindZoneUnion( zoneEquivalency, srcZone, targetZone );
}
+// Both arrays must be flat on entry. The merge loop below turns zoneArray back into a union-find
+// forest, so its reads go through pathfindZoneFind and it flattens the array again on the way out
+// - callers past this point index it directly.
static void flattenZones(zoneStorageType *zoneArray, zoneStorageType *zoneHierarchical, Int sizeOfZones)
{
Int i;
@@ -1929,21 +2056,22 @@ static void flattenZones(zoneStorageType *zoneArray, zoneStorageType *zoneHierar
#if 1
for (i=0; i<sizeOfZones; i++) {
- Int zone1 = zoneArray[i];
+ Int zone1 = pathfindZoneFind(zoneArray, i);
Int zone2 = zoneHierarchical[i];
if (zone1!=zone2) {
resolveZones(zone1, zone2, zoneArray, sizeOfZones);
}
}
+ pathfindZoneFlatten(zoneArray, sizeOfZones);
#endif
}
inline void applyZone(PathfindCell &targetCell, const PathfindCell &sourceCell, zoneStorageType *zoneEquivalency, Int sizeOfZE)
{
DEBUG_ASSERTCRASH(sourceCell.getZone()!=0, ("Unset source zone."));
- Int srcZone = zoneEquivalency[sourceCell.getZone()];
+ Int srcZone = pathfindZoneFind(zoneEquivalency, sourceCell.getZone());
//DEBUG_ASSERTCRASH(srcZone!=0, ("Bad zone equivalency zone."));
- Int targetZone = zoneEquivalency[targetCell.getZone()];
+ Int targetZone = pathfindZoneFind(zoneEquivalency, targetCell.getZone());
if (targetZone == 0) {
targetCell.setZone(srcZone);
@@ -2320,6 +2448,7 @@ static Bool s_stopForceCalling = FALSE;
void PathfindZoneManager::calculateZones( PathfindCell **map, PathfindLayer layers[], const IRegion2D &globalBounds )
{
+ PathProfileInner pfProfile( PF_ZONES );
#ifdef DEBUG_QPF
#if defined(DEBUG_LOGGING)
@@ -2401,6 +2530,8 @@ void PathfindZoneManager::calculateZones( PathfindCell **map, PathfindLayer laye
}
Int totalZones = m_maxZone;
+ // The merges above left a union-find forest; the collapse below indexes the array directly.
+ pathfindZoneFlatten(zoneEquivalency, totalZones);
// if (totalZones>maxZones/2) {
// DEBUG_LOG(("Max zones %d\n", m_maxZone));
// }
@@ -2788,6 +2919,13 @@ void PathfindZoneManager::calculateZones( PathfindCell **map, PathfindLayer laye
+ // Same again for the arrays sweep 2 merged into: flattenZones wants them flat on entry.
+ pathfindZoneFlatten(m_groundCliffZones, m_maxZone);
+ pathfindZoneFlatten(m_groundWaterZones, m_maxZone);
+ pathfindZoneFlatten(m_groundRubbleZones, m_maxZone);
+ pathfindZoneFlatten(m_terrainZones, m_maxZone);
+ pathfindZoneFlatten(m_crusherZones, m_maxZone);
+
//THIS BLOCK IS 20%
flattenZones(m_groundCliffZones, m_hierarchicalZones, m_maxZone);
flattenZones(m_groundWaterZones, m_hierarchicalZones, m_maxZone);
@@ -2859,6 +2997,7 @@ void PathfindZoneManager::calculateZones( PathfindCell **map, PathfindLayer laye
*/
void PathfindZoneManager::updateZonesForModify(PathfindCell **map, PathfindLayer layers[], const IRegion2D &structureBounds, const IRegion2D &globalBounds )
{
+ PathProfileInner pfProfile( PF_ZONEMOD );
#ifdef DEBUG_QPF
#if defined(DEBUG_LOGGING)
@@ -3050,6 +3189,24 @@ void PathfindZoneManager::setPassable(Int cellX, Int cellY, Bool passable)
m_zoneBlocks[blockX][blockY].setPassable(passable);
}
+//
+// Set the passable flag for the block at this location and the eight blocks around it.
+//
+void PathfindZoneManager::setPassableWithNeighbors(Int cellX, Int cellY)
+{
+ Int blockX = cellX/ZONE_BLOCK_SIZE;
+ Int blockY = cellY/ZONE_BLOCK_SIZE;
+
+ Int i, j;
+ for (i = blockX-1; i <= blockX+1; i++) {
+ if (i<0 || i>=m_zoneBlockExtent.x) continue;
+ for (j = blockY-1; j <= blockY+1; j++) {
+ if (j<0 || j>=m_zoneBlockExtent.y) continue;
+ m_zoneBlocks[i][j].setPassable(true);
+ }
+ }
+}
+
//
// Get the passable flag for the block at this location.
//
@@ -3860,8 +4017,46 @@ Pathfinder::~Pathfinder( void )
PathfindCellInfo::releaseCellInfos();
}
+
+void Pathfinder::resetProfile( void )
+{
+ for( Int i = 0; i < PF_SLOTS; i++ )
+ {
+ thePFTicks[ i ] = 0;
+ thePFCalls[ i ] = 0;
+ }
+ thePFDepth = 0;
+}
+
+const char *Pathfinder::getProfileReport( void )
+{
+ __int64 freq = 0;
+ QueryPerformanceFrequency( (LARGE_INTEGER *)&freq );
+ thePFReport[ 0 ] = 0;
+ Int len = 0;
+ for( Int i = 0; i < PF_SLOTS; i++ )
+ {
+ if( thePFCalls[ i ] == 0 )
+ continue;
+ const Real ms = freq ? (Real)(thePFTicks[ i ] * 1000.0 / (double)freq) : 0.0f;
+ char one[ 64 ];
+ if( i >= PF_EXPAND )
+ sprintf( one, "%s %dx ", thePFSlotName[ i ], thePFCalls[ i ] );
+ else
+ sprintf( one, "%s %dx/%.1f ", thePFSlotName[ i ], thePFCalls[ i ], ms );
+ Int oneLen = strlen( one );
+ if( len + oneLen >= (Int)sizeof( thePFReport ) - 1 )
+ break;
+ strcpy( thePFReport + len, one );
+ len += oneLen;
+ }
+ return thePFReport;
+}
+
+
void Pathfinder::reset( void )
{
+ m_probeBestDistSqr = 0x7FFFFFFF;
frameToShowObstacles = 0;
DEBUG_LOG(("Pathfind cell is %d bytes, PathfindCellInfo is %d bytes\n", sizeof(PathfindCell), sizeof(PathfindCellInfo)));
@@ -3897,6 +4092,7 @@ void Pathfinder::reset( void )
// pathfind grid cells have not been classified yet
m_isMapReady = false;
m_cumulativeCellsAllocated = 0;
+ m_lastSearchRestricted = false;
debugPathPos.x = 0.0f;
debugPathPos.y = 0.0f;
@@ -4147,6 +4343,7 @@ void Pathfinder::classifyFence( Object *obj, Bool insert )
*/
void Pathfinder::classifyObjectFootprint( Object *obj, Bool insert )
{
+ PathProfile pfProfile( PF_FOOTPRINT );
if (obj->isKindOf(KINDOF_MINE)) {
return; // don't pathfind around mines.
}
@@ -4839,6 +5036,8 @@ Bool Pathfinder::validMovementTerrain( PathfindLayerEnum layer, const Locomotor*
// Releases the cells on the open & closed lists.
//
void Pathfinder::cleanOpenAndClosedLists(void) {
+ m_probeBestDistSqr = 0x7FFFFFFF; // a new search gets a fresh probe budget
+ PathfindCell::setOpenListSeed( NULL );
Int count = 0;
if (m_openList) {
count += PathfindCell::releaseOpenList(m_openList);
@@ -5023,6 +5222,7 @@ Bool Pathfinder::checkDestination(const Object *obj, Int cellX, Int cellY, Pathf
*/
Bool Pathfinder::checkForMovement(const Object *obj, TCheckMovementInfo &info)
{
+ PathProfile pfProfile( PF_MOVECHECK );
info.allyFixedCount = 0;
info.allyMoving = false;
info.allyGoal = false;
@@ -5351,6 +5551,7 @@ Bool Pathfinder::checkForLanding(Int cellX, Int cellY, PathfindLayerEnum layer,
*/
Bool Pathfinder::adjustToLandingDestination(Object *obj, Coord3D *dest)
{
+ PathProfile pfProfile( PF_ADJUST );
Int iRadius;
Bool center;
getRadiusAndCenter(obj, iRadius, center);
@@ -5429,6 +5630,7 @@ Bool Pathfinder::adjustToLandingDestination(Object *obj, Coord3D *dest)
*/
Bool Pathfinder::adjustDestination(Object *obj, const LocomotorSet& locomotorSet, Coord3D *dest, const Coord3D *groupDest)
{
+ PathProfile pfProfile( PF_ADJUST );
if( obj->isKindOf(KINDOF_PROJECTILE) )
{
return true; // missiles can go wherever they want to. jba.
@@ -5538,6 +5740,7 @@ Bool Pathfinder::checkForTarget(const Object *obj, Int cellX, Int cellY, const
Bool Pathfinder::adjustTargetDestination(const Object *obj, const Object *target, const Coord3D *targetPos,
const Weapon *weapon, Coord3D *dest)
{
+ PathProfile pfProfile( PF_ADJUST );
Int iRadius;
Bool center;
getRadiusAndCenter(obj, iRadius, center);
@@ -5620,6 +5823,7 @@ Bool Pathfinder::checkForPossible(Bool isCrusher, Int fromZone, Bool center, co
Bool Pathfinder::adjustToPossibleDestination(Object *obj, const LocomotorSet& locomotorSet,
Coord3D *dest)
{
+ PathProfile pfProfile( PF_ADJUST );
Int radius;
Bool center;
getRadiusAndCenter(obj, radius, center);
@@ -5890,6 +6094,7 @@ void Pathfinder::doDebugIcons(void) {
*/
Path *Pathfinder::getAircraftPath( const Object *obj, const Coord3D *to )
{
+ PathProfile pfProfile( PF_FIND );
// for now, quick path objects don't pathfind, generally airborne units
// build a trivial one-node path containing destination, then avoid buildings.
@@ -5966,6 +6171,7 @@ Path *Pathfinder::getAircraftPath( const Object *obj, const Coord3D *to )
//DECLARE_PERF_TIMER(processPathfindQueue)
void Pathfinder::processPathfindQueue(void)
{
+ PathProfile pfProfile( PF_QUEUE );
//USE_PERF_TIMER(processPathfindQueue)
if (!m_isMapReady) {
return;
@@ -6141,6 +6347,7 @@ struct ExamineCellsStruct
info.radius = d->radius;
info.considerTransient = false;
info.acceptableSurfaces = d->theLoco->getValidSurfaces();
+ pfBump( PF_MC_LINE );
if (!d->thePathfinder->checkForMovement(d->obj, info) || info.enemyFixed) {
return 1; //abort.
}
@@ -6208,6 +6415,7 @@ Int Pathfinder::examineNeighboringCells(PathfindCell *parentCell, PathfindCell *
Bool isHuman, Bool centerInCell, Int radius, const ICoord2D &startCellNdx,
const Object *obj, Int attackDistance)
{
+ pfBump( PF_EXPAND );
Bool canPathThroughUnits = false;
if (obj && obj->getAIUpdateInterface()) {
canPathThroughUnits = obj->getAIUpdateInterface()->canPathThroughUnits();
@@ -6216,7 +6424,26 @@ Int Pathfinder::examineNeighboringCells(PathfindCell *parentCell, PathfindCell *
unregisterPathUsage(obj->getAIUpdateInterface()->getPath());
}
Bool isCrusher = obj ? obj->getCrusherLevel() > 0 : false;
- if (attackDistance==NO_ATTACK && !m_isTunneling && !locomotorSet.isDownhillOnly() && goalCell) {
+ /* The straight-line-to-goal probe below walks every cell between this cell and the goal and
+ runs a full checkForMovement on each of them. EA fired it from *every* cell the search
+ expanded, so an open map cost O(cells expanded * distance to goal) movement checks - a
+ single 5000-cell search was measured at 1.4 million of them, and that was the whole of the
+ pathfinder's frame time. The probe only ever adds shortcut cells to the open list, so
+ skipping one costs nothing but a little more exploring; fire it only when this cell is
+ strictly closer to the goal than any cell we have probed from in this search, which is
+ exactly when the shortcut has a new chance of getting through. Deterministic: the state
+ is a plain function of the search's own cell order and is cleared with the lists. */
+ Bool probeToGoal = false;
+ if (goalCell) {
+ Int pdx = IABS(goalCell->getXIndex()-parentCell->getXIndex());
+ Int pdy = IABS(goalCell->getYIndex()-parentCell->getYIndex());
+ Int pdSqr = pdx*pdx + pdy*pdy;
+ if (pdSqr < m_probeBestDistSqr) {
+ m_probeBestDistSqr = pdSqr;
+ probeToGoal = true;
+ }
+ }
+ if (probeToGoal && attackDistance==NO_ATTACK && !m_isTunneling && !locomotorSet.isDownhillOnly() && goalCell) {
ExamineCellsStruct info;
info.thePathfinder = this;
info.theLoco = &locomotorSet;
@@ -6351,6 +6578,7 @@ Int Pathfinder::examineNeighboringCells(PathfindCell *parentCell, PathfindCell *
if (dy<0) dy = -dy;
if (dx>1+radius) info.considerTransient = false;
if (dy>1+radius) info.considerTransient = false;
+ pfBump( PF_MC_EXPAND );
if (!checkForMovement(obj, info) || info.enemyFixed) {
if (!m_isTunneling) {
continue;
@@ -6495,6 +6723,7 @@ Int Pathfinder::examineNeighboringCells(PathfindCell *parentCell, PathfindCell *
Path *Pathfinder::findPath( Object *obj, const LocomotorSet& locomotorSet, const Coord3D *from,
const Coord3D *rawTo)
{
+ PathProfile pfProfile( PF_FIND );
if (!clientSafeQuickDoesPathExist(locomotorSet, from, rawTo)) {
return NULL;
}
@@ -6505,29 +6734,24 @@ Path *Pathfinder::findPath( Object *obj, const LocomotorSet& locomotorSet, const
m_zoneManager.clearPassableFlags();
Path *hPat = findHierarchicalPath(isHuman, locomotorSet, from, rawTo, false);
- Bool hadCorridor = (hPat != NULL);
if (hPat) {
hPat->deleteInstance();
} else {
m_zoneManager.setAllPassable();
}
+ /* the corridor the hierarchical search laid out used to get a second, unrestricted retry
+ when the cell search failed inside it - on the grounds that the corridor can be too
+ tight for the unit's footprint. That retry searches the whole map, and the whole map
+ is what makes a logic frame take seconds: measured searches ran to 140513 cells / 285ms
+ against a 5000-cell-per-frame budget. A corridor that is too tight is a corridor to
+ widen, not a reason to drop the corridor, so the retry is gone. */
+ m_lastSearchRestricted = (hPat != NULL);
Path *pat = internalFindPath(obj, locomotorSet, from, rawTo);
if (pat!=NULL) {
return pat;
}
- // the block corridor the hierarchical search laid out can be too tight for this unit's
- // footprint (or simply wrong); a failed corridor search is cheap, so fall back to the
- // unrestricted search rather than report no path
- if (hadCorridor) {
- m_zoneManager.setAllPassable();
- pat = internalFindPath(obj, locomotorSet, from, rawTo);
- if (pat!=NULL) {
- return pat;
- }
- }
-
/* hierarchical build path code.
if (pat) {
@@ -6728,18 +6952,38 @@ Path *Pathfinder::internalFindPath( Object *obj, const LocomotorSet& locomotorSe
// initialize "open" list to contain start cell
m_openList = parentCell;
+ PathfindCell::setOpenListSeed( parentCell );
// "closed" list is initially empty
m_closedList = NULL;
Int cellCount = 0;
+ /* 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
+ one, the main one, had none: it ran until the open list emptied, which on a failed search
+ means every reachable cell on the map. The per-frame budget does not catch it either,
+ because PATHFIND_CELLS_PER_FRAME is only tested between queued requests and
+ m_cumulativeCellsAllocated is only credited once a search has already finished. So one
+ 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. */
+ enum { MAX_INTERNAL_CELL_COUNT = 20000 };
+ PathfindCell *closestCell = NULL;
+ Real closestDistanceSqr = FLT_MAX;
+ Bool hitCellCap = false;
+
//
// Continue search until "open" list is empty, or
// until goal is found.
//
while( m_openList != NULL )
{
+ if (cellCount > MAX_INTERNAL_CELL_COUNT) {
+ hitCellCap = true;
+ break;
+ }
+
// take head cell off of open list - it has lowest estimated total path cost
parentCell = m_openList;
m_openList = parentCell->removeFromOpenList(m_openList);
@@ -6780,8 +7024,9 @@ Path *Pathfinder::internalFindPath( Object *obj, const LocomotorSet& locomotorSe
if (path)
for (const PathNode *n = path->getFirstNode(); n; n = n->getNext())
nodes++;
- DEBUG_LOG(("Pathfind frame %d '%s': %d cells, search %.1f ms, build+optimize %.1f ms, %d nodes, (%.0f,%.0f)->(%.0f,%.0f)\n",
+ DEBUG_LOG(("Pathfind frame %d '%s' [%s]: %d cells, search %.1f ms, build+optimize %.1f ms, %d nodes, (%.0f,%.0f)->(%.0f,%.0f)\n",
TheGameLogic->getFrame(), obj ? obj->getTemplate()->getName().str() : "?",
+ m_lastSearchRestricted ? "corridor" : "openmap",
cellCount, searchMs, buildMs, nodes, from->x, from->y, rawTo->x, rawTo->y));
}
}
@@ -6793,6 +7038,19 @@ Path *Pathfinder::internalFindPath( Object *obj, const LocomotorSet& locomotorSe
// put parent cell onto closed list - its evaluation is finished
m_closedList = parentCell->putOnClosedList( m_closedList );
+ /* remember the cell that got nearest the goal, so a search stopped by the cap can still
+ hand back the part of the route it did work out. Reporting no path at all would leave
+ the unit standing there refusing the order. */
+ {
+ 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;
+ }
+ }
+
// Check to see if we can change layers in this cell.
checkChangeLayers(parentCell);
@@ -6800,6 +7058,30 @@ Path *Pathfinder::internalFindPath( Object *obj, const LocomotorSet& locomotorSe
}
+ /* 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 (partial) {
+ if (fpFreq64 > 0) {
+ __int64 fpTCap = 0;
+ QueryPerformanceCounter((LARGE_INTEGER *)&fpTCap);
+ DEBUG_LOG(("Pathfind CAPPED frame %d unit '%s' [%s]: %d cells, %.1f ms, partial to %d cells short of goal, (%.0f,%.0f)->(%.0f,%.0f)\n",
+ 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));
+ }
+ m_isTunneling = false;
+ cleanOpenAndClosedLists();
+ parentCell->releaseInfo();
+ goalCell->releaseInfo();
+ return partial;
+ }
+ }
+
// failure - goal cannot be reached
#if defined _DEBUG || defined _INTERNAL
#ifdef INTENSE_DEBUG
@@ -6858,9 +7140,15 @@ Path *Pathfinder::internalFindPath( Object *obj, const LocomotorSet& locomotorSe
// release-visible trace (DebugLogFile.txt): a failed search is otherwise invisible outside
// debug builds, and "no path" reports need the cell count to tell a dry pool from a real
// dead end
- DEBUG_LOG(("Pathfind FAILED frame %d unit '%s' from (%.0f,%.0f) to (%.0f,%.0f), %d cells\n",
- TheGameLogic->getFrame(), obj ? obj->getTemplate()->getName().str() : "?",
- from->x, from->y, to->x, to->y, cellCount));
+ {
+ __int64 fpTFail = 0;
+ QueryPerformanceCounter((LARGE_INTEGER *)&fpTFail);
+ const Real failMs = (fpFreq64 > 0) ? 1000.0f * (Real)(fpTFail - fpT0) / (Real)fpFreq64 : 0.0f;
+ DEBUG_LOG(("Pathfind FAILED frame %d unit '%s' [%s] from (%.0f,%.0f) to (%.0f,%.0f), %d cells, %.1f ms\n",
+ TheGameLogic->getFrame(), obj ? obj->getTemplate()->getName().str() : "?",
+ m_lastSearchRestricted ? "corridor" : "openmap",
+ from->x, from->y, to->x, to->y, cellCount, failMs));
+ }
m_isTunneling = false;
cleanOpenAndClosedLists();
parentCell->releaseInfo();
@@ -6993,23 +7281,19 @@ Path *Pathfinder::buildHierachicalPath( const Coord3D *fromPos, PathfindCell *go
prependCells(path, fromPos, goalCell, true);
- // Expand the hierarchical path around the starting point. jba [8/24/2003]
- // This allows the unit to get around friendly units that may be near it.
- Coord3D pos = *path->getFirstNode()->getPosition();
- Coord3D minPos = pos;
- minPos.x -= PathfindZoneManager::ZONE_BLOCK_SIZE*PATHFIND_CELL_SIZE_F;
- minPos.y -= PathfindZoneManager::ZONE_BLOCK_SIZE*PATHFIND_CELL_SIZE_F;
- Coord3D maxPos = pos;
- maxPos.x += PathfindZoneManager::ZONE_BLOCK_SIZE*PATHFIND_CELL_SIZE_F;
- maxPos.y += PathfindZoneManager::ZONE_BLOCK_SIZE*PATHFIND_CELL_SIZE_F;
- ICoord2D cellNdxMin, cellNdxMax;
- worldToCell(&minPos, &cellNdxMin);
- worldToCell(&maxPos, &cellNdxMax);
- Int i, j;
- for (i=cellNdxMin.x; i<=cellNdxMax.x; i++) {
- for (j=cellNdxMin.y; j<=cellNdxMax.y; j++) {
- m_zoneManager.setPassable(i, j, true);
- }
+ /* Widen the corridor by one zone block on every side, along its whole length.
+ EA did this around the starting point only - jba [8/24/2003], "This allows the unit to get
+ around friendly units that may be near it" - and the rest of the corridor stayed one block
+ wide. A block is ZONE_BLOCK_SIZE cells, so a wide unit whose footprint does not fit that
+ ribbon failed the cell search, and findPath used to answer that by searching the whole map
+ instead (measured at 140513 cells / 285 ms against a 5000-cell-per-frame budget). Widening
+ is the same rescue at the right level: the search stays bounded by the length of the path
+ rather than by the area of the map. */
+ for( PathNode *node = path->getFirstNode(); node; node = node->getNext() )
+ {
+ ICoord2D cellNdx;
+ worldToCell(node->getPosition(), &cellNdx);
+ m_zoneManager.setPassableWithNeighbors(cellNdx.x, cellNdx.y);
}
#if defined _DEBUG || defined _INTERNAL
@@ -7267,6 +7551,7 @@ Path *Pathfinder::findGroundPath( const Coord3D *from,
// initialize "open" list to contain start cell
m_openList = parentCell;
+ PathfindCell::setOpenListSeed( parentCell );
// "closed" list is initially empty
m_closedList = NULL;
@@ -7610,6 +7895,7 @@ void Pathfinder::processHierarchicalCell( const ICoord2D &scanCell, const ICoord
Path *Pathfinder::findHierarchicalPath( Bool isHuman, const LocomotorSet& locomotorSet, const Coord3D *from,
const Coord3D *to, Bool crusher)
{
+ PathProfile pfProfile( PF_HIER );
return internal_findHierarchicalPath(isHuman, locomotorSet.getValidSurfaces(), from, to, crusher, FALSE);
}
@@ -7621,6 +7907,7 @@ Path *Pathfinder::findHierarchicalPath( Bool isHuman, const LocomotorSet& locomo
Path *Pathfinder::findClosestHierarchicalPath( Bool isHuman, const LocomotorSet& locomotorSet, const Coord3D *from,
const Coord3D *to, Bool crusher)
{
+ PathProfile pfProfile( PF_HIER );
return internal_findHierarchicalPath(isHuman, locomotorSet.getValidSurfaces(), from, to, crusher, TRUE);
}
@@ -7718,8 +8005,10 @@ Path *Pathfinder::internal_findHierarchicalPath( Bool isHuman, const LocomotorSu
if (parentCell->getLayer()==LAYER_GROUND) {
// initialize "open" list to contain start cell
m_openList = parentCell;
+ PathfindCell::setOpenListSeed( parentCell );
} else {
m_openList = parentCell;
+ PathfindCell::setOpenListSeed( parentCell );
PathfindLayerEnum layer = parentCell->getLayer();
// We're starting on a bridge, so link to land at the bridge end points.
ICoord2D ndx;
@@ -8219,6 +8508,7 @@ Bool Pathfinder::clientSafeQuickDoesPathExist( const LocomotorSet& locomotorSet,
const Coord3D *from,
const Coord3D *to )
{
+ PathProfile pfProfile( PF_EXIST );
// See if terrain or building is blocking the destination.
PathfindLayerEnum destinationLayer = TheTerrainLogic->getLayerForDestination(to);
if (!validMovementPosition(false, destinationLayer, locomotorSet, to)) {
@@ -8277,6 +8567,7 @@ Bool Pathfinder::clientSafeQuickDoesPathExistForUI( const LocomotorSet& locomoto
const Coord3D *from,
const Coord3D *to )
{
+ PathProfile pfProfile( PF_EXIST );
// See if terrain or building is blocking the destination.
PathfindLayerEnum destinationLayer = TheTerrainLogic->getLayerForDestination(to);
PathfindLayerEnum fromLayer = TheTerrainLogic->getLayerForDestination(from);
@@ -8335,6 +8626,7 @@ Bool Pathfinder::slowDoesPathExist( Object *obj,
const Coord3D *to,
ObjectID ignoreObject)
{
+ PathProfile pfProfile( PF_EXIST );
AIUpdateInterface *ai = obj->getAI();
if (ai==NULL) {
return false;
@@ -8444,6 +8736,7 @@ Bool Pathfinder::pathDestination( Object *obj, const LocomotorSet& locomotorSet
// initialize "open" list to contain start cell
m_openList = parentCell;
+ PathfindCell::setOpenListSeed( parentCell );
// "closed" list is initially empty
m_closedList = NULL;
@@ -8716,6 +9009,7 @@ Int Pathfinder::checkPathCost(Object *obj, const LocomotorSet& locomotorSet, con
// initialize "open" list to contain start cell
m_openList = parentCell;
+ PathfindCell::setOpenListSeed( parentCell );
// "closed" list is initially empty
m_closedList = NULL;
@@ -8868,6 +9162,7 @@ Int Pathfinder::checkPathCost(Object *obj, const LocomotorSet& locomotorSet, con
Path *Pathfinder::findClosestPath( Object *obj, const LocomotorSet& locomotorSet, const Coord3D *from,
Coord3D *rawTo, Bool blocked, Real pathCostMultiplier, Bool moveAllies)
{
+ PathProfile pfProfile( PF_CLOSEST );
//CRCDEBUG_LOG(("Pathfinder::findClosestPath()\n"));
#if defined _DEBUG || defined _INTERNAL
Int startTimeMS = ::GetTickCount();
@@ -9007,6 +9302,7 @@ Path *Pathfinder::findClosestPath( Object *obj, const LocomotorSet& locomotorSet
// initialize "open" list to contain start cell
m_openList = parentCell;
+ PathfindCell::setOpenListSeed( parentCell );
// "closed" list is initially empty
m_closedList = NULL;
@@ -9803,6 +10099,7 @@ struct LinePassableStruct
info.radius = d->radius;
info.considerTransient = d->blocked;
info.acceptableSurfaces = d->acceptableSurfaces;
+ pfBump( PF_MC_LINEPASS );
if (!pathfinder->checkForMovement(d->obj, info))
{
return 1; // bail out
@@ -9940,6 +10237,7 @@ void Pathfinder::getRadiusAndCenter(const Object *obj, Int &iRadius, Bool &cente
*/
void Pathfinder::updateGoal( Object *obj, const Coord3D *newGoalPos, PathfindLayerEnum layer)
{
+ PathProfile pfProfile( PF_GOAL );
if (obj->isKindOf(KINDOF_IMMOBILE)) {
// Only consider mobile.
return;
@@ -10042,6 +10340,7 @@ void Pathfinder::updateGoal( Object *obj, const Coord3D *newGoalPos, PathfindLay
*/
void Pathfinder::updateAircraftGoal( Object *obj, const Coord3D *newGoalPos)
{
+ PathProfile pfProfile( PF_GOAL );
if (obj->isKindOf(KINDOF_IMMOBILE)) {
// Only consider mobile.
return;
@@ -10100,6 +10399,7 @@ void Pathfinder::updateAircraftGoal( Object *obj, const Coord3D *newGoalPos)
*/
void Pathfinder::removeGoal( Object *obj)
{
+ PathProfile pfProfile( PF_GOAL );
if (obj->isKindOf(KINDOF_IMMOBILE)) {
// Only consider mobile.
return;
@@ -10160,6 +10460,7 @@ void Pathfinder::removeGoal( Object *obj)
*/
void Pathfinder::updatePos( Object *obj, const Coord3D *newPos)
{
+ PathProfile pfProfile( PF_POS );
if (obj->isKindOf(KINDOF_IMMOBILE))
{
// Only consider mobile.
@@ -10269,6 +10570,7 @@ void Pathfinder::updatePos( Object *obj, const Coord3D *newPos)
*/
void Pathfinder::removePos( Object *obj)
{
+ PathProfile pfProfile( PF_POS );
if (obj->isKindOf(KINDOF_IMMOBILE)) {
// Only consider mobile.
return;
@@ -10327,6 +10629,7 @@ void Pathfinder::removeUnitFromPathfindMap( Object *obj )
Bool Pathfinder::moveAllies(Object *obj, Path *path)
{
+ PathProfile pfProfile( PF_MOVEAWAY );
#ifdef DO_UNIT_TIMINGS
#pragma MESSAGE("*** WARNING *** DOING DO_UNIT_TIMINGS!!!!")
@@ -10411,6 +10714,7 @@ if (g_UT_startTiming) return false;
Path *Pathfinder::getMoveAwayFromPath(Object* obj, Object *otherObj,
Path *pathToAvoid, Object *otherObj2, Path *pathToAvoid2)
{
+ PathProfile pfProfile( PF_MOVEAWAY );
if (m_isMapReady == false) return false; // Should always be ok.
#if defined _DEBUG || defined _INTERNAL
Int startTimeMS = ::GetTickCount();
@@ -10472,6 +10776,7 @@ Path *Pathfinder::getMoveAwayFromPath(Object* obj, Object *otherObj,
// initialize "open" list to contain start cell
m_openList = parentCell;
+ PathfindCell::setOpenListSeed( parentCell );
// "closed" list is initially empty
m_closedList = NULL;
@@ -10585,6 +10890,7 @@ Path *Pathfinder::getMoveAwayFromPath(Object* obj, Object *otherObj,
Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSet,
Path *originalPath, Bool blocked )
{
+ PathProfile pfProfile( PF_PATCH );
//CRCDEBUG_LOG(("Pathfinder::patchPath()\n"));
#if defined _DEBUG || defined _INTERNAL
Int startTimeMS = ::GetTickCount();
@@ -10632,6 +10938,7 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSet
// initialize "open" list to contain start cell
m_openList = parentCell;
+ PathfindCell::setOpenListSeed( parentCell );
// "closed" list is initially empty
m_closedList = NULL;
@@ -10770,6 +11077,7 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSet
Path *Pathfinder::findAttackPath( const Object *obj, const LocomotorSet& locomotorSet, const Coord3D *from,
const Object *victim, const Coord3D* victimPos, const Weapon *weapon )
{
+ PathProfile pfProfile( PF_ATTACK );
/*
CRCDEBUG_LOG(("Pathfinder::findAttackPath() for object %d (%s)\n", obj->getID(), obj->getTemplate()->getName().str()));
XferCRC xferCRC;
@@ -10913,6 +11221,7 @@ Path *Pathfinder::findAttackPath( const Object *obj, const LocomotorSet& locomot
// initialize "open" list to contain start cell
m_openList = parentCell;
+ PathfindCell::setOpenListSeed( parentCell );
// "closed" list is initially empty
m_closedList = NULL;
@@ -11126,6 +11435,7 @@ Path *Pathfinder::findAttackPath( const Object *obj, const LocomotorSet& locomot
Path *Pathfinder::findSafePath( const Object *obj, const LocomotorSet& locomotorSet,
const Coord3D *from, const Coord3D* repulsorPos1, const Coord3D* repulsorPos2, Real repulsorRadius)
{
+ PathProfile pfProfile( PF_SAFE );
//CRCDEBUG_LOG(("Pathfinder::findSafePath()\n"));
if (m_isMapReady == false) return false; // Should always be ok.
#if defined _DEBUG || defined _INTERNAL
@@ -11164,6 +11474,7 @@ Path *Pathfinder::findSafePath( const Object *obj, const LocomotorSet& locomotor
// initialize "open" list to contain start cell
m_openList = parentCell;
+ PathfindCell::setOpenListSeed( parentCell );
// "closed" list is initially empty
m_closedList = NULL;
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
index c780d32ad..3c2ab8258 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
@@ -103,6 +103,28 @@ m_curWarehouseID(INVALID_ID)
m_baseCenterSet = false;
m_difficulty = TheScriptEngine->getGlobalDifficulty();
m_teamSeconds = TheAI->getAiData()->m_teamSeconds;
+
+ //
+ // Stagger this player's repeating checks. doBaseBuilding re-arms itself for 2 seconds,
+ // doTeamBuilding for 5 and updateBridgeRepair for 1, all from constants, and every AIPlayer is
+ // built with the same timers on the same frame, so a lobby full of them checks in unison from
+ // the first frame to the last and the whole cost of it lands on one logic frame. The offset
+ // moves each player to its own slot in the cycle; nothing runs less often.
+ //
+ // The two "ready" timers get the offset as well: they are what anchors the cadence that follows
+ // (both hand their delay a zero on the frame they expire, and both expire on frame 2 for
+ // everyone), so leaving them alone would re-align the players two frames in. The price is that
+ // the last player's first base-building check comes up to 2 seconds late and its first team
+ // check up to 5 - once, at the start of the match.
+ //
+ const Int playerIndex = p->getPlayerIndex();
+ m_buildDelay = computeUpdatePhase( playerIndex, 2*LOGICFRAMES_PER_SECOND );
+ m_teamDelay = computeUpdatePhase( playerIndex, 5*LOGICFRAMES_PER_SECOND );
+ m_structureTimer += m_buildDelay;
+ m_teamTimer += m_teamDelay;
+ // ...and EA never initialized this one at all. updateBridgeRepair returns before reading it
+ // while the repair queue is empty, which it is here, so it has been benign - but only just.
+ m_bridgeTimer = computeUpdatePhase( playerIndex, LOGICFRAMES_PER_SECOND );
}
// ------------------------------------------------------------------------------------------------
@@ -2739,6 +2761,19 @@ Int AIPlayer::computeStructureDelay( void )
getBuildRateScale() );
}
+//----------------------------------------------------------------------------------------------------------
+/**
+ * Where in a repeating check's cycle this player sits. A player's slot is its index alone, so the
+ * answer is the same on every machine and survives a save/load.
+ */
+Int AIPlayer::computeUpdatePhase( Int playerIndex, Int cycleFrames )
+{
+ if (playerIndex < 0 || cycleFrames < 1) {
+ return 0;
+ }
+ return ((playerIndex % MAX_PLAYER_COUNT) * cycleFrames) / MAX_PLAYER_COUNT;
+}
+
//----------------------------------------------------------------------------------------------------------
/**
* The delay arithmetic, with nothing of the Player in it so a test can drive it: the written
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp
index 943fa9071..16bb56dd2 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp
@@ -5500,6 +5500,97 @@ void ScriptEngine::newMap( void )
/** Update */
//-------------------------------------------------------------------------------------------------
DECLARE_PERF_TIMER(ScriptEngine)
+#ifdef DEBUG_LOGGING
+//
+// The frame's worst script. Filled in by executeScript, read by GameLogic when a frame runs over
+// budget, cleared at the top of every update.
+//
+static Real theWorstScriptMS = 0.0f;
+static AsciiString theWorstScriptName;
+static Real theScriptTotalMS = 0.0f;
+static Int theScriptRunCount = 0;
+
+//
+// update() is billed as "scripts" by GameLogic's slow-frame line, but only a part of it is scripts:
+// it also runs the script actions' and conditions' own per-frame work, walks every team of every
+// player, and steps the sequential scripts. A map with no scripts at all can still spend twenty
+// milliseconds in here, so the phases are timed separately or there is nothing to go on.
+//
+enum { SCRIPT_PHASE_ACTIONS = 0, SCRIPT_PHASE_CONDITIONS, SCRIPT_PHASE_EVAL, SCRIPT_PHASE_TEAMS,
+ SCRIPT_PHASE_SEQUENTIAL, SCRIPT_PHASE_COUNT };
+static const char *theScriptPhaseName[ SCRIPT_PHASE_COUNT ] = { "act", "cond", "eval", "teams", "seq" };
+static Real theScriptPhaseMS[ SCRIPT_PHASE_COUNT ];
+static Int64 theScriptPhaseStart = 0;
+
+//
+// The sequential-script step turned out to be the whole of the "scripts" cost on a script-free
+// skirmish map, so it gets counted from the inside: how many entries the list holds, how many times
+// the loop went round, how many AIGroups it built to ask a team whether it is idle, and how long
+// the actions themselves took.
+//
+static Int theSeqCount = 0, theSeqIters = 0, theSeqGroups = 0, theSeqMembers = 0, theSeqActions = 0;
+static Real theSeqGroupMS = 0.0f, theSeqActionMS = 0.0f;
+static Int theSeqWorstAction = -1;
+static Real theSeqWorstActionMS = 0.0f;
+static Int64 theSeqSubStart = 0;
+
+static void seqSubBegin( void )
+{
+ QueryPerformanceCounter( (LARGE_INTEGER *)&theSeqSubStart );
+}
+
+static Real seqSubEnd( void )
+{
+ Int64 now, freq;
+ QueryPerformanceCounter( (LARGE_INTEGER *)&now );
+ QueryPerformanceFrequency( (LARGE_INTEGER *)&freq );
+ if( freq < 1 )
+ return 0.0f;
+ return (Real)((double)(now - theSeqSubStart) * 1000.0 / (double)freq);
+}
+#define SEQ_SUB_BEGIN() seqSubBegin()
+#define SEQ_SUB_END(acc) do { (acc) += seqSubEnd(); } while(0)
+#define SEQ_BUMP(c) do { ++(c); } while(0)
+#define SEQ_ADD(c,n) do { (c) += (n); } while(0)
+
+static void scriptPhaseBegin( void )
+{
+ QueryPerformanceCounter( (LARGE_INTEGER *)&theScriptPhaseStart );
+}
+
+static void scriptPhaseEnd( Int phase )
+{
+ Int64 now, freq;
+ QueryPerformanceCounter( (LARGE_INTEGER *)&now );
+ QueryPerformanceFrequency( (LARGE_INTEGER *)&freq );
+ if( freq > 0 )
+ theScriptPhaseMS[ phase ] += (Real)((double)(now - theScriptPhaseStart) * 1000.0 / (double)freq);
+}
+#define SCRIPT_PHASE_BEGIN() scriptPhaseBegin()
+#define SCRIPT_PHASE_END(p) scriptPhaseEnd(p)
+
+const char *ScriptEngine::getProfileReport( void )
+{
+ static char report[ 512 ];
+ Int used = sprintf( report, "%d scripts/%.1fms worst '%s' %.1fms |", theScriptRunCount, theScriptTotalMS,
+ theWorstScriptName.isEmpty() ? "<none>" : theWorstScriptName.str(), theWorstScriptMS );
+ for( Int phase = 0; phase < SCRIPT_PHASE_COUNT; phase++ )
+ used += sprintf( report + used, " %s %.1f", theScriptPhaseName[phase], theScriptPhaseMS[phase] );
+ sprintf( report + used, " | seqlist %d iters %d grp %dx/%.1f (%d members) act %dx/%.1f worstact %d/%.1f",
+ theSeqCount, theSeqIters, theSeqGroups, theSeqGroupMS, theSeqMembers, theSeqActions, theSeqActionMS,
+ theSeqWorstAction, theSeqWorstActionMS );
+ return report;
+}
+#else
+const char *ScriptEngine::getProfileReport( void ) { return ""; }
+#define SCRIPT_PHASE_BEGIN()
+#define SCRIPT_PHASE_END(p)
+#define SEQ_SUB_BEGIN()
+#define SEQ_SUB_END(acc)
+#define SEQ_BUMP(c)
+#define SEQ_ADD(c,n)
+#endif
+
void ScriptEngine::update( void )
{
USE_PERF_TIMER(ScriptEngine)
@@ -5520,6 +5611,17 @@ void ScriptEngine::update( void )
DEBUG_LOG(("\n\n"));
*/
#endif
+#endif
+#ifdef DEBUG_LOGGING
+ theWorstScriptMS = 0.0f;
+ theWorstScriptName.clear();
+ theScriptTotalMS = 0.0f;
+ theScriptRunCount = 0;
+ for( Int phase = 0; phase < SCRIPT_PHASE_COUNT; phase++ )
+ theScriptPhaseMS[ phase ] = 0.0f;
+ theSeqCount = theSeqIters = theSeqGroups = theSeqMembers = theSeqActions = 0;
+ theSeqGroupMS = theSeqActionMS = theSeqWorstActionMS = 0.0f;
+ theSeqWorstAction = -1;
#endif
if (m_firstUpdate) {
createNamedCache();
@@ -5557,12 +5659,16 @@ void ScriptEngine::update( void )
return; // we are just timing down
}
+ SCRIPT_PHASE_BEGIN();
if (TheScriptActions) {
TheScriptActions->update();
}
+ SCRIPT_PHASE_END( SCRIPT_PHASE_ACTIONS );
+ SCRIPT_PHASE_BEGIN();
if (TheScriptConditions) {
TheScriptConditions->update();
}
+ SCRIPT_PHASE_END( SCRIPT_PHASE_CONDITIONS );
// Update any countdown timers.
Int i;
// Note - counters start at 1. 0 means not assigned.
@@ -5576,6 +5682,7 @@ void ScriptEngine::update( void )
}
// Evaluate the scripts.
+ SCRIPT_PHASE_BEGIN();
for (i=0; i<TheSidesList->getNumSides(); i++) {
m_currentPlayer = ThePlayerList->getNthPlayer(i);
ScriptList *pSL = TheSidesList->getSideInfo(i)->getScriptList();
@@ -5593,16 +5700,21 @@ void ScriptEngine::update( void )
}
m_currentPlayer = NULL;
}
+ SCRIPT_PHASE_END( SCRIPT_PHASE_EVAL );
// Reset the entered/exited flag in teams, so the next update sets them
// correctly. Also, execute any team created scripts.
+ SCRIPT_PHASE_BEGIN();
ThePlayerList->updateTeamStates();
+ SCRIPT_PHASE_END( SCRIPT_PHASE_TEAMS );
// Clear the UI Interaction flags.
m_uiInteractions.clear();
// update all sequential stuff.
+ SCRIPT_PHASE_BEGIN();
evaluateAndProgressAllSequentialScripts();
+ SCRIPT_PHASE_END( SCRIPT_PHASE_SEQUENTIAL );
// Script debugger stuff
st_CurrentFrame++;
@@ -7047,6 +7159,16 @@ void ScriptEngine::executeScript( Script *pScript )
QueryPerformanceCounter((LARGE_INTEGER *)&endTime64);
timeToEvaluate = ((Real)(endTime64-startTime64) / (Real)(freq64));
pScript->setCurTime(timeToEvaluate);
+ {
+ const Real scriptMS = timeToEvaluate * 1000.0f;
+ theScriptRunCount++;
+ theScriptTotalMS += scriptMS;
+ if( scriptMS > theWorstScriptMS )
+ {
+ theWorstScriptMS = scriptMS;
+ theWorstScriptName = pScript->getName();
+ }
+ }
#endif
#endif
@@ -7881,13 +8003,39 @@ void ScriptEngine::setSequentialTimer(Team *team, Int frameCount)
}
+Bool ScriptEngine::isThrottledTeamMoveAction( Int actionType )
+{
+ switch( actionType )
+ {
+ case ScriptAction::MOVE_TEAM_TO:
+ case ScriptAction::TEAM_FOLLOW_WAYPOINTS:
+ case ScriptAction::TEAM_FOLLOW_WAYPOINTS_EXACT:
+ case ScriptAction::SKIRMISH_FOLLOW_APPROACH_PATH:
+ case ScriptAction::SKIRMISH_MOVE_TO_APPROACH_PATH:
+ case ScriptAction::CREATE_REINFORCEMENT_TEAM:
+ case ScriptAction::SKIRMISH_ATTACK_NEAREST_GROUP_WITH_VALUE:
+ return TRUE;
+ }
+ return FALSE;
+}
+
+//
+// How many of those team moves may be issued in one logic frame. One is enough to keep the AI
+// moving at the same rate it always did - a team reaches its move instruction once, not every
+// frame - while a lobby full of AI players can no longer stack seven searches onto one frame.
+//
+static const Int MAX_TEAM_MOVES_PER_FRAME = 1;
+
void ScriptEngine::evaluateAndProgressAllSequentialScripts( void )
{
VecSequentialScriptPtrIt it, lastIt;
lastIt = m_sequentialScripts.end();
+ SEQ_ADD(theSeqCount, (Int)m_sequentialScripts.size());
+ Int teamMovesThisFrame = 0;
Int spinCount = 0;
for (it = m_sequentialScripts.begin(); it != m_sequentialScripts.end(); /* empty */) {
+ SEQ_BUMP(theSeqIters);
if (it == lastIt) {
++spinCount;
} else {
@@ -7932,10 +8080,14 @@ void ScriptEngine::evaluateAndProgressAllSequentialScripts( void )
}
AIUpdateInterface *ai = obj ? obj->getAIUpdateInterface() : NULL;
+ SEQ_SUB_BEGIN();
AIGroup *aigroup = (team ? TheAI->createGroup() : NULL);
if (aigroup) {
team->getTeamAsAIGroup(aigroup);
+ SEQ_BUMP(theSeqGroups);
+ SEQ_ADD(theSeqMembers, (Int)aigroup->getCount());
}
+ SEQ_SUB_END(theSeqGroupMS);
if( ai || aigroup ) {
if (((ai && (ai->isIdle()) || (aigroup && aigroup->isIdle())) &&
@@ -7993,8 +8145,32 @@ void ScriptEngine::evaluateAndProgressAllSequentialScripts( void )
if (TheScriptConditions->evaluateTeamIsContained(action->getParameter(0), false)) {
seqScript->m_dontAdvanceInstruction = TRUE;
}
+ } else if (m_currentPlayer && teamMovesThisFrame >= MAX_TEAM_MOVES_PER_FRAME &&
+ isThrottledTeamMoveAction( action->getActionType() )) {
+ //
+ // A skirmish AI team wants a full-map group path and one has already been paid for
+ // this frame. Hold the instruction and come back to it next frame - the script is
+ // not skipped, only delayed, and the team is idle either way.
+ //
+ seqScript->m_dontAdvanceInstruction = TRUE;
} else {
+ if (m_currentPlayer && isThrottledTeamMoveAction( action->getActionType() )) {
+ ++teamMovesThisFrame;
+ }
+#ifdef DEBUG_LOGGING
+ const Real seqActionBefore = theSeqActionMS;
+#endif
+ SEQ_SUB_BEGIN();
executeActions(action);
+ SEQ_SUB_END(theSeqActionMS);
+ SEQ_BUMP(theSeqActions);
+#ifdef DEBUG_LOGGING
+ if( theSeqActionMS - seqActionBefore > theSeqWorstActionMS )
+ {
+ theSeqWorstActionMS = theSeqActionMS - seqActionBefore;
+ theSeqWorstAction = (Int)action->getActionType();
+ }
+#endif
}
if (displayMessage) {
@@ -8018,8 +8194,12 @@ void ScriptEngine::evaluateAndProgressAllSequentialScripts( void )
itAdvanced = true;
} else if (team) {
// attempt to rebuild the aigroup, as it probably expired during the action execution
+ SEQ_SUB_BEGIN();
aigroup = (team ? TheAI->createGroup() : NULL);
team->getTeamAsAIGroup(aigroup);
+ SEQ_BUMP(theSeqGroups);
+ SEQ_ADD(theSeqMembers, aigroup ? (Int)aigroup->getCount() : 0);
+ SEQ_SUB_END(theSeqGroupMS);
}
if (aigroup && aigroup->isIdle()) {
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
index 9404b4030..125a8d963 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
@@ -3601,6 +3601,47 @@ static Real logicElapsedMS( const Int64 &from, const Int64 &to )
return (Real)( (double)(to - from) * 1000.0 / (double)freq );
}
+#ifdef DEBUG_LOGGING
+//
+// Which update module ate the frame. The `objects` figure in the slow-frame line is the whole
+// sleepy-update sweep, thousands of modules deep, and that alone never says which one. Two
+// QueryPerformanceCounter reads per module cost about 0.2ms over a busy frame - they sit inside
+// the `objects` window, so the sweep's own total carries that and the per-module figures do not.
+//
+static Int64 theWorstModuleTicks = 0;
+static NameKeyType theWorstModuleKey = NAMEKEY_INVALID;
+static const ThingTemplate *theWorstModuleThing = NULL;
+static Int theModuleUpdateCount = 0;
+
+static void resetModuleProfile( void )
+{
+ theWorstModuleTicks = 0;
+ theWorstModuleKey = NAMEKEY_INVALID;
+ theWorstModuleThing = NULL;
+ theModuleUpdateCount = 0;
+}
+
+static const char *getModuleProfileReport( void )
+{
+ static char report[ 256 ];
+ if( theWorstModuleKey == NAMEKEY_INVALID )
+ {
+ sprintf( report, "%d updates", theModuleUpdateCount );
+ }
+ else
+ {
+ Int64 freq = 0;
+ QueryPerformanceFrequency( (LARGE_INTEGER *)&freq );
+ const Real worstMS = freq ? (Real)( (double)theWorstModuleTicks * 1000.0 / (double)freq ) : 0.0f;
+ sprintf( report, "%d updates, worst %s on %s %.1fms", theModuleUpdateCount,
+ TheNameKeyGenerator->keyToName( theWorstModuleKey ).str(),
+ theWorstModuleThing ? theWorstModuleThing->getName().str() : "<none>",
+ worstMS );
+ }
+ return report;
+}
+#endif
+
void GameLogic::update( void )
{
USE_PERF_TIMER(GameLogic_update)
@@ -3658,6 +3699,10 @@ void GameLogic::update( void )
costs nothing next to the 33ms the frame is allowed. */
Int64 tFrameStart = 0, tScripts = 0, tObjects = 0, tAI = 0, tPartition = 0, tFrameEnd = 0;
QueryPerformanceCounter( (LARGE_INTEGER *)&tFrameStart );
+ Pathfinder::resetProfile();
+#ifdef DEBUG_LOGGING
+ resetModuleProfile();
+#endif
// update (execute) scripts
{
@@ -3788,7 +3833,44 @@ void GameLogic::update( void )
//DEBUG_LOG(("calling update %08lx (%d %d)... ",update,update->friend_getNextCallFrame(),update->friend_getNextCallPhase()));
m_curUpdateModule = u;
+#ifdef DEBUG_LOGGING
+ // read the identity before the update - a module may kill its own object
+ const NameKeyType profModuleKey = u->getModuleNameKey();
+ const ThingTemplate *profModuleThing = u->friend_getObject() ? u->friend_getObject()->getTemplate() : NULL;
+ const ObjectID profModuleObjID = u->friend_getObject() ? u->friend_getObject()->getID() : INVALID_ID;
+ Int64 profModuleStart;
+ QueryPerformanceCounter( (LARGE_INTEGER *)&profModuleStart );
+#endif
+
sleepLen = u->update();
+
+#ifdef DEBUG_LOGGING
+ {
+ Int64 profModuleEnd;
+ QueryPerformanceCounter( (LARGE_INTEGER *)&profModuleEnd );
+ theModuleUpdateCount++;
+ const Int64 profModuleTicks = profModuleEnd - profModuleStart;
+ if( profModuleTicks > theWorstModuleTicks )
+ {
+ theWorstModuleTicks = profModuleTicks;
+ theWorstModuleKey = profModuleKey;
+ theWorstModuleThing = profModuleThing;
+ }
+ //
+ // A single module that eats a third of the frame on its own is a bug, not load, and the
+ // end-of-frame summary only ever names one of them. Say so the moment it happens, with
+ // the object id, so the surrounding log lines are that object's own.
+ //
+ const Real profModuleMS = logicElapsedMS( profModuleStart, profModuleEnd );
+ if( profModuleMS > 10.0f )
+ {
+ DEBUG_LOG(("SLOW MODULE frame %d: %s on %s (obj %d) %.1fms\n", now,
+ TheNameKeyGenerator->keyToName( profModuleKey ).str(),
+ profModuleThing ? profModuleThing->getName().str() : "<none>",
+ (Int)profModuleObjID, profModuleMS));
+ }
+ }
+#endif
DEBUG_ASSERTCRASH(sleepLen > 0, ("you may not return 0 from update"));
if (sleepLen < 1)
sleepLen = UPDATE_SLEEP_NONE;
@@ -3879,8 +3961,11 @@ void GameLogic::update( void )
const Real ai = logicElapsedMS( tObjects, tAI );
const Real partition = logicElapsedMS( tAI, tPartition );
const Real rest = total - scripts - objects - ai - partition;
- DEBUG_LOG(("SLOW LOGIC FRAME %d: %.1fms | scripts %.1f | objects %.1f | ai %.1f (pathfind %.1f, players %.1f) | partition %.1f | rest %.1f\n",
- now, total, scripts, objects, ai, AI::getLastPathfindMS(), AI::getLastPlayerUpdateMS(), partition, rest));
+ DEBUG_LOG(("SLOW LOGIC FRAME %d: %.1fms | scripts %.1f | objects %.1f | ai %.1f (pathfind %.1f, players %.1f) | partition %.1f | rest %.1f\n sc: %s\n ob: %s\n pf: %s\n",
+ now, total, scripts, objects, ai, AI::getLastPathfindMS(), AI::getLastPlayerUpdateMS(), partition, rest,
+ TheScriptEngine->getProfileReport(),
+ getModuleProfileReport(),
+ Pathfinder::getProfileReport()));
}
}
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp
index 4279d9348..459cded98 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp
@@ -1371,6 +1371,46 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData )
if (!upgradeT) // sanity
break;
+ //
+ // Argument 0 is the building the command bar picked to research this. It matters for a
+ // multi-selection: a player upgrade is researched exactly once, so handing the whole
+ // group to `queueUpgrade` below always lands it on the first member of the selection -
+ // the first one to pass the affordability check withdraws the money and every other
+ // member then fails it. That is why clicking four upgrades on four selected barracks
+ // stacked all four on one of them. The bar already chose the least loaded building;
+ // honour that choice when the id is one of the selected objects the player controls,
+ // and fall back to the old group-wide path otherwise. An object upgrade is bought per
+ // building, and the bar now sends one message per building it wants it on, so the
+ // group-wide path must not fire for those either - it would queue N messages on N
+ // buildings each.
+ //
+ Object *producer = NULL;
+ if( currentlySelectedGroup )
+ {
+ ObjectID producerID = msg->getArgument( 0 )->objectID;
+ const VecObjectID& ids = currentlySelectedGroup->getAllIDs();
+ if( std::find( ids.begin(), ids.end(), producerID ) != ids.end() )
+ producer = TheGameLogic->findObjectByID( producerID );
+ }
+
+ if( producer && producer->getControllingPlayer() == thisPlayer )
+ {
+ // same revalidation AIGroup::queueUpgrade does per member, to stop cheaters
+ if( !TheUpgradeCenter->canAffordUpgrade( producer->getControllingPlayer(), upgradeT, FALSE ) )
+ break;
+ if( upgradeT->getUpgradeType() == UPGRADE_TYPE_OBJECT &&
+ ( producer->hasUpgrade( upgradeT ) || !producer->affectedByUpgrade( upgradeT ) ) )
+ break;
+ if( !producer->canProduceUpgrade( upgradeT ) )
+ break;
+ ProductionUpdateInterface *pu = producer->getProductionUpdateInterface();
+ if( pu == NULL || pu->canQueueUpgrade( upgradeT ) == CANMAKE_QUEUE_FULL )
+ break;
+
+ pu->queueUpgrade( upgradeT );
+ break;
+ }
+
if (currentlySelectedGroup)
currentlySelectedGroup->queueUpgrade( upgradeT );
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 88b726389..0d3f913fa 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -35,6 +35,7 @@
#include "GameLogic/IncomingDamage.h"
#include "GameLogic/AIPlayer.h"
#include "GameLogic/AIPathfind.h"
+#include "GameLogic/ScriptEngine.h"
#include "Common/TunnelTracker.h"
#include "Common/StateMachine.h"
@@ -1245,6 +1246,69 @@ TEST(skirmish_build_rate_keeps_the_old_pace_but_not_the_old_flat_clamp)
CHECK_EQ(AIPlayer::computeBuildDelay(0.0f, 9000, AIDATA_POOR, AIDATA_WEALTHY, 0.6f, 2.0f, SKIRMISH_RATE), 0);
}
+TEST(skirmish_team_move_actions_are_the_throttled_ones)
+{
+ /* Every action listed here reaches AIGroup::friend_computeGroundPath, which runs a full-map A*
+ * synchronously. Six of them landed on one logic frame in a 1v7 skirmish and cost 80ms of a
+ * 33ms budget, so the sequential-script step lets one through per frame. Pin the set: adding a
+ * team-move action without adding it here quietly puts the pile-up back. */
+ CHECK(ScriptEngine::isThrottledTeamMoveAction(ScriptAction::MOVE_TEAM_TO));
+ CHECK(ScriptEngine::isThrottledTeamMoveAction(ScriptAction::TEAM_FOLLOW_WAYPOINTS));
+ CHECK(ScriptEngine::isThrottledTeamMoveAction(ScriptAction::TEAM_FOLLOW_WAYPOINTS_EXACT));
+ CHECK(ScriptEngine::isThrottledTeamMoveAction(ScriptAction::SKIRMISH_FOLLOW_APPROACH_PATH));
+ CHECK(ScriptEngine::isThrottledTeamMoveAction(ScriptAction::SKIRMISH_MOVE_TO_APPROACH_PATH));
+ CHECK(ScriptEngine::isThrottledTeamMoveAction(ScriptAction::CREATE_REINFORCEMENT_TEAM));
+ CHECK(ScriptEngine::isThrottledTeamMoveAction(ScriptAction::SKIRMISH_ATTACK_NEAREST_GROUP_WITH_VALUE));
+
+ /* ...and nothing cheap is throttled, or the AI would crawl for no reason. */
+ CHECK(!ScriptEngine::isThrottledTeamMoveAction(ScriptAction::DEBUG_MESSAGE_BOX));
+ CHECK(!ScriptEngine::isThrottledTeamMoveAction(ScriptAction::ENABLE_SCRIPT));
+ CHECK(!ScriptEngine::isThrottledTeamMoveAction(ScriptAction::SET_FLAG));
+ CHECK(!ScriptEngine::isThrottledTeamMoveAction(ScriptAction::NO_OP));
+ CHECK(!ScriptEngine::isThrottledTeamMoveAction(-1));
+ CHECK(!ScriptEngine::isThrottledTeamMoveAction(0x7fffffff));
+}
+
+TEST(ai_players_do_not_all_check_in_on_the_same_frame)
+{
+ /* Every AIPlayer used to be built with the same timers on the same frame, and every one of
+ * its repeating checks re-arms itself from a constant, so seven bots ran their base building,
+ * team building and bridge repair together for the whole match and the cost of all seven
+ * landed on one logic frame. The phase is what pulls them apart. */
+ const Int cycle = 2 * LOGICFRAMES_PER_SECOND;
+ Int seen[ MAX_PLAYER_COUNT ];
+ Int i, j;
+ for (i = 0; i < MAX_PLAYER_COUNT; i++)
+ {
+ seen[i] = AIPlayer::computeUpdatePhase(i, cycle);
+ /* A phase is a slot inside the cycle, never a cycle of its own - the check still runs
+ * exactly as often as it did, just not at the same moment as the neighbour's. */
+ CHECK(seen[i] >= 0);
+ CHECK(seen[i] < cycle);
+ }
+ for (i = 0; i < MAX_PLAYER_COUNT; i++)
+ for (j = i + 1; j < MAX_PLAYER_COUNT; j++)
+ CHECK_NE(seen[i], seen[j]);
+
+ /* It is a function of the player index and nothing else - no clock, no random - or the
+ * lockstep simulation would desync the moment two machines disagreed. */
+ CHECK_EQ(AIPlayer::computeUpdatePhase(3, cycle), AIPlayer::computeUpdatePhase(3, cycle));
+
+ /* A one-second cycle has fewer frames than MAX_PLAYER_COUNT has players, so the slots
+ * collide there; what must not happen is a phase outside the cycle. */
+ for (i = 0; i < MAX_PLAYER_COUNT; i++)
+ {
+ const Int shortPhase = AIPlayer::computeUpdatePhase(i, LOGICFRAMES_PER_SECOND);
+ CHECK(shortPhase >= 0);
+ CHECK(shortPhase < LOGICFRAMES_PER_SECOND);
+ }
+
+ /* Garbage in stays harmless: an unset index or a zero cycle means "no offset". */
+ CHECK_EQ(AIPlayer::computeUpdatePhase(-1, cycle), 0);
+ CHECK_EQ(AIPlayer::computeUpdatePhase(0, cycle), 0);
+ CHECK_EQ(AIPlayer::computeUpdatePhase(5, 0), 0);
+}
+
//////////////////////////////////////////////////////////////////////////////
// Pathfinder cell info pool
//////////////////////////////////////////////////////////////////////////////
@@ -1455,3 +1519,225 @@ TEST(statemachine_outlives_the_owner_that_lets_go_of_it_mid_update)
machine = NULL;
machine->deleteInstance();
}
+
+
+/* ------------------------------------------------------------------------------------------------
+ * The A* open list.
+ *
+ * `PathfindCell::putOnSortedOpenList` used to walk from the head on every insert, past every cell
+ * of equal cost, which is O(open list) per expanded cell - 62 million walk steps over 108 slow
+ * frames in a real skirmish. It now keeps a tail pointer and enters from whichever end is nearer
+ * the new cost. The insertion *point* has to stay exactly where it was, or the search expands a
+ * different set of cells and lockstep breaks, so these check the resulting order against a stable
+ * sort of the same insertion sequence: ascending cost, ties in insertion order.
+ * ---------------------------------------------------------------------------------------------- */
+static PathfindCell *theOpenTestCells = NULL;
+
+static Bool openListOrderMatches( PathfindCell *list, const std::vector<Int>& expected )
+{
+ UnsignedInt n = 0;
+ UnsignedInt prevCost = 0;
+ for( PathfindCell *c = list; c; c = c->getNextOpen() )
+ {
+ if( n >= expected.size() )
+ return false; // longer than it should be
+ if( c->getTotalCost() < prevCost )
+ return false; // not sorted
+ if( (Int)(c - theOpenTestCells) != expected[ n ] )
+ return false; // right costs, wrong tie order
+ prevCost = c->getTotalCost();
+ n++;
+ }
+ return n == expected.size();
+}
+
+TEST(pathfind_open_list_insert_keeps_ascending_cost_and_insertion_order_on_ties)
+{
+ CHECK(bootOnce());
+ PathfindCellInfo::allocateCellInfos();
+
+ const Int count = 400;
+ PathfindCell *cells = MSGNEW("PathfindCellInfo") PathfindCell[ count ];
+ theOpenTestCells = cells;
+
+ /* costs with a lot of ties (the grid quantises everything to multiples of ten) and no
+ monotonic order, so every branch of the new insert gets used */
+ std::vector<Int> expected;
+ PathfindCell *list = NULL;
+ Int seed = 12345;
+ Int i;
+ for( i = 0; i < count; i++ )
+ {
+ seed = seed * 1103515245 + 12345;
+ UnsignedInt cost = 10 * (UnsignedInt)(((seed >> 16) & 0x7fff) % 25);
+ ICoord2D pos;
+ pos.x = (UnsignedShort)(i % 64);
+ pos.y = (UnsignedShort)(i / 64);
+ CHECK(cells[ i ].allocateInfo( pos ));
+ cells[ i ].setTotalCost( cost );
+
+ /* the reference: insert after every cell of equal or lower cost */
+ std::vector<Int>::iterator it = expected.begin();
+ while( it != expected.end() && cells[ *it ].getTotalCost() <= cost )
+ ++it;
+ expected.insert( it, i );
+
+ list = cells[ i ].putOnSortedOpenList( list );
+ }
+ CHECK(openListOrderMatches( list, expected ));
+
+ /* pull cells out - including the head and the tail, the two the fast paths depend on - and
+ put fresh ones back, which is exactly what an A* loop does */
+ Int removed[ 5 ];
+ removed[ 0 ] = expected.front();
+ removed[ 1 ] = expected.back();
+ removed[ 2 ] = expected[ expected.size() / 2 ];
+ removed[ 3 ] = expected[ 1 ];
+ removed[ 4 ] = expected[ expected.size() - 2 ];
+ for( i = 0; i < 5; i++ )
+ {
+ list = cells[ removed[ i ] ].removeFromOpenList( list );
+ expected.erase( std::find( expected.begin(), expected.end(), removed[ i ] ) );
+ }
+ CHECK(openListOrderMatches( list, expected ));
+
+ for( i = 0; i < 5; i++ )
+ {
+ Int c = removed[ i ];
+ UnsignedInt cost = 10 * (UnsignedInt)(i * 7 % 25);
+ cells[ c ].setTotalCost( cost );
+ std::vector<Int>::iterator it = expected.begin();
+ while( it != expected.end() && cells[ *it ].getTotalCost() <= cost )
+ ++it;
+ expected.insert( it, c );
+ list = cells[ c ].putOnSortedOpenList( list );
+ }
+ CHECK(openListOrderMatches( list, expected ));
+
+ /* emptying it one at a time from the tail end must not leave a stale tail behind */
+ while( !expected.empty() )
+ {
+ Int c = expected.back();
+ expected.pop_back();
+ list = cells[ c ].removeFromOpenList( list );
+ }
+ CHECK(list == NULL);
+
+ cells[ 0 ].setTotalCost( 100 );
+ list = cells[ 0 ].putOnSortedOpenList( NULL );
+ cells[ 1 ].setTotalCost( 50 );
+ list = cells[ 1 ].putOnSortedOpenList( list );
+ CHECK(list == &cells[ 1 ]);
+ CHECK(list->getNextOpen() == &cells[ 0 ]);
+
+ PathfindCell::releaseOpenList( list );
+ for( i = 0; i < count; i++ )
+ cells[ i ].releaseInfo();
+ delete [] cells;
+ theOpenTestCells = NULL;
+ PathfindCellInfo::releaseCellInfos();
+}
+
+
+//-------------------------------------------------------------------------------------------------
+// Zone equivalency sets (pathfindZoneFind / pathfindZoneUnion / pathfindZoneFlatten).
+//
+// The pathfinder merges zone ids with a union-find over the equivalency array instead of EA's
+// relabel-the-whole-array loop. The contract the rest of the pathfinder relies on is exact, not
+// approximate: after flattening, array[i] must be the *smallest* id in i's set, which is what the
+// relabelling version produced. This drives a long random merge sequence through both the real
+// implementation and a straight-line reference relabeller and requires the two arrays to match
+// entry for entry.
+//-------------------------------------------------------------------------------------------------
+
+// EA's original merge: canonicalize both, keep the lower, relabel every entry.
+static void referenceResolveZones( zoneStorageType *zones, Int srcZone, Int targetZone, Int numZones )
+{
+ srcZone = zones[srcZone];
+ targetZone = zones[targetZone];
+ zoneStorageType finalZone = (targetZone < srcZone) ? zones[targetZone] : zones[srcZone];
+ for (Int i = 0; i < numZones; i++) {
+ zoneStorageType ze = zones[i];
+ if (ze == targetZone || ze == srcZone) {
+ zones[i] = finalZone;
+ }
+ }
+}
+
+TEST(pathfind_zone_union_find_matches_the_relabelling_merge_it_replaced)
+{
+ enum { NUM_ZONES = 500, NUM_MERGES = 4000 };
+ static zoneStorageType real[ NUM_ZONES ];
+ static zoneStorageType ref[ NUM_ZONES ];
+ Int i;
+ for (i = 0; i < NUM_ZONES; i++) {
+ real[ i ] = (zoneStorageType)i;
+ ref[ i ] = (zoneStorageType)i;
+ }
+
+ // A fixed LCG, so a failure is reproducible.
+ UnsignedInt seed = 12345;
+ Int mismatches = 0;
+ Int merges;
+ for (merges = 0; merges < NUM_MERGES; merges++) {
+ seed = seed * 1103515245 + 12345;
+ Int a = 1 + (Int)((seed >> 16) % (NUM_ZONES - 1));
+ seed = seed * 1103515245 + 12345;
+ Int b = 1 + (Int)((seed >> 16) % (NUM_ZONES - 1));
+
+ pathfindZoneUnion( real, a, b );
+ referenceResolveZones( ref, a, b, NUM_ZONES );
+
+ // Reading a set representative mid-sequence must agree too - the merge loops in
+ // calculateZones compare representatives between merges to decide what to merge next.
+ if (pathfindZoneFind( real, a ) != ref[ a ]) mismatches++;
+ if (pathfindZoneFind( real, b ) != ref[ b ]) mismatches++;
+ }
+ CHECK_EQ( mismatches, 0 );
+
+ pathfindZoneFlatten( real, NUM_ZONES );
+ Int diffs = 0;
+ for (i = 0; i < NUM_ZONES; i++) {
+ if (real[ i ] != ref[ i ]) diffs++;
+ }
+ CHECK_EQ( diffs, 0 );
+
+ // The whole array must be flat afterwards: array[array[i]] == array[i].
+ Int notFlat = 0;
+ for (i = 0; i < NUM_ZONES; i++) {
+ if (real[ real[ i ] ] != real[ i ]) notFlat++;
+ }
+ CHECK_EQ( notFlat, 0 );
+
+ // And every representative must be the minimum id of its set.
+ Int notMinimum = 0;
+ for (i = 0; i < NUM_ZONES; i++) {
+ if (real[ i ] > (zoneStorageType)i) notMinimum++;
+ }
+ CHECK_EQ( notMinimum, 0 );
+}
+
+TEST(pathfind_zone_flatten_collapses_a_deep_chain_in_one_pass)
+{
+ // pathfindZoneFlatten is a single ascending pass, which is only correct because every link
+ // points from a higher id to a lower one. Build the deepest chain the union can produce -
+ // 1 <- 2 <- 3 <- ... - by merging in an order that never gives path compression a chance.
+ enum { NUM_ZONES = 64 };
+ zoneStorageType zones[ NUM_ZONES ];
+ Int i;
+ for (i = 0; i < NUM_ZONES; i++) {
+ zones[ i ] = (zoneStorageType)i;
+ }
+ for (i = NUM_ZONES - 1; i >= 2; i--) {
+ zones[ i ] = (zoneStorageType)(i - 1); // hand-built chain, no compression
+ }
+ CHECK_EQ( (Int)zones[ NUM_ZONES - 1 ], NUM_ZONES - 2 );
+
+ pathfindZoneFlatten( zones, NUM_ZONES );
+ Int notOne = 0;
+ for (i = 1; i < NUM_ZONES; i++) {
+ if (zones[ i ] != 1) notOne++;
+ }
+ CHECK_EQ( notOne, 0 );
+ CHECK_EQ( (Int)zones[ 0 ], 0 );
+}