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 captures the oil derricks instead of shelling them

Olcay Seygan886b981591f2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 997483809..983690335 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,6 +27,7 @@ found and fixed — EA's own, not port damage.**
- Difficulty and AI money change build pace again; every order was pinned at three seconds.
- The computer no longer shoots at what it cannot see. Its units, and its base defences, used to auto-target through the fog of war - a hard exemption written into the code for computer players only. Stealth works against it now, and so does anything it has not scouted.
- 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. And it tours on purpose rather than in a circle: it goes to whichever base it has gone longest without seeing, nearest first, and it does not walk across the map to look again at something it looked at a minute ago - it stays and watches instead. Two scouts never trail each other round the same lap.
+- It takes the oil derricks instead of blowing them up. An oil derrick pays whoever owns it and costs one infantryman to walk in - and the computer used to march past the neutral ones and shell yours, which is the one thing you can do with a derrick that earns nobody anything. It now keeps a cheap infantryman doing the rounds of every derrick, refinery and hospital it has found, takes them, and when there is nothing left to take it leaves him standing on the last one instead of walking him home. And it no longer picks a capturable building as a target of its own accord: it can still be ordered to level one, and one that shoots back is still shot back at.
- Nor does it know which start position you took. It used to read that straight off the lobby, for every player, from the first second. Now it works it out: each position it has not looked at is a suspect, and the odds are simply how many opponents are still unaccounted for over how many places they could be - three of you on an eight-position map is 3 in 7 for each. Every empty position its scout crosses off makes the rest likelier, 3 in 6, then 3 in 5. When the numbers meet, it stops looking: three opponents with three places left to be is not a guess, and walking over to confirm it would waste the trip. On a two-player map that is true from the start, so nothing changed there - it never wastes a second hunting for an address it can work out by subtraction. Where it has not worked you out yet, it attacks the position you are most likely to be on, and finds out on arrival.
- 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.
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
index b945239de..b4d7299a2 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
@@ -289,6 +289,15 @@ Real aiScoutScore( UnsignedInt now, UnsignedInt lastSeenFrame, Real distance, Un
* scout is even built. */
Real aiStartOccupiedOdds( Int unlocatedEnemies, Int uncheckedPositions );
+/** Is this building income rather than a target? An oil derrick pays whoever owns it and costs one
+ * infantryman to take, so a computer player razing the enemy's is the one thing it can do with a
+ * derrick that earns nobody anything.
+ *
+ * Two things are deliberately still targets. One that shoots back has to be shootable back at, or
+ * the AI walks past a bunker forever. And one that cannot be captured at all is only ever a
+ * building in the way. */
+Bool aiIsIncomeNotATarget( Bool isTechBuilding, Bool isCapturable, Bool isTechBaseDefense );
+
/** How attractive an enemy player is to go after, as a cost - lower is better, and it is a squared
* distance with the other terms folded into it so the units stay comparable.
*
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
index 36563702c..5525ed62b 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
@@ -268,6 +268,14 @@ protected:
void countStartIntel(Int *enemies, Int *occupied, Int *unchecked) const; ///< the three numbers the odds are made of
Bool enemyStartGuess(Int playerNdx, Coord3D *pos); ///< where this enemy is, or the best address we have for him
+ /** B?: an oil derrick is income standing in the open. The AI used to walk past the neutral ones
+ * and shoot the enemy's, which is the one thing you can do with a derrick that earns nothing. */
+ virtual void doCapture(void);
+ Object *findCapturer(void); ///< a unit of ours that can walk into a building and own it
+ Object *nearestTechBuilding(const Coord3D *from, Bool wantOurs); ///< the closest one worth taking, or worth sitting on
+ void queueCapturer(void); ///< ... or build the cheapest thing that can take one
+ void queueSupportUnit(const ThingTemplate *tmpl, const char *what); ///< one cheap unit, outside the team system
+
virtual void doBaseBuilding(void);
virtual void checkReadyTeams(void);
virtual void checkQueuedTeams(void);
@@ -350,6 +358,8 @@ protected:
Bool m_startOccupied[ MAX_PLAYER_COUNT ]; ///< ... and which of those turned out to hold an enemy
Int m_playerStartNdx[ MAX_PLAYER_COUNT ]; ///< the start position each player is known to be at; -1 == not found yet
UnsignedInt m_startIntelFrame; ///< frame the above was last brought up to date
+ ObjectID m_capturerID; ///< the unit currently out taking tech buildings for us
+ Int m_captureTimer; ///< frames until the next look for something to capture
Int m_retreatTimer; ///< frames until the next look at how the fights are going
Int m_expandTimer; ///< frames until the next look for somewhere to expand to
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
index 80d59f096..ac3487980 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
@@ -1121,6 +1121,12 @@ Real aiStartOccupiedOdds( Int unlocatedEnemies, Int uncheckedPositions )
return (Real)unlocatedEnemies / (Real)uncheckedPositions;
}
+//-------------------------------------------------------------------------------------------------
+Bool aiIsIncomeNotATarget( Bool isTechBuilding, Bool isCapturable, Bool isTechBaseDefense )
+{
+ return isTechBuilding && isCapturable && !isTechBaseDefense;
+}
+
//-------------------------------------------------------------------------------------------------
Real aiRoleMassFraction( AIRole role )
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
index 92e567965..1cf269436 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
@@ -62,6 +62,8 @@
#include "GameLogic/Module/SupplyTruckAIUpdate.h"
#include "GameLogic/Module/SupplyWarehouseDockUpdate.h"
#include "GameLogic/PartitionManager.h"
+#include "Common/ActionManager.h" // canCaptureBuilding, for the tech buildings
+#include "GameLogic/Module/SpecialPowerModule.h" // ... and the module that does it
#ifdef _INTERNAL
// for occasional debugging...
@@ -195,6 +197,8 @@ m_role(AIROLE_AGGRESSIVE)
m_playerStartNdx[startNdx] = -1; // nobody located yet, not even us - updateStartIntel seeds it
}
m_startIntelFrame = 0;
+ m_capturerID = INVALID_ID;
+ m_captureTimer = 1;
m_frameLastBuildingBuilt = TheGameLogic->getFrame();
p->setCanBuildUnits(false); // turn off ai production by default.
@@ -3583,6 +3587,8 @@ void AIPlayer::update( void )
doExpansion(); // Go and take the money that is lying around.
+ doCapture(); // ... and the money that is standing around.
+
}
//----------------------------------------------------------------------------------------------------------
@@ -4060,11 +4066,19 @@ Bool AIPlayer::scoutInQueue( void )
*/
void AIPlayer::queueScout( void )
{
- if( scoutInQueue() )
- return;
+ queueSupportUnit( cheapestScoutTemplate( m_player ), "SCOUT" );
+}
- const ThingTemplate *tTemplate = cheapestScoutTemplate( m_player );
- if( tTemplate == NULL )
+//----------------------------------------------------------------------------------------------------------
+/**
+ * Put one cheap unit on order for a job outside the team system - the scout, the capturer. Same
+ * shape as queueDozer: a one-order priority team on the player's default team, so it never disturbs
+ * the team the AI is massing, and it waits for spare change so it can never be what stops a base
+ * going up. One at a time, whichever job asked first.
+ */
+void AIPlayer::queueSupportUnit( const ThingTemplate *tTemplate, const char *what )
+{
+ if( tTemplate == NULL || scoutInQueue() )
return;
// scouting must never be what stops a base going up, so it waits for spare change
@@ -4093,7 +4107,8 @@ void AIPlayer::queueScout( void )
team->m_frameStarted = TheGameLogic->getFrame();
team->m_team = m_player->getDefaultTeam();
- AsciiString msg = "SCOUT - building one at the ";
+ AsciiString msg = what;
+ msg.concat( " - building one at the " );
msg.concat( factory->getTemplate()->getName() );
TheScriptEngine->AppendDebugMessage( msg, false );
@@ -4424,6 +4439,230 @@ Bool AIPlayer::nextScoutTarget( Int slot, const Coord3D *from, Coord3D *pos )
return TRUE;
}
+//----------------------------------------------------------------------------------------------------------
+/** How often the AI looks for something to capture. It only ever gets an order when it is idle, so
+ * this is a check, not a re-path. */
+static const Int CAPTURE_CHECK_RATE = 5 * LOGICFRAMES_PER_SECOND;
+
+/** The cheapest infantry this player can build that can walk into a building and own it. Read off
+ * the command set rather than a per-faction table, so it lands on the Ranger, the Rebel and the
+ * Red Guard - and on whatever a mod gave the ability to. */
+static const ThingTemplate *cheapestCapturerTemplate( Player *player )
+{
+ if( TheControlBar == NULL )
+ return NULL;
+
+ const ThingTemplate *best = NULL;
+ Int bestCost = 0;
+
+ for( const ThingTemplate *t = TheThingFactory->firstTemplate(); t; t = t->friend_getNextTemplate() )
+ {
+ if( !t->isKindOf( KINDOF_INFANTRY ) || t->isKindOf( KINDOF_DOZER ) )
+ continue;
+ if( !player->canBuild( t ) )
+ continue;
+
+ const Int cost = t->calcCostToBuild( player );
+ if( cost <= 0 || (best != NULL && cost >= bestCost) )
+ continue;
+
+ const CommandSet *set = TheControlBar->findCommandSet( t->friend_getCommandSetString() );
+ if( set == NULL )
+ continue;
+
+ Bool canCapture = FALSE;
+ for( Int i = 0; i < MAX_COMMANDS_PER_SET; ++i )
+ {
+ const CommandButton *button = set->getCommandButton( i );
+ if( button == NULL || button->getCommandType() != GUI_COMMAND_SPECIAL_POWER )
+ continue;
+ const SpecialPowerTemplate *power = button->getSpecialPowerTemplate();
+ if( power && power->getSpecialPowerType() == SPECIAL_INFANTRY_CAPTURE_BUILDING )
+ canCapture = TRUE;
+ }
+ if( !canCapture )
+ continue;
+
+ best = t;
+ bestCost = cost;
+ }
+ return best;
+}
+
+//----------------------------------------------------------------------------------------------------------
+/**
+ * A unit of ours that can take a building. Same rule as findScout: the default team only, so
+ * nothing is pulled off a team that has a mission.
+ */
+Object *AIPlayer::findCapturer( void )
+{
+ Team *team = m_player->getDefaultTeam();
+ if( team == NULL )
+ return NULL;
+
+ for( DLINK_ITERATOR<Object> iter = team->iterate_TeamMemberList(); !iter.done(); iter.advance() )
+ {
+ Object *obj = iter.cur();
+ if( obj == NULL || obj->isEffectivelyDead() || obj->getAI() == NULL )
+ continue;
+ if( obj->findSpecialPowerModuleInterface( SPECIAL_INFANTRY_CAPTURE_BUILDING ) == NULL )
+ continue;
+
+ Bool busy = FALSE;
+ for( Int slot = 0; slot < MAX_AI_SCOUTS; ++slot )
+ if( m_scoutID[ slot ] == obj->getID() )
+ busy = TRUE; // the map still has to be looked at
+ if( busy )
+ continue;
+
+ return obj;
+ }
+ return NULL;
+}
+
+//----------------------------------------------------------------------------------------------------------
+/**
+ * The closest tech building worth walking to: one to take (wantOurs FALSE) or one of ours to stand
+ * on (wantOurs TRUE).
+ *
+ * Fog-aware like everything else here - a derrick nobody has seen yet is not a plan. Uncaptured
+ * ones belong to the neutral player, captured ones to whoever took them, so both are found by
+ * walking the player list, which is the same shape getPlayerStructureBounds uses.
+ */
+Object *AIPlayer::nearestTechBuilding( const Coord3D *from, Bool wantOurs )
+{
+ if( ThePlayerList == NULL || from == NULL )
+ return NULL;
+
+ const Int myNdx = m_player->getPlayerIndex();
+ Object *best = NULL;
+ Real bestDistSqr = 0.0f;
+
+ const Int playerCount = ThePlayerList->getPlayerCount();
+ for( Int i = 0; i < playerCount; ++i )
+ {
+ Player *p = ThePlayerList->getNthPlayer( i );
+ if( p == NULL )
+ continue;
+ if( wantOurs != (p == m_player) )
+ continue;
+ if( !wantOurs && p != m_player && m_player->getRelationship( p->getDefaultTeam() ) == ALLIES )
+ continue; // it is not polite to capture an ally's buildings
+
+ for( Player::PlayerTeamList::const_iterator it = p->getPlayerTeams()->begin();
+ it != p->getPlayerTeams()->end(); ++it )
+ {
+ for( DLINK_ITERATOR<Team> teamIter = (*it)->iterate_TeamInstanceList(); !teamIter.done(); teamIter.advance() )
+ {
+ Team *team = teamIter.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_TECH_BUILDING ) )
+ continue;
+ if( !wantOurs && obj->isKindOf( KINDOF_IMMUNE_TO_CAPTURE ) )
+ continue;
+ if( !observerKnowsAbout( obj, myNdx ) )
+ continue; // not found yet, so not a plan
+
+ const Coord3D *at = obj->getPosition();
+ const Real dx = at->x - from->x;
+ const Real dy = at->y - from->y;
+ const Real distSqr = dx*dx + dy*dy;
+ if( best == NULL || distSqr < bestDistSqr )
+ {
+ best = obj;
+ bestDistSqr = distSqr;
+ }
+ }
+ }
+ }
+ }
+ return best;
+}
+
+//----------------------------------------------------------------------------------------------------------
+/**
+ * Go and take the buildings that pay.
+ *
+ * An oil derrick is a supply pile that never runs out and costs one infantryman to own, and the AI
+ * had no concept of one: it walked past the neutral ones and shot the enemy's. One cheap unit now
+ * does the rounds, and when there is nothing left to take it stands on what we own - an uncaptured
+ * derrick is free money for whoever walks up to it next, and a captured one is free money for
+ * whoever walks up to it after that.
+ */
+void AIPlayer::doCapture( void )
+{
+ if( --m_captureTimer > 0 )
+ return;
+ m_captureTimer = CAPTURE_CHECK_RATE;
+
+ Object *capturer = TheGameLogic->findObjectByID( m_capturerID );
+ if( capturer && (capturer->isEffectivelyDead() || capturer->getControllingPlayer() != m_player) )
+ capturer = NULL;
+ if( capturer == NULL )
+ {
+ m_capturerID = INVALID_ID;
+ capturer = findCapturer();
+ if( capturer )
+ m_capturerID = capturer->getID();
+ }
+
+ Coord3D from = m_baseCenter;
+ if( capturer )
+ from = *capturer->getPosition();
+
+ Object *target = nearestTechBuilding( &from, FALSE );
+
+ if( capturer == NULL )
+ {
+ // only pay for one when there is something to spend it on
+ if( target )
+ queueCapturer();
+ return;
+ }
+
+ AIUpdateInterface *ai = capturer->getAI();
+ if( ai == NULL || !ai->isIdle() )
+ return; // still on its way
+
+ if( target == NULL )
+ {
+ // nothing left to take: sit on what we own rather than wander home and let it be taken back
+ Object *ours = nearestTechBuilding( &from, TRUE );
+ if( ours )
+ ai->aiGuardObject( ours, GUARDMODE_NORMAL, CMD_FROM_AI );
+ return;
+ }
+
+ //
+ // canCaptureBuilding refuses through the shroud and the capture itself has a range, so a target
+ // we know about but cannot reach from here is walked to first and asked again next check.
+ //
+ SpecialPowerModuleInterface *mod = capturer->findSpecialPowerModuleInterface( SPECIAL_INFANTRY_CAPTURE_BUILDING );
+ if( mod && TheActionManager->canCaptureBuilding( capturer, target, CMD_FROM_AI ) )
+ {
+ mod->doSpecialPowerAtObject( target, 0 );
+ DEBUG_LOG(("AI player %d capturing a '%s'\n", m_player->getPlayerIndex(),
+ target->getTemplate()->getName().str()));
+ }
+ else
+ {
+ ai->aiMoveToObject( target, CMD_FROM_AI );
+ }
+}
+
+//----------------------------------------------------------------------------------------------------------
+void AIPlayer::queueCapturer( void )
+{
+ queueSupportUnit( cheapestCapturerTemplate( m_player ), "CAPTURE" );
+}
+
//----------------------------------------------------------------------------------------------------------
/**
* Keep one unit looking at the map. Cheap by construction: one unit, ordered only when it has
@@ -4682,7 +4921,7 @@ void AIPlayer::xfer( Xfer *xfer )
{
// version
- XferVersion currentVersion = 4; // 2: the scout 3: skill rung and role 4: the scouting stamps
+ XferVersion currentVersion = 5; // 2: scout 3: rung and role 4: scouting stamps 5: the capturer
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
@@ -4863,6 +5102,12 @@ void AIPlayer::xfer( Xfer *xfer )
xfer->xferInt( &m_retreatTimer );
xfer->xferInt( &m_expandTimer );
}
+ // the capturer, so a loaded game does not build a second one
+ if( version >= 5 )
+ {
+ xfer->xferObjectID( &m_capturerID );
+ xfer->xferInt( &m_captureTimer );
+ }
// 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/Object/PartitionManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
index dcfa5ad0d..71701dfb2 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
@@ -1,4 +1,4 @@
-/*
+/*
** Command & Conquer Generals Zero Hour(tm)
** Copyright 2025 Electronic Arts Inc.
**
@@ -73,6 +73,7 @@
#include "GameLogic/Module/ContainModule.h"
#include "GameLogic/Module/StealthUpdate.h"
#include "GameLogic/PartitionManager.h"
+#include "GameLogic/AI.h" // aiIsIncomeNotATarget - a derrick is money, not a target
#include "GameLogic/PolygonTrigger.h"
#include "GameLogic/Squad.h"
#include "GameLogic/GhostObject.h"
@@ -5482,6 +5483,19 @@ Bool PartitionFilterPossibleToAttack::allow(Object *objOther)
if (IncomingDamageTracker::isAlreadyDoomed(objOther))
return FALSE;
+ //
+ // A capturable tech building is income, not a target. The computer razed the enemy's oil derricks
+ // on sight - the one thing you can do with a derrick that earns nobody anything - when it could
+ // have walked an infantryman in and owned it. As above, this filter only ever runs when a unit is
+ // picking its own target, so an explicit order to level one still goes through, and a tech
+ // building that shoots back is still shot back at.
+ //
+ if (m_obj->getControllingPlayer() && m_obj->getControllingPlayer()->getPlayerType() == PLAYER_COMPUTER &&
+ aiIsIncomeNotATarget(objOther->isKindOf(KINDOF_TECH_BUILDING),
+ objOther->isKindOf(KINDOF_CAPTURABLE),
+ objOther->isKindOf(KINDOF_TECH_BASE_DEFENSE)))
+ return FALSE;
+
CanAttackResult result = m_obj->getAbleToAttackSpecificObject( m_attackType, objOther, m_commandSource );
if( result == ATTACKRESULT_POSSIBLE || result == ATTACKRESULT_POSSIBLE_AFTER_MOVING )
{
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index fb6640d35..665428f6a 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -6025,6 +6025,29 @@ TEST(elimination_narrows_the_start_positions_until_it_knows)
}
+/** An oil derrick pays whoever owns it and costs one infantryman to take, so the computer razing the
+ enemy's was the one thing it could do with a derrick that earned nobody anything. It captures them
+ now, and stops picking them up as targets on its own initiative - but only the ones that are
+ actually worth owning and cannot shoot back. */
+TEST(a_capturable_tech_building_is_income_not_a_target)
+{
+ // the oil derrick: a tech building, capturable, unarmed
+ CHECK( aiIsIncomeNotATarget( TRUE, TRUE, FALSE ) );
+
+ //
+ // The two that stay targets. A tech building that acts as a base defence when captured shoots at
+ // us, and something that is never shot back at is something the AI walks past for ever.
+ //
+ CHECK( !aiIsIncomeNotATarget( TRUE, TRUE, TRUE ) );
+ // ... and one nobody can capture is only ever a building in the way
+ CHECK( !aiIsIncomeNotATarget( TRUE, FALSE, FALSE ) );
+
+ // everything else is untouched: this rule is about tech buildings and nothing else
+ CHECK( !aiIsIncomeNotATarget( FALSE, TRUE, FALSE ) );
+ CHECK( !aiIsIncomeNotATarget( FALSE, FALSE, FALSE ) );
+}
+
+
/** C2: whether a finished wave waits at the rally point or goes now. EA sent every team the moment
it was ready, and a string of small waves is free veterancy for whoever is on the other end.
Three things override the arithmetic, and each of them is a way of getting the AI stuck if it is