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): the AI builds against what it can see you fielding

Olcay Seygan4b68c730b4de
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 33f559349..4cf282dbf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -29,6 +29,13 @@ found and fixed — EA's own, not port damage.**
- It scouts. There was no such thing as scouting in the computer opponent - it never needed to look, because it could already see everything. One cheap unit now tours the enemy start positions and keeps going round for the rest of the match, replaced out of spare change when it dies. Every difficulty scouts; an opponent that never looks reads as broken, not as easy.
- Nor does it read your base off the map. Where your base is, what it is worth, which supply dock to expand to and where to aim a superweapon all came off a walk of your object list, in the shroud, from the first second of the match. The computer now only counts what it can see, plus the buildings it has already found - buildings do not walk away. Before it has scouted you, all it knows is where you started, which is on the map preview anyway.
+## The computer builds against what you field
+
+- Which unit it trained next was a coin flip. It gathered the teams sharing the highest priority number in its data and picked one at random - not one line looked at what it was fighting. An opponent facing nothing but aircraft went on building tanks.
+- Now the priority is the start of a score, not the whole of it. What it can *see* you fielding weights the choice: air pushes anti-air up, stealth pushes detectors up, armour pushes anti-tank up. Its own data decides what counts as the answer to what, so a mod's units are read correctly too.
+- How much that weighs depends on the level, from nothing at all on Easy - which is what the game always did - to fully on Merciless.
+- Anti-air was the computer's oldest hole. It is closed.
+
## Six difficulty levels, and none of them cheat
- Easy, Steady, Medium, Hard, Brutal, Merciless. Medium to Brutal used to be a cliff; the steps in between are where a player actually needs them.
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
index 5ff3c9690..1cc1240ef 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
@@ -196,6 +196,40 @@ struct AIDifficultyProfile
Int m_cashHoardThreshold; ///< above this, spend faster; 0 = never hurry
};
+//-------------------------------------------------------------------------------------------------
+/** What an enemy is fielding, as shares of the threat value the observer can actually see. The
+ * four shares overlap (a stealth tank is both armour and stealth) and each is 0..1. */
+//-------------------------------------------------------------------------------------------------
+struct AIEnemyComposition
+{
+ Real m_air; ///< share of the enemy's visible threat value that flies
+ Real m_armour; ///< ... that is a vehicle
+ Real m_infantry;
+ Real m_stealth; ///< ... that can go invisible
+
+ AIEnemyComposition() : m_air(0.0f), m_armour(0.0f), m_infantry(0.0f), m_stealth(0.0f) {}
+};
+
+//-------------------------------------------------------------------------------------------------
+/** What a team can answer, read off the unit templates it is built from. */
+//-------------------------------------------------------------------------------------------------
+struct AITeamCapability
+{
+ Bool m_hitsAir;
+ Bool m_hitsGround;
+ Bool m_detectsStealth;
+ Bool m_prefersVehicles; ///< carries a weapon declared PreferredAgainst a vehicle: anti-tank
+ Bool m_prefersInfantry; ///< ... or against infantry: splash, flame, machine gun
+
+ AITeamCapability() : m_hitsAir(FALSE), m_hitsGround(FALSE), m_detectsStealth(FALSE),
+ m_prefersVehicles(FALSE), m_prefersInfantry(FALSE) {}
+};
+
+/** How well this team answers what the enemy is fielding, 0 (answers none of it) to 1 (answers all
+ * of it). Pure arithmetic on purpose - the whole point of B1 is a score you can test and tune
+ * rather than a coin flip, and this is the half of it that has no engine in it. */
+Real aiCounterScore( const AIEnemyComposition &enemy, const AITeamCapability &team );
+
class TAiData : public Snapshot
{
public:
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
index a69ebd89a..ce9edf6a8 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
@@ -256,6 +256,7 @@ protected:
virtual void doUpgradesAndSkills(void);
virtual Object *findDozer(const Coord3D *pos);
virtual void queueDozer(void);
+ void computeEnemyComposition( AIEnemyComposition *out ); ///< what this AI can see the enemy fielding
virtual Bool selectTeamToBuild( void ); ///< determine the next team to build
virtual Bool selectTeamToReinforce( Int minPriority ); ///< determine the next team to reinforce
virtual Bool startTraining( WorkOrder *order, Bool busyOK, AsciiString teamName); ///< find a production building that can handle the order, and start building
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
index 99fa5b884..68f9ac6bb 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
@@ -1022,6 +1022,38 @@ static const AIDifficultyProfile s_defaultSkillLadder[ AISKILL_COUNT ] =
/* Merciless */ { 25.0f, 2, 0.0f, 1.5f, 1.00f, TRUE, 0.85f, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 4000 }
};
+//-------------------------------------------------------------------------------------------------
+/** How well a team answers what the enemy is fielding.
+ *
+ * Anti-air and stealth detection carry their enemy's whole share, because a team that cannot
+ * touch what it is walking into is worth nothing against it - AA is the AI's classic hole and
+ * stealth became a real threat to it the moment its units stopped shooting through fog. A
+ * weapon declared PreferredAgainst something is the data's own statement that it is the answer to
+ * it, so that is what "anti-tank" and "anti-infantry" mean here rather than a hand-kept list.
+ *
+ * Merely being able to shoot at the ground is worth a quarter share: almost every team can, so
+ * it barely discriminates, but a team that cannot is genuinely useless against a ground army. */
+//-------------------------------------------------------------------------------------------------
+Real aiCounterScore( const AIEnemyComposition &enemy, const AITeamCapability &team )
+{
+ Real score = 0.0f;
+
+ if( team.m_hitsAir )
+ score += enemy.m_air;
+ if( team.m_detectsStealth )
+ score += enemy.m_stealth;
+ if( team.m_prefersVehicles )
+ score += enemy.m_armour;
+ if( team.m_prefersInfantry )
+ score += enemy.m_infantry;
+ if( team.m_hitsGround )
+ score += 0.25f * (enemy.m_armour + enemy.m_infantry);
+
+ if( score < 0.0f ) score = 0.0f;
+ if( score > 1.0f ) score = 1.0f;
+ return score;
+}
+
//-------------------------------------------------------------------------------------------------
const AIDifficultyProfile *AI::getDifficultyProfile( AISkillLevel level ) const
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
index 37ceea7a1..e140e0b9e 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
@@ -51,6 +51,7 @@
#include "GameLogic/SidesList.h"
#include "GameLogic/AI.h"
#include "GameLogic/AIPathfind.h"
+#include "GameLogic/Weapon.h" // the anti-masks B1 reads off a team's weapons
#include "GameLogic/TerrainLogic.h"
#include "GameLogic/Module/AIUpdate.h"
#include "GameLogic/Module/DozerAIUpdate.h"
@@ -1736,6 +1737,129 @@ Bool AIPlayer::selectTeamToReinforce( Int minPriority )
// ------------------------------------------------------------------------------------------------
/** Determine the next team to build. Return true if one was selected. */
// ------------------------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------------------------
+/** What one unit template can answer. Read off its weapons: what they are allowed to shoot at,
+ * and what the data says they are the preferred answer to. */
+//-------------------------------------------------------------------------------------------------
+static void addTemplateCapability( const ThingTemplate *tmpl, AITeamCapability *cap )
+{
+ if( tmpl == NULL )
+ return;
+
+ //
+ // "Can it see stealth" is not a KindOf - it is a module the data hangs on the unit, so ask the
+ // template's module list by name. That is the same question the game itself answers when it
+ // builds the object, one INI edit away from being right for a mod's own detector.
+ //
+ const ModuleInfo &modules = tmpl->getBehaviorModuleInfo();
+ for( Int m = 0; m < modules.getCount(); ++m )
+ {
+ if( modules.getNthName( m ).compareNoCase( "StealthDetectorUpdate" ) == 0 )
+ {
+ cap->m_detectsStealth = TRUE;
+ break;
+ }
+ }
+
+ const WeaponTemplateSetVector &sets = tmpl->getWeaponTemplateSets();
+ for( WeaponTemplateSetVector::const_iterator it = sets.begin(); it != sets.end(); ++it )
+ {
+ for( Int slot = 0; slot < WEAPONSLOT_COUNT; ++slot )
+ {
+ const WeaponTemplate *w = it->getNth( (WeaponSlotType)slot );
+ if( w == NULL )
+ continue;
+
+ const Int anti = w->getAntiMask();
+ if( anti & (WEAPON_ANTI_AIRBORNE_VEHICLE | WEAPON_ANTI_AIRBORNE_INFANTRY) )
+ cap->m_hitsAir = TRUE;
+ if( anti & WEAPON_ANTI_GROUND )
+ cap->m_hitsGround = TRUE;
+
+ const KindOfMaskType &preferred = it->getNthPreferredAgainstMask( (WeaponSlotType)slot );
+ if( preferred.test( KINDOF_VEHICLE ) )
+ cap->m_prefersVehicles = TRUE;
+ if( preferred.test( KINDOF_INFANTRY ) )
+ cap->m_prefersInfantry = TRUE;
+ }
+ }
+}
+
+//-------------------------------------------------------------------------------------------------
+/** What a team prototype can answer, over every unit it is built from. */
+//-------------------------------------------------------------------------------------------------
+static AITeamCapability teamCapability( const TeamPrototype *proto )
+{
+ AITeamCapability cap;
+ const TeamTemplateInfo *info = proto ? proto->getTemplateInfo() : NULL;
+ if( info == NULL )
+ return cap;
+
+ for( Int i = 0; i < info->m_numUnitsInfo; ++i )
+ addTemplateCapability( TheThingFactory->findTemplate( info->m_unitsInfo[ i ].unitThingName, FALSE ), &cap );
+
+ return cap;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** What this AI can see of what its enemies are fielding, weighted by threat value so a tank
+ * counts for more than a rifleman. Fog-aware by construction - it asks observerKnowsAbout of
+ * every object, which is what makes B1 A2's first customer. */
+//-------------------------------------------------------------------------------------------------
+void AIPlayer::computeEnemyComposition( AIEnemyComposition *out )
+{
+ Real air = 0.0f, armour = 0.0f, infantry = 0.0f, stealth = 0.0f, total = 0.0f;
+ const Int me = m_player->getPlayerIndex();
+
+ for( Int i = 0; i < ThePlayerList->getPlayerCount(); ++i )
+ {
+ Player *p = ThePlayerList->getNthPlayer( i );
+ if( p == NULL || p == m_player )
+ continue;
+ if( 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() )
+ {
+ Team *team = iter.cur();
+ if( team == NULL )
+ continue;
+ for( DLINK_ITERATOR<Object> objIter = team->iterate_TeamMemberList(); !objIter.done(); objIter.advance() )
+ {
+ Object *obj = objIter.cur();
+ if( obj == NULL || obj->isEffectivelyDead() )
+ continue;
+ if( obj->isKindOf( KINDOF_STRUCTURE ) || obj->isKindOf( KINDOF_PROJECTILE ) )
+ continue; // this is about the army, not the base
+ if( !observerKnowsAbout( obj, me ) )
+ continue;
+
+ const Real threat = INT_TO_REAL( obj->getTemplate()->getThreatValue() );
+ if( threat <= 0.0f )
+ continue;
+
+ total += threat;
+ if( obj->isKindOf( KINDOF_AIRCRAFT ) ) air += threat;
+ if( obj->isKindOf( KINDOF_VEHICLE ) ) armour += threat;
+ if( obj->isKindOf( KINDOF_INFANTRY ) ) infantry += threat;
+ if( obj->getStatusBits().test( OBJECT_STATUS_CAN_STEALTH ) ) stealth += threat;
+ }
+ }
+ }
+ }
+
+ if( total <= 0.0f )
+ return; // nothing seen: the caller's zeroed composition means "no opinion"
+
+ out->m_air = air / total;
+ out->m_armour = armour / total;
+ out->m_infantry = infantry / total;
+ out->m_stealth = stealth / total;
+}
+
Bool AIPlayer::selectTeamToBuild( void )
{
@@ -1771,12 +1895,55 @@ Bool AIPlayer::selectTeamToBuild( void )
TheScriptEngine->AppendDebugMessage("**AI** Selecting team to build", false);
}
- // collect all teams that are possible to build, and are at the highest priority
+ //
+ // EA's version stopped here: take the highest static productionPriority and flip a coin among
+ // the ties. Not one line of it looked at what the enemy was fielding, which is why an AI facing
+ // nothing but aircraft would go on building tanks.
+ //
+ // So the static priority is the base of a score rather than the whole of it, and two situational
+ // terms ride on top:
+ //
+ // - how well the team answers what this AI can *see* the enemy fielding (B1), scaled by the
+ // rung's counterCompositionWeight - zero on the bottom two rungs, which is EA's behaviour
+ // exactly, up to one at the top;
+ // - what this AI is trying to do (D8): an aggressive one leans towards attack teams, a
+ // defensive one towards the teams the data flags as base or perimeter defence. A
+ // preference, not a bonus - both spend the same money.
+ //
+ // The coin flip stays, for the ties that remain. Determinism: GameLogicRandomValue, as before.
+ //
+ const AIDifficultyProfile *profile = getSkillProfile();
+ AIEnemyComposition enemy;
+ if (profile->m_counterCompositionWeight > 0.0f)
+ computeEnemyComposition( &enemy );
+
+ // what a perfect counter, and the role preference, are worth in units of production priority
+ const Real COUNTER_SPAN = 20.0f;
+ const Real ROLE_SPAN = 10.0f;
+
Player::PlayerTeamList candidateList;
Int count = 0;
+ Real bestScore = 0.0f;
+ Bool haveBest = FALSE;
for (t = candidateList1.begin(); t != candidateList1.end(); ++t)
{
- if ((*t)->getTemplateInfo()->m_productionPriority == hiPri)
+ const TeamTemplateInfo *info = (*t)->getTemplateInfo();
+ const Bool isDefenceTeam = info->m_isBaseDefense || info->m_isPerimeterDefense;
+
+ Real score = INT_TO_REAL( info->m_productionPriority );
+ score += profile->m_counterCompositionWeight * COUNTER_SPAN *
+ aiCounterScore( enemy, teamCapability( *t ) );
+ if( (m_role == AIROLE_DEFENSIVE) == (isDefenceTeam != FALSE) )
+ score += ROLE_SPAN;
+
+ if( !haveBest || score > bestScore )
+ {
+ bestScore = score;
+ haveBest = TRUE;
+ candidateList.clear();
+ count = 0;
+ }
+ if( score >= bestScore )
{
candidateList.push_back( (*t) );
count++;
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 1d81ac82c..c27e76a95 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -5834,3 +5834,57 @@ TEST(the_difficulty_ladder_climbs_in_every_direction_it_should)
CHECK( data.m_skill[ i ].m_maxScouts >= 1 );
}
}
+
+
+/** B1's arithmetic, the half of "build what counters what he is fielding" that has no engine in it.
+ The bug it replaces was not a bad score, it was no score at all: EA picked at random among the
+ teams sharing the highest static priority, so an AI facing nothing but aircraft went on building
+ tanks. */
+TEST(counter_score_answers_what_the_enemy_actually_fields)
+{
+ AIEnemyComposition allAir;
+ allAir.m_air = 1.0f;
+
+ AITeamCapability aa; aa.m_hitsAir = TRUE;
+ AITeamCapability tanks; tanks.m_hitsGround = TRUE; tanks.m_prefersVehicles = TRUE;
+
+ // against an all-air enemy the AA team is the answer and the tank team is not
+ CHECK_NEAR( 1.0f, aiCounterScore( allAir, aa ), 0.0001f );
+ CHECK_NEAR( 0.0f, aiCounterScore( allAir, tanks ), 0.0001f );
+
+ // against an all-armour enemy it is the other way round: anti-tank scores its share plus the
+ // quarter share every ground-capable team gets
+ AIEnemyComposition allArmour;
+ allArmour.m_armour = 1.0f;
+ CHECK_NEAR( 1.0f, aiCounterScore( allArmour, tanks ), 0.0001f );
+ CHECK_NEAR( 0.0f, aiCounterScore( allArmour, aa ), 0.0001f );
+
+ // a team that can only shoot the ground is worth something against a ground army, but far less
+ // than one built for it
+ AITeamCapability generic; generic.m_hitsGround = TRUE;
+ CHECK_NEAR( 0.25f, aiCounterScore( allArmour, generic ), 0.0001f );
+ CHECK( aiCounterScore( allArmour, generic ) < aiCounterScore( allArmour, tanks ) );
+
+ // stealth is the case A1 created: the AI stopped shooting through fog, so a detector earns its
+ // place the moment the enemy fields anything that can hide
+ AIEnemyComposition halfStealth;
+ halfStealth.m_armour = 1.0f;
+ halfStealth.m_stealth = 0.5f;
+ AITeamCapability detector; detector.m_hitsGround = TRUE; detector.m_detectsStealth = TRUE;
+ CHECK( aiCounterScore( halfStealth, detector ) > aiCounterScore( halfStealth, generic ) );
+
+ // seen nothing yet -> no opinion, whatever the team is. The static priority then decides,
+ // which is EA's behaviour and the right fallback.
+ AIEnemyComposition unknown;
+ CHECK_NEAR( 0.0f, aiCounterScore( unknown, aa ), 0.0001f );
+ CHECK_NEAR( 0.0f, aiCounterScore( unknown, tanks ), 0.0001f );
+
+ // the score is a share, so it never leaves 0..1 however many terms a team answers
+ AIEnemyComposition mixed;
+ mixed.m_air = 0.4f; mixed.m_armour = 0.4f; mixed.m_infantry = 0.2f; mixed.m_stealth = 0.3f;
+ AITeamCapability everything;
+ everything.m_hitsAir = everything.m_hitsGround = everything.m_detectsStealth = TRUE;
+ everything.m_prefersVehicles = everything.m_prefersInfantry = TRUE;
+ CHECK( aiCounterScore( mixed, everything ) <= 1.0f );
+ CHECK( aiCounterScore( mixed, everything ) > aiCounterScore( mixed, generic ) );
+}