Skip to content

Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.

perf(gameengine): cut the stalls out of crowded battles

Olcay Seygan4f3e8b0069d2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cdbb39a0e..e4fd2827c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1001,8 +1001,19 @@ found and fixed — EA's own, not port damage.**
- Every unit on the move re-checked the entire road ahead of it, every single frame. A tank sent across the map holds one long straight leg of its route, and each frame it asked whether that whole leg - three hundred squares of it - was clear, walking every square and testing a block of twenty-five around each one. That one question was a sixth of the game's entire running time. It now looks twenty squares ahead, which is thirty frames of driving, and asks again next frame like it always did. Units also drive better for it, not worse: over four battles the time spent standing behind each other fell 10% and the number left properly stuck fell from 296 a match to 10.
- Sending a group across the map could freeze the picture for a twenty-fifth of a second. The wide corridor a group travels down is its own search, the most expensive kind the game runs, and it was the only one in the pathfinder allowed to run without a limit - a three-unit team once spent 40 milliseconds on one. It now gives up after a set amount of looking and the group falls back to individual routes, which is what happens on ground too tight for a corridor anyway.
- The movement code was timing itself thirty thousand times a frame. Reading the clock that often cost 4.6% of the whole game to measure something already counted for free.
+- Big fights run a quarter lighter. Every moving unit wrote out a line of text naming itself, every frame, for a sync-checking log that is switched off in every game anyone plays; the text was built and thrown away. In a 530-unit battle that was about a tenth of the game's time, and the average turn went from 3.9ms to 3.0ms.
+- A driving unit worked out where to steer from scratch every frame, checking twenty squares of road ahead and a block of twenty-five around each square. The answer now holds until the unit has covered half a square, and it is still worked out fresh every frame near the end of the route and near a corner. Units also stamped their planned route a dozen seconds ahead over a five-square-wide strip, so other units could avoid busy crossings; the strip is three squares and about six seconds now. Together those took the same 530-unit battle from 2.9ms a turn to 2.4ms. Twenty tanks pushed through a ramp on four maps arrive within 7% of the time they took before any of this, and none got stuck.
+- A computer player that had lost the building that makes dozers searched the whole catalogue of units for one it could build, once for every missing building in its plan. A late eight-player match did that 33 times every two seconds, for 13ms. It now asks once per turn.
+- A computer player looking for room beside a crowded base could hold the game at 20 to 37ms a turn for eight turns running. Its search was meant to stop after 32 spots a turn, but it only looked at the limit between rings of spots, and a ring far from the base holds more than 200. It stops at 32 wherever it is now, picks up at that spot next turn, and settles on the same place it always did.
+- Choosing which team to build next scored every team the computer could make against every kind of enemy unit it could see, working out from scratch how long each would take to kill the other. One such choice in an eight-player match took 84ms. Those answers depend only on the units' own data, so each is worked out once per match and remembered.
+- A route got straightened by testing every point on it against every later point. The limit of 32 points ahead had been lifted for an experiment and never put back, so one long route could cost 12ms. With it back, a 40,000-frame match spent 4ms on straightening where it spent 1.7 seconds, and turns slower than a thirtieth of a second went from 8 to 1.
+- Single units no longer freeze the game for a tenth of a second at random. The game's diary was forced out to disk after every line it wrote, and a gunner holding fire wrote one every time it waited, 104,000 of them in one match. That line is gone, and the diary is written out once a second, and in full if the game ever crashes.
- The queue that answers "where do I walk" was allowed to answer as many units as asked in the same instant. Ordering a group, or a fight breaking out, would drop ten questions into it at once and one frame would answer all ten. It now answers three a frame, which is still many times more than a match ever asks for on average, and the rest wait a frame. Units move better for it as well as the game running smoother: the number of routes computed in a whole battle fell by a fifth, because a unit whose answer comes one frame later usually no longer needs the second and third answer it used to ask for while stuck in traffic.
- The four together, on the same four battles: the average logic frame is a fifth shorter, the worst frame of a match went from 38.6 milliseconds to 16.0, frames over a sixtieth of a second went from 2 to none at all, and the number of frames costing more than 3 milliseconds fell from 14,105 to 3,360. In an eight-player 4v4 the average frame is a tenth shorter and the worst one went from 26.7 milliseconds to 17.9.
+- A unit told to hunt looks across the whole map for something to shoot. That search stepped through every patch of ground on both sides of the unit, most of it past the edge of the map, and asked "can I hurt this one" of every enemy it passed. One hunter in an eight-player fight could hold the game for a thirtieth of a second. It now walks the list of units that actually exist, and only asks that question of an enemy that would be picked. It picks the same target, and hunting no longer shows up among the slow frames at all.
+- A computer player planning its base checked whether every unbuilt spot in its plan was safe from the enemy on every pass, including spots it was never going to pick that pass. Thirty-six of those checks took 28ms in one frame. Only a spot that could be chosen gets checked now.
+- A computer player expanding to a far supply dock ordered a second supply centre there every minute until the first one stood, and searched the ground around the dock for room each time, 23 to 33ms a go. It now waits for the one it already ordered.
+- All of it together, on the same two eight-player 4v4 battles of 30,000 frames that opened this section: the slowest frame went from 150 and 267 milliseconds to 42 and 26, and frames longer than a thirtieth of a second went from 13 and 8 to one. Two four-player battles went from 132 and 65 milliseconds at worst to 30 and 26, with none over a thirtieth.
- Putting a building on uneven ground froze the picture for a sixteenth of a second. Levelling the dirt under a foundation asked the game to re-light every blade of grass on the map - sixty-one milliseconds, measured, for a patch a few paces wide. It now redoes the patch. Over a seven-minute four-way battle that took the worst frame of the match from 82 milliseconds down to 19, and left nothing at all above a thirtieth of a second.
- The rest of the same mob. A mob is a leader and ten rioters, and a rioter only reconsiders where it is standing once every sixteen frames - but it was woken on all sixteen anyway, just to be sent back to sleep, and every mob on the map is eleven of those. EA left a note in the code asking for exactly this and never came back to it. The rioters sleep properly now, and one whose mob is dead stops being woken at all. Eight mobs on the field is eighty rioters: where all eighty were woken every frame, five are. Measured against the number in the complaint rather than a comfortable one: a hundred mobs is 1,100 men and costs 4.3 milliseconds of a 33 millisecond frame, two hundred and fifty is 2,750 men and 7.1, four hundred is 4,400 men and 12.6, and not one frame of any of those three ran over budget. Four hundred mobs is past anything a match will produce; what the rioters cost there is a fifth of a millisecond.
@@ -1087,6 +1098,7 @@ found and fixed — EA's own, not port damage.**
- The three-piece command bar was reverted once, for having nowhere to put the painting of the bar, and is back now that the painting has been cut into three to match. Each piece is fitted by matching it against the artwork it was cut from rather than by eye: the eyeballed fit was four percent out, which nobody sees on the metal and everybody sees on the money readout.
- The opponent's decisions are argued with a number: 20 headless matches per change, same seeds, win rate and match length before and after.
- That caught two changes that looked right and measured catastrophic - a wave that waited jammed the whole production line, and a retreat rule that counted buildings as gunfire sent every attack home. Both showed up as twenty matches with zero kills.
+- The same habit caught a speed fix that measured beautifully for the wrong reason. Capping the search for room beside a supply dock cut a once-a-minute stall and dropped the average eight-player frame below a millisecond, which was the giveaway: the first supply centre of every match went down on a blocked spot and never went up, so no computer player had an economy and nothing was happening. Counting supply trucks and attack waves next to the frame times showed it at once. The cap came out, and the stall was cured instead by not ordering the same supply centre twice.
- Massing an army before attacking is written and measured but switched off: it needs somewhere to wait that is not the production queue.
- The whole of the group movement work is out of the game again, and that is the largest single thing this list has taken back. Lanes priced by how many other units already plan to drive over a square, a unit giving up on a queue and planning its way round, the shared corridor a selection travels down, routes priced by when somebody else will be standing on a square, spacing measured off the units you selected: all of it built, all of it measured, all of it removed. What sank it was that the self-play harness cannot see a traffic jam. A computer opponent moves five units at a time and never forms the queue a person makes by dragging a box round fifteen tanks, so thirty-three of forty-eight maps came out bit-identical over ninety-six matches and the rule fired about twice a match. Then it was asked to swing wider, and four ways of doing that were tried and thrown away - two changed nothing at all, two made units wait longer than doing nothing. Overtaking went the same way over forty matches, with the time units spend properly stuck moving in the wrong direction, which is the one column it had been rebuilt to protect. EA wrote a version of that in 2003 and switched theirs off too. The speed work underneath it stayed; the behaviour is retail's again, and this is a problem to come back to with a way of measuring it that a machine opponent cannot flatter.
- Bugs deliberately left alone are pinned by a test documenting the behaviour.
diff --git a/GeneralsMD/Code/Data/Scenarios/crowdbattle.txt b/GeneralsMD/Code/Data/Scenarios/crowdbattle.txt
new file mode 100644
index 000000000..78c19b2fe
--- /dev/null
+++ b/GeneralsMD/Code/Data/Scenarios/crowdbattle.txt
@@ -0,0 +1,43 @@
+# Crowd battle: two large mixed armies attack-moving into each other on Twilight Flame.
+#
+# A symmetric AI batch cannot judge a logic change's cost, because the change alters the match and
+# the two builds end up measuring different armies. This spawns the same crowd on the same frames in
+# both builds, so HEADLESS LOGICTIME compares like with like.
+#
+# generals.exe -headless -quickstart -noshellmap -observer -multiInstance -noFPSLimit
+# -map "Maps\Twilight Flame\Twilight Flame.map" -autoskirmish 2 -takeover
+# -side 0 FactionAmerica -side 1 FactionChina -seed 7 -maxframes 4500
+# -scenario crowdbattle -logPrefix crowd_
+#
+# Four waves a side, 140 units each, so the fight in the middle keeps being fed rather than ending
+# after the first clash.
+
+30 spawn 0 AmericaTankCrusader 30 start0:0:300 40
+30 spawn 0 AmericaInfantryRanger 30 start0:250:300 18
+30 spawn 0 AmericaInfantryMissileDefender 20 start0:-250:300 18
+30 spawn 1 ChinaTankBattleMaster 30 start1:0:300 40
+30 spawn 1 ChinaInfantryRedguard 40 start1:250:300 18
+30 spawn 1 ChinaInfantryTankHunter 20 start1:-250:300 18
+60 attackmove 0 * start1
+60 attackmove 1 * start0
+
+900 spawn 0 AmericaTankCrusader 30 start0:0:300 40
+900 spawn 0 AmericaInfantryRanger 30 start0:250:300 18
+900 spawn 1 ChinaTankBattleMaster 30 start1:0:300 40
+900 spawn 1 ChinaInfantryRedguard 30 start1:250:300 18
+930 attackmove 0 * start1
+930 attackmove 1 * start0
+
+1800 spawn 0 AmericaTankCrusader 30 start0:0:300 40
+1800 spawn 0 AmericaInfantryRanger 30 start0:250:300 18
+1800 spawn 1 ChinaTankBattleMaster 30 start1:0:300 40
+1800 spawn 1 ChinaInfantryRedguard 30 start1:250:300 18
+1830 attackmove 0 * start1
+1830 attackmove 1 * start0
+
+2700 spawn 0 AmericaTankCrusader 30 start0:0:300 40
+2700 spawn 0 AmericaInfantryMissileDefender 30 start0:250:300 18
+2700 spawn 1 ChinaTankBattleMaster 30 start1:0:300 40
+2700 spawn 1 ChinaInfantryTankHunter 30 start1:250:300 18
+2730 attackmove 0 * start1
+2730 attackmove 1 * start0
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/CRCDebug.h b/GeneralsMD/Code/GameEngine/Include/Common/CRCDebug.h
index 99408dad6..de90d5f2f 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/CRCDebug.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/CRCDebug.h
@@ -47,20 +47,28 @@
#include "wwmath/vector3.h"
#include "wwmath/matrix3d.h"
+ extern Int TheCRCFirstFrameToLog;
+ extern UnsignedInt TheCRCLastFrameToLog;
+
+ /* Every macro below tests this before it touches its arguments. The logging functions test the
+ frame range themselves, but only after the call, and the call has already built the arguments:
+ Path::computePointOnPath and doLocomotor pass DescribeObject(obj), an AsciiString::format per
+ moving unit per frame, and the DUMP macros build AsciiStrings out of __FILE__. With the log off,
+ which is every run that does not pass -DebugCRCFromFrame, that was about a tenth of a 530-unit
+ battle's logic frame spent formatting text nobody kept. */
+ #define CRC_DEBUG_LOGGING_ON (TheCRCFirstFrameToLog >= 0)
+
#define AS_INT(x) (*(Int *)(&x))
#define DUMPVEL DUMPCOORD3DNAMED(&m_vel, "m_vel")
#define DUMPACCEL DUMPCOORD3DNAMED(&m_accel, "m_accel")
#define DUMPVECTOR3(x) DUMPVECTOR3NAMED(x, #x)
- #define DUMPVECTOR3NAMED(x, y) dumpVector3(x, y, __FILE__, __LINE__)
+ #define DUMPVECTOR3NAMED(x, y) do { if (CRC_DEBUG_LOGGING_ON) dumpVector3(x, y, __FILE__, __LINE__); } while (0)
#define DUMPCOORD3D(x) DUMPCOORD3DNAMED(x, #x)
- #define DUMPCOORD3DNAMED(x, y) dumpCoord3D(x, y, __FILE__, __LINE__)
+ #define DUMPCOORD3DNAMED(x, y) do { if (CRC_DEBUG_LOGGING_ON) dumpCoord3D(x, y, __FILE__, __LINE__); } while (0)
#define DUMPMATRIX3D(x) DUMPMATRIX3DNAMED(x, #x)
- #define DUMPMATRIX3DNAMED(x, y) dumpMatrix3D(x, y, __FILE__, __LINE__)
+ #define DUMPMATRIX3DNAMED(x, y) do { if (CRC_DEBUG_LOGGING_ON) dumpMatrix3D(x, y, __FILE__, __LINE__); } while (0)
#define DUMPREAL(x) DUMPREALNAMED(x, #x)
- #define DUMPREALNAMED(x, y) dumpReal(x, y, __FILE__, __LINE__)
-
- extern Int TheCRCFirstFrameToLog;
- extern UnsignedInt TheCRCLastFrameToLog;
+ #define DUMPREALNAMED(x, y) do { if (CRC_DEBUG_LOGGING_ON) dumpReal(x, y, __FILE__, __LINE__); } while (0)
void dumpVector3(const Vector3 *v, AsciiString name, AsciiString fname, Int line);
void dumpCoord3D(const Coord3D *c, AsciiString name, AsciiString fname, Int line);
@@ -73,9 +81,9 @@
void addCRCDebugLine(const char *fmt, ...);
void addCRCDumpLine(const char *fmt, ...);
void addCRCGenLine(const char *fmt, ...);
- #define CRCDEBUG_LOG(x) addCRCDebugLine x
- #define CRCDUMP_LOG(x) addCRCDumpLine x
- #define CRCGEN_LOG(x) addCRCGenLine x
+ #define CRCDEBUG_LOG(x) do { if (CRC_DEBUG_LOGGING_ON) addCRCDebugLine x; } while (0)
+ #define CRCDUMP_LOG(x) do { if (CRC_DEBUG_LOGGING_ON) addCRCDumpLine x; } while (0)
+ #define CRCGEN_LOG(x) do { if (CRC_DEBUG_LOGGING_ON) addCRCGenLine x; } while (0)
class CRCVerification
{
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Player.h b/GeneralsMD/Code/GameEngine/Include/Common/Player.h
index 5c21613af..50c11b7e2 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/Player.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/Player.h
@@ -240,12 +240,38 @@ public:
* m_map from public access and make access methods for our operations */
PlayerRelationMapType m_map;
+ /* Every "is that unit my enemy" asked in a fight ends in a hash lookup on this map, keyed by a
+ player index that is never more than fifteen: 3% of a 530-unit battle. The map stays the saved
+ form; this array is the same contents indexed directly, and every write goes through the three
+ calls below so the two cannot drift. */
+ Bool lookup( PlayerIndex index, Relationship *r ) const
+ {
+ if (index < 0 || index >= MAX_PLAYER_COUNT)
+ {
+ PlayerRelationMapType::const_iterator it = m_map.find( index );
+ if (it == m_map.end())
+ return FALSE;
+ *r = (*it).second;
+ return TRUE;
+ }
+ if (!m_present[index])
+ return FALSE;
+ *r = m_dense[index];
+ return TRUE;
+ }
+ void assign( PlayerIndex index, Relationship r );
+ Bool remove( PlayerIndex index );
+ void removeAll( void );
+
protected:
virtual void crc( Xfer *xfer );
virtual void xfer( Xfer *xfer );
virtual void loadPostProcess( void );
+ Relationship m_dense[ MAX_PLAYER_COUNT ];
+ Bool m_present[ MAX_PLAYER_COUNT ];
+
};
// ----------------------------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
index ab430d975..13186873e 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
@@ -716,7 +716,7 @@ enum
PF_CLAIM_TABLE_SIZE = 32768, ///< power of two: the hash is masked, not divided
PF_CLAIM_PROBES = 8, ///< linear probe depth; past it a claim is simply dropped
PF_CLAIM_UNITS_MAX = 4, ///< claims beyond this on one cell-moment cost nothing more
- PF_CLAIM_SAMPLES_MAX = 64, ///< cells of its own plan one unit may stamp per refresh
+ PF_CLAIM_SAMPLES_MAX = 32, ///< cells of its own plan one unit may stamp per refresh; 64 was 5% of a 530-unit battle
PF_CLEARANCE_REBUILD_FRAMES = 30, ///< how often a dirty clearance field is actually rebuilt
PF_CROSSING_NUM = 1, ///< peak crossing penalty is NUM/DEN of a step
PF_CROSSING_DEN = 2,
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
index 4d1d12b31..afdf05b1f 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
@@ -418,6 +418,7 @@ protected:
both machines in a network game compute them the same way from the same frames, and a
savegame that restarts a half-finished scan loses nothing but a few frames of searching. */
Real m_buildProbeOffset;
+ Int m_buildProbeSkip; ///< position pairs of the ring at m_buildProbeOffset already tried
Coord3D m_buildProbePos;
GameDifficulty m_difficulty;
@@ -432,6 +433,7 @@ protected:
enum {MAX_STRUCTURES_TO_REPAIR = 2};
ObjectID m_structuresToRepair[MAX_STRUCTURES_TO_REPAIR];
ObjectID m_repairDozer;
+ UnsignedInt m_frameAfterFailedDozerQueue; ///< frame+1 of the last queueDozer that found no factory, 0 for never
Coord3D m_repairDozerOrigin;
Int m_structuresInQueue;
Bool m_dozerQueuedForRepair;
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIStateMachine.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIStateMachine.h
index 626ef559e..d472c4f81 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIStateMachine.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIStateMachine.h
@@ -982,8 +982,7 @@ class AIAttackFireWeaponState : public State
public:
AIAttackFireWeaponState( StateMachine *machine, NotifyWeaponFiredInterface* att ) :
State( machine, "AIAttackFireWeaponState" ),
- m_att(att),
- m_saidHeldFire(FALSE)
+ m_att(att)
{
}
virtual Bool isAttack() const { return TRUE; }
@@ -997,7 +996,6 @@ protected:
virtual void loadPostProcess(){};
private:
NotifyWeaponFiredInterface *const m_att; // this is NOT owned by us and should not be freed
- Bool m_saidHeldFire; // one log line per held shot, not one per frame of holding it
};
EMPTY_DTOR(AIAttackFireWeaponState)
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp
index 9f9b23a9d..e65e445ac 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp
@@ -211,6 +211,11 @@ void dumpBattlePlanBonuses(const BattlePlanBonuses *b, AsciiString name, const P
// ------------------------------------------------------------------------------------------------
PlayerRelationMap::PlayerRelationMap( void )
{
+ for (Int i = 0; i < MAX_PLAYER_COUNT; ++i)
+ {
+ m_dense[ i ] = NEUTRAL;
+ m_present[ i ] = FALSE;
+ }
} // end PlayerRelationMap
@@ -224,6 +229,37 @@ PlayerRelationMap::~PlayerRelationMap( void )
} // end ~PlayerRelationmap
+// ------------------------------------------------------------------------------------------------
+void PlayerRelationMap::assign( PlayerIndex index, Relationship r )
+{
+ m_map[ index ] = r;
+ if (index >= 0 && index < MAX_PLAYER_COUNT)
+ {
+ m_dense[ index ] = r;
+ m_present[ index ] = TRUE;
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+Bool PlayerRelationMap::remove( PlayerIndex index )
+{
+ PlayerRelationMapType::iterator it = m_map.find( index );
+ if (it == m_map.end())
+ return FALSE;
+ m_map.erase( it );
+ if (index >= 0 && index < MAX_PLAYER_COUNT)
+ m_present[ index ] = FALSE;
+ return TRUE;
+}
+
+// ------------------------------------------------------------------------------------------------
+void PlayerRelationMap::removeAll( void )
+{
+ m_map.clear();
+ for (Int i = 0; i < MAX_PLAYER_COUNT; ++i)
+ m_present[ i ] = FALSE;
+}
+
// ------------------------------------------------------------------------------------------------
/** CRC */
// ------------------------------------------------------------------------------------------------
@@ -285,7 +321,7 @@ void PlayerRelationMap::xfer( Xfer *xfer )
xfer->xferUser( &r, sizeof( Relationship ) );
// assign relationship
- m_map[ playerIndex ] = r;
+ assign( playerIndex, r );
} // end for, i
@@ -594,10 +630,10 @@ Relationship Player::getRelationship(const Team *that) const
const Player* thatPlayer = that->getControllingPlayer();
if (thatPlayer != NULL)
{
- PlayerRelationMapType::const_iterator it = m_playerRelations->m_map.find(thatPlayer->getPlayerIndex());
- if (it != m_playerRelations->m_map.end())
+ Relationship r;
+ if (m_playerRelations->lookup(thatPlayer->getPlayerIndex(), &r))
{
- return (*it).second;
+ return r;
}
}
}
@@ -611,7 +647,7 @@ void Player::setPlayerRelationship(const Player *that, Relationship r)
if (that != NULL)
{
// note that this creates the entry if it doesn't exist.
- m_playerRelations->m_map[that->getPlayerIndex()] = r;
+ m_playerRelations->assign(that->getPlayerIndex(), r);
}
}
@@ -622,15 +658,13 @@ Bool Player::removePlayerRelationship(const Player *that)
{
if (that == NULL)
{
- m_playerRelations->m_map.clear();
+ m_playerRelations->removeAll();
return true;
}
else
{
- PlayerRelationMapType::iterator it = m_playerRelations->m_map.find(that->getPlayerIndex());
- if (it != m_playerRelations->m_map.end())
+ if (m_playerRelations->remove(that->getPlayerIndex()))
{
- m_playerRelations->m_map.erase(it);
return true;
}
}
@@ -1045,7 +1079,7 @@ void Player::initFromDict(const Dict* d)
m_handicap.readFromDict(d);
/// @todo Ack! the todo in PlayerList::reset() mentioning the need for a Player::reset() really needs to get done.
- m_playerRelations->m_map.clear(); // For now, it has been decided to just fix this one. Dear god me must reset.
+ m_playerRelations->removeAll(); // For now, it has been decided to just fix this one. Dear god me must reset.
m_teamRelations->m_map.clear(); // For now, it has been decided to just fix this one. Dear god me must reset.
Int i;
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp
index 3b94b827e..0327f8de6 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp
@@ -1487,10 +1487,10 @@ Relationship Team::getRelationship(const Team *that) const
Player* thatPlayer = that->getControllingPlayer();
if (thatPlayer != NULL)
{
- PlayerRelationMapType::const_iterator it = m_playerRelations->m_map.find(thatPlayer->getPlayerIndex());
- if (it != m_playerRelations->m_map.end())
+ Relationship r;
+ if (m_playerRelations->lookup(thatPlayer->getPlayerIndex(), &r))
{
- return (*it).second;
+ return r;
}
}
}
@@ -1593,7 +1593,7 @@ void Team::setOverridePlayerRelationship( Int playerIndex, Relationship r )
if (playerIndex != PLAYER_INDEX_INVALID)
{
// note that this creates the entry if it doesn't exist.
- m_playerRelations->m_map[playerIndex] = r;
+ m_playerRelations->assign(playerIndex, r);
}
}
@@ -1604,15 +1604,13 @@ Bool Team::removeOverridePlayerRelationship( Int playerIndex )
{
if (playerIndex == PLAYER_INDEX_INVALID)
{
- m_playerRelations->m_map.clear();
+ m_playerRelations->removeAll();
return true;
}
else
{
- PlayerRelationMapType::iterator it = m_playerRelations->m_map.find(playerIndex);
- if (it != m_playerRelations->m_map.end())
+ if (m_playerRelations->remove(playerIndex))
{
- m_playerRelations->m_map.erase(it);
return true;
}
}
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp
index ab7d2aceb..803d2b104 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp
@@ -233,6 +233,23 @@ static const char *prepBuffer(const char* format, char *buffer, size_t bufferSiz
*/
// ----------------------------------------------------------------------------
#ifdef DEBUG_LOGGING
+/* The log used to be flushed after every line, which made each DEBUG_LOG inside a logic frame a
+ synchronous write to disk. Single units in big fights logged update times of 60 to 145ms with
+ nothing in the pathfinder, always beside a log line, and did not repeat on a rerun of the same
+ seed. The file is flushed at most once a second now, and in full on every crash path before the
+ process exits, so the last lines before a crash still reach it. */
+static const DWORD LOG_FLUSH_INTERVAL_MS = 1000;
+static DWORD theLastLogFlushMS = 0;
+
+static void flushLogFileAtMostOnceASecond(void)
+{
+ const DWORD nowMS = ::GetTickCount();
+ if (nowMS - theLastLogFlushMS < LOG_FLUSH_INTERVAL_MS)
+ return;
+ theLastLogFlushMS = nowMS;
+ fflush(theLogFile);
+}
+
static void doLogOutput(const char *buffer)
{
// log message to file
@@ -241,7 +258,7 @@ static void doLogOutput(const char *buffer)
if (theLogFile)
{
fprintf(theLogFile, "%s", buffer); // note, no \n (should be there already)
- fflush(theLogFile);
+ flushLogFileAtMostOnceASecond();
}
}
@@ -277,6 +294,8 @@ static int doCrashBox(const char *buffer, Bool logResult)
#ifdef DEBUG_LOGGING
if (logResult)
DebugLog("[Abort]\n");
+ if (theLogFile)
+ fflush(theLogFile);
#endif
_exit(1);
break;
@@ -697,6 +716,12 @@ double SimpleProfiler::getAverageTime()
void ReleaseCrash(const char *reason)
{
+#ifdef DEBUG_LOGGING
+ // the debug log is flushed on a timer, and this function ends in _exit, which skips the CRT's own flush
+ if (theLogFile)
+ fflush(theLogFile);
+#endif
+
/// do additional reporting on the crash, if possible
if (!DX8Wrapper_IsWindowed) {
@@ -790,6 +815,11 @@ void ReleaseCrash(const char *reason)
void ReleaseCrashLocalized(const AsciiString& p, const AsciiString& m)
{
+#ifdef DEBUG_LOGGING
+ // see ReleaseCrash: the log is flushed on a timer and _exit below skips the CRT's flush
+ if (theLogFile)
+ fflush(theLogFile);
+#endif
if (!TheGameText) {
ReleaseCrash(m.str());
// This won't ever return
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
index bc65bc1e5..1beafc0ea 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
@@ -673,7 +673,17 @@ Int AI_threatScore( Int templateThreatValue, Int buildCost, Bool threatensMe,
/**
* Return the closest enemy, according to the qualifiers.
*/
-Object *AI::findClosestEnemy( const Object *me, Real range, UnsignedInt qualifiers,
+static Bool AI_filtersAllow( PartitionFilter **filters, Object *candidate )
+{
+ for ( ; *filters; ++filters )
+ {
+ if (!(*filters)->allow(candidate))
+ return false;
+ }
+ return true;
+}
+
+Object *AI::findClosestEnemy( const Object *me, Real range, UnsignedInt qualifiers,
const AttackPriorityInfo *info, PartitionFilter *optionalFilter)
{
@@ -735,7 +745,7 @@ Object *AI::findClosestEnemy( const Object *me, Real range, UnsignedInt qualifie
// -- filterStealth is BY FAR the least common to be useful, so it goes last.
// GS Fog check used to be inside can attack, so it feels right to be right after it
- filters[numFilters++] = &filterObvious;
+ filters[numFilters++] = &filterObvious;
if( !(qualifiers & ATTACK_BUILDINGS) )
filters[numFilters++] = &filterBldgs;
@@ -743,6 +753,17 @@ Object *AI::findClosestEnemy( const Object *me, Real range, UnsignedInt qualifie
if (qualifiers & WITHIN_ATTACK_RANGE)
filters[numFilters++] = &filterWithinAttackRange;
+ /* The two gathering searches below used to run every filter over every enemy in range and only
+ then pick one. A hunting unit searches the whole map, and the can-attack filter on a thousand
+ enemies was a single 30-47ms unit update in an eight-player match. They now gather with the
+ cheap filters above and ask the rest only of a candidate that would take the lead, which picks
+ the same enemy. */
+ PartitionFilter *gatherFilters[16];
+ const Int numGatherFilters = numFilters;
+ for (Int f = 0; f < numGatherFilters; ++f)
+ gatherFilters[f] = filters[f];
+ gatherFilters[numGatherFilters] = NULL;
+
if (qualifiers & CAN_SEE)
filters[numFilters++] = &filterLOS;
@@ -775,7 +796,7 @@ Object *AI::findClosestEnemy( const Object *me, Real range, UnsignedInt qualifie
Real distanceModifier = TheAI->getAiData()->m_attackPriorityDistanceModifier;
Object *bestThreat = NULL;
Int bestScore = 0;
- ObjectIterator *threatIter = ThePartitionManager->iterateObjectsInRange(me, range, FROM_BOUNDINGSPHERE_2D, filters, ITER_SORTED_NEAR_TO_FAR);
+ ObjectIterator *threatIter = ThePartitionManager->iterateObjectsInRange(me, range, FROM_BOUNDINGSPHERE_2D, gatherFilters, ITER_SORTED_NEAR_TO_FAR);
MemoryPoolObjectHolder threatHolder(threatIter);
for (Object *theEnemy = threatIter->first(); theEnemy; theEnemy = threatIter->next())
{
@@ -793,7 +814,7 @@ Object *AI::findClosestEnemy( const Object *me, Real range, UnsignedInt qualifie
const Int armedScore = AI_threatScore( theEnemy->getTemplate()->getThreatValue(),
theEnemy->getTemplate()->calcCostToBuild( theEnemy->getControllingPlayer() ),
true, dist, distanceModifier );
- if (armedScore <= bestScore)
+ if (armedScore <= bestScore || !AI_filtersAllow(filters + numGatherFilters, theEnemy))
continue;
Bool threatensMe = theEnemy->isAbleToAttack(); // cheap bit test, and required before the call below
@@ -822,7 +843,7 @@ Object *AI::findClosestEnemy( const Object *me, Real range, UnsignedInt qualifie
Object *bestEnemy = NULL;
Int effectivePriority=0;
Int actualPriority=0;
- ObjectIterator *iter = ThePartitionManager->iterateObjectsInRange(me, range, FROM_BOUNDINGSPHERE_2D, filters, ITER_SORTED_NEAR_TO_FAR);
+ ObjectIterator *iter = ThePartitionManager->iterateObjectsInRange(me, range, FROM_BOUNDINGSPHERE_2D, gatherFilters, ITER_SORTED_NEAR_TO_FAR);
MemoryPoolObjectHolder holder(iter);
for (Object *theEnemy = iter->first(); theEnemy; theEnemy = iter->next())
{
@@ -846,15 +867,11 @@ Object *AI::findClosestEnemy( const Object *me, Real range, UnsignedInt qualifie
Real dist = sqrt(distSqr);
Int modifier = dist/TheAI->getAiData()->m_attackPriorityDistanceModifier;
Int modPriority = curPriority-modifier;
- if (modPriority < 1)
+ if (modPriority < 1)
modPriority = 1;
- if (modPriority > effectivePriority)
- {
- effectivePriority = modPriority;
- actualPriority = curPriority;
- bestEnemy = theEnemy;
- }
- if (modPriority == effectivePriority && curPriority > actualPriority)
+ const Bool takesLead = modPriority > effectivePriority ||
+ (modPriority == effectivePriority && curPriority > actualPriority);
+ if (takesLead && AI_filtersAllow(filters + numGatherFilters, theEnemy))
{
effectivePriority = modPriority;
actualPriority = curPriority;
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
index f06440b07..563e3f58b 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
@@ -618,7 +618,7 @@ void Path::optimize( const Object *obj, LocomotorSurfaceTypeMask acceptableSurfa
The straightening still covers the whole path - the anchor advances and the next step
looks another thirty-two nodes on - it just cannot pay for the entire remaining route in
one step any more. Thirty-two cells is longer than a unit drives in a second. */
- const Int MAX_OPTIMIZE_LOOKAHEAD = 100000; // TEMP: cap off, isolating the early-out
+ const Int MAX_OPTIMIZE_LOOKAHEAD = 32;
for (node = anchor->getNext(); node->getNext(); node=node->getNext()) {
count++;
if (count >= MAX_OPTIMIZE_LOOKAHEAD) {
@@ -757,7 +757,7 @@ void Path::optimizeGroundPath( Bool crusher, Int pathDiameter )
The straightening still covers the whole path - the anchor advances and the next step
looks another thirty-two nodes on - it just cannot pay for the entire remaining route in
one step any more. Thirty-two cells is longer than a unit drives in a second. */
- const Int MAX_OPTIMIZE_LOOKAHEAD = 100000; // TEMP: cap off, isolating the early-out
+ const Int MAX_OPTIMIZE_LOOKAHEAD = 32;
for (node = anchor->getNext(); node->getNext(); node=node->getNext()) {
count++;
if (count >= MAX_OPTIMIZE_LOOKAHEAD) {
@@ -1008,6 +1008,34 @@ void Path::computePointOnPath(
CRCDEBUG_LOG(("Path::computePointOnPath() end because we're really close\n"));
return;
}
+
+ /* A unit that is driving, not standing, used to miss the cache above every frame and pay for the
+ whole answer again: a check of the next twenty cells of road, twenty-five cells around each
+ one, for every moving unit, every frame. In a 530-unit battle that was the single most
+ expensive thing in the game. The steering point is a node well ahead of the unit, and half a
+ cell of driving does not move it, so the answer is kept until the unit has covered that much
+ ground. Near the end of the route, or once the point is close enough to be driven past, it is
+ worked out every frame as before, so arrival and corners are exactly what they were. */
+ if (m_cpopValid && m_cpopCountdown>0)
+ {
+ const Real CPOP_REUSE_DRIVEN = PATHFIND_CELL_SIZE_F * 0.5f;
+ const Real CPOP_REUSE_MIN_AHEAD = PATHFIND_CELL_SIZE_F * 2.0f;
+ const Real CPOP_REUSE_MIN_REMAINING = PATHFIND_CELL_SIZE_F * 4.0f;
+ const Real drivenX = pos.x - m_cpopIn.x;
+ const Real drivenY = pos.y - m_cpopIn.y;
+ const Real drivenSqr = drivenX*drivenX + drivenY*drivenY;
+ const Real aheadX = m_cpopOut.posOnPath.x - pos.x;
+ const Real aheadY = m_cpopOut.posOnPath.y - pos.y;
+ if (drivenSqr < sqr(CPOP_REUSE_DRIVEN)
+ && aheadX*aheadX + aheadY*aheadY > sqr(CPOP_REUSE_MIN_AHEAD)
+ && m_cpopOut.distAlongPath > CPOP_REUSE_MIN_REMAINING)
+ {
+ out = m_cpopOut;
+ out.distAlongPath -= (Real)sqrt(drivenSqr);
+ m_cpopCountdown--;
+ return;
+ }
+ }
m_cpopCountdown = MAX_CPOP;
// default pathPos to end of the path
@@ -2879,6 +2907,9 @@ static Bool s_stopForceCalling = FALSE;
void PathfindZoneManager::calculateZones( PathfindCell **map, PathfindLayer layers[], const IRegion2D &globalBounds )
{
PathProfileInner pfProfile( PF_ZONES );
+ __int64 zoneTicksPerSecond = 0, zoneStart = 0, zoneCellsDone = 0, zoneBlocksDone = 0, zoneEnd = 0;
+ QueryPerformanceFrequency((LARGE_INTEGER *)&zoneTicksPerSecond);
+ QueryPerformanceCounter((LARGE_INTEGER *)&zoneStart);
#ifdef DEBUG_QPF
#if defined(DEBUG_LOGGING)
@@ -2959,6 +2990,7 @@ void PathfindZoneManager::calculateZones( PathfindCell **map, PathfindLayer laye
}
}
+ QueryPerformanceCounter((LARGE_INTEGER *)&zoneCellsDone);
Int totalZones = m_maxZone;
// The merges above left a union-find forest; the collapse below indexes the array directly.
pathfindZoneFlatten(zoneEquivalency, totalZones);
@@ -3128,6 +3160,7 @@ void PathfindZoneManager::calculateZones( PathfindCell **map, PathfindLayer laye
m_zoneBlocks[xBlock][yBlock].blockCalculateZones(map, layers, bounds);
}
}
+ QueryPerformanceCounter((LARGE_INTEGER *)&zoneBlocksDone);
@@ -3416,6 +3449,18 @@ void PathfindZoneManager::calculateZones( PathfindCell **map, PathfindLayer laye
}
}
#endif
+ QueryPerformanceCounter((LARGE_INTEGER *)&zoneEnd);
+ const Real SLOW_ZONES_MS = 10.0f;
+ const Real zoneTotalMS = 1000.0f * (Real)(zoneEnd - zoneStart) / (Real)zoneTicksPerSecond;
+ if (zoneTotalMS > SLOW_ZONES_MS) {
+ DEBUG_LOG(("SLOW ZONES frame %d: %.1fms | cells %.1f | blocks %.1f (%dx%d) | hierarchy %.1f | %d zones, %d allocated\n",
+ TheGameLogic->getFrame(), zoneTotalMS,
+ 1000.0f * (Real)(zoneCellsDone - zoneStart) / (Real)zoneTicksPerSecond,
+ 1000.0f * (Real)(zoneBlocksDone - zoneCellsDone) / (Real)zoneTicksPerSecond,
+ xCount, yCount,
+ 1000.0f * (Real)(zoneEnd - zoneBlocksDone) / (Real)zoneTicksPerSecond,
+ (Int)m_maxZone, (Int)m_zonesAllocated));
+ }
m_nextFrameToCalculateZones = 0xffffffff;
}
@@ -4851,8 +4896,12 @@ void Pathfinder::claimPathTiming( const Object *obj, Path *path )
Int radius = 0;
Bool center = true;
getRadiusAndCenter(obj, radius, center);
+ /* Capped at one cell either side, not two. A claim is read by a search deciding whether a crossing
+ is busy, and three cells of a tank's width answer that as well as five; five cost 25 table
+ writes per sample against 9, three times a sample, for every vehicle once a second, and in a
+ 530-unit battle the stamping was a twentieth of the game. */
Int dilation = radius;
- if (dilation > 2) dilation = 2;
+ if (dilation > 1) dilation = 1;
if (dilation < 0) dilation = 0;
// one sample per body width: a tank stamping every cell would claim the same ground five times
const Int stride = dilation > 0 ? dilation : 1;
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
index 2c797a2db..43a25740b 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
@@ -68,6 +68,7 @@
#include "GameLogic/PartitionManager.h"
#include "Common/ActionManager.h" // canCaptureBuilding, for the tech buildings
#include "GameLogic/Module/SpecialPowerModule.h" // ... and the module that does it
+#include <map>
#ifdef _INTERNAL
// for occasional debugging...
@@ -244,6 +245,19 @@ static Int64 theAIBaseSubStart;
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
+/* How long one unit template takes to kill another, read off template data alone (see
+ templateFramesToKill). selectTeamToBuild asks it for every unit of every candidate team against
+ every kind of enemy in sight, both ways round, and each answer walks module names, weapon sets and
+ armour: an eight-player match spent 84ms of one frame there. Nothing it reads changes during a
+ match, so the answer is kept. The destructor empties it, because the next match can free a template
+ and hand its address to another. */
+typedef std::pair<const ThingTemplate *, const ThingTemplate *> AITemplatePair;
+static std::map<AITemplatePair, Real> theFramesToKillCache;
+// the two questions under it that walk a template's module list by name, kept the same way: the first
+// team choice of a match fills all three at once, and that one choice was the 90ms frame
+static std::map<const ThingTemplate *, Real> theMaxHealthCache;
+static std::map<const ThingTemplate *, Bool> theDetectsStealthCache;
+
AIPlayer::AIPlayer( Player *p ) :
m_player(p),
m_buildDelay(0),
@@ -254,6 +268,7 @@ m_readyToBuildTeam(false),
m_readyToBuildStructure(false),
m_structuresInQueue(0),
m_repairDozer(INVALID_ID),
+m_frameAfterFailedDozerQueue(0),
m_skillsetSelector(INVALID_SKILLSET_SELECTION),
m_dozerQueuedForRepair(false),
m_supplySourceAttackCheckFrame(0),
@@ -261,6 +276,7 @@ m_attackedSupplyCenter(INVALID_ID),
m_teamSeconds(10),
m_curWarehouseID(INVALID_ID),
m_buildProbeOffset(0.0f),
+m_buildProbeSkip(0),
m_scoutTimer(1),
m_retreatTimer(1),
m_expandTimer(1),
@@ -362,6 +378,9 @@ m_role(AIROLE_AGGRESSIVE)
AIPlayer::~AIPlayer()
{
clearTeamsInQueue();
+ theFramesToKillCache.clear();
+ theMaxHealthCache.clear();
+ theDetectsStealthCache.clear();
}
// ------------------------------------------------------------------------------------------------
@@ -890,19 +909,31 @@ Object *AIPlayer::buildStructureWithDozer(const ThingTemplate *bldgPlan, BuildLi
sampling as well - while the outer rings are mostly off the map and are rejected on
the first line. A budget of 100 left a 19.7ms frame made of about 120 inner
positions; at 32 the first frame walks three rings and the worst frame this can cost
- is either those, or one whole outer ring of 240 cheap ones. */
+ is either those, or one whole outer ring of 240 cheap ones.
+
+ That last claim was wrong. A four-player match on 2026-09-15 spent 20 to 37ms of eight
+ logic frames in a row here, and a timer put inside the loop showed why: the budget was
+ only checked between rings, and a ring 72 to 104 cells out holds 152 to 216 positions,
+ every one of them finished once started. So the budget is checked before every pair
+ of positions now, and the pair it stopped at is kept beside the ring, which is still
+ the same order and still the same spot. */
const Int BUILD_PROBES_PER_FRAME = 32;
Int probes = 0;
Bool outOfBudget = false;
Real firstOffset = 0;
- if (m_buildProbeOffset > 0 &&
+ Int skipPairs = 0;
+ if ((m_buildProbeOffset > 0 || m_buildProbeSkip > 0) &&
m_buildProbePos.x == pos.x && m_buildProbePos.y == pos.y) {
firstOffset = m_buildProbeOffset; // same spot as last frame: carry on from there
+ skipPairs = m_buildProbeSkip; // ... from the pair it stopped at inside that ring
}
m_buildProbePos = pos;
m_buildProbeOffset = 0;
+ m_buildProbeSkip = 0;
for (posOffset = firstOffset; posOffset<limit; posOffset += 2*PATHFIND_CELL_SIZE_F) {
+ const Real ringOffset = posOffset;
+ Int pair = 0;
if (probes >= BUILD_PROBES_PER_FRAME) {
// out of budget with rings left to walk: pick this one up again next frame
m_buildProbeOffset = posOffset;
@@ -917,6 +948,14 @@ Object *AIPlayer::buildStructureWithDozer(const ThingTemplate *bldgPlan, BuildLi
yPos = pos.y-offset;
for (xPos = pos.x-offset; xPos <= pos.x+offset; xPos+=PATHFIND_CELL_SIZE_F) {
if (isSkirmishAI()) xPos += PATHFIND_CELL_SIZE_F;
+ if (skipPairs > 0) { --skipPairs; ++pair; continue; } // tried last frame
+ if (probes >= BUILD_PROBES_PER_FRAME) {
+ m_buildProbeOffset = ringOffset;
+ m_buildProbeSkip = pair;
+ outOfBudget = true;
+ break;
+ }
+ ++pair;
probes += 2;
newPos.x = xPos;
newPos.y = yPos;
@@ -933,10 +972,18 @@ Object *AIPlayer::buildStructureWithDozer(const ThingTemplate *bldgPlan, BuildLi
BuildAssistant::NO_OBJECT_OVERLAP,
dozer, m_player ) == LBC_OK;
}
- if (valid) break;
+ if (valid || outOfBudget) break;
xPos = pos.x-offset;
for (yPos = pos.y-offset; yPos <= pos.y+offset; yPos+=PATHFIND_CELL_SIZE_F) {
if (isSkirmishAI()) yPos += PATHFIND_CELL_SIZE_F;
+ if (skipPairs > 0) { --skipPairs; ++pair; continue; } // tried last frame
+ if (probes >= BUILD_PROBES_PER_FRAME) {
+ m_buildProbeOffset = ringOffset;
+ m_buildProbeSkip = pair;
+ outOfBudget = true;
+ break;
+ }
+ ++pair;
probes += 2;
newPos.x = xPos;
newPos.y = yPos;
@@ -953,7 +1000,7 @@ Object *AIPlayer::buildStructureWithDozer(const ThingTemplate *bldgPlan, BuildLi
BuildAssistant::NO_OBJECT_OVERLAP,
dozer, m_player ) == LBC_OK;
}
- if (valid) break;
+ if (valid || outOfBudget) break;
}
if (valid) pos = newPos;
if (!valid && outOfBudget) {
@@ -2028,7 +2075,7 @@ Bool AIPlayer::selectTeamToReinforce( Int minPriority )
/** The health a unit template is built with. Every body module that can be hurt keeps it in
* ActiveBodyModuleData; the one that cannot, InactiveBody, is not on the list and answers zero. */
//-------------------------------------------------------------------------------------------------
-static Real templateMaxHealth( const ThingTemplate *tmpl )
+static Real computeTemplateMaxHealth( const ThingTemplate *tmpl )
{
static const char *BODIES_WITH_HEALTH[] =
{ "ActiveBody", "StructureBody", "HiveStructureBody", "UndeadBody", "HighlanderBody", "ImmortalBody", NULL };
@@ -2045,6 +2092,37 @@ static Real templateMaxHealth( const ThingTemplate *tmpl )
return 0.0f;
}
+static Real templateMaxHealth( const ThingTemplate *tmpl )
+{
+ std::map<const ThingTemplate *, Real>::const_iterator known = theMaxHealthCache.find( tmpl );
+ if( known != theMaxHealthCache.end() )
+ return known->second;
+ const Real health = computeTemplateMaxHealth( tmpl );
+ theMaxHealthCache[ tmpl ] = health;
+ return health;
+}
+
+/** "Can it see stealth" is not a KindOf - it is a module the data hangs on the unit, so ask the
+ * template's module list by name, once per template. */
+static Bool templateDetectsStealth( const ThingTemplate *tmpl )
+{
+ std::map<const ThingTemplate *, Bool>::const_iterator known = theDetectsStealthCache.find( tmpl );
+ if( known != theDetectsStealthCache.end() )
+ return known->second;
+ Bool detects = FALSE;
+ const ModuleInfo &modules = tmpl->getBehaviorModuleInfo();
+ for( Int m = 0; m < modules.getCount(); ++m )
+ {
+ if( modules.getNthName( m ).compareNoCase( "StealthDetectorUpdate" ) == 0 )
+ {
+ detects = TRUE;
+ break;
+ }
+ }
+ theDetectsStealthCache[ tmpl ] = detects;
+ return detects;
+}
+
// ponytail: an aircraft that empties its clip flies home to rearm; a flat twenty seconds stands in
// for the trip, until a measured sortie replaces it
static const Real AI_SORTIE_FRAMES = 20.0f * LOGICFRAMES_PER_SECOND;
@@ -2114,7 +2192,7 @@ static Bool shotPatternAgainst( const WeaponTemplate *weapon, const ThingTemplat
//-------------------------------------------------------------------------------------------------
/** Frames one unit template needs to kill another, with the best weapon it carries against it. */
//-------------------------------------------------------------------------------------------------
-static Real templateFramesToKill( const ThingTemplate *attacker, const ThingTemplate *target )
+static Real computeTemplateFramesToKill( const ThingTemplate *attacker, const ThingTemplate *target )
{
if( attacker->getWeaponTemplateSets().empty() )
return AI_CANNOT_KILL; // a dozer, a supply truck: the data gives it nothing to shoot with
@@ -2136,6 +2214,17 @@ static Real templateFramesToKill( const ThingTemplate *attacker, const ThingTemp
return best;
}
+static Real templateFramesToKill( const ThingTemplate *attacker, const ThingTemplate *target )
+{
+ const AITemplatePair key( attacker, target );
+ std::map<AITemplatePair, Real>::const_iterator known = theFramesToKillCache.find( key );
+ if( known != theFramesToKillCache.end() )
+ return known->second;
+ const Real frames = computeTemplateFramesToKill( attacker, target );
+ theFramesToKillCache[ key ] = frames;
+ return frames;
+}
+
//-------------------------------------------------------------------------------------------------
/** Count one visible enemy unit into the army: one entry per kind of unit, in the order first seen. */
//-------------------------------------------------------------------------------------------------
@@ -2177,20 +2266,10 @@ static AITeamCapability teamCapability( const TeamPrototype *proto, const Player
if( tmpl == NULL )
continue; // a map's team naming a unit this game does not have
- //
- // "Can it see stealth" is not a KindOf - it is a module the data hangs on the unit, so ask the
- // template's module list by name. That is the same question the game itself answers when it
- // builds the object, one INI edit away from being right for a mod's own detector.
- //
- const ModuleInfo &modules = tmpl->getBehaviorModuleInfo();
- for( Int m = 0; m < modules.getCount(); ++m )
- {
- if( modules.getNthName( m ).compareNoCase( "StealthDetectorUpdate" ) == 0 )
- {
- cap.m_detectsStealth = TRUE;
- break;
- }
- }
+ // the same question the game itself answers when it builds the object, one INI edit away from
+ // being right for a mod's own detector
+ if( templateDetectsStealth( tmpl ) )
+ cap.m_detectsStealth = TRUE;
const Int minUnits = info->m_unitsInfo[ i ].minUnits;
const Real fielded = INT_TO_REAL( minUnits > 1 ? minUnits : 1 );
@@ -4155,6 +4234,18 @@ void AIPlayer::doExpansion( void )
if( supplyCenterName.isEmpty() )
return;
+ //
+ // A centre queued by the last check and not yet standing does not count as "a centre beside that
+ // dock", so the same dock was picked again every minute, a fresh copy queued, and its placement
+ // search run again: 2,300 checks, 23-33ms, each time. The base builder still owns the queued one.
+ //
+ for( BuildListInfo *info = m_player->getBuildList(); info; info = info->getNext() )
+ {
+ if( info->isPriorityBuild() && info->getTemplateName() == supplyCenterName &&
+ info->getObjectID() == INVALID_ID && info->isBuildable() )
+ return;
+ }
+
const ThingTemplate *tmpl = TheThingFactory->findTemplate( supplyCenterName, FALSE );
if( tmpl == NULL )
return;
@@ -5624,6 +5715,13 @@ void AIPlayer::queueDozer( void )
{
if (dozerInQueue()) return;
+ /* A player with no factory that can make a dozer walks every thing template in the game here and
+ finds nothing, and base building asks once per missing build-list entry: 33 walks and 13ms in
+ one pass of a late 4v4, every two seconds. Nothing a factory needs can change between two calls
+ in the same frame, so the answer is kept for the frame. */
+ const UnsignedInt frameAfterNow = TheGameLogic->getFrame() + 1;
+ if (m_frameAfterFailedDozerQueue == frameAfterNow) return;
+ m_frameAfterFailedDozerQueue = frameAfterNow;
// Find a factory that can build a dozer.
Bool canBuildUnits = m_player->getCanBuildUnits();
@@ -5699,78 +5797,81 @@ const AIDifficultyProfile *AIPlayer::getSkillProfile( void ) const
/**
* Finds a dozer that isn't building or collecting resources.
*/
-Object * AIPlayer::findDozer( const Coord3D *pos )
+struct FindDozerSearch
{
- // Add any factories placed to the build list.
- Object *obj;
- Object *dozer = NULL;
- Bool needDozer = true;
- Object *closestDozer=NULL;
- Real closestDistSqr = 0;
+ const Coord3D *pos;
+ ObjectID repairDozer;
+ Bool needDozer;
+ Object *dozer;
+ Object *closestDozer;
+ Real closestDistSqr;
+};
- for( obj = TheGameLogic->getFirstObject(); obj; obj = obj->getNextObject() )
- {
-
- Player *owner = obj->getControllingPlayer();
- if (owner==m_player) {
- // See if it's a dozer.
- if (obj->isKindOf(KINDOF_DOZER)) {
+static void considerDozer( Object *obj, void *userData )
+{
+ FindDozerSearch *search = (FindDozerSearch *)userData;
+ if (!obj->isKindOf(KINDOF_DOZER))
+ return;
- AIUpdateInterface *ai = obj->getAIUpdateInterface();
- if (ai==NULL) {
- continue;
- }
+ AIUpdateInterface *ai = obj->getAIUpdateInterface();
+ if (ai==NULL)
+ return;
+ DozerAIInterface* dozerAI = ai->getDozerAIInterface();
+ if (!dozerAI)
+ return;
- DozerAIInterface* dozerAI = ai->getDozerAIInterface();
- if (dozerAI) {
- // Since workers can be dozers, hmmm....
- SupplyTruckAIInterface* supplyTruckAI = ai->getSupplyTruckAIInterface();
- if( !dozerAI->isAnyTaskPending() && supplyTruckAI ) {
- // If it is gathering supplies, don't steal it.
- if (supplyTruckAI->isCurrentlyFerryingSupplies() || supplyTruckAI->isForcedIntoWantingState())
- {
- continue;
- }
- }
- if (obj->getID() == m_repairDozer) {
- continue; // don't steal the repair dozer.
- }
- needDozer = false; // dozer exists, may be busy.
- if (dozerAI->isTaskPending(DOZER_TASK_BUILD)) {
- continue; // already building.
- }
- if (!dozerAI->isAnyTaskPending()) {
- dozer = obj; // prefer an idle dozer
- }
- if (dozer==NULL) {
- dozer = obj; // but we'll take one doing stuff.
- }
- if (dozer && !dozerAI->isAnyTaskPending()) {
- // Got a good one, track closest.
- Real distSqr;
- Real dx, dy;
- dx = pos->x - dozer->getPosition()->x;
- dy = pos->y - dozer->getPosition()->y;
- distSqr = dx*dx+dy*dy;
- if (closestDozer == NULL) {
- closestDozer = dozer;
- closestDistSqr = distSqr;
- } else if (distSqr < closestDistSqr) {
- closestDozer = dozer;
- closestDistSqr = distSqr;
- }
- }
- }
- }
+ // Since workers can be dozers, hmmm....
+ SupplyTruckAIInterface* supplyTruckAI = ai->getSupplyTruckAIInterface();
+ if( !dozerAI->isAnyTaskPending() && supplyTruckAI ) {
+ // If it is gathering supplies, don't steal it.
+ if (supplyTruckAI->isCurrentlyFerryingSupplies() || supplyTruckAI->isForcedIntoWantingState())
+ return;
+ }
+ if (obj->getID() == search->repairDozer)
+ return; // don't steal the repair dozer.
+
+ search->needDozer = false; // dozer exists, may be busy.
+ if (dozerAI->isTaskPending(DOZER_TASK_BUILD))
+ return; // already building.
+
+ if (!dozerAI->isAnyTaskPending())
+ search->dozer = obj; // prefer an idle dozer
+ if (search->dozer==NULL)
+ search->dozer = obj; // but we'll take one doing stuff.
+
+ if (search->dozer && !dozerAI->isAnyTaskPending()) {
+ // Got a good one, track closest.
+ const Real dx = search->pos->x - search->dozer->getPosition()->x;
+ const Real dy = search->pos->y - search->dozer->getPosition()->y;
+ const Real distSqr = dx*dx+dy*dy;
+ if (search->closestDozer == NULL || distSqr < search->closestDistSqr) {
+ search->closestDozer = search->dozer;
+ search->closestDistSqr = distSqr;
}
-
}
- if (needDozer) {
+}
+
+/* Walks this player's own objects rather than every object in the game. The skirmish AI asks once per
+ missing build-list entry, so a late 4v4 walked the whole world twenty times in one frame here:
+ 27ms of a 50ms base-building pass. The player's own list is a few dozen objects. */
+Object * AIPlayer::findDozer( const Coord3D *pos )
+{
+ FindDozerSearch search;
+ search.pos = pos;
+ search.repairDozer = m_repairDozer;
+ search.needDozer = true;
+ search.dozer = NULL;
+ search.closestDozer = NULL;
+ search.closestDistSqr = 0;
+
+ m_player->iterateObjects( considerDozer, &search );
+
+ if (search.needDozer) {
queueDozer();
}
- if (closestDozer) return closestDozer;
- return dozer;
+ if (search.closestDozer) return search.closestDozer;
+ return search.dozer;
}
// ------------------------------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp
index 599bd6f5f..d95f9ae75 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp
@@ -199,6 +199,16 @@ void AISkirmishPlayer::processBaseBuilding( void )
if (bldg) {
continue; // already built.
}
+ // The safety check below is a range query over everything near the spot, most of a
+ // millisecond each late in a 4v4, and it ran for every unbuilt entry on every pass (36 of
+ // them, 28ms, in one frame). An entry that cannot change what this pass picks skips it.
+ const Bool couldBePriority = info->isPriorityBuild() && !isPriority;
+ const Bool couldBePower = powerPlan==NULL && curPlan->isKindOf(KINDOF_FS_POWER) &&
+ !curPlan->isKindOf(KINDOF_CASH_GENERATOR) && (isUnderPowered || info->isAutomaticBuild());
+ const Bool couldBeBuilt = bldgPlan==NULL && info->isAutomaticBuild() && info->isBuildable();
+ if (!couldBePriority && !couldBePower && !couldBeBuilt) {
+ continue;
+ }
// Make sure it is safe to build here.
AIPlayer::profileBaseSubBegin();
const Bool locationSafe = isLocationSafe(info->getLocation(), curPlan);
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
index ffaf5207b..30c3e9b92 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
@@ -5731,8 +5731,6 @@ StateReturnType AIAttackFireWeaponState::onEnter()
}
}
- m_saidHeldFire = FALSE;
-
obj->setStatus( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_IS_FIRING_WEAPON ) );
obj->preFireCurrentWeapon( getMachineGoalObject() );
return STATE_CONTINUE;
@@ -5822,18 +5820,7 @@ StateReturnType AIAttackFireWeaponState::update()
// damage lapses on its own if the shot never lands, so nothing holds fire forever.
//
if (IncomingDamageTracker::isSpokenFor(victim, obj->getID()))
- {
- if (!m_saidHeldFire)
- {
- m_saidHeldFire = TRUE;
- DEBUG_LOG(("held fire: %s holds, %s has %.0f left and %.0f is already in the air\n",
- obj->getTemplate()->getName().str(),
- victim->getTemplate()->getName().str(),
- victim->getBodyModule()->getHealth(),
- IncomingDamageTracker::getBookedDamage(victim->getID())));
- }
return STATE_FAILURE;
- }
// still ours to take, so keep saying so: the wind-up before a shot can run for a second and
// nothing is in the air during it
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
index c7094c9e2..76be16de7 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
@@ -3344,6 +3344,36 @@ Object *PartitionManager::getClosestObjects(
static Int theIterFlag = 1; // nonzero, thanks
++theIterFlag;
+ /* A gathering query keeps everything in range in whatever order it finds it, and the caller sorts
+ afterwards. When the range covers the whole map the ring walk below still steps through every
+ cell offset either side of the centre, four times the map's cells and most of them off it: a
+ hunting unit's whole-map search spent 15-33ms there to find 3,600 objects. The master module
+ list holds exactly the objects that sit in cells, so walking it gathers the same set. */
+ if (iterArg && maxRadius >= m_maxGcoRadius)
+ {
+ for (PartitionData *thisMod = m_moduleList; thisMod; thisMod = thisMod->getNext())
+ {
+ if (thisMod->friend_getCoiInUseCount() == 0)
+ continue;
+
+ Object *thisObj = thisMod->getObject();
+ ++thePartitionQueryObjects;
+ if (thisObj == obj || thisObj == NULL)
+ continue;
+
+ Real thisDistSqr;
+ Coord3D distVec;
+ if (!(*distProc)(objPos, objToUse, thisObj->getPosition(), thisObj, thisDistSqr, distVec, closestDistSqr))
+ continue;
+
+ if (!filtersAllow(filters, thisObj))
+ continue;
+
+ iterArg->insert(thisObj, thisDistSqr);
+ }
+ maxRadiusLimit = -1; // nothing left for the ring walk to find
+ }
+
/*
m_radiusVec[curRadius] contains a list of the cells (foo) that could
contain objects that are <= (curRadius * cellSize) distance away from cell (0,0).