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.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
feat(gameengine): log what the AI sends out and what it loses alone
Olcay Seygan6b9d1c297562
diff --git a/GeneralsMD/Code/Data/Scenarios/overlordrush.txt b/GeneralsMD/Code/Data/Scenarios/overlordrush.txtnew file mode 100644index 000000000..a8f673669--- /dev/null+++ b/GeneralsMD/Code/Data/Scenarios/overlordrush.txt@@ -0,0 +1,47 @@+# Overlord rush: a player who builds nothing but Overlords, against a Hard AI playing a whole game.+#+# The owner's complaint, staged: a player with ten Overlords walks into a Hard AI and wins, because the+# AI never answers an army made of one unit. Seat 0 is driverless (-takeover 0) and gets its Overlords+# from this file, a few at a time beside its own base, where they stay and guard it the way a player's+# would until there are ten; then all of them go at the AI's start together, and the ones built after+# follow in groups. Seat 1 is a Hard AI that builds, scouts and attacks as in any match. The AI wins by+# taking seat 0's base, which it only reaches by beating the Overlords and the tanks left at home.+#+# generals.exe -headless -quickstart -noshellmap -observer -multiInstance -noFPSLimit+# -map "Maps\Winter Wolf\Winter Wolf.map" -autoskirmish 2 -takeover 0 -aidiff hard+# -side 0 FactionChina -side 1 FactionAmerica -seed 1 -maxframes 36000+# -scenario overlordrush -logPrefix orush_+#+# or through the batch: .\ai-batch.ps1 -Scenario overlordrush -Takeover 0 -Map "Winter Wolf"+# -Sides FactionChina,FactionGLA -MaxFrames 36000+#+# HEADLESS VALUE says what each side's units cost and what they killed; AI ENGAGE and AI LOSS lines+# say what the AI sent and what died alone. Twenty Overlords by frame 12000, ten more at 18000 and ten+# at 24000: 80,000 of army, and ten tanks at home worth 8,000.+#+# The AI wins this every time, and the file is kept for what the AI pays to win it, not whether it+# does. On 2026-10-09, two seeds a faction on Winter Wolf and Tournament Desert, the Hard AI before the+# fight-choosing changes won 12 of 12 at every size tried: batches of 5, 7, 9 and 11 sent 4000 frames+# apart, a fist of 10 then two of 6, a fist of 16 then two of 8, and this one. Its base defences+# stop an attack-move on its start, which no player would make twice. Here it lost 0.49 to 0.75 of+# what it killed, and 13 to 27% of its team deaths were units dying away from a team still alive.++# a few tanks at home, so the AI has to beat the Overlords to win rather than walk round them+30 spawn 0 ChinaTankBattleMaster 6 start0:0:200 50+30 spawn 0 ChinaTankGattling 4 start0:0:200 50++# the fist, built at home+3000 spawn 0 ChinaTankOverlord 4 start0:0:260 60+6000 spawn 0 ChinaTankOverlord 5 start0:0:260 60+9000 spawn 0 ChinaTankOverlord 5 start0:0:260 60+12000 spawn 0 ChinaTankOverlord 6 start0:0:260 60+12030 attackmove 0 ChinaTankOverlord start1++18000 spawn 0 ChinaTankOverlord 10 start0:0:260 60+18030 attackmove 0 ChinaTankOverlord start1++24000 spawn 0 ChinaTankOverlord 10 start0:0:260 60+24030 attackmove 0 ChinaTankOverlord start1++# survivors sitting in the ruins of the AI's base go on to whatever is left of it+30000 attackmove 0 ChinaTankOverlord start1diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.hindex c14d447af..1648b675c 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h@@ -110,6 +110,14 @@ enum TextLanguageTypeTEXT_LANGUAGE_COUNT = 3,};+/** The AI profile knobs -aiknobsoff can switch off for a measurement. */+enum+{+ AIKNOB_ENGAGE_GATE = 1,+ AIKNOB_ANSWER_ARMY = 2,+ AIKNOB_MASS_UNIT = 4,+};+//-------------------------------------------------------------------------------------------------/** Global data container class* Defines all global game data used by the system@@ -467,6 +475,8 @@ public:Bool m_turbo; ///< -turbo: draw, but run one logic frame a pass instead of pacing it to the wall clockInt m_autoSkirmishAIStateOdd; ///< -aidiff2 <name>: rung for the odd-numbered slots (0 = same as -aidiff)Int m_noTacticsSlotParity; ///< -notactics even|odd: those slots of a skirmish fight without Hard's unit tactics; -1 none+ Int m_aiKnobsOffParity; ///< -aiknobsoff even|odd|all <names>: those slots of a skirmish play with these profile knobs off; -1 none, 2 all+ Int m_aiKnobsOffMask; ///< ... which knobs: AIKNOB_* bitsInt m_autoSkirmishTeams; ///< -teams <n>: split the auto-skirmish slots into n allied teams (0 or 1 = free-for-all)Int m_peaceTime; ///< -peacetime <n>: the lobby's peace time, in minutes, for an -autoskirmish runBool m_unitLimit; ///< -unitlimit: the lobby's unit limit for an -autoskirmish run@@ -503,6 +513,7 @@ public:AsciiString m_scenarioFile; ///< -scenario <name>: play Run/Scenarios/<name>.txt instead of leaving the match to a person or an AI (empty = off)AsciiString m_cinemaScript; ///< -cinema <name>: interface off, camera flown by Run/Cinema/<name>.txt (empty = off)Bool m_autoSkirmishTakeover; ///< -takeover: give every -autoskirmish slot a driverless human seat, so nothing thinks unless a scenario says so+ Int m_autoSkirmishTakeoverSlot; ///< -takeover <slot>: only that seat is driverless and the AI plays the rest; -1 for every seatAsciiString m_autoSkirmishSide[ MAX_PLAYER_COUNT ]; ///< -side <slot> <faction>: name that slot's faction instead of drawing it from the seedInt m_autoSkirmishTeam[ MAX_PLAYER_COUNT ]; ///< -team <slot> <n>: that slot's team, -1 for none; AUTO_SKIRMISH_TEAM_UNSET leaves it to -teamsAsciiString m_autoSkirmishSeatName[ MAX_PLAYER_COUNT ]; ///< -seatname <slot> <name>: what that seat is called instead of its difficultydiff --git a/GeneralsMD/Code/GameEngine/Include/Common/Player.h b/GeneralsMD/Code/GameEngine/Include/Common/Player.hindex f273637eb..fe1a3747c 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/Player.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/Player.h@@ -623,6 +623,12 @@ public:/// TRUE when the AI parks this team to go out with the rest of its wave instead of on its own.Bool holdTeamForWave(Team *team, const AsciiString &approach, Int pathSuffix);+ /// TRUE when the AI parks this team instead of letting a script send it hunting or at an area from home.+ Bool gateTeamAttack(Team *team, const char *cause);++ /// One of this player's units died; the AI keeps count of the ones that died alone.+ void onUnitLost(const Object *obj);+/// Get the center of the ai's base.virtual Bool getAiBaseCenter(Coord3D *pos);diff --git a/GeneralsMD/Code/GameEngine/Include/Common/ScoreKeeper.h b/GeneralsMD/Code/GameEngine/Include/Common/ScoreKeeper.hindex 517c2d43b..210d3352f 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/ScoreKeeper.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/ScoreKeeper.h@@ -97,6 +97,8 @@ public:Int getTotalFactionBuildingsCaptured( void ) { return m_totalFactionBuildingsCaptured; }Int getTotalObjectsBuilt( const ThingTemplate *pTemplate ); // get a count of objects built matching a specific thing templateconst ThingTemplate *getMostBuiltUnit( void ) const; ///< the fighting unit built most often, or NULL before the first+ Int getUnitValueLost( void ) const; ///< what the units this player lost cost it, buildings left out+ Int getUnitValueDestroyed( void ) const; ///< what the enemy units it killed cost their owners// for battle honor calculation. done once at the end of each online gameInt getTotalUnitsBuilt( KindOfMaskType validMask, KindOfMaskType invalidMask );@@ -131,7 +133,8 @@ private:ObjectCountMap m_objectsLost; ///< how many and what kinds of objects did we looseObjectCountMap m_objectsCaptured;void xferObjectCountMap( Xfer *xfer, ObjectCountMap *map );-+ static Int unitValueOf( const ObjectCountMap &map, Int ownerIdx );+};//-----------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.hindex c6ec1a936..f392fda84 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h@@ -209,6 +209,11 @@ struct AIDifficultyProfile// Fighting: decisions only, from what it knows can shoot whereBool m_tacticalMicro; ///< kite what it outranges, take the high ground, pull hurt units out++ // Choosing fights: what it remembers of the enemy army, not only what is in sight+ Bool m_engageGate; ///< weigh a fight by unit against unit, not money alone; nothing leaves home on its own+ Bool m_answerArmy; ///< remember the enemy army it has seen, and train the answer to the biggest part of it+ Bool m_massUnit; ///< pick one unit the enemy has no answer to, build a fist of it and hit with it};//-------------------------------------------------------------------------------------------------@@ -291,6 +296,12 @@ Real aiFramesToKill( Real targetHealth, const AIShotPattern &shots );* faster for its price (or cannot be hurt back), 0 when it cannot hurt the other side. */Real aiMatchupScore( Real myFramesToKill, Real theirFramesToKill, Real myCost, Real theirCost );+/** How one army's mix trades against another's, money for money: 1 an even trade, above 1 when my+ * money kills theirs faster than theirs kills mine, clamped to 1/16..16. score holds myKinds rows of+ * theirKinds entries, aiMatchupScore of my kind i against their kind j, and each side's values weigh+ * its kinds. Ten Overlords against ten Crusaders cost the same and are not the same fight. */+Real aiArmyAdvantage( const Real *myValue, Int myKinds, const Real *theirValue, Int theirKinds, const Real *score );+/** How the exchange is going, as the ratio of how long this force lasts to how long it needs to* kill what is shooting at it. Below 1 it is losing; below the rung's retreatTtkRatio it should* break off. This is Sins of a Solar Empire's aiRetreatThreshold, and it is the right metricdiff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.hindex 205c220c9..d6c6961d0 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h@@ -37,6 +37,7 @@#include "GameLogic/AI.h" // AISkillLevel, AIRole and the difficulty profile the ladder reads#include "Common/GameCommon.h" // MAX_PLAYER_COUNT, for the per-enemy scouting stamps#include "GameLogic/AIInfluenceMap.h"+#include <map>enum { INVALID_SKILLSET_SELECTION = -1 };@@ -227,8 +228,13 @@ public: // AIPlayer interface, may be overridden by AISkirmishPlayer. jba.* The script's own label when the rung does not read the map, or the label is not one of the three. */AsciiString chooseApproachLabel(const Coord3D *from, const AsciiString &requested, Int pathSuffix);/** C2: park an attack team that is not a wave on its own until the rest of the wave is in hand.- * TRUE when it is parked, and the caller's own order must not go out. */- Bool holdTeamForWave(Team *team, const AsciiString &approach, Int pathSuffix);+ * TRUE when it is parked, and the caller's own order must not go out. logRefusal writes the AI+ * ENGAGE line for a team that goes on its own instead; a caller that logs its own passes FALSE. */+ Bool holdTeamForWave(Team *team, const AsciiString &approach, Int pathSuffix, Bool logRefusal = TRUE);+ /** A script sends this team hunting or at an area: logged, and with EngageGate a team still at+ * home parks for the next wave instead. TRUE when it is parked, and the script's order must not go out. */+ Bool gateTeamAttack(Team *team, const char *cause);+ void onUnitLost(const Object *obj); ///< one of ours died: was it alone, away from a team that is still alive?virtual void repairStructure(ObjectID structure);virtual void selectSkillset(Int skillset);@@ -373,7 +379,12 @@ protected:Real addHomeStrays(AIGroup *wave) const; ///< the default team's fighters idle at home go with the waveReal knownFirepowerNear(const Coord3D *pos); ///< what this AI has seen that can shoot, near a pointBool forwardHoldPoint(const AsciiString &approach, Int pathSuffix, const Coord3D *enemyPos, Coord3D *hold); ///< where a wave gathers on its road- void sendWave(AIGroup *wave, const AsciiString &approach, Int pathSuffix, Int teams, Real power, UnsignedInt heldFrames);+ void sendWave(AIGroup *wave, const AsciiString &approach, Int pathSuffix, Int teams, Real power, UnsignedInt heldFrames, const char *cause);+ void logEngage(const char *cause, const std::vector<Object *> &units); ///< AI ENGAGE: what goes out, and how it weighs against the army it remembers+ Bool refuseHold(Team *team, const char *why, Bool logIt); ///< FALSE, after logging the team holdTeamForWave lets go+ Bool holdReinforcement(Object *obj); ///< a top-up for a team out on the map waits for the next wave instead of walking out alone+ void rememberEnemies(void); ///< bring the seen-enemy ledger up to date with what is in sight now+ void rememberedArmy(std::vector<AIVisibleEnemy> *army) const; ///< the ledger, one entry a kind, weighed by combat powervoid sendWaveThroughTunnels(AIGroup *wave, const Coord3D *center, Waypoint *way); ///< whoever can goes by tunnel when the path is the long way roundvirtual void doBaseBuilding(void);@@ -459,6 +470,7 @@ protected:Player *m_player; ///< the Player we representAISkillLevel m_skillLevel; ///< rung of the ladder: how well this AI plays+ mutable AIDifficultyProfile m_measuredProfile; ///< the rung's profile less the knobs -aiknobsoff turns off for this slotAIRole m_role; ///< what it is trying to do; rolled once, kept for the matchenum { MAX_AI_SCOUTS = 2 }; ///< the ladder's maxScouts never asks for more than this@@ -588,6 +600,19 @@ protected:void sendIdleUnitsHunting(void); ///< attack units idle at the end of their road, and the guards once the enemy is finishedBool holdsTeamsForWaves(void) const; ///< this rung parks attack teams at the current levelBool leavesToFinish(const Object *obj) const; ///< a fighter the last push takes off guard, as against a worker or a scout+ /** Every enemy unit this AI has seen and not since lost track of: what it was, whose, and where and+ * when it was last in sight. An army that walks back into the fog is still an army. A row goes when+ * it has not been seen for LEDGER_FORGET_FRAMES, or when the ground it was last seen on is in sight+ * and it is not there and no longer exists: the AI looked and it was gone. */+ struct SeenEnemy+ {+ const ThingTemplate *tmpl;+ Int owner; ///< player index+ UnsignedInt seen; ///< last frame it was in sight+ Coord3D pos; ///< where+ Bool stealth; ///< it can go invisible+ };+ std::map<ObjectID, SeenEnemy> m_seenEnemies;AIPressure m_pressure;Real m_knownEnemyPower; ///< his army as this AI believes it: what is in sight at least, less for each look at his base that does not find it, more for each look not takenInt m_pressureEnemy; ///< the player index that figure is about, -1 for nobody yetdiff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cppindex c6a915162..e8a2047e9 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp@@ -1221,6 +1221,27 @@ Int parseNoTactics(char *args[], int num)return 2;}+/** -aiknobsoff even|odd|all engagegate,answerarmy,massunit: those slots keep their rung with these knobs+ * of its profile off, so a batch can play Hard against Hard without them, or a scenario against the AI+ * as it was. A measuring aid like -notactics: read only in a single-player skirmish, never in a+ * network game, and a replay made with it is played back with it given again. */+Int parseAIKnobsOff(char *args[], int num)+{+ if (TheWritableGlobalData && num > 2)+ {+ AsciiString parity = args[1];+ TheWritableGlobalData->m_aiKnobsOffParity = parity.compareNoCase("even") == 0 ? 0 : (parity.compareNoCase("odd") == 0 ? 1 : 2);+ AsciiString names = args[2];+ names.toLower();+ Int mask = 0;+ if (strstr(names.str(), "engagegate")) mask |= AIKNOB_ENGAGE_GATE;+ if (strstr(names.str(), "answerarmy")) mask |= AIKNOB_ANSWER_ARMY;+ if (strstr(names.str(), "massunit")) mask |= AIKNOB_MASS_UNIT;+ TheWritableGlobalData->m_aiKnobsOffMask = mask;+ }+ return 3;+}+Int parseObserver(char *args[], int num){if (TheWritableGlobalData)@@ -2102,12 +2123,21 @@ Int parseSeatName(char *args[], int num)it, so Player::setPlayerType never news an AIPlayer and that player sits waiting to be told whatto do. For a measurement that is exactly the point. An AI that builds, expands and attacks costsmore of the frame than whatever is under test, and it costs a different amount every run; with- the seats empty, nothing happens at all unless -scenario says it does. */+ the seats empty, nothing happens at all unless -scenario says it does.++ -takeover <slot> empties that one seat and leaves the AI in the others: a scenario then plays one+ side by hand against a computer that plays the whole game, which is how an AI is asked what it+ does about a given army. */Int parseTakeover(char *args[], int num){if (TheWritableGlobalData){TheWritableGlobalData->m_autoSkirmishTakeover = TRUE;+ if (num > 1 && args[1][0] >= '0' && args[1][0] <= '9')+ {+ TheWritableGlobalData->m_autoSkirmishTakeoverSlot = atoi(args[1]);+ return 2;+ }}return 1;}@@ -2625,6 +2655,7 @@ static CommandLineParam params[] ={ "-aidiff", parseAIDifficulty },{ "-aidiff2", parseAIDifficulty2 },{ "-notactics", parseNoTactics },+ { "-aiknobsoff", parseAIKnobsOff },{ "-observer", parseObserver },{ "-headless", parseHeadless },/* -noaudio was in the Debug/Internal block above, so a Release build ignored it and a windowed rundiff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cppindex db240fe7c..e637fc0ef 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp@@ -681,7 +681,7 @@ static void startAutoSkirmish( Int numPlayersWanted )slot.setState( SLOT_PLAYER, localName );slot.setName( localName );}- else if (takeover)+ else if (takeover && (TheGlobalData->m_autoSkirmishTakeoverSlot < 0 || TheGlobalData->m_autoSkirmishTakeoverSlot == i)){slot.setState( SLOT_TAKEOVER );}@@ -2534,6 +2534,9 @@ static void updateHeadlessRun( void )peakUnits[ i ],score->getTotalBuildingsBuilt(), score->getTotalBuildingsLost(),slot, team));+ // the exchange in money, on a line of its own so the PLAYER line's readers keep matching it+ DEBUG_LOG(("HEADLESS VALUE %d: units worth %d lost, %d killed\n", i,+ score->getUnitValueLost(), score->getUnitValueDestroyed()));}if (scouting)diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cppindex 1d5a3b9f3..28bbaf40b 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp@@ -716,6 +716,8 @@ GlobalData::GlobalData()m_autoSkirmishAIState = SLOT_BRUTAL_AI;m_autoSkirmishAIStateOdd = 0; // 0 = not set: every slot plays at -aidiffm_noTacticsSlotParity = -1;+ m_aiKnobsOffParity = -1;+ m_aiKnobsOffMask = 0;m_autoSkirmishTeams = 0; // 0 = not set: every slot fights every other slotm_peaceTime = 0; // no truce unless -peacetime asks for onem_unitLimit = FALSE; // no unit limit unless -unitlimit asks for one@@ -755,6 +757,7 @@ GlobalData::GlobalData()m_scenarioFile.clear(); // nothing is scripted; -scenario is a measuring tool and ruins the match it runs inm_cinemaScript.clear(); // the interface is on and the camera belongs to the playerm_autoSkirmishTakeover = FALSE; // the AI plays the opponents unless -takeover empties their seats+ m_autoSkirmishTakeoverSlot = -1;for( Int slot = 0; slot < MAX_PLAYER_COUNT; slot++ ){m_autoSkirmishSide[ slot ].clear(); // every faction still comes out of the seed unless -side names onediff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cppindex 5d757b26d..4ad2e5b05 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp@@ -1660,6 +1660,19 @@ Bool Player::holdTeamForWave(Team *team, const AsciiString &approach, Int pathSureturn m_ai ? m_ai->holdTeamForWave(team, approach, pathSuffix) : FALSE;}+//-------------------------------------------------------------------------------------------------+Bool Player::gateTeamAttack(Team *team, const char *cause)+{+ return m_ai ? m_ai->gateTeamAttack(team, cause) : FALSE;+}++//-------------------------------------------------------------------------------------------------+void Player::onUnitLost(const Object *obj)+{+ if (m_ai)+ m_ai->onUnitLost(obj);+}+//-------------------------------------------------------------------------------------------------/** Do any bridges need repair, and if so repair them. *///-------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ScoreKeeper.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ScoreKeeper.cppindex 9a5b98e3a..061a8ff2c 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ScoreKeeper.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ScoreKeeper.cpp@@ -59,6 +59,7 @@#include "Common/GameState.h"#include "Common/KindOf.h"#include "Common/Player.h"+#include "Common/PlayerList.h"#include "Common/ScoreKeeper.h"#include "Common/ThingFactory.h"#include "Common/ThingTemplate.h"@@ -408,6 +409,32 @@ Int ScoreKeeper::getTotalBuildingsDestroyed( void )}return count;}+/** The build cost of every unit in one of the count maps, at its owner's price; a building is not+ * army. For the HEADLESS VALUE line an AI batch reads the exchange from. */+Int ScoreKeeper::unitValueOf( const ObjectCountMap &map, Int ownerIdx )+{+ const Player *owner = ThePlayerList->getNthPlayer( ownerIdx );+ Int value = 0;+ for( ObjectCountMap::const_iterator it = map.begin(); it != map.end(); ++it )+ if( !it->first->isKindOf( KINDOF_STRUCTURE ) )+ value += it->second * it->first->calcCostToBuild( owner );+ return value;+}++Int ScoreKeeper::getUnitValueLost( void ) const+{+ return unitValueOf( m_objectsLost, m_myPlayerIdx );+}++Int ScoreKeeper::getUnitValueDestroyed( void ) const+{+ Int value = 0;+ for( Int i = 0; i < MAX_PLAYER_COUNT; ++i )+ if( ThePlayerList->getNthPlayer( i ) )+ value += unitValueOf( m_objectsDestroyed[ i ], i );+ return value;+}+Int ScoreKeeper::getTotalUnitsDestroyed( void ){int count = 0;diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cppindex 74a2d1764..82208973d 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp@@ -1101,12 +1101,12 @@ Real AI::getAdjustedVisionRangeForObject(const Object *object, Int factorsToCons* expansions, extra buildings and tactical fighting stay on Hard, and the two measured columns* above were left where the matches put them.*- * scoutS maxSc decis cntr mass ttk indiv team infl focus save harv expand guard hoard econ micro */+ * scoutS maxSc decis cntr mass ttk indiv team infl focus save harv expand guard hoard econ micro gate answer massU */static const AIDifficultyProfile s_defaultSkillLadder[ AISKILL_COUNT ] ={- /* Easy */ { 75.0f, 1, 7.0f, 0.00f, FALSE, 0.00f, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, 0, FALSE, FALSE },- /* Medium */ { 45.0f, 1, 3.0f, 0.50f, FALSE, 0.35f, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, 6000, FALSE, FALSE },- /* Brutal */ { 25.0f, 2, 1.5f, 1.00f, TRUE, 0.50f, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 4000, TRUE, TRUE }+ /* Easy */ { 75.0f, 1, 7.0f, 0.00f, FALSE, 0.00f, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, 0, FALSE, FALSE, FALSE, FALSE, FALSE },+ /* Medium */ { 45.0f, 1, 3.0f, 0.50f, FALSE, 0.35f, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, 6000, FALSE, FALSE, FALSE, FALSE, FALSE },+ /* Brutal */ { 25.0f, 2, 1.5f, 1.00f, TRUE, 0.50f, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 4000, TRUE, TRUE, FALSE, FALSE, FALSE }};//-------------------------------------------------------------------------------------------------@@ -1548,6 +1548,36 @@ Real aiMatchupScore( Real myFramesToKill, Real theirFramesToKill, Real myCost, Rreturn score;}+//-------------------------------------------------------------------------------------------------+/** The value-weighted mean of every pairing's score, turned back into an advantage as s / (1 - s):+ * even at 0.5, three at 0.75, the inverse when the sides swap. That stays near the doublings the+ * score was made from (0.75 was four times better) with no exp() in logic. */+//-------------------------------------------------------------------------------------------------+Real aiArmyAdvantage( const Real *myValue, Int myKinds, const Real *theirValue, Int theirKinds, const Real *score )+{+ const Real MOST = 16.0f;++ Real weighed = 0.0f;+ Real scored = 0.0f;+ for( Int i = 0; i < myKinds; ++i )+ {+ for( Int j = 0; j < theirKinds; ++j )+ {+ const Real weight = myValue[ i ] * theirValue[ j ];+ weighed += weight;+ scored += weight * score[ i * theirKinds + j ];+ }+ }+ if( weighed <= 0.0f )+ return 1.0f; // one side is empty: no exchange to weigh++ Real s = scored / weighed;+ const Real lowest = 1.0f / (MOST + 1.0f);+ if( s < lowest ) s = lowest;+ if( s > 1.0f - lowest ) s = 1.0f - lowest;+ return s / (1.0f - s);+}+//-------------------------------------------------------------------------------------------------const AIDifficultyProfile *AI::getDifficultyProfile( AISkillLevel level ) const{@@ -1583,6 +1613,9 @@ void AI::parseSkillLevel(INI *ini, void *instance, void* /*store*/, const void*{ "CashHoardThreshold", INI::parseInt, NULL, offsetof( AIDifficultyProfile, m_cashHoardThreshold ) },{ "EconomyBuildings", INI::parseBool, NULL, offsetof( AIDifficultyProfile, m_economyBuildings ) },{ "TacticalMicro", INI::parseBool, NULL, offsetof( AIDifficultyProfile, m_tacticalMicro ) },+ { "EngageGate", INI::parseBool, NULL, offsetof( AIDifficultyProfile, m_engageGate ) },+ { "AnswerArmy", INI::parseBool, NULL, offsetof( AIDifficultyProfile, m_answerArmy ) },+ { "MassUnit", INI::parseBool, NULL, offsetof( AIDifficultyProfile, m_massUnit ) },{ NULL, NULL, NULL, 0 }};diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cppindex 0f269879e..f49d58a0b 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp@@ -122,15 +122,8 @@ static Bool observerKnowsAbout( const Object *obj, Int observerNdx )* at nothing and did nothing at all. Build cost is the fallback: always present, and a fair* proxy - the data already prices a tank above a rifleman.*/-static Real aiCombatPower( const Object *obj )+static Real templateCombatPower( const ThingTemplate *tmpl, const Player *owner ){- if( obj == NULL )- return 0.0f;-- const ThingTemplate *tmpl = obj->getTemplate();- if( tmpl == NULL )- return 0.0f;-//// Only what can shoot has any power in an exchange. Cost as a proxy is only fair among things// that fight: a war factory costs as much as a tank column and cannot fire a shot, and the@@ -145,7 +138,15 @@ static Real aiCombatPower( const Object *obj )if( threat > 0.0f )return threat;- return INT_TO_REAL( tmpl->calcCostToBuild( obj->getControllingPlayer() ) );+ return INT_TO_REAL( tmpl->calcCostToBuild( owner ) );+}++/** The same figure for a unit on the field. */+static Real aiCombatPower( const Object *obj )+{+ if( obj == NULL || obj->getTemplate() == NULL )+ return 0.0f;+ return templateCombatPower( obj->getTemplate(), obj->getControllingPlayer() );}/** One of the map's own Player_N_Start waypoints, by 0-based position index. Where the start@@ -2611,6 +2612,155 @@ static void addToVisibleArmy( std::vector<AIVisibleEnemy> *army, const ThingTemparmy->push_back( kind );}+//-------------------------------------------------------------------------------------------------+/** How one army trades against another, unit against unit and money for money (aiArmyAdvantage). */+//-------------------------------------------------------------------------------------------------+static Real armyAdvantage( const std::vector<AIVisibleEnemy> &mine, const std::vector<AIVisibleEnemy> &theirs )+{+ if( mine.empty() || theirs.empty() )+ return 1.0f;+ std::vector<Real> myValue, theirValue, score;+ for( size_t i = 0; i < mine.size(); ++i )+ myValue.push_back( mine[ i ].m_weight );+ for( size_t j = 0; j < theirs.size(); ++j )+ theirValue.push_back( theirs[ j ].m_weight );+ for( size_t i = 0; i < mine.size(); ++i )+ for( size_t j = 0; j < theirs.size(); ++j )+ score.push_back( aiMatchupScore( templateFramesToKill( mine[ i ].m_template, theirs[ j ].m_template ),+ templateFramesToKill( theirs[ j ].m_template, mine[ i ].m_template ), mine[ i ].m_cost, theirs[ j ].m_cost ) );+ return aiArmyAdvantage( &myValue[ 0 ], (Int)myValue.size(), &theirValue[ 0 ], (Int)theirValue.size(), &score[ 0 ] );+}++/** How often the ledger of seen enemies is brought up to date, and how long a unit nobody has seen is+ * still believed in. Three minutes is long enough for an army that walked back into the fog to be+ * remembered when it walks out again, and short enough that one the AI never saw die is let go. */+static const Int LEDGER_RATE = 2 * LOGICFRAMES_PER_SECOND;+static const UnsignedInt LEDGER_FORGET_FRAMES = 180 * LOGICFRAMES_PER_SECOND;++//-------------------------------------------------------------------------------------------------+/** Write down every enemy unit in sight, and cross off the ones it has looked for and not found. Only+ * what observerKnowsAbout allows, so the ledger is what a player would know from his own screen. */+//-------------------------------------------------------------------------------------------------+void AIPlayer::rememberEnemies( void )+{+ const Int me = m_player->getPlayerIndex();+ const UnsignedInt now = TheGameLogic->getFrame();+ if( !isSkirmishAI() || (now + computeUpdatePhase( me, LEDGER_RATE )) % LEDGER_RATE != 0 )+ return;++ for( Int i = 0; i < ThePlayerList->getPlayerCount(); ++i )+ {+ Player *p = ThePlayerList->getNthPlayer( i );+ if( p == NULL || p == m_player || m_player->getRelationship( p->getDefaultTeam() ) != ENEMIES )+ continue;+ for( Player::PlayerTeamList::const_iterator t = p->getPlayerTeams()->begin(); t != p->getPlayerTeams()->end(); ++t )+ {+ for( DLINK_ITERATOR<Team> iter = (*t)->iterate_TeamInstanceList(); !iter.done(); iter.advance() )+ {+ for( DLINK_ITERATOR<Object> objIter = iter.cur()->iterate_TeamMemberList(); !objIter.done(); objIter.advance() )+ {+ Object *obj = objIter.cur();+ if( obj->isEffectivelyDead() || obj->isContained() || obj->isKindOf( KINDOF_STRUCTURE ) ||+ obj->isKindOf( KINDOF_PROJECTILE ) || aiCombatPower( obj ) <= 0.0f || !observerKnowsAbout( obj, me ) )+ continue;+ SeenEnemy &row = m_seenEnemies[ obj->getID() ];+ row.tmpl = obj->getTemplate();+ row.owner = p->getPlayerIndex();+ row.seen = now;+ row.pos = *obj->getPosition();+ row.stealth = obj->getStatusBits().test( OBJECT_STATUS_CAN_STEALTH );+ }+ }+ }+ }++ for( std::map<ObjectID, SeenEnemy>::iterator it = m_seenEnemies.begin(); it != m_seenEnemies.end(); )+ {+ Bool forget = it->second.seen + LEDGER_FORGET_FRAMES <= now;+ if( !forget && it->second.seen != now &&+ ThePartitionManager->getShroudStatusForPlayer( me, &it->second.pos ) == CELLSHROUD_CLEAR )+ {+ // the ground it stood on is in sight and it is not there: gone, unless it still exists and only+ // walked off, in which case it is somewhere in the fog still+ const Object *obj = TheGameLogic->findObjectByID( it->first );+ forget = obj == NULL || obj->isEffectivelyDead() || obj->getControllingPlayer()->getPlayerIndex() != it->second.owner;+ }+ if( forget )+ m_seenEnemies.erase( it++ );+ else+ ++it;+ }+}++//-------------------------------------------------------------------------------------------------+/** The ledger as an army: one entry a kind of unit, weighed by what each is worth in a fight, in the+ * order of the units' IDs. */+//-------------------------------------------------------------------------------------------------+void AIPlayer::rememberedArmy( std::vector<AIVisibleEnemy> *army ) const+{+ for( std::map<ObjectID, SeenEnemy>::const_iterator it = m_seenEnemies.begin(); it != m_seenEnemies.end(); ++it )+ {+ const Player *owner = ThePlayerList->getNthPlayer( it->second.owner );+ addToVisibleArmy( army, it->second.tmpl, owner, templateCombatPower( it->second.tmpl, owner ) );+ }+}++//-------------------------------------------------------------------------------------------------+/** AI ENGAGE: something of ours sets off at the enemy. What it is worth, what the enemy army it+ * remembers is worth, and the two ratios a fight is decided by: money against money, and how the+ * units fare against each other (armyAdvantage). The cause says who sent it. */+//-------------------------------------------------------------------------------------------------+void AIPlayer::logEngage( const char *cause, const std::vector<Object *> &units )+{+ std::vector<AIVisibleEnemy> mine;+ Real power = 0.0f;+ for( std::vector<Object *>::const_iterator u = units.begin(); u != units.end(); ++u )+ {+ const Real p = aiCombatPower( *u );+ if( (*u)->isEffectivelyDead() || p <= 0.0f )+ continue;+ power += p;+ addToVisibleArmy( &mine, (*u)->getTemplate(), m_player, p );+ }+ if( mine.empty() )+ return;+ std::vector<AIVisibleEnemy> theirs;+ rememberedArmy( &theirs );+ Real theirPower = 0.0f;+ for( std::vector<AIVisibleEnemy>::const_iterator k = theirs.begin(); k != theirs.end(); ++k )+ theirPower += k->m_weight;+ DEBUG_LOG(("AI ENGAGE frame %d player %d %s: %d units, %.0f power against %.0f remembered, cost %.2f matchup %.2f\n",+ TheGameLogic->getFrame(), m_player->getPlayerIndex(), cause, (Int)units.size(), power, theirPower,+ theirPower > 0.0f ? power / theirPower : 99.0f, armyAdvantage( mine, theirs )));+}++//-------------------------------------------------------------------------------------------------+/** AI LOSS: one of a team's units died. Straggling when two or more of its team are still alive and+ * at most one of them stands within 300 of it: the unit that went in on its own, as against the last+ * survivor of a lost fight, which dies alone whatever the AI did. */+//-------------------------------------------------------------------------------------------------+void AIPlayer::onUnitLost( const Object *obj )+{+ const Team *team = obj->getTeam();+ if( !isSkirmishAI() || obj->isKindOf( KINDOF_STRUCTURE ) || team == NULL || team == m_player->getDefaultTeam() )+ return;+ const Real NEAR_SQR = 300.0f * 300.0f;+ Int alive = 0;+ Int beside = 0; // not "near": windef.h makes that a macro+ for( DLINK_ITERATOR<Object> m = team->iterate_TeamMemberList(); !m.done(); m.advance() )+ {+ const Object *mate = m.cur();+ if( mate == obj || mate->isEffectivelyDead() || mate->isKindOf( KINDOF_STRUCTURE ) )+ continue;+ ++alive;+ if( sqr( mate->getPosition()->x - obj->getPosition()->x ) + sqr( mate->getPosition()->y - obj->getPosition()->y ) <= NEAR_SQR )+ ++beside;+ }+ DEBUG_LOG(("AI LOSS frame %d player %d '%s' of '%s' %s, %d teammates alive, %d within 300\n", TheGameLogic->getFrame(),+ m_player->getPlayerIndex(), obj->getTemplate()->getName().str(), team->getName().str(),+ alive < 2 ? "last" : (beside <= 1 ? "straggling" : "grouped"), alive, beside));+}+//-------------------------------------------------------------------------------------------------/** What a team prototype can answer, over every unit it is built from: each of its units against* each kind of enemy unit in sight, both ways round, weighted by how much of the visible army that@@ -4119,6 +4269,34 @@ Bool AIPlayer::shouldHoldForMassing( TeamInQueue *team )return aiShouldMass( waitingThreat, enemy.m_totalThreat, massFraction, timeExpired, baseUnderAttack );}+/** A unit trained to top up a team that is out on the map walks to it on its own, across the map.+ * Logged as an AI ENGAGE; with EngageGate it stays at home instead, where sendIdleAttackTeams calls+ * it up with the next wave. TRUE when it stays. */+Bool AIPlayer::holdReinforcement( Object *obj )+{+ Team *team = obj->getTeam();+ if( !isSkirmishAI() || team == NULL || team == m_player->getDefaultTeam() )+ return FALSE;+ const TeamTemplateInfo *info = team->getPrototype()->getTemplateInfo();+ if( info->m_isBaseDefense || info->m_isPerimeterDefense )+ return FALSE;+ Bool away = FALSE;+ for( DLINK_ITERATOR<Object> m = team->iterate_TeamMemberList(); !m.done(); m.advance() )+ if( m.cur() != obj && !m.cur()->isEffectivelyDead() && !isAtHome( m.cur()->getPosition() ) )+ away = TRUE;+ if( !away )+ return FALSE; // the team is at home: joining it is a walk across the base+ if( getSkillProfile()->m_engageGate && aiTeamAttacks( info ) )+ {+ DEBUG_LOG(("AI ENGAGE frame %d player %d keeps '%s' for '%s' at home for the next wave\n", TheGameLogic->getFrame(),+ m_player->getPlayerIndex(), obj->getTemplate()->getName().str(), team->getName().str()));+ return TRUE;+ }+ std::vector<Object *> units( 1, obj );+ logEngage( "reinforce", units );+ return FALSE;+}+void AIPlayer::checkReadyTeams( void ){// See if any ready teams are gathered at their rally point@@ -4189,7 +4367,7 @@ void AIPlayer::checkReadyTeams( void )removeFrom_TeamReadyQueue(team);if (team->m_reinforcement) {Object *obj = TheGameLogic->findObjectByID(team->m_reinforcementID);- if (obj&&obj->getAIUpdateInterface()) {+ if (obj&&obj->getAIUpdateInterface() && !holdReinforcement(obj)) {obj->getAIUpdateInterface()->joinTeam();}} else {@@ -4508,6 +4686,7 @@ void AIPlayer::update( void )AI_PHASE( AIP_ECONOMY, doEconomy() ); // ... and the money sitting in the bank.AI_PHASE( AIP_POWER, doPower() ); // Keep the lights on, and out of reach.AI_PHASE( AIP_ECONOMY, doSuperweapons() ); // The big guns, as soon as they can be bought.+ AI_PHASE( AIP_WAVE, rememberEnemies() ); // Write down the enemy army in sight.AI_PHASE( AIP_WAVE, doWaves() ); // Send the parked attack teams out together.AI_PHASE( AIP_TACTICS, doTactics() ); // Fight each unit from where it is strongest.AI_PHASE( AIP_TACTICS, doTransports() ); // Put the helicopters' riders down at the fight.@@ -6760,17 +6939,37 @@ Bool aiTeamAttacks( const TeamTemplateInfo *info )* production carries on, and doWaves sends everything parked out together.*///-----------------------------------------------------------------------------------------------------------Bool AIPlayer::holdTeamForWave( Team *team, const AsciiString &approach, Int pathSuffix )+/** Every living member of a team. */+static void collectTeamUnits( Team *team, std::vector<Object *> *units )+{+ for( DLINK_ITERATOR<Object> iter = team->iterate_TeamMemberList(); !iter.done(); iter.advance() )+ if( !iter.cur()->isEffectivelyDead() )+ units->push_back( iter.cur() );+}++/** holdTeamForWave lets this team go as its script said: say so, and why. */+Bool AIPlayer::refuseHold( Team *team, const char *why, Bool logIt )+{+ if( logIt )+ {+ std::vector<Object *> units;+ collectTeamUnits( team, &units );+ logEngage( why, units );+ }+ return FALSE;+}++Bool AIPlayer::holdTeamForWave( Team *team, const AsciiString &approach, Int pathSuffix, Bool logRefusal ){// a base being hit keeps what its scripts would send out, on every rung, until the fight at home is overif( team == NULL || !isSkirmishAI() )return FALSE;- const Bool underAttack = isBaseUnderAttack();- if( !underAttack && !holdsTeamsForWaves() )- return FALSE;const TeamTemplateInfo *info = team->getPrototype()->getTemplateInfo();if( info->m_isBaseDefense || info->m_isPerimeterDefense )return FALSE;+ const Bool underAttack = isBaseUnderAttack();+ if( !underAttack && !holdsTeamsForWaves() )+ return refuseHold( team, "press", logRefusal );Int freeSlot = -1;Bool anyParked = FALSE;@@ -6787,9 +6986,9 @@ Bool AIPlayer::holdTeamForWave( Team *team, const AsciiString &approach, Int patanyParked = TRUE;}if( freeSlot < 0 )- return FALSE; // the staging point is full, so this one goes as the script said+ return refuseHold( team, "full", logRefusal ); // the staging point is full, so this one goes as the script saidif( !underAttack && aiReleaseWaveAt( m_pressure, waitingPower( team, NULL ), WAVE_POWER, 0, WAVE_MAX_HOLD_FRAMES ) )- return FALSE; // a wave on its own waits for nobody+ return refuseHold( team, "alone", logRefusal ); // a wave on its own waits for nobodym_heldUsed[ freeSlot ] = TRUE;m_heldTeam[ freeSlot ] = team->getID();@@ -6840,6 +7039,39 @@ Bool AIPlayer::holdTeamForWave( Team *team, const AsciiString &approach, Int patreturn TRUE;}+//----------------------------------------------------------------------------------------------------------+/** A skirmish script sends a team hunting, or at an area. Both go from wherever the team stands, on+ * their own, the moment the script fires: a team just out of the factory walks across the map alone,+ * past the wave parked at the staging point. With EngageGate a team still mostly at home parks with+ * that wave instead, and goes out with it. */+//----------------------------------------------------------------------------------------------------------+Bool AIPlayer::gateTeamAttack( Team *team, const char *cause )+{+ if( team == NULL || !isSkirmishAI() )+ return FALSE;+ const TeamTemplateInfo *info = team->getPrototype()->getTemplateInfo();+ if( info->m_isBaseDefense || info->m_isPerimeterDefense )+ return FALSE;+ std::vector<Object *> units;+ collectTeamUnits( team, &units );+ if( units.empty() )+ return FALSE;+ Int home = 0;+ for( std::vector<Object *>::const_iterator u = units.begin(); u != units.end(); ++u )+ if( isAtHome( (*u)->getPosition() ) )+ ++home;+ Player *enemy = getAiEnemy();+ if( getSkillProfile()->m_engageGate && enemy && m_baseCenterSet && 2 * home >= (Int)units.size() &&+ holdTeamForWave( team, AsciiString( "Center" ), enemy->getMpStartIndex() + 1, FALSE ) )+ {+ DEBUG_LOG(("AI ENGAGE frame %d player %d parks '%s' for the next wave instead of its script's %s\n",+ TheGameLogic->getFrame(), m_player->getPlayerIndex(), team->getName().str(), cause));+ return TRUE;+ }+ logEngage( cause, units );+ return FALSE;+}+//----------------------------------------------------------------------------------------------------------/** One player's army as an observer knows it: everything that moves and shoots, in aiCombatPower's* currency. observer -1 is the player counting its own. An enemy carried inside something is not@@ -7042,6 +7274,7 @@ void AIPlayer::doWaves( void )// and a rung that does not mass lets go the moment the fight at home is overif( teams < MAX_HELD_TEAMS && holdsTeamsForWaves() && !aiReleaseWaveAt( m_pressure, power, WAVE_POWER, heldFrames, WAVE_MAX_HOLD_FRAMES ) )return;+ const char *cause = !holdsTeamsForWaves() ? "press" : teams >= MAX_HELD_TEAMS ? "full" : power >= WAVE_POWER ? "wave" : "timeout";// a gunship still being filled holds the wave a little while its riders walk over or come out of// the barracks. Without the wait 13 of 15 bunkered Helixes left with nobody aboard: the riders@@ -7122,10 +7355,10 @@ void AIPlayer::doWaves( void )wave->remove( obj );flankGroup->add( obj );}- sendWave( flankGroup, flank, pathSuffix, teams, flankPower, heldFrames );+ sendWave( flankGroup, flank, pathSuffix, teams, flankPower, heldFrames, cause );power -= flankPower;}- sendWave( wave, approach, pathSuffix, teams, power, heldFrames );+ sendWave( wave, approach, pathSuffix, teams, power, heldFrames, cause );}//----------------------------------------------------------------------------------------------------------@@ -7585,7 +7818,7 @@ void AIPlayer::buyGunshipChinook( void )}//-----------------------------------------------------------------------------------------------------------void AIPlayer::sendWave( AIGroup *wave, const AsciiString &approach, Int pathSuffix, Int teams, Real power, UnsignedInt heldFrames )+void AIPlayer::sendWave( AIGroup *wave, const AsciiString &approach, Int pathSuffix, Int teams, Real power, UnsignedInt heldFrames, const char *cause ){Coord3D center;wave->getCenter( ¢er );@@ -7596,6 +7829,15 @@ void AIPlayer::sendWave( AIGroup *wave, const AsciiString &approach, Int pathSufm_player->getPlayerIndex(), teams, wave->getCount(), power, heldFrames / LOGICFRAMES_PER_SECOND, pathLabel.str()));if( way == NULL )return;+ std::vector<Object *> units;+ const VecObjectID &ids = wave->getAllIDs();+ for( VecObjectID::const_iterator it = ids.begin(); it != ids.end(); ++it )+ {+ Object *obj = TheGameLogic->findObjectByID( *it );+ if( obj )+ units.push_back( obj );+ }+ logEngage( cause, units );computeShuttleFront( way, wave );wave->groupFollowWaypointPathAsTeam( way, CMD_FROM_AI );@@ -7670,13 +7912,13 @@ void AIPlayer::sendIdleAttackTeams( void )DEBUG_LOG(("AI WAVE frame %d player %d calls up '%s', %d units idle at home\n", TheGameLogic->getFrame(),m_player->getPlayerIndex(), team->getName().str(), waiting));- if( holdTeamForWave( team, center, pathSuffix ) )+ if( holdTeamForWave( team, center, pathSuffix, FALSE ) )continue;AIGroup *group = TheAI->createGroup();const Real power = waitingPower( team, group );Coord3D from;group->getCenter( &from );- sendWave( group, chooseApproachLabel( &from, center, pathSuffix ), pathSuffix, 1, power, 0 );+ sendWave( group, chooseApproachLabel( &from, center, pathSuffix ), pathSuffix, 1, power, 0, "calledup" );}}}@@ -7732,6 +7974,7 @@ void AIPlayer::sendIdleUnitsHunting( void )const Real reachSqr = sqr( 2.0f * m_baseRadius );Int hunters = 0;Int guards = 0;+ std::vector<Object *> hunting;for( Player::PlayerTeamList::const_iterator t = m_player->getPlayerTeams()->begin(); t != m_player->getPlayerTeams()->end(); ++t ){@@ -7770,14 +8013,18 @@ void AIPlayer::sendIdleUnitsHunting( void )continue;obj->getAI()->aiHunt( CMD_FROM_AI );++hunters;+ hunting.push_back( obj );if( !attacks )++guards;}}}if( hunters > 0 )+ {DEBUG_LOG(("AI WAVE frame %d player %d sends %d idle units hunting, %d of them off guard\n", TheGameLogic->getFrame(),m_player->getPlayerIndex(), hunters, guards));+ logEngage( "idlehunt", hunting );+ }}//----------------------------------------------------------------------------------------------------------@@ -11524,7 +11771,22 @@ AISkillLevel AIPlayer::skillLevelForDifficulty( GameDifficulty difficulty )//-------------------------------------------------------------------------------------------------const AIDifficultyProfile *AIPlayer::getSkillProfile( void ) const{- return TheAI->getDifficultyProfile( m_skillLevel );+ const AIDifficultyProfile *profile = TheAI->getDifficultyProfile( m_skillLevel );+ const Int parity = TheGlobalData->m_aiKnobsOffParity;+ if( parity < 0 )+ return profile;+ // -aiknobsoff: a skirmish, or the playback of one given the switch again, as -notactics reads it+ const Int originalMode = (TheRecorder && TheRecorder->getMode() == RECORDERMODETYPE_PLAYBACK)+ ? TheRecorder->getGameMode() : TheGameLogic->getGameMode();+ if( originalMode != GAME_SKIRMISH ||+ (parity != 2 && (ThePlayerList->getSlotIndex( m_player->getPlayerIndex() ) & 1) != parity) )+ return profile;+ m_measuredProfile = *profile;+ const Int mask = TheGlobalData->m_aiKnobsOffMask;+ if( mask & AIKNOB_ENGAGE_GATE ) m_measuredProfile.m_engageGate = FALSE;+ if( mask & AIKNOB_ANSWER_ARMY ) m_measuredProfile.m_answerArmy = FALSE;+ if( mask & AIKNOB_MASS_UNIT ) m_measuredProfile.m_massUnit = FALSE;+ return &m_measuredProfile;}@@ -11661,7 +11923,7 @@ void AIPlayer::xfer( Xfer *xfer ){// version- XferVersion currentVersion = 16; // 2: scout 3: rung and role 4: scouting stamps 5: the capturer 6: parked waves 7: superweapon aims 8: the hijacker 9: tactical steps 10: the ferry and dropped riders 11: the outward placement ring 12: the pressure level 13: falling back 14: gunship Chinooks and the boarding wait 15: transport Chinooks and the lent one 16: healer and raider Helixes+ XferVersion currentVersion = 17; // 2: scout 3: rung and role 4: scouting stamps 5: the capturer 6: parked waves 7: superweapon aims 8: the hijacker 9: tactical steps 10: the ferry and dropped riders 11: the outward placement ring 12: the pressure level 13: falling back 14: gunship Chinooks and the boarding wait 15: transport Chinooks and the lent one 16: healer and raider Helixes 17: the seen-enemy ledgerXferVersion version = currentVersion;xfer->xferVersion( &version, currentVersion );@@ -11978,6 +12240,45 @@ void AIPlayer::xfer( Xfer *xfer )xfer->xferReal( &duty.targetHealth );}}+ // the enemy units it has seen, so a loaded game remembers the army that went back into the fog+ if( version >= 17 )+ {+ UnsignedShort seen = (UnsignedShort)m_seenEnemies.size();+ xfer->xferUnsignedShort( &seen );+ if( xfer->getXferMode() == XFER_SAVE )+ {+ for( std::map<ObjectID, SeenEnemy>::iterator it = m_seenEnemies.begin(); it != m_seenEnemies.end(); ++it )+ {+ ObjectID id = it->first;+ AsciiString name = it->second.tmpl->getName();+ xfer->xferObjectID( &id );+ xfer->xferAsciiString( &name );+ xfer->xferInt( &it->second.owner );+ xfer->xferUnsignedInt( &it->second.seen );+ xfer->xferCoord3D( &it->second.pos );+ xfer->xferBool( &it->second.stealth );+ }+ }+ else+ {+ m_seenEnemies.clear();+ for( UnsignedShort i = 0; i < seen; ++i )+ {+ ObjectID id;+ AsciiString name;+ SeenEnemy row;+ xfer->xferObjectID( &id );+ xfer->xferAsciiString( &name );+ xfer->xferInt( &row.owner );+ xfer->xferUnsignedInt( &row.seen );+ xfer->xferCoord3D( &row.pos );+ xfer->xferBool( &row.stealth );+ row.tmpl = TheThingFactory->findTemplate( name, FALSE );+ if( row.tmpl )+ m_seenEnemies[ id ] = row;+ }+ }+ }// the ladder rung and the role, which are rolled once and must come back the same wayif( version >= 3 )diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cppindex 1d8421e7e..c13d23328 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp@@ -3197,6 +3197,7 @@ void Object::scoreTheKill( const Object *victim )if (victimController){victimController->getScoreKeeper()->addObjectLost(victim);+ victimController->onUnitLost(victim);}Relationship r = getRelationship(victim);diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cppindex eb614a2ca..a5d925fcb 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp@@ -1416,6 +1416,10 @@ void ScriptActions::doTeamAttackArea(const AsciiString& teamName, const AsciiStrif (!theTeam) {return;}+ // a skirmish AI may keep a team still at home for its next wave rather than send it on its own+ if (theTeam->getControllingPlayer() && theTeam->getControllingPlayer()->gateTeamAttack(theTeam, "attackarea")) {+ return;+ }AIGroup* theGroup = TheAI->createGroup();if (!theGroup) {@@ -2046,6 +2050,10 @@ void ScriptActions::doTeamHunt(const AsciiString& teamName)if (!theTeam) {return;}+ // a skirmish AI may keep a team still at home for its next wave rather than let it hunt alone+ if (theTeam->getControllingPlayer() && theTeam->getControllingPlayer()->gateTeamAttack(theTeam, "hunt")) {+ return;+ }AIGroup* theGroup = TheAI->createGroup();if (!theGroup) {diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex 5029ab44e..fcf433bb7 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -11062,6 +11062,35 @@ TEST(matchup_score_is_money_for_money)CHECK_NEAR( 0.625f, faster, 0.00001f );}+/** The exchange between two mixed armies: the value-weighted mean of their pairings, as an advantage. */+TEST(army_advantage_weighs_the_mix)+{+ // one kind a side, an even pairing: an even trade+ const Real even = 0.5f;+ const Real one = 1000.0f;+ CHECK_NEAR( 1.0f, aiArmyAdvantage( &one, 1, &one, 1, &even ), 0.0001f );++ // four times better reads as three, and the other side of it as a third+ const Real better = 0.75f;+ const Real worse = 0.25f;+ CHECK_NEAR( 3.0f, aiArmyAdvantage( &one, 1, &one, 1, &better ), 0.0001f );+ CHECK_NEAR( 1.0f / 3.0f, aiArmyAdvantage( &one, 1, &one, 1, &worse ), 0.0001f );++ // nothing to hurt, or nothing to hurt it with, saturates at sixteen either way+ const Real none = 0.0f;+ const Real all = 1.0f;+ CHECK_NEAR( 16.0f, aiArmyAdvantage( &one, 1, &one, 1, &all ), 0.0001f );+ CHECK_NEAR( 1.0f / 16.0f, aiArmyAdvantage( &one, 1, &one, 1, &none ), 0.0001f );++ // an empty side is no exchange+ CHECK_NEAR( 1.0f, aiArmyAdvantage( &one, 1, NULL, 0, NULL ), 0.0001f );++ // two kinds of mine against one of theirs: the dearer kind weighs three times as much+ const Real mine[ 2 ] = { 3000.0f, 1000.0f };+ const Real scores[ 2 ] = { 0.75f, 0.25f }; // (0.75 * 3 + 0.25) / 4 = 0.625+ CHECK_NEAR( 0.625f / 0.375f, aiArmyAdvantage( mine, 2, &one, 1, scores ), 0.0001f );+}+/** C1's arithmetic: the ratio of how long a force lasts to how long it needs to finish what isshooting at it. The word "retreat" did not appear anywhere in the AI before this - teams foughtdiff --git a/ai-batch.ps1 b/ai-batch.ps1index 05eea111c..8ab92a8e1 100644--- a/ai-batch.ps1+++ b/ai-batch.ps1@@ -63,6 +63,13 @@ param(# extra arguments handed to every run, for sweeping a knob the game reads from the command line# (e.g. -ExtraArgs "-unitlimit") without a rebuild between batches[string[]] $ExtraArgs = @(),+ # a scenario file from Run/Scenarios played in every match, e.g. overlordrush. With -Takeover the+ # scenario plays that seat by hand and the AI plays the others+ [string] $Scenario = "",+ # the one seat left without an AI (-takeover <slot>); -1 leaves every seat to the AI+ [int] $Takeover = -1,+ # faction per seat, in seat order, e.g. FactionChina,FactionGLA; empty lets the seed draw+ [string[]] $Sides = @(),# minutes before a wedged run is killed rather than waited on forever[int] $TimeoutMinutes = 20,# matches played at once. A headless match is one logic thread, so one a core runs the batch@@ -127,6 +134,9 @@ for ($i = 0; $i -lt $Runs; $i++) {# a second rung for the odd slots, so one rung can be played against anotherif ($Difficulty2) { $args += "-aidiff2"; $args += $Difficulty2 }if ($Teams -gt 1) { $args += "-teams"; $args += $Teams }+ if ($Scenario) { $args += "-scenario"; $args += $Scenario }+ if ($Takeover -ge 0) { $args += "-takeover"; $args += $Takeover }+ for ($s = 0; $s -lt $Sides.Count; $s++) { if ($Sides[$s]) { $args += @("-side", $s, $Sides[$s]) } }if ($ExtraArgs.Count) { $args += $ExtraArgs }while (@($started | Where-Object { -not $_.Proc.HasExited }).Count -ge $Parallel) {@@ -184,8 +194,35 @@ foreach ($run in $started) {# and the count of frames that missed a 60Hz budget. Present in every build.$ft = $null$spikes = 0+ # the AI's own account of its fights, per player index: what it lost and killed in money, its team+ # deaths by how alone each one died, what it sent out and why, and the economy lines that say the+ # match was played at all+ $value = @{}+ $loss = @{}+ $engage = @{}+ $econ = [pscustomobject]@{ Reattach = 0; Waves = 0; Counter = 0 }foreach ($line in Get-Content $log) {+ if ($line -match "^AI LOSS frame \d+ player (\d+) .* (straggling|grouped|last), ") {+ $p = [int]$Matches[1]+ if (-not $loss.ContainsKey($p)) { $loss[$p] = @{ straggling = 0; grouped = 0; last = 0 } }+ $loss[$p][$Matches[2]]+++ continue+ }+ if ($line -match "^AI ENGAGE frame \d+ player (\d+) (\w+): (\d+) units, ([\d.]+) power against ([\d.]+) remembered, cost ([\d.]+) matchup ([\d.]+)") {+ $p = [int]$Matches[1]+ if (-not $engage.ContainsKey($p)) { $engage[$p] = @() }+ $engage[$p] += [pscustomobject]@{ Cause = $Matches[2]; Units = [int]$Matches[3]; Power = [double]$Matches[4]+ Theirs = [double]$Matches[5]; Cost = [double]$Matches[6]; Matchup = [double]$Matches[7] }+ continue+ }+ if ($line -match "Re-attaching supply truck") { $econ.Reattach++; continue }+ if ($line -match "^AI WAVE .* sends \d+ teams") { $econ.Waves++; continue }+ if ($line -match "^AI COUNTER") { $econ.Counter++; continue }+ if ($line -match "HEADLESS VALUE (\d+): units worth (\d+) lost, (\d+) killed") {+ $value[[int]$Matches[1]] = [pscustomobject]@{ Lost = [int]$Matches[2]; Killed = [int]$Matches[3] }+ continue+ }if ($line -match "HEADLESS PERF (\S+): ([\d.]+) \(([\d.]+)\) x([\d.]+) worst ([\d.]+)") {$perf[$Matches[1]] = [pscustomobject]@{Net = [double]$Matches[2]; Gross = [double]$Matches[3]; Calls = [double]$Matches[4]@@ -249,7 +286,8 @@ foreach ($run in $started) {$winnerText = if ($null -ne $winner) { "player $winner" } else { "no winner" }Write-Host ("{0}, {1}, frame {2}, {3:n0}s" -f $why, $winnerText, $frames, $wall)- $rows += [pscustomobject]@{ Seed = $seed; Cells = $cells; Why = $why; Frames = $frames; Wall = $wall; Slots = $slots; Pf = $pf; Perf = $perf; Jobs = $jobs; Ft = $ft; Spikes = $spikes }+ $rows += [pscustomobject]@{ Seed = $seed; Cells = $cells; Why = $why; Frames = $frames; Wall = $wall; Slots = $slots; Pf = $pf; Perf = $perf; Jobs = $jobs; Ft = $ft; Spikes = $spikes+ Value = $value; Loss = $loss; Engage = $engage; Econ = $econ; Winner = $winner }}# ---------------------------------------------------------------------------------------------@@ -288,6 +326,40 @@ $summary = foreach ($p in $slotIds) {}if ($summary) { $summary | Format-Table -AutoSize | Out-String | Write-Host }+# The exchange each side made, in money: lost over killed below 1 is a side that trades well. Team+# deaths by how alone each one died, straggling being the one the AI could have prevented. What it+# sent out and why, with the two odds it set off on.+$played = @($rows | Where-Object { $_.Value -and $_.Value.Count -gt 0 })+$fightIds = $played | ForEach-Object { $_.Value.Keys } | Sort-Object -Unique+$fights = foreach ($p in $fightIds) {+ $vals = @($played | Where-Object { $_.Value.ContainsKey($p) } | ForEach-Object { $_.Value[$p] })+ $lost = ($vals | Measure-Object Lost -Sum).Sum+ $killed = ($vals | Measure-Object Killed -Sum).Sum+ $deaths = @($played | Where-Object { $_.Loss.ContainsKey($p) } | ForEach-Object { $_.Loss[$p] })+ $strag = ($deaths | ForEach-Object { $_.straggling } | Measure-Object -Sum).Sum+ $all = ($deaths | ForEach-Object { $_.straggling + $_.grouped + $_.last } | Measure-Object -Sum).Sum+ $sent = @($played | Where-Object { $_.Engage.ContainsKey($p) } | ForEach-Object { $_.Engage[$p] })+ [pscustomobject]@{+ Player = $p+ AvgValLost = [math]::Round($lost / $vals.Count, 0)+ AvgValKill = [math]::Round($killed / $vals.Count, 0)+ "Lost/Kill" = if ($killed -gt 0) { [math]::Round($lost / $killed, 2) } else { "-" }+ "Strag%" = if ($all -gt 0) { [math]::Round(100.0 * $strag / $all, 1) } else { "-" }+ TeamDeaths = $all+ Sent = $sent.Count+ Causes = (($sent | Group-Object Cause | Sort-Object Count -Descending | ForEach-Object { "$($_.Name) $($_.Count)" }) -join ", ")+ "Matchup<1" = if ($sent.Count) { [math]::Round(100.0 * @($sent | Where-Object { $_.Matchup -lt 1 -and $_.Theirs -gt 0 }).Count / $sent.Count, 1) } else { "-" }+ }+}+if ($fights) {+ Write-Host "fights (money; Strag% = team deaths with 2+ teammates alive and at most one within 300):"+ $fights | Format-Table -AutoSize | Out-String -Width 400 | Write-Host+ Write-Host ("economy per match: {0:n1} supply truck re-attaches, {1:n1} AI WAVE sends, {2:n1} AI COUNTER picks" -f+ (($played | ForEach-Object { $_.Econ.Reattach } | Measure-Object -Average).Average),+ (($played | ForEach-Object { $_.Econ.Waves } | Measure-Object -Average).Average),+ (($played | ForEach-Object { $_.Econ.Counter } | Measure-Object -Average).Average))+}+# With -Teams the question is which block won, not which seat: allies share a victory, so a team# is counted once per match it won, and its kills and losses are the sum over its members.$teamIds = $rows | ForEach-Object { $_.Slots.Values } | Where-Object { $_.Team -ge 0 } | ForEach-Object { $_.Team } | Sort-Object -Unique@@ -394,6 +466,8 @@ if ($perfRows.Count -gt 0) {# the per-match detail, for whoever wants to look at one game rather than the average$csv = Join-Path $RunDir "$Tag-batch.csv"$rows | Select-Object Seed, Cells, Why, Frames, Wall,+ @{n="Winner";e={ $_.Winner }},+ @{n="ValueLostKilled";e={ $v = $_.Value; if ($v) { ($v.Keys | Sort-Object | ForEach-Object { "{0}:{1}/{2}" -f $_, $v[$_].Lost, $v[$_].Killed }) -join " " } }},@{n="Searches";e={ if ($_.Pf) { $_.Pf.Finds } }},@{n="SearchMs";e={ if ($_.Pf) { [math]::Round($_.Pf.FindMs, 1) } }},@{n="Expands";e={ if ($_.Pf) { $_.Pf.Expands } }},