Skip to content

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

feat(gameengine): hard ai saves up for its top purchase

Olcay Seyganecae25003de4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2f9a90033..696666643 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -175,6 +175,7 @@ found and fixed — EA's own, not port damage.**
- It no longer sits on a pile of cash. Past a level that depends on the difficulty, the more money it has the faster it builds - twice the pile, half the wait, and it stops at four times. It is spending sooner, not building faster: the rate itself is untouched.
- A full bank buys a bigger army. Late in a match the computer's plan allows one of each attack group, so once they were all on the map it only replaced its losses and banked the rest: a Hard USA sat on 117,000 on Twilight Flame. Now every 8,000 in the bank on Hard allows one more copy of each attack group, up to four of them.
- Hard builds past its plan. A tank factory or a barracks gets another copy when units are waiting in its queue, and a factory that was destroyed is put back. Airfields keep going up for as long as the money is there. Supply drop zones and black markets go up one after another as soon as the bank is past a small cushion, whatever else it is buying; they used to wait until production had nothing to ask for, which on a busy map was never, and over twelve four-player matches the count went from 5 to 95. Internet centers follow that same rule. The spot search used to give up two rings outside the opening base, so a full base simply stopped. It now keeps looking further out until the map ends, for factories and power plants; the income buildings stay at home. Strategy centers, propaganda centers and palaces stop at three, so one of them blowing up leaves the tech tree standing. Extra factories still go beside the newest expansion it holds, nearer the fighting. China trains a hacker from every barracks that has room in its queue, not one barracks at a time: 120 hackers across those matches became 375. A hacker left standing still is put to work. It stops at six, an internet center's four plus a couple, because nothing counted them before: a Hard Tank General trained 67 over twenty thousand frames, about two thirds of everything it spent, and every one of them went through the barracks queue its army was waiting in. A player watching it from the other side of the map said China's tank general builds nothing but infantry, and he was right. Seven now, and the teams at the top of its build list are tanks. The limit grows with the match: one hacker for every four fighting units, never more than its Internet Centers have seats for plus four working outside, and never fewer than four. A computer that has not built an army does not buy an economy instead, and one with a full Internet Center and ninety units behind it keeps eight. Replays recorded before this change play out differently.
+- Hard saves up for what it needs most. It used to buy whatever the bank covered the moment it covered it, so the drop zone it needed waited while tank after tank rolled off the line. Every purchase is ranked now: income and power come first for the opening six minutes, the army after that, and when the top one cannot be paid for yet its price is set aside and anything that ranks lower waits until the bank holds more than that price. The saving never turns into a hoard. It lapses after forty seconds, and once the bank is past Hard's cash cushion nothing waits at all. The first drop zone and the first black market also go up in those opening minutes without waiting for the cushion. Over twenty matches with Hard computers on Winter Wolf, 27 computer players had a drop zone or black market standing where 19 had, the first one came at five and a half minutes instead of seven and a half, and 104 of them went up against 46. Replays recorded before this change play out differently.
- Hard picks its road into your base. Of the three approaches it takes the one with the fewest guns it has seen along it, and keeps to the one its plan named until it has scouted something. Aiming at your money instead was tried first and walked it straight past your army.
- Hard sends its attack groups out together. A group too small to be a wave on its own waits on the near side of its base until about seven tanks' worth has gathered, or a minute and a half has passed, and then everything waiting leaves on one road at the pace of its slowest unit. A lone artillery piece or a single bomb truck used to drive across the map by itself, and nearly a third of Hard's units died with barely anyone of their own nearby.
- It reads the odds before it attacks. Every attack was sized the same way whoever it was aimed at, so a computer with an army at home went on waiting for a full wave while the enemy across the map had nothing left to fight with. It now weighs its own army against what it has seen of yours, and an army it cannot see it assumes is growing back towards the size of its own. It has to be looking at your buildings before it believes it is ahead. Ahead by about two to one with your base in view, Hard stops waiting and sends each group as it forms. Ahead by about six to one, the computer on any difficulty sends the guards it used to keep at home for the whole match hunting as well, half a minute apart. Outnumbered two to one, Hard and Medium keep their groups at home until twice the usual wave has gathered, and a handful is never sent into an army that size. Two leaks went with it. Units that reached the end of their road into your base used to stop there and wait for something to shoot at them; they now go looking. A group that got reinforcements at home was ordered out again as a whole, which marched the half already fighting in your base back to the middle of the map to start the walk over. Only the ones at home leave now. Over sixteen Hard against Hard matches on Twilight Flame stopped at seventeen minutes, the five that finished took 12 minutes 26 seconds on average where they had taken 13 minutes 55. The other eleven still ran to the stop: the side that is ahead kills units faster than buildings, and a defender with 120,000 in the bank replaces them at its own door. Replays recorded before this change play out differently.
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
index f392fda84..3bfa3c037 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
@@ -37,6 +37,7 @@
#include "Common/SubsystemInterface.h"
#include "Common/GameMemory.h"
#include "Common/GameType.h"
+#include "Common/GameCommon.h" // LOGICFRAMES_PER_SECOND
#include "GameLogic/Damage.h"
#include "Common/STLTypedefs.h"
@@ -452,6 +453,75 @@ Int aiHoardAdjustedDelay( Int frames, Int money, Int hoardAt );
* at zero, and no threshold leaves EA's limit alone. */
Int aiHoardAllowedTeamInstances( Int maxInstances, Int money, Int hoardAt );
+/** What a computer player's money can go to, as the purchase queue ranks it. */
+enum AIPurchaseKind
+{
+ AIBUY_POWER = 0, ///< a power plant
+ AIBUY_DOZER,
+ AIBUY_ECONOMY, ///< supply center, gatherer, drop zone, black market, internet center, hacker
+ AIBUY_BASE, ///< a factory or anything else on the build list
+ AIBUY_SUPERWEAPON, ///< a superweapon, or the tech building it needs
+ AIBUY_DEFENSE, ///< a base defense
+ AIBUY_ARMY,
+ AIBUY_UPGRADE,
+ AIBUY_EMERGENCY, ///< fighters trained against enemies already standing in the base
+ AIBUY_KIND_COUNT
+};
+
+/** The first minutes of a match, while economy and power outrank the army. */
+const UnsignedInt AI_PURCHASE_EARLY_FRAMES = 6 * 60 * LOGICFRAMES_PER_SECOND;
+
+/** How much a purchase of this kind matters next to the others; the higher wins the money. Early in a
+ * match income and power come before the army, which is how a Hard AI kept attacking with two
+ * gatherers and no drop zone. */
+Int aiPurchaseScore( AIPurchaseKind kind, Bool earlyGame );
+
+/** A Hard skirmish AI's purchase queue. Every spender asks it before it pays, with a stable key (a
+ * template id), the price, its score and whether the thing could start right now (an idle factory,
+ * a dozer). It remembers one request: the best one it could not afford. That one has the money
+ * saved for it, and nothing that ranks below it is bought while the purchase would take the bank
+ * under its price.
+ *
+ * The reservation is bounded every way, since the skirmish scripts keep seven to twenty priority
+ * builds waiting all match and a queue that waits on all of them never buys anything. Only a
+ * request that could start now reserves. A reservation whose spender stops asking goes after
+ * AI_PURCHASE_STALE_FRAMES, one that is not met in AI_PURCHASE_HOLD_FRAMES goes and may not reserve
+ * again for as long, and above the hoard threshold (or the reserved price, if that is more) nothing
+ * is held back at all, so the queue never makes the bank grow past one reserved price. Ties go to
+ * the lower key. */
+struct AIPurchaseQueue
+{
+ enum { NONE = -1 };
+ enum Verdict
+ {
+ BUY, ///< pay for it
+ SHORT, ///< cannot afford it, and nothing was saved for it
+ SAVING, ///< cannot afford it, and the money is being saved for it
+ RESERVED, ///< ... from this request on
+ HELD ///< could afford it, but it would eat the money saved for something better
+ };
+ enum Lapse { KEPT, STALE, TIMED_OUT };
+
+ Int m_key; ///< what the money is saved for, NONE for nothing
+ Int m_cost;
+ Int m_score;
+ UnsignedInt m_since; ///< frame the reservation was made
+ UnsignedInt m_seen; ///< last frame its spender asked
+ Int m_held; ///< purchases held back for it so far
+ Int m_lapsedKey; ///< the last reservation that timed out ...
+ UnsignedInt m_lapsedUntil; ///< ... and the frame it may reserve again
+
+ AIPurchaseQueue() : m_key( NONE ), m_cost( 0 ), m_score( 0 ), m_since( 0 ), m_seen( 0 ), m_held( 0 ),
+ m_lapsedKey( NONE ), m_lapsedUntil( 0 ) {}
+
+ Lapse expire( UnsignedInt frame );
+ Verdict ask( Int key, Int cost, Int score, Bool startable, Int money, Int hoardAt, UnsignedInt frame );
+ void bought( Int key ) { if( key == m_key ) m_key = NONE; }
+};
+
+const UnsignedInt AI_PURCHASE_STALE_FRAMES = 20 * LOGICFRAMES_PER_SECOND;
+const UnsignedInt AI_PURCHASE_HOLD_FRAMES = 40 * LOGICFRAMES_PER_SECOND;
+
/** Which approach a team takes: the lane with the least known enemy firepower along it. A negative
* entry is a lane this map does not have. A tie, or nothing known anywhere, keeps the lane the
* script asked for, so an AI that has not scouted plays exactly as the script wrote it. */
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
index 4c7c5bae6..fdbb3b6ea 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
@@ -45,6 +45,7 @@ class BuildListInfo;
// this header used to compile only behind whoever happened to include Team.h first
class TeamPrototype;
class TeamTemplateInfo;
+class ProductionUpdateInterface;
/// the skirmish scripts send this team at the enemy at some point, rather than keeping it home on guard
Bool aiTeamAttacks(const TeamTemplateInfo *info);
@@ -339,6 +340,18 @@ protected:
* tech building so one of them blowing up leaves the tree standing. */
virtual void doSuperweapons(void);
+ /** The purchase queue (AIPurchaseQueue): every Hard skirmish spender asks before it pays, and the
+ * thing at the top that cannot be afforded yet has the money saved for it. Off, every ask is yes
+ * and the engine's own money check decides, as before. */
+ Bool purchaseQueueOn(void);
+ Bool purchaseAllowed(Int key, Int cost, AIPurchaseKind kind, Bool startable, const AsciiString &what);
+ void purchased(Int key, Int cost, AIPurchaseKind kind, const AsciiString &what);
+ Bool buyUnit(ProductionUpdateInterface *pu, const ThingTemplate *unit, AIPurchaseKind kind); ///< queueCreateUnit through the queue
+ Bool buyUpgrade(ProductionUpdateInterface *pu, const UpgradeTemplate *upgrade); ///< queueUpgrade through the queue
+ static AIPurchaseKind purchaseKindOf(const ThingTemplate *tmpl);
+ AIPurchaseQueue m_purchases;
+ AsciiString m_purchaseSavingFor; ///< the reserved item's name, for the log only
+
Bool enemyDirection(Coord3D *dir); ///< unit vector from this base towards the nearest enemy's best known address
Bool isHeldExpansion(const Object *warehouse); ///< our supply center stands at it, and it is nearer our base than any enemy's
Bool isOurSideOfMap(const Coord3D *pos); ///< no nearer any living enemy's base than ours
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
index 1c88780ed..3b42bd413 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
@@ -1402,6 +1402,75 @@ Int aiHoardAllowedTeamInstances( Int maxInstances, Int money, Int hoardAt )
return maxInstances + extra;
}
+//-------------------------------------------------------------------------------------------------
+Int aiPurchaseScore( AIPurchaseKind kind, Bool earlyGame )
+{
+ switch( kind )
+ {
+ case AIBUY_EMERGENCY: return 200;
+ case AIBUY_POWER: return 100;
+ case AIBUY_DOZER: return 90;
+ case AIBUY_ECONOMY: return earlyGame ? 85 : 50;
+ case AIBUY_BASE: return 70;
+ case AIBUY_SUPERWEAPON: return 60;
+ case AIBUY_ARMY: return earlyGame ? 30 : 55;
+ case AIBUY_DEFENSE: return 45;
+ case AIBUY_UPGRADE: return 35;
+ default: return 0;
+ }
+}
+
+//-------------------------------------------------------------------------------------------------
+AIPurchaseQueue::Lapse AIPurchaseQueue::expire( UnsignedInt frame )
+{
+ if( m_key == NONE )
+ return KEPT;
+ if( frame - m_since >= AI_PURCHASE_HOLD_FRAMES )
+ {
+ m_lapsedKey = m_key;
+ m_lapsedUntil = frame + AI_PURCHASE_HOLD_FRAMES;
+ m_key = NONE;
+ return TIMED_OUT;
+ }
+ if( frame - m_seen >= AI_PURCHASE_STALE_FRAMES )
+ {
+ m_key = NONE;
+ return STALE;
+ }
+ return KEPT;
+}
+
+//-------------------------------------------------------------------------------------------------
+AIPurchaseQueue::Verdict AIPurchaseQueue::ask( Int key, Int cost, Int score, Bool startable, Int money, Int hoardAt, UnsignedInt frame )
+{
+ if( key == m_key )
+ {
+ m_seen = frame;
+ m_cost = cost;
+ return cost <= money ? BUY : SAVING;
+ }
+
+ const Bool outranks = m_key == NONE || score > m_score || (score == m_score && key < m_key);
+ if( cost <= money )
+ {
+ const Int ceiling = hoardAt > m_cost ? hoardAt : m_cost;
+ if( outranks || money - cost >= m_cost || money > ceiling )
+ return BUY;
+ ++m_held;
+ return HELD;
+ }
+
+ if( !startable || !outranks || money > hoardAt || (key == m_lapsedKey && frame < m_lapsedUntil) )
+ return SHORT;
+ m_key = key;
+ m_cost = cost;
+ m_score = score;
+ m_since = frame;
+ m_seen = frame;
+ m_held = 0;
+ return RESERVED;
+}
+
//-------------------------------------------------------------------------------------------------
Int aiLeastDefendedLane( const Real *laneFirepower, Int laneCount, Int requestedLane )
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
index b4650ecc9..970234307 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
@@ -1108,9 +1108,13 @@ Object *AIPlayer::buildStructureWithDozer(const ThingTemplate *bldgPlan, BuildLi
if (dozer==NULL) {
return NULL;
}
- // Check available funds.
+ // Check available funds, and with a Hard AI whether the money is saved for something better.
Money *money = m_player->getMoney();
- if (money->countMoney()<bldgPlan->calcCostToBuild(m_player)) {
+ const Int cost = bldgPlan->calcCostToBuild(m_player);
+ if (!purchaseAllowed(bldgPlan->getTemplateID(), cost, purchaseKindOf(bldgPlan), TRUE, bldgPlan->getName())) {
+ return NULL;
+ }
+ if ((Int)money->countMoney()<cost) {
return NULL;
}
@@ -1332,6 +1336,7 @@ Object *AIPlayer::buildStructureWithDozer(const ThingTemplate *bldgPlan, BuildLi
info->setObjectID( bldg->getID() );
info->setObjectTimestamp( TheGameLogic->getFrame()+1 ); // Has to be non-zero, so add 1.
info->setUnderConstruction(true);
+ purchased( bldgPlan->getTemplateID(), cost, purchaseKindOf(bldgPlan), bldgPlan->getName() );
if (TheGlobalData->m_debugAI) {
AsciiString bldgName = bldgPlan->getName();
@@ -2212,8 +2217,8 @@ Bool AIPlayer::startTraining( WorkOrder *order, Bool busyOK, AsciiString teamNam
if( factory )
{
ProductionUpdateInterface *pu = factory->getProductionUpdateInterface();
- if (pu && pu->queueCreateUnit( order->m_thing, pu->requestUniqueUnitID() )) {
- order->m_factoryID = factory->getID();
+ if (pu && buyUnit( pu, order->m_thing, purchaseKindOf( order->m_thing ) )) {
+ order->m_factoryID = factory->getID();
if (TheGlobalData->m_debugAI) {
AsciiString teamStr = "Queuing ";
teamStr.concat(order->m_thing->getName());
@@ -3225,7 +3230,7 @@ void AIPlayer::buildUpgrade(const AsciiString &upgrade)
// If it doesn't produce, continue.
if (!pu) continue;
// Try to queue it.
- if (pu->queueUpgrade(curUpgrade)) {
+ if (buyUpgrade(pu, curUpgrade)) {
AsciiString msg = TheNameKeyGenerator->keyToName(m_player->getPlayerNameKey());
msg.concat(" queues ");
msg.concat(curUpgrade->getUpgradeName());
@@ -5145,8 +5150,9 @@ static Bool groundLineClear( const Coord3D *from, const Coord3D *to )
}
/** Something of this kind the builder can make right now, off the builder's own buttons, so the
- * answer is right for every faction and general without a table of names. */
-static const ThingTemplate *buildableOfKind( Object *builder, GUICommandType commandType, KindOfType kind )
+ * answer is right for every faction and general without a table of names. moneyLater also takes one
+ * the bank cannot pay for yet, for a request the purchase queue saves up for. */
+static const ThingTemplate *buildableOfKind( Object *builder, GUICommandType commandType, KindOfType kind, Bool moneyLater = FALSE )
{
const CommandSet *commandSet = TheControlBar->findCommandSet( builder->getCommandSetString() );
if( commandSet == NULL )
@@ -5158,7 +5164,10 @@ static const ThingTemplate *buildableOfKind( Object *builder, GUICommandType com
if( button == NULL || button->getCommandType() != commandType )
continue;
const ThingTemplate *tmpl = button->getThingTemplate();
- if( tmpl && tmpl->isKindOf( kind ) && TheBuildAssistant->canMakeUnit( builder, tmpl ) == CANMAKE_OK )
+ if( tmpl == NULL || !tmpl->isKindOf( kind ) )
+ continue;
+ const CanMakeType canMake = TheBuildAssistant->canMakeUnit( builder, tmpl );
+ if( canMake == CANMAKE_OK || (moneyLater && canMake == CANMAKE_NO_MONEY) )
return tmpl;
}
return NULL;
@@ -5783,7 +5792,8 @@ void AIPlayer::doPower( void )
if( dozer == NULL )
return;
- const ThingTemplate *tmpl = buildableOfKind( dozer, GUI_COMMAND_DOZER_CONSTRUCT, KINDOF_FS_POWER );
+ // with the purchase queue the plant is asked for before the bank can pay, and the queue saves for it
+ const ThingTemplate *tmpl = buildableOfKind( dozer, GUI_COMMAND_DOZER_CONSTRUCT, KINDOF_FS_POWER, purchaseQueueOn() );
if( tmpl == NULL || tmpl->isKindOf( KINDOF_CASH_GENERATOR ) || priorityBuildPending( m_player, tmpl ) )
return;
@@ -5853,6 +5863,30 @@ void AIPlayer::doEconomy( void )
doTunnels( dozer );
}
+ // Early in the match the first drop zone and the first black market do not wait for the hoard: they
+ // are asked for when none stands, and the purchase queue ranks them over the army and saves for them.
+ // Behind the hoard alone a Hard AI went out to fight on two gatherers before it owned either.
+ if( purchaseQueueOn() && TheGameLogic->getFrame() < AI_PURCHASE_EARLY_FRAMES && m_player->getCanBuildBase() &&
+ m_baseCenterSet && !isBaseUnderAttack() )
+ {
+ Object *dozer = NULL;
+ m_player->iterateObjects( findAnyDozer, &dozer );
+ const KindOfType EARLY_INCOME[ 2 ] = { KINDOF_FS_SUPPLY_DROPZONE, KINDOF_FS_BLACK_MARKET };
+ for( Int i = 0; dozer && i < 2; ++i )
+ {
+ const ThingTemplate *tmpl = buildableOfKind( dozer, GUI_COMMAND_DOZER_CONSTRUCT, EARLY_INCOME[ i ], TRUE );
+ if( tmpl == NULL || priorityBuildPending( m_player, tmpl ) )
+ continue;
+ TechCount owned;
+ owned.kind = EARLY_INCOME[ i ];
+ owned.standing = 0;
+ owned.onTheWay = 0;
+ m_player->iterateObjects( countTechBuildings, &owned );
+ if( owned.standing + owned.onTheWay == 0 )
+ placeNear( tmpl, &m_baseCenter, 0.5f * m_baseRadius, FALSE );
+ }
+ }
+
// hackers and the buildings that pay out on a timer earn their price back, so they only wait for
// the hoard threshold, and each of them is bought on every pass the bank allows one ...
if( m_player->getMoney()->countMoney() <= profile->m_cashHoardThreshold )
@@ -6207,8 +6241,9 @@ void AIPlayer::doSuperweapons( void )
if( dozer == NULL )
return;
- const ThingTemplate *superweapon = buildableOfKind( dozer, GUI_COMMAND_DOZER_CONSTRUCT, KINDOF_FS_SUPERWEAPON );
- const ThingTemplate *techBuilding = buildableOfKind( dozer, GUI_COMMAND_DOZER_CONSTRUCT, KINDOF_FS_ADVANCED_TECH );
+ // with the purchase queue they are asked for before the bank can pay, and the queue saves for them
+ const ThingTemplate *superweapon = buildableOfKind( dozer, GUI_COMMAND_DOZER_CONSTRUCT, KINDOF_FS_SUPERWEAPON, purchaseQueueOn() );
+ const ThingTemplate *techBuilding = buildableOfKind( dozer, GUI_COMMAND_DOZER_CONSTRUCT, KINDOF_FS_ADVANCED_TECH, purchaseQueueOn() );
TechCount tech;
tech.kind = KINDOF_FS_ADVANCED_TECH;
@@ -6236,6 +6271,109 @@ void AIPlayer::doSuperweapons( void )
buildAsap( superweapon );
}
+//----------------------------------------------------------------------------------------------------------
+/** The purchase queue. Hard skirmish only, the rung that already spends on its own economy; Easy and
+ * Medium, and every campaign AI, buy exactly as they did. */
+//----------------------------------------------------------------------------------------------------------
+Bool AIPlayer::purchaseQueueOn( void )
+{
+ return isSkirmishAI() && getSkillProfile()->m_economyBuildings && getSkillProfile()->m_cashHoardThreshold > 0;
+}
+
+AIPurchaseKind AIPlayer::purchaseKindOf( const ThingTemplate *tmpl )
+{
+ if( tmpl->isKindOf( KINDOF_DOZER ) )
+ return AIBUY_DOZER;
+ if( tmpl->isKindOf( KINDOF_FS_POWER ) && !tmpl->isKindOf( KINDOF_CASH_GENERATOR ) )
+ return AIBUY_POWER;
+ if( tmpl->isKindOf( KINDOF_HARVESTER ) || tmpl->isKindOf( KINDOF_MONEY_HACKER ) || tmpl->isKindOf( KINDOF_FS_SUPPLY_CENTER ) ||
+ tmpl->isKindOf( KINDOF_FS_SUPPLY_DROPZONE ) || tmpl->isKindOf( KINDOF_FS_BLACK_MARKET ) || tmpl->isKindOf( KINDOF_FS_INTERNET_CENTER ) )
+ return AIBUY_ECONOMY;
+ if( tmpl->isKindOf( KINDOF_FS_SUPERWEAPON ) || tmpl->isKindOf( KINDOF_FS_ADVANCED_TECH ) )
+ return AIBUY_SUPERWEAPON;
+ if( tmpl->isKindOf( KINDOF_FS_BASE_DEFENSE ) )
+ return AIBUY_DEFENSE;
+ if( tmpl->isKindOf( KINDOF_STRUCTURE ) )
+ return AIBUY_BASE;
+ return AIBUY_ARMY;
+}
+
+Bool AIPlayer::purchaseAllowed( Int key, Int cost, AIPurchaseKind kind, Bool startable, const AsciiString &what )
+{
+ if( !purchaseQueueOn() )
+ return TRUE;
+
+ const UnsignedInt now = TheGameLogic->getFrame();
+ const Int money = (Int)m_player->getMoney()->countMoney();
+ const Int held = m_purchases.m_held;
+ const AIPurchaseQueue::Lapse lapse = m_purchases.expire( now );
+ if( lapse != AIPurchaseQueue::KEPT )
+ DEBUG_LOG(("AI QUEUE frame %d player %d stops saving for '%s', %s, %d held back for it, %d in the bank\n", now,
+ m_player->getPlayerIndex(), m_purchaseSavingFor.str(), lapse == AIPurchaseQueue::STALE ? "no longer asked for" : "timed out",
+ held, money));
+
+ const Int score = aiPurchaseScore( kind, now < AI_PURCHASE_EARLY_FRAMES );
+ const AIPurchaseQueue::Verdict verdict = m_purchases.ask( key, cost, score, startable, money,
+ getSkillProfile()->m_cashHoardThreshold, now );
+ if( verdict == AIPurchaseQueue::RESERVED )
+ {
+ m_purchaseSavingFor = what;
+ DEBUG_LOG(("AI QUEUE frame %d player %d saves for '%s', %d of %d in the bank, score %d\n", now,
+ m_player->getPlayerIndex(), what.str(), money, cost, score));
+ }
+ return verdict == AIPurchaseQueue::BUY;
+}
+
+void AIPlayer::purchased( Int key, Int cost, AIPurchaseKind kind, const AsciiString &what )
+{
+ if( !purchaseQueueOn() )
+ return;
+ const UnsignedInt now = TheGameLogic->getFrame();
+ if( key == m_purchases.m_key )
+ DEBUG_LOG(("AI QUEUE frame %d player %d buys '%s' for %d, score %d, %d left in the bank, saved for over %d frames and %d held buys\n",
+ now, m_player->getPlayerIndex(), what.str(), cost, aiPurchaseScore( kind, now < AI_PURCHASE_EARLY_FRAMES ),
+ m_player->getMoney()->countMoney(), now - m_purchases.m_since, m_purchases.m_held));
+ else
+ DEBUG_LOG(("AI QUEUE frame %d player %d buys '%s' for %d, score %d, %d left in the bank\n", now,
+ m_player->getPlayerIndex(), what.str(), cost, aiPurchaseScore( kind, now < AI_PURCHASE_EARLY_FRAMES ),
+ m_player->getMoney()->countMoney()));
+ m_purchases.bought( key );
+}
+
+Bool AIPlayer::buyUnit( ProductionUpdateInterface *pu, const ThingTemplate *unit, AIPurchaseKind kind )
+{
+ const Int cost = unit->calcCostToBuild( m_player );
+ if( !purchaseAllowed( unit->getTemplateID(), cost, kind, pu->getProductionCount() == 0, unit->getName() ) )
+ return FALSE;
+ if( !pu->queueCreateUnit( unit, pu->requestUniqueUnitID() ) )
+ return FALSE;
+ purchased( unit->getTemplateID(), cost, kind, unit->getName() );
+ return TRUE;
+}
+
+/** An upgrade's key: its bit in the upgrade mask, which the upgrade center hands out in INI order,
+ * past every template id. */
+static Int upgradePurchaseKey( const UpgradeTemplate *upgrade )
+{
+ const UpgradeMaskType mask = upgrade->getUpgradeMask();
+ for( Int i = 0; i < UPGRADE_MAX_COUNT; ++i )
+ if( mask.test( i ) )
+ return 0x10000 + i;
+ return 0x10000 + UPGRADE_MAX_COUNT;
+}
+
+Bool AIPlayer::buyUpgrade( ProductionUpdateInterface *pu, const UpgradeTemplate *upgrade )
+{
+ const Int key = upgradePurchaseKey( upgrade );
+ const Int cost = upgrade->calcCostToBuild( m_player );
+ if( !purchaseAllowed( key, cost, AIBUY_UPGRADE, pu->getProductionCount() == 0, upgrade->getUpgradeName() ) )
+ return FALSE;
+ if( !pu->queueUpgrade( upgrade ) )
+ return FALSE;
+ purchased( key, cost, AIBUY_UPGRADE, upgrade->getUpgradeName() );
+ return TRUE;
+}
+
//----------------------------------------------------------------------------------------------------------
/** A money unit from every factory that trains one and has at most one thing in its queue. An
* idle-only rule measured as two hackers in a whole match, because a barracks feeding the army is
@@ -6262,7 +6400,7 @@ void AIPlayer::buyMoneyUnits( void )
if( pu == NULL || pu->getProductionCount() > MAX_QUEUED_AHEAD )
continue;
const ThingTemplate *moneyUnit = buildableOfKind( factory, GUI_COMMAND_UNIT_BUILD, KINDOF_MONEY_HACKER );
- if( moneyUnit && pu->queueCreateUnit( moneyUnit, pu->requestUniqueUnitID() ) )
+ if( moneyUnit && buyUnit( pu, moneyUnit, AIBUY_ECONOMY ) )
{
DEBUG_LOG(("AI ECONOMY frame %d player %d trains '%s', %d in the bank, room for %d more\n",
TheGameLogic->getFrame(), m_player->getPlayerIndex(), moneyUnit->getName().str(),
@@ -6879,7 +7017,7 @@ void AIPlayer::defendHome( void )
if( army[ k ].m_weight - answered[ k ] > army[ kind ].m_weight - answered[ kind ] )
kind = k;
const ThingTemplate *unit = bestDefender( *f, m_player, army[ kind ] );
- if( unit == NULL || !pu->queueCreateUnit( unit, pu->requestUniqueUnitID() ) )
+ if( unit == NULL || !buyUnit( pu, unit, AIBUY_EMERGENCY ) )
break;
answered[ kind ] += INT_TO_REAL( unit->calcCostToBuild( m_player ) );
DEBUG_LOG(("AI DEFEND frame %d player %d trains '%s' at '%s' against %d intruders, %d in the bank\n",
@@ -7043,7 +7181,7 @@ void AIPlayer::answerArmy( void )
if( unit == NULL || score < ANSWER_SCORE )
continue;
const Int cost = unit->calcCostToBuild( m_player );
- if( m_player->getMoney()->countMoney() < (UnsignedInt)(cost + ANSWER_RESERVE) || !pu->queueCreateUnit( unit, pu->requestUniqueUnitID() ) )
+ if( m_player->getMoney()->countMoney() < (UnsignedInt)(cost + ANSWER_RESERVE) || !buyUnit( pu, unit, AIBUY_ARMY ) )
continue;
answered[ kind ] += INT_TO_REAL( cost );
DEBUG_LOG(("AI ANSWER frame %d player %d trains '%s' at '%s' against '%s', %.0f of %.0f unanswered, score %.2f, %d in the bank\n",
@@ -7243,7 +7381,7 @@ void AIPlayer::doMass( void )
TheBuildAssistant->canMakeUnit( *f, m_massTemplate ) != CANMAKE_OK ||
m_player->getMoney()->countMoney() < (UnsignedInt)(cost + MASS_RESERVE) )
continue;
- if( pu->queueCreateUnit( m_massTemplate, pu->requestUniqueUnitID() ) )
+ if( buyUnit( pu, m_massTemplate, AIBUY_ARMY ) )
DEBUG_LOG(("AI MASS frame %d player %d trains '%s' at '%s', %d in the fist, %d in the bank\n", now,
m_player->getPlayerIndex(), m_massTemplate->getName().str(), (*f)->getTemplate()->getName().str(),
(Int)m_massUnits.size(), m_player->getMoney()->countMoney()));
@@ -8380,7 +8518,7 @@ Int AIPlayer::buyGunshipRiders( Int freeSeats )
ProductionUpdateInterface *pu = barracks->getProductionUpdateInterface();
Int queued = 0;
- while( queued < wanted && pu->queueCreateUnit( rider, pu->requestUniqueUnitID() ) )
+ while( queued < wanted && buyUnit( pu, rider, AIBUY_ARMY ) )
++queued;
if( queued > 0 )
DEBUG_LOG(("AI GUNSHIP frame %d player %d trains %d '%s' at '%s' for %d free seats, %d in the bank, against %s (%d infantry, %d vehicles known)\n",
@@ -9560,7 +9698,7 @@ void AIPlayer::upgradeHelix( Object *helix, Int role, AIEnemyComposition *enemy,
return;
if( role < 0 && (Int)m_player->getMoney()->countMoney() <= getSkillProfile()->m_cashHoardThreshold + next->calcCostToBuild( m_player ) )
return;
- if( pu->queueUpgrade( next ) )
+ if( buyUpgrade( pu, next ) )
DEBUG_LOG(("AI HELIX frame %d player %d upgrades '%s' %d with '%s' as a %s, enemy known: %d infantry, %d vehicles, threat %.0f%% infantry %.0f%% ground vehicles\n",
TheGameLogic->getFrame(), m_player->getPlayerIndex(), helix->getTemplate()->getName().str(), helix->getID(),
next->getUpgradeName().str(), role < 0 ? "team gunship" : HELIX_ROLE_NAME[ role ], enemy->m_infantryCount, enemy->m_vehicleCount,
@@ -13053,7 +13191,7 @@ void AIPlayer::xfer( Xfer *xfer )
{
// version
- XferVersion currentVersion = 20; // 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 ledger 18: the fist 19: the Ambulances 20: the last Ambulance lost
+ XferVersion currentVersion = 21; // 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 ledger 18: the fist 19: the Ambulances 20: the last Ambulance lost 21: the purchase queue's reservation
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
@@ -13435,6 +13573,18 @@ void AIPlayer::xfer( Xfer *xfer )
}
if( version >= 20 )
xfer->xferUnsignedInt( &m_ambulanceLost );
+ if( version >= 21 )
+ {
+ xfer->xferInt( &m_purchases.m_key );
+ xfer->xferInt( &m_purchases.m_cost );
+ xfer->xferInt( &m_purchases.m_score );
+ xfer->xferUnsignedInt( &m_purchases.m_since );
+ xfer->xferUnsignedInt( &m_purchases.m_seen );
+ xfer->xferInt( &m_purchases.m_held );
+ xfer->xferInt( &m_purchases.m_lapsedKey );
+ xfer->xferUnsignedInt( &m_purchases.m_lapsedUntil );
+ xfer->xferAsciiString( &m_purchaseSavingFor );
+ }
// the ladder rung and the role, which are rolled once and must come back the same way
if( version >= 3 )
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp
index 4b959e348..07340e595 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp
@@ -115,6 +115,11 @@ void AISkirmishPlayer::processBaseBuilding( void )
Bool isPriority = false;
const Bool rushBigGuns = getSkillProfile()->m_economyBuildings;
Bool rushTaken = false;
+ // With the purchase queue the priority entries are taken by its score, the first of the best in
+ // list order, so an early drop zone does not wait behind the scripts' bunkers.
+ const Bool byScore = purchaseQueueOn();
+ const Bool earlyGame = TheGameLogic->getFrame() < AI_PURCHASE_EARLY_FRAMES;
+ Int bldgScore = 0;
Object *bldg = NULL;
const ThingTemplate *powerPlan=NULL;
BuildListInfo *powerInfo = NULL;
@@ -228,7 +233,9 @@ void AISkirmishPlayer::processBaseBuilding( void )
// of an outage waited 45 seconds in that queue and the base went dark before it was started.
const Bool rushThis = rushBigGuns && (curPlan->isKindOf(KINDOF_FS_SUPERWEAPON) || curPlan->isKindOf(KINDOF_FS_ADVANCED_TECH) ||
(powerThin && curPlan->isKindOf(KINDOF_FS_POWER) && !curPlan->isKindOf(KINDOF_CASH_GENERATOR)));
- const Bool couldBePriority = info->isPriorityBuild() && (!isPriority || (rushThis && !rushTaken)) && m_player->canBuild(curPlan);
+ const Int planScore = byScore ? aiPurchaseScore(purchaseKindOf(curPlan), earlyGame) : 0;
+ const Bool couldBePriority = info->isPriorityBuild() &&
+ (!isPriority || (rushThis && !rushTaken) || planScore > bldgScore) && m_player->canBuild(curPlan);
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();
@@ -248,6 +255,7 @@ void AISkirmishPlayer::processBaseBuilding( void )
bldgInfo = info;
isPriority = true;
rushTaken = rushThis;
+ bldgScore = planScore;
}
if (curPlan->isKindOf(KINDOF_FS_POWER)) {
if (powerPlan==NULL && !curPlan->isKindOf(KINDOF_CASH_GENERATOR)) {
@@ -377,7 +385,7 @@ Bool AISkirmishPlayer::startTraining( WorkOrder *order, Bool busyOK, AsciiString
if( factory )
{
ProductionUpdateInterface *pu = factory->getProductionUpdateInterface();
- if (pu && pu->queueCreateUnit( order->m_thing, pu->requestUniqueUnitID() )) {
+ if (pu && buyUnit( pu, order->m_thing, purchaseKindOf( order->m_thing ) )) {
order->m_factoryID = factory->getID();
if (TheGlobalData->m_debugAI) {
AsciiString teamStr = "Queuing ";
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 71da909d2..4da2f2af9 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -11676,6 +11676,107 @@ TEST(a_cash_hoard_allows_more_copies_of_a_team)
}
+/** The purchase queue: a Hard AI saves for the best thing it cannot afford yet instead of buying
+ whatever the bank covers, and every way the saving could turn into a hoard or a deadlock is
+ bounded. ask() changes the queue, so every verdict is taken into a local before it is checked. */
+TEST(the_purchase_queue_saves_for_the_best_thing_it_cannot_afford)
+{
+ const Int HOARD = 4000;
+ const Int ARMY = aiPurchaseScore( AIBUY_ARMY, TRUE );
+ const Int POWER = aiPurchaseScore( AIBUY_POWER, TRUE );
+ AIPurchaseQueue q;
+ AIPurchaseQueue::Verdict v;
+
+ // nothing saved for: whatever the bank covers is bought
+ v = q.ask( 10, 1000, ARMY, TRUE, 2000, HOARD, 100 );
+ CHECK_EQ( AIPurchaseQueue::BUY, v );
+
+ // a power plant it cannot pay for, with a dozer free, has the money saved for it
+ v = q.ask( 5, 1200, POWER, TRUE, 800, HOARD, 100 );
+ CHECK_EQ( AIPurchaseQueue::RESERVED, v );
+ CHECK_EQ( 5, q.m_key );
+
+ // a tank that would take the bank under the plant's price waits ...
+ v = q.ask( 10, 600, ARMY, TRUE, 800, HOARD, 110 );
+ CHECK_EQ( AIPurchaseQueue::HELD, v );
+ CHECK_EQ( 1, q.m_held );
+ // ... and one that leaves the price in the bank does not
+ v = q.ask( 10, 600, ARMY, TRUE, 2000, HOARD, 120 );
+ CHECK_EQ( AIPurchaseQueue::BUY, v );
+
+ // something that ranks above the plant is bought regardless
+ v = q.ask( 20, 500, aiPurchaseScore( AIBUY_EMERGENCY, TRUE ), TRUE, 800, HOARD, 130 );
+ CHECK_EQ( AIPurchaseQueue::BUY, v );
+
+ // a better thing that could not start now never takes the reservation
+ v = q.ask( 3, 5000, 150, FALSE, 800, HOARD, 140 );
+ CHECK_EQ( AIPurchaseQueue::SHORT, v );
+ CHECK_EQ( 5, q.m_key );
+
+ // the plant itself, once the bank covers it, and then nothing is saved for
+ v = q.ask( 5, 1200, POWER, TRUE, 800, HOARD, 150 );
+ CHECK_EQ( AIPurchaseQueue::SAVING, v );
+ v = q.ask( 5, 1200, POWER, TRUE, 1300, HOARD, 160 );
+ CHECK_EQ( AIPurchaseQueue::BUY, v );
+ q.bought( 5 );
+ CHECK_EQ( (Int)AIPurchaseQueue::NONE, q.m_key );
+
+ // above the hoard threshold nothing is saved for: the bank is already big enough
+ v = q.ask( 7, 6000, 60, TRUE, 4500, HOARD, 200 );
+ CHECK_EQ( AIPurchaseQueue::SHORT, v );
+ CHECK_EQ( (Int)AIPurchaseQueue::NONE, q.m_key );
+
+ // a price above the threshold is saved for from under it, and holds the bank only up to that price
+ v = q.ask( 7, 6000, 60, TRUE, 3000, HOARD, 210 );
+ CHECK_EQ( AIPurchaseQueue::RESERVED, v );
+ v = q.ask( 10, 1000, ARMY, TRUE, 5000, HOARD, 220 );
+ CHECK_EQ( AIPurchaseQueue::HELD, v );
+ v = q.ask( 10, 1000, ARMY, TRUE, 6500, HOARD, 230 );
+ CHECK_EQ( AIPurchaseQueue::BUY, v );
+
+ // a reservation its spender stops asking for goes
+ CHECK_EQ( AIPurchaseQueue::KEPT, q.expire( 210 + AI_PURCHASE_STALE_FRAMES - 1 ) );
+ CHECK_EQ( AIPurchaseQueue::STALE, q.expire( 210 + AI_PURCHASE_STALE_FRAMES ) );
+ CHECK_EQ( (Int)AIPurchaseQueue::NONE, q.m_key );
+
+ // one asked for all along but never met times out, and may not take the money again for as long
+ const UnsignedInt start = 1000;
+ v = q.ask( 8, 3000, 50, TRUE, 100, HOARD, start );
+ CHECK_EQ( AIPurchaseQueue::RESERVED, v );
+ UnsignedInt frame = start;
+ for( ; frame < start + AI_PURCHASE_HOLD_FRAMES; frame += 100 )
+ {
+ CHECK_EQ( AIPurchaseQueue::KEPT, q.expire( frame ) );
+ v = q.ask( 8, 3000, 50, TRUE, 100, HOARD, frame );
+ CHECK_EQ( AIPurchaseQueue::SAVING, v );
+ }
+ CHECK_EQ( AIPurchaseQueue::TIMED_OUT, q.expire( frame ) );
+ v = q.ask( 8, 3000, 50, TRUE, 100, HOARD, frame );
+ CHECK_EQ( AIPurchaseQueue::SHORT, v );
+ v = q.ask( 9, 3000, 50, TRUE, 100, HOARD, frame );
+ CHECK_EQ( AIPurchaseQueue::RESERVED, v );
+ q.bought( 9 );
+ v = q.ask( 8, 3000, 50, TRUE, 100, HOARD, frame + AI_PURCHASE_HOLD_FRAMES );
+ CHECK_EQ( AIPurchaseQueue::RESERVED, v );
+
+ // two of the same score: the lower key wins, whichever asked first, so the order is the same everywhere
+ v = q.ask( 4, 3000, 50, TRUE, 100, HOARD, frame + AI_PURCHASE_HOLD_FRAMES );
+ CHECK_EQ( AIPurchaseQueue::RESERVED, v );
+ CHECK_EQ( 4, q.m_key );
+ v = q.ask( 12, 3000, 50, TRUE, 100, HOARD, frame + AI_PURCHASE_HOLD_FRAMES );
+ CHECK_EQ( AIPurchaseQueue::SHORT, v );
+ v = q.ask( 12, 500, 50, TRUE, 1000, HOARD, frame + AI_PURCHASE_HOLD_FRAMES );
+ CHECK_EQ( AIPurchaseQueue::HELD, v );
+
+ // early on income and power outrank the army; later the army climbs past income
+ CHECK( aiPurchaseScore( AIBUY_ECONOMY, TRUE ) > aiPurchaseScore( AIBUY_ARMY, TRUE ) );
+ CHECK( aiPurchaseScore( AIBUY_POWER, TRUE ) > aiPurchaseScore( AIBUY_ARMY, TRUE ) );
+ CHECK( aiPurchaseScore( AIBUY_DOZER, TRUE ) > aiPurchaseScore( AIBUY_ARMY, TRUE ) );
+ CHECK( aiPurchaseScore( AIBUY_ARMY, FALSE ) > aiPurchaseScore( AIBUY_ECONOMY, FALSE ) );
+ CHECK( aiPurchaseScore( AIBUY_POWER, FALSE ) > aiPurchaseScore( AIBUY_ARMY, FALSE ) );
+}
+
+
/** B4, second attempt. The cash map aimed at the enemy's money and walked past his army, 7-9; this
one counts the guns the AI knows about along each approach and takes the quietest. */
TEST(an_attack_takes_the_least_defended_lane)