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(ai): hard fights from an influence map, kites and takes high ground

Olcay Seygan28c38ada4733
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ba23fb10a..efd79a5c1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -105,6 +105,16 @@ found and fixed — EA's own, not port damage.**
- It weighs a fight by what is in it, not by who is nearby: only things that can shoot count, and buildings do not. Its own base is not a reason to feel safe and yours is not a reason to run.
- Its aircraft are left out of it. A retreat order was what took a parked jet off the runway, so while a fight raged near the airfield the whole wing took off, flew at the base, landed, and did it again every few seconds instead of ever reaching you. Aircraft already fly home on their own when the load is spent.
- Matches finish. Two of these opponents used to fail to settle 65% of their games inside sixteen minutes; it is half that now, and they end in under seven minutes on average instead of ten.
+- On Hard the retreat actually happens now. The order home was handed to units that were already fighting, and the game laid it over their attack instead of replacing it, so a team told to break off carried on driving at what it was shooting, and its aggressive mood turned any walk that did start into a fight on the way. Medium still retreats the old way.
+
+## Hard fights each unit from where it is strongest
+
+- Hard keeps a map of what it knows can shoot where. Every gun it has seen, including the bunkers it spotted once, is marked on the ground it reaches, and a gun on a ridge reaches further, the way it does in the game. Its own and its allies' firepower goes on the same map. It picks its road into your base by how much of that road your guns cover, not by how many of them stand near its waypoints. That old count also took in the computer's own tanks as if they were yours.
+- It kites. Infantry and anything with a turret step back out of the reach of a slower gun they outrange, from the far edge of their own range, and go on shooting the thing that was closing on them. A base defense it outranges gets the same treatment, so it is shelled from outside its reach instead of driven up to. It does not run from a rifleman its tank could drive over. Cars with fixed rocket racks do not kite, because the turn back to aim cost them more than the step saved.
+- It keeps the high ground when the high ground matters. A unit being hit by what it is shooting looks for a rise nearby from where its longer reach lets it keep firing while the other gun no longer reaches it, with a straight road up and no more of your guns covering it.
+- Hurt units leave ground they cannot win. One below about a third of its health, standing where your guns outweigh its side's, walks to the first cell on the way home that nothing of yours covers, and rejoins its team when the fight is over.
+- A unit walking to a far target stops to shoot what is already in its reach. Four Rocket Buggies sent at the last of four tanks used to drive past the other three with their rockets loaded.
+- Over 128 matches on Twilight Flame, one Hard against the same Hard without any of this, the side with it lost 18,048 units where the other lost 18,774, and killed 17,684 where the other killed 16,892. That is a small, steady edge rather than a new opponent. Over 128 matches on small generated maps the two came out even. Two more ideas were tried and taken out again: gathering waves on the nearest high ground, and holding a wave back until it matched the guns on its road. Neither beat not doing it.
## The computer builds against what you field
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
index 4ac5571db..d7a03ed92 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
@@ -429,6 +429,7 @@ public:
Bool m_headless; ///< -headless: never draw a frame, never pace the logic tick, quit when the match ends
Bool m_turbo; ///< -turbo: draw, but run one logic frame a pass instead of pacing it to the wall clock
Int 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_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 run
Bool m_unitLimit; ///< -unitlimit: the lobby's unit limit for an -autoskirmish run
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
index 8305edfd4..1ea51c6b3 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
@@ -204,6 +204,9 @@ struct AIDifficultyProfile
Bool m_defendExpansions;
Int m_cashHoardThreshold; ///< above this, spend faster; 0 = never hurry
Bool m_economyBuildings; ///< past the hoard, buy production and income the build list never had
+
+ // Fighting: decisions only, from what it knows can shoot where
+ Bool m_tacticalMicro; ///< kite what it outranges, take the high ground, pull hurt units out
};
//-------------------------------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIInfluenceMap.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIInfluenceMap.h
new file mode 100644
index 000000000..81fc508b5
--- /dev/null
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIInfluenceMap.h
@@ -0,0 +1,91 @@
+/*
+** Command & Conquer Generals Zero Hour(tm)
+** Copyright 2025 Electronic Arts Inc.
+**
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+** GNU General Public License for more details.
+**
+** You should have received a copy of the GNU General Public License
+** along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+// AIInfluenceMap.h
+// What one computer player knows can shoot at each patch of ground, and what it has there itself.
+
+#pragma once
+
+#ifndef _AI_INFLUENCE_MAP_H_
+#define _AI_INFLUENCE_MAP_H_
+
+#include <vector>
+
+class Xfer;
+
+/** A grid over the map, one per computer player, rebuilt from what that player knows about.
+ *
+ * The engine's own per-cell threat layer is built from ThingTemplate::ThreatValue, which the shipped
+ * data almost never sets, so every one of its cells reads zero. This one stamps each armed thing's
+ * combat power onto every cell its guns reach, the reach stretched by the high ground the way
+ * Weapon_elevatedRange stretches it, so "how much can hit me here" is one lookup. The friendly
+ * layer is the same stamp for this player's own units and its allies'.
+ *
+ * Everything here is plain arithmetic on logic state in the order the caller hands it over, so two
+ * machines that stamp the same objects in the same order hold the same map. */
+class AIInfluenceMap
+{
+public:
+ AIInfluenceMap();
+
+ /** Size the grid to a map and forget everything on it. heights is filled by the caller through
+ * setCellHeight, once per map, since the ground does not move. */
+ void reset( Real originX, Real originY, Real width, Real height, Real cellSize );
+ Bool isSized() const { return m_cols > 0; }
+ void clear();
+
+ Int getCols() const { return m_cols; }
+ Int getRows() const { return m_rows; }
+ void cellCenter( Int col, Int row, Real *x, Real *y ) const;
+ void setCellHeight( Int col, Int row, Real z );
+
+ /** Add power to every cell a weapon of this range, fired from (x, y, z), reaches. */
+ void stampEnemy( Real x, Real y, Real z, Real range, Real power );
+ void stampFriend( Real x, Real y, Real z, Real range, Real power );
+
+ Real enemyAt( Real x, Real y ) const;
+ Real friendAt( Real x, Real y ) const;
+
+ /** The whole map, into a save and back: a loaded game reads the same map the uninterrupted one
+ * holds until its next rebuild, which can be most of a second away. */
+ void xfer( Xfer *xfer );
+
+ void markBuilt( UnsignedInt frame ) { m_builtFrame = frame; m_built = TRUE; }
+ Bool isBuilt() const { return m_built; }
+ UnsignedInt getBuiltFrame() const { return m_builtFrame; }
+
+private:
+ void stamp( std::vector<Real> &layer, Real x, Real y, Real z, Real range, Real power );
+ Int cellIndexAt( Real x, Real y ) const;
+
+ Real m_originX, m_originY, m_cellSize;
+ Int m_cols, m_rows;
+ std::vector<Real> m_enemy;
+ std::vector<Real> m_friend;
+ std::vector<Real> m_height;
+ Bool m_built;
+ UnsignedInt m_builtFrame;
+};
+
+/** Where a unit that outranges what is closing on it should step to: on the line from the enemy
+ * through the unit, at the far edge of its own reach, which is as far from the enemy's gun as it can
+ * stand and still shoot. FALSE when it has no such room, which is when its range is not longer than
+ * the enemy's by twice the margin. */
+Bool AIKite_standoffDistance( Real myRange, Real enemyRange, Real margin, Real *distance );
+
+#endif
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
index b6ca0e0fb..cfa779d2f 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
@@ -35,6 +35,7 @@
#include "Common/Snapshot.h"
#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"
enum { INVALID_SKILLSET_SELECTION = -1 };
@@ -500,6 +501,36 @@ protected:
Coord3D m_strikeAim[ MAX_REMEMBERED_STRIKES ];
UnsignedInt m_strikeFrame[ MAX_REMEMBERED_STRIKES ]; ///< frame each was aimed; 0 == slot never used
Int m_strikeNext; ///< slot the next aim is written to
+
+ /** What this player knows can shoot at each patch of the map, and what it has there itself. */
+ AIInfluenceMap m_influence;
+ void rebuildInfluence(void);
+
+ /** Hard's fighting units, one at a time: step back from what they outrange, climb onto ground
+ * that lengthens their guns, and take a hurt unit out of ground it cannot win on. */
+ virtual void doTactics(void);
+ void tacticsFor(Object *obj);
+ struct TacticalStep
+ {
+ ObjectID unit;
+ ObjectID target; ///< what it goes back to shooting when the step is done
+ Coord3D origin; ///< where it stepped from, to walk back to when the target is gone
+ UnsignedInt resumeFrame; ///< 0 while it is not stepping
+ UnsignedInt nextClimbFrame; ///< no look for higher ground before this
+ UnsignedInt leaveAloneUntil; ///< sent home by the retreat, not to be turned round
+ Bool rejoin; ///< stepped out of its team's order, and goes back to the team when the fight is over
+ Int savedAttitude; ///< its mood before a step calmed it, AI_INVALID when it has its own
+ UnsignedInt lastKiteFrame; ///< last time it stepped back from something it outranges, 0 for never
+ UnsignedInt lastSeenFrame; ///< a unit not looked at for a while has died or left, and its row goes
+ };
+ std::vector<TacticalStep> m_tactics;
+ TacticalStep *findTacticalStep(ObjectID unit);
+ TacticalStep *tacticalStepFor(ObjectID unit); ///< ... making the row if there is none
+ void leaveTacticsAlone(ObjectID unit);
+ void stepCalmly(Object *obj, TacticalStep *step, const Coord3D *spot); ///< a move the unit's mood cannot turn into an attack move
+ void restoreMood(Object *obj, TacticalStep *step);
+ Bool pickTacticalSpot(const Object *obj, const Coord3D *from, const Coord3D *awayFrom, Real distance,
+ const Coord3D *mustReach, Real reach, Coord3D *spot);
};
#endif // _AI_PLAYER_H_
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
index 1c05537a1..a746ee8cb 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
@@ -1175,6 +1175,19 @@ Int parseAIDifficulty2(char *args[], int num)
return 2;
}
+/** -notactics even|odd: those slots keep their rung but fight without its unit tactics, so a batch can
+ * play Hard against the same Hard minus one thing, from both sides of the map. Read only in a
+ * single-player skirmish (AIPlayer::doTactics), so a network game never sees it. */
+Int parseNoTactics(char *args[], int num)
+{
+ if (TheWritableGlobalData && num > 1)
+ {
+ AsciiString parity = args[1];
+ TheWritableGlobalData->m_noTacticsSlotParity = (parity.compareNoCase("even") == 0) ? 0 : 1;
+ }
+ return 2;
+}
+
Int parseObserver(char *args[], int num)
{
if (TheWritableGlobalData)
@@ -2382,6 +2395,7 @@ static CommandLineParam params[] =
{ "-autoskirmish", parseAutoSkirmish },
{ "-aidiff", parseAIDifficulty },
{ "-aidiff2", parseAIDifficulty2 },
+ { "-notactics", parseNoTactics },
{ "-observer", parseObserver },
{ "-headless", parseHeadless },
{ "-maxframes", parseMaxGameFrames },
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
index ced1a9c0e..35fb609f8 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
@@ -703,6 +703,7 @@ GlobalData::GlobalData()
m_autoSkirmishPlayers = 0; // no skirmish from the command line
m_autoSkirmishAIState = SLOT_BRUTAL_AI;
m_autoSkirmishAIStateOdd = 0; // 0 = not set: every slot plays at -aidiff
+ m_noTacticsSlotParity = -1;
m_autoSkirmishTeams = 0; // 0 = not set: every slot fights every other slot
m_peaceTime = 0; // no truce unless -peacetime asks for one
m_unitLimit = FALSE; // no unit limit unless -unitlimit asks for one
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
index 17bd6ba16..168be2c7a 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
@@ -1082,9 +1082,9 @@ Real AI::getAdjustedVisionRangeForObject(const Object *object, Int factorsToCons
* scoutS maxSc react decis cntr mass ttk indiv team infl focus save harv expand guard hoard econ */
static const AIDifficultyProfile s_defaultSkillLadder[ AISKILL_COUNT ] =
{
- /* Easy */ { 90.0f, 1, 15.0f, 10.0f, 0.00f, FALSE, 0.00f, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, 0, FALSE },
- /* Medium */ { 60.0f, 1, 6.0f, 5.0f, 0.25f, FALSE, 0.35f, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, 10000, FALSE },
- /* Brutal */ { 25.0f, 2, 0.0f, 1.5f, 1.00f, TRUE, 0.50f, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 4000, TRUE }
+ /* Easy */ { 90.0f, 1, 15.0f, 10.0f, 0.00f, FALSE, 0.00f, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, 0, FALSE, FALSE },
+ /* Medium */ { 60.0f, 1, 6.0f, 5.0f, 0.25f, FALSE, 0.35f, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, 10000, FALSE, FALSE },
+ /* Brutal */ { 25.0f, 2, 0.0f, 1.5f, 1.00f, TRUE, 0.50f, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 4000, TRUE, TRUE }
};
//-------------------------------------------------------------------------------------------------
@@ -1388,6 +1388,7 @@ void AI::parseSkillLevel(INI *ini, void *instance, void* /*store*/, const void*
{ "DefendExpansions", INI::parseBool, NULL, offsetof( AIDifficultyProfile, m_defendExpansions ) },
{ "CashHoardThreshold", INI::parseInt, NULL, offsetof( AIDifficultyProfile, m_cashHoardThreshold ) },
{ "EconomyBuildings", INI::parseBool, NULL, offsetof( AIDifficultyProfile, m_economyBuildings ) },
+ { "TacticalMicro", INI::parseBool, NULL, offsetof( AIDifficultyProfile, m_tacticalMicro ) },
{ NULL, NULL, NULL, 0 }
};
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIInfluenceMap.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIInfluenceMap.cpp
new file mode 100644
index 000000000..c403f7b74
--- /dev/null
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIInfluenceMap.cpp
@@ -0,0 +1,153 @@
+/*
+** Command & Conquer Generals Zero Hour(tm)
+** Copyright 2025 Electronic Arts Inc.
+**
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+** GNU General Public License for more details.
+**
+** You should have received a copy of the GNU General Public License
+** along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+// AIInfluenceMap.cpp
+
+#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine
+
+#include "Common/Xfer.h"
+#include "GameLogic/AIInfluenceMap.h"
+#include "GameLogic/Weapon.h"
+
+AIInfluenceMap::AIInfluenceMap() :
+ m_originX( 0.0f ), m_originY( 0.0f ), m_cellSize( 1.0f ), m_cols( 0 ), m_rows( 0 ),
+ m_built( FALSE ), m_builtFrame( 0 )
+{
+}
+
+void AIInfluenceMap::reset( Real originX, Real originY, Real width, Real height, Real cellSize )
+{
+ m_originX = originX;
+ m_originY = originY;
+ m_cellSize = cellSize;
+ m_cols = (width > 0.0f) ? REAL_TO_INT_CEIL( width / cellSize ) : 0;
+ m_rows = (height > 0.0f) ? REAL_TO_INT_CEIL( height / cellSize ) : 0;
+ m_enemy.assign( m_cols * m_rows, 0.0f );
+ m_friend.assign( m_cols * m_rows, 0.0f );
+ m_height.assign( m_cols * m_rows, 0.0f );
+ m_built = FALSE;
+}
+
+void AIInfluenceMap::clear()
+{
+ m_enemy.assign( m_enemy.size(), 0.0f );
+ m_friend.assign( m_friend.size(), 0.0f );
+}
+
+void AIInfluenceMap::cellCenter( Int col, Int row, Real *x, Real *y ) const
+{
+ *x = m_originX + (col + 0.5f) * m_cellSize;
+ *y = m_originY + (row + 0.5f) * m_cellSize;
+}
+
+void AIInfluenceMap::setCellHeight( Int col, Int row, Real z )
+{
+ m_height[ row * m_cols + col ] = z;
+}
+
+Int AIInfluenceMap::cellIndexAt( Real x, Real y ) const
+{
+ const Int col = REAL_TO_INT_FLOOR( (x - m_originX) / m_cellSize );
+ const Int row = REAL_TO_INT_FLOOR( (y - m_originY) / m_cellSize );
+ if( col < 0 || row < 0 || col >= m_cols || row >= m_rows )
+ return -1;
+ return row * m_cols + col;
+}
+
+/** The high ground can at most double a range (ELEVATION_RANGE_CAP), so the square walked is twice
+ * the range out, and each cell inside it is cut back to the reach its own height allows. */
+void AIInfluenceMap::stamp( std::vector<Real> &layer, Real x, Real y, Real z, Real range, Real power )
+{
+ if( m_cols <= 0 || power <= 0.0f || range <= 0.0f )
+ return;
+
+ const Real farthest = range + Weapon_elevationRangeBonus( range, FLT_MAX );
+ const Int colLo = max<Int>( 0, REAL_TO_INT_FLOOR( (x - farthest - m_originX) / m_cellSize ) );
+ const Int colHi = min<Int>( m_cols - 1, REAL_TO_INT_FLOOR( (x + farthest - m_originX) / m_cellSize ) );
+ const Int rowLo = max<Int>( 0, REAL_TO_INT_FLOOR( (y - farthest - m_originY) / m_cellSize ) );
+ const Int rowHi = min<Int>( m_rows - 1, REAL_TO_INT_FLOOR( (y + farthest - m_originY) / m_cellSize ) );
+ for( Int row = rowLo; row <= rowHi; ++row )
+ {
+ const Real cy = m_originY + (row + 0.5f) * m_cellSize;
+ for( Int col = colLo; col <= colHi; ++col )
+ {
+ const Int index = row * m_cols + col;
+ const Real cx = m_originX + (col + 0.5f) * m_cellSize;
+ const Real reach = range + Weapon_elevationRangeBonus( range, z - m_height[ index ] );
+ if( sqr( cx - x ) + sqr( cy - y ) <= sqr( reach ) )
+ layer[ index ] += power;
+ }
+ }
+}
+
+void AIInfluenceMap::stampEnemy( Real x, Real y, Real z, Real range, Real power )
+{
+ stamp( m_enemy, x, y, z, range, power );
+}
+
+void AIInfluenceMap::stampFriend( Real x, Real y, Real z, Real range, Real power )
+{
+ stamp( m_friend, x, y, z, range, power );
+}
+
+Real AIInfluenceMap::enemyAt( Real x, Real y ) const
+{
+ const Int index = cellIndexAt( x, y );
+ return (index < 0) ? 0.0f : m_enemy[ index ];
+}
+
+Real AIInfluenceMap::friendAt( Real x, Real y ) const
+{
+ const Int index = cellIndexAt( x, y );
+ return (index < 0) ? 0.0f : m_friend[ index ];
+}
+
+void AIInfluenceMap::xfer( Xfer *xfer )
+{
+ xfer->xferReal( &m_originX );
+ xfer->xferReal( &m_originY );
+ xfer->xferReal( &m_cellSize );
+ xfer->xferInt( &m_cols );
+ xfer->xferInt( &m_rows );
+ xfer->xferBool( &m_built );
+ xfer->xferUnsignedInt( &m_builtFrame );
+ const size_t cells = (size_t)m_cols * (size_t)m_rows;
+ if( xfer->getXferMode() == XFER_LOAD )
+ {
+ m_enemy.assign( cells, 0.0f );
+ m_friend.assign( cells, 0.0f );
+ m_height.assign( cells, 0.0f );
+ }
+ for( size_t i = 0; i < cells; ++i )
+ {
+ xfer->xferReal( &m_enemy[ i ] );
+ xfer->xferReal( &m_friend[ i ] );
+ xfer->xferReal( &m_height[ i ] );
+ }
+}
+
+Bool AIKite_standoffDistance( Real myRange, Real enemyRange, Real margin, Real *distance )
+{
+ if( myRange < enemyRange + 2.0f * margin )
+ return FALSE;
+ // the far edge of its own reach: the most room between it and the gun closing on it, so the step
+ // that follows is a long way off. Stepping to just past the enemy's reach left a vehicle turning
+ // round inside it by the time the turn was done.
+ *distance = myRange - margin;
+ return TRUE;
+}
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
index 20e6466dc..cabc22b59 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
@@ -4162,9 +4162,9 @@ void AIPlayer::doUpgradesAndSkills( void )
Pathfinder already break theirs down: per job, plus whichever single player cost the most.
Reset once per logic frame by AI::update. */
enum { AIP_BASE, AIP_READY, AIP_QUEUED, AIP_TEAM, AIP_UPGRADE,
- AIP_BRIDGE, AIP_SCOUT, AIP_RETREAT, AIP_EXPAND, AIP_CAPTURE, AIP_ECONOMY, AIP_POWER, AIP_WAVE, AIP_PHASE_COUNT };
+ AIP_BRIDGE, AIP_SCOUT, AIP_RETREAT, AIP_EXPAND, AIP_CAPTURE, AIP_ECONOMY, AIP_POWER, AIP_WAVE, AIP_TACTICS, AIP_PHASE_COUNT };
static const char *theAIPhaseName[ AIP_PHASE_COUNT ] =
- { "base", "ready", "queued", "team", "upg", "bridge", "scout", "retreat", "expand", "capture", "economy", "power", "wave" };
+ { "base", "ready", "queued", "team", "upg", "bridge", "scout", "retreat", "expand", "capture", "economy", "power", "wave", "tactics" };
static Real theAIPhaseMS[ AIP_PHASE_COUNT ];
static Real theAIWorstPlayerMS = 0.0f;
static Int theAIWorstPlayer = -1;
@@ -4242,6 +4242,7 @@ void AIPlayer::update( void )
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, doWaves() ); // Send the parked attack teams out together.
+ AI_PHASE( AIP_TACTICS, doTactics() ); // Fight each unit from where it is strongest.
#ifdef DEBUG_LOGGING
Int64 playerEnd;
@@ -4506,6 +4507,36 @@ static const Real APPROACH_WATCH_RADIUS = 250.0f;
/** Longest approach walked, in waypoints; a path that loops would otherwise never end. */
static const Int APPROACH_MAX_WAYPOINTS = 64;
+/** The influence map's cell: a fifth of a tank's range, so the edge of a gun's reach is placed to
+ * within a tank's length. */
+static const Real INFLUENCE_CELL_SIZE = 60.0f;
+
+/** A unit that kited this recently is left in its fight by the retreat. */
+static const UnsignedInt KITE_KEEPS_FIGHT_FRAMES = 5 * LOGICFRAMES_PER_SECOND;
+
+/** Clear ground all the way on the straight line between two points: no cliff, water or wall cell in
+ * between. A spot on top of a ledge is a short step on the map and a long drive round by the ramp,
+ * and a tactical step is only worth it when it is the short one. */
+static Bool groundLineClear( const Coord3D *from, const Coord3D *to )
+{
+ const Real dx = to->x - from->x;
+ const Real dy = to->y - from->y;
+ const Int samples = 1 + REAL_TO_INT_FLOOR( sqrt( dx * dx + dy * dy ) / (PATHFIND_CELL_SIZE_F * 0.5f) );
+ for( Int i = 1; i <= samples; ++i )
+ {
+ Coord3D at;
+ at.x = from->x + dx * i / samples;
+ at.y = from->y + dy * i / samples;
+ at.z = 0.0f;
+ ICoord2D cell;
+ TheAI->pathfinder()->worldToCell( &at, &cell );
+ const PathfindCell *pathCell = TheAI->pathfinder()->getCell( LAYER_GROUND, cell.x, cell.y );
+ if( pathCell == NULL || pathCell->getType() != PathfindCell::CELL_CLEAR )
+ return FALSE;
+ }
+ return TRUE;
+}
+
/** 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 )
@@ -5394,7 +5425,22 @@ Real AIPlayer::knownFirepowerAlongPath( Waypoint *way )
for( Int step = 0; way != NULL && step < APPROACH_MAX_WAYPOINTS; ++step )
{
firepower += knownFirepowerNear( way->getLocation() );
- way = (way->getNumLinks() > 0) ? way->getLink( 0 ) : NULL;
+ Waypoint *next = (way->getNumLinks() > 0) ? way->getLink( 0 ) : NULL;
+ if( next && m_influence.isBuilt() )
+ {
+ // the whole leg, not only its ends: a gun that covers the middle of a long leg between two
+ // waypoints out of its reach is still on the road
+ const Coord3D *a = way->getLocation();
+ const Coord3D *b = next->getLocation();
+ const Real length = sqrt( sqr( b->x - a->x ) + sqr( b->y - a->y ) );
+ const Int samples = REAL_TO_INT_FLOOR( length / INFLUENCE_CELL_SIZE );
+ for( Int i = 1; i < samples; ++i )
+ {
+ const Real t = INT_TO_REAL( i ) / INT_TO_REAL( samples );
+ firepower += m_influence.enemyAt( a->x + (b->x - a->x) * t, a->y + (b->y - a->y) * t );
+ }
+ }
+ way = next;
}
return firepower;
}
@@ -5404,6 +5450,12 @@ Real AIPlayer::knownFirepowerAlongPath( Waypoint *way )
//----------------------------------------------------------------------------------------------------------
Real AIPlayer::knownFirepowerNear( const Coord3D *pos )
{
+ // the influence map answers the question the radius only approximated: not what stands near the
+ // road, but what can shoot onto it, the high ground's reach included. The radius count below also
+ // took in this player's own units, which the affiliation filter lets through whatever it is asked.
+ if( m_influence.isBuilt() )
+ return m_influence.enemyAt( pos->x, pos->y );
+
PartitionFilterPlayerAffiliation enemies( m_player, ALLOW_ENEMIES, true );
PartitionFilterAlive alive;
PartitionFilter *filters[] = { &enemies, &alive, NULL };
@@ -6085,13 +6137,622 @@ void AIPlayer::doRetreats( void )
// round at the mouth
if( obj->getAI()->hasTunnelTrip() )
continue;
- if( homeTunnel == NULL || !obj->getAI()->takeTunnelTrip( homeTunnel, &m_baseCenter, TUNNEL_TRIP_MOVE, CMD_FROM_AI ) )
+ // one that is kiting the fight is winning its own share of it however the totals read: a
+ // Rocket Buggy turned for home in front of four tanks it outran and outranged died turning
+ const TacticalStep *kiting = findTacticalStep( obj->getID() );
+ if( kiting && kiting->lastKiteFrame != 0 && TheGameLogic->getFrame() - kiting->lastKiteFrame < KITE_KEEPS_FIGHT_FRAMES )
+ continue;
+ if( homeTunnel != NULL && obj->getAI()->takeTunnelTrip( homeTunnel, &m_baseCenter, TUNNEL_TRIP_MOVE, CMD_FROM_AI ) )
+ leaveTacticsAlone( obj->getID() );
+ else if( m_influence.isBuilt() )
+ {
+ // the walk home taken calm, or its mood turns it into an attack move back into the fight
+ leaveTacticsAlone( obj->getID() );
+ stepCalmly( obj, tacticalStepFor( obj->getID() ), &m_baseCenter );
+ }
+ else
obj->getAI()->aiMoveToPosition( &m_baseCenter, CMD_FROM_AI );
}
}
}
}
+//----------------------------------------------------------------------------------------------------------
+/** How often the influence map is redrawn, and how often each fighting unit is looked at. Both are on
+ * the frame and the player's slot, so there is no timer to save and every machine does it on the
+ * same frame. */
+static const Int INFLUENCE_REBUILD_RATE = LOGICFRAMES_PER_SECOND;
+static const Int TACTICS_RATE = LOGICFRAMES_PER_SECOND / 3;
+
+/** Kiting. A unit steps back from something it outranges once that thing is inside its own reach
+ * plus this much, and stops where the enemy's gun is this far short of it. */
+static const Real KITE_MARGIN = 25.0f;
+/** ... and starts watching it this far outside the enemy's reach, so the turn is done before it arrives. */
+static const Real KITE_WATCH_MARGIN = 2.0f * KITE_MARGIN;
+/** ... and only from something at least this share of what it is worth itself. */
+static const Real KITE_WORTHY_SHARE = 0.5f;
+/** ... and, when that something can move, only with at least this much more range than it. */
+static const Real KITE_MOBILE_RANGE_RATIO = 1.5f;
+/** The longest a step lasts before it goes back to shooting, whether it got there or not. */
+static const UnsignedInt TACTICAL_STEP_MAX_FRAMES = 2 * LOGICFRAMES_PER_SECOND;
+/** A kite is a hop, not a walk: every frame on the move is a frame not shooting. It gets the turn and
+ * the drive to its spot, and never more than this. */
+static const UnsignedInt KITE_STEP_MAX_FRAMES = 3 * LOGICFRAMES_PER_SECOND;
+static const UnsignedInt KITE_TURN_FRAMES = LOGICFRAMES_PER_SECOND;
+
+/** The high ground. Worth a climb when it is this much higher than where the unit stands, which is
+ * thirty more units of range; looked for this far round the unit, and not again for a while. */
+static const Real CLIMB_MIN_GAIN = 10.0f;
+static const Real CLIMB_SEARCH_RADIUS = 110.0f;
+static const UnsignedInt CLIMB_INTERVAL_FRAMES = 6 * LOGICFRAMES_PER_SECOND;
+
+/** A unit this hurt, standing where what can shoot it outweighs what is on its side, is spent for
+ * nothing if it stays. */
+static const Real HURT_HEALTH_SHARE = 0.35f;
+
+/** Rows for units not looked at for this long are dropped: dead, garrisoned, or gone home. */
+static const UnsignedInt TACTICAL_ROW_EXPIRY_FRAMES = 10 * LOGICFRAMES_PER_SECOND;
+/** A unit the retreat sent home is not turned round by a kite. */
+static const UnsignedInt LEAVE_ALONE_FRAMES = 10 * LOGICFRAMES_PER_SECOND;
+
+static void collectObject( Object *obj, void *userData )
+{
+ ((std::vector<Object *> *)userData)->push_back( obj );
+}
+
+/** The longest gun this has that can hit something standing on the ground. */
+static Real groundAttackRange( const Object *obj )
+{
+ Real best = 0.0f;
+ for( Int slot = PRIMARY_WEAPON; slot < WEAPONSLOT_COUNT; ++slot )
+ {
+ const Weapon *weapon = obj->getWeaponInWeaponSlot( (WeaponSlotType)slot );
+ if( weapon == NULL || (weapon->getTemplate()->getAntiMask() & WEAPON_ANTI_GROUND) == 0 )
+ continue;
+ const Real range = weapon->getAttackRange( obj );
+ if( range > best )
+ best = range;
+ }
+ return best;
+}
+
+/** Where a gun fires from, for the high ground's reach: an aircraft's range is flat
+ * (Weapon_elevatedRange), so it counts as standing on the ground under it. */
+static Real firingHeight( const Object *obj )
+{
+ const Coord3D *pos = obj->getPosition();
+ if( obj->isKindOf( KINDOF_AIRCRAFT ) )
+ return TheTerrainLogic->getGroundHeight( pos->x, pos->y );
+ return pos->z;
+}
+
+//----------------------------------------------------------------------------------------------------------
+/** B4, the map itself. Every armed thing this player knows about is stamped onto the cells its guns
+ * reach: the enemy's into one layer, this player's and its allies' into the other. Known means
+ * observerKnowsAbout, the same line every other decision here draws, so a gun it has never seen
+ * does not steer it and a bunker it saw once keeps doing so. */
+//----------------------------------------------------------------------------------------------------------
+void AIPlayer::rebuildInfluence( void )
+{
+ if( !m_influence.isSized() )
+ {
+ Region3D extent;
+ TheTerrainLogic->getExtent( &extent );
+ m_influence.reset( extent.lo.x, extent.lo.y, extent.hi.x - extent.lo.x, extent.hi.y - extent.lo.y, INFLUENCE_CELL_SIZE );
+ for( Int row = 0; row < m_influence.getRows(); ++row )
+ {
+ for( Int col = 0; col < m_influence.getCols(); ++col )
+ {
+ Real x, y;
+ m_influence.cellCenter( col, row, &x, &y );
+ m_influence.setCellHeight( col, row, TheTerrainLogic->getGroundHeight( x, y ) );
+ }
+ }
+ }
+
+ m_influence.clear();
+ const Int me = m_player->getPlayerIndex();
+ for( Object *obj = TheGameLogic->getFirstObject(); obj; obj = obj->getNextObject() )
+ {
+ if( obj->isEffectivelyDead() || obj->isKindOf( KINDOF_PROJECTILE ) )
+ continue;
+ const Bool mine = obj->getControllingPlayer() == m_player;
+ const Relationship relation = m_player->getRelationship( obj->getTeam() );
+ if( !mine && relation != ENEMIES && relation != ALLIES )
+ continue;
+ const Real power = aiCombatPower( obj );
+ if( power <= 0.0f )
+ continue;
+ const Real range = groundAttackRange( obj );
+ if( range <= 0.0f )
+ continue;
+ const Coord3D *pos = obj->getPosition();
+ if( mine || relation == ALLIES )
+ m_influence.stampFriend( pos->x, pos->y, firingHeight( obj ), range, power );
+ else if( observerKnowsAbout( obj, me ) )
+ m_influence.stampEnemy( pos->x, pos->y, firingHeight( obj ), range, power );
+ }
+ m_influence.markBuilt( TheGameLogic->getFrame() );
+}
+
+//----------------------------------------------------------------------------------------------------------
+AIPlayer::TacticalStep *AIPlayer::findTacticalStep( ObjectID unit )
+{
+ for( size_t i = 0; i < m_tactics.size(); ++i )
+ {
+ if( m_tactics[ i ].unit == unit )
+ return &m_tactics[ i ];
+ }
+ return NULL;
+}
+
+AIPlayer::TacticalStep *AIPlayer::tacticalStepFor( ObjectID unit )
+{
+ TacticalStep *existing = findTacticalStep( unit );
+ if( existing )
+ return existing;
+ TacticalStep step;
+ step.unit = unit;
+ step.target = INVALID_ID;
+ step.resumeFrame = 0;
+ step.nextClimbFrame = 0;
+ step.leaveAloneUntil = 0;
+ step.lastSeenFrame = TheGameLogic->getFrame();
+ step.origin.zero();
+ step.rejoin = FALSE;
+ step.savedAttitude = AI_INVALID;
+ step.lastKiteFrame = 0;
+ m_tactics.push_back( step );
+ return &m_tactics.back();
+}
+
+void AIPlayer::leaveTacticsAlone( ObjectID unit )
+{
+ if( !m_influence.isBuilt() )
+ return; // no tactics running for this player
+ TacticalStep *step = tacticalStepFor( unit );
+ step->resumeFrame = 0;
+ step->leaveAloneUntil = TheGameLogic->getFrame() + LEAVE_ALONE_FRAMES;
+}
+
+/** A computer player's teams are set aggressive, and an aggressive mood turns every plain move into
+ * an attack move (AIMoveToState::update): the kite, the climb and the walk out of a lost fight would
+ * turn round at the first enemy in reach and go back to shooting. So the step is taken calm, and the
+ * mood comes back when the step is over. */
+void AIPlayer::stepCalmly( Object *obj, TacticalStep *step, const Coord3D *spot )
+{
+ AIUpdateInterface *ai = obj->getAI();
+ if( step->savedAttitude == AI_INVALID )
+ {
+ // getAttitude is protected; the mood matrix carries the same answer
+ switch( ai->getMoodMatrixValue() & MM_Mood_Bitmask )
+ {
+ case MM_Mood_Sleep: step->savedAttitude = AI_SLEEP; break;
+ case MM_Mood_Passive: step->savedAttitude = AI_PASSIVE; break;
+ case MM_Mood_Alert: step->savedAttitude = AI_ALERT; break;
+ case MM_Mood_Aggressive: step->savedAttitude = AI_AGGRESSIVE; break;
+ default: step->savedAttitude = AI_NORMAL; break;
+ }
+ }
+ ai->setAttitude( AI_NORMAL );
+ // and given as an order rather than an AI's aside: a CMD_FROM_AI move to a unit that is busy is laid
+ // over its attack as a temporary state (privateMoveToPosition), and the attack carries on under it
+ // - the buggy that was told to back away drove on towards the tank it was shooting
+ ai->aiMoveToPosition( spot, CMD_FROM_SCRIPT );
+}
+
+void AIPlayer::restoreMood( Object *obj, TacticalStep *step )
+{
+ if( step->savedAttitude == AI_INVALID )
+ return;
+ obj->getAI()->setAttitude( (AttitudeType)step->savedAttitude );
+ step->savedAttitude = AI_INVALID;
+}
+
+//----------------------------------------------------------------------------------------------------------
+/** A spot distance out from awayFrom, on the side the unit is on, that the ground lets it stand on and
+ * from which mustReach is still inside reach (stretched by any height it gains). Of the candidates,
+ * the one the fewest known guns cover; among the ones about as quiet as that, the highest. */
+//----------------------------------------------------------------------------------------------------------
+Bool AIPlayer::pickTacticalSpot( const Object *obj, const Coord3D *from, const Coord3D *awayFrom, Real distance,
+ const Coord3D *mustReach, Real reach, Coord3D *spot )
+{
+ Real dx = from->x - awayFrom->x;
+ Real dy = from->y - awayFrom->y;
+ Real length = sqrt( dx * dx + dy * dy );
+ if( length < 1.0f )
+ {
+ // standing on top of it: step towards home
+ dx = m_baseCenter.x - from->x;
+ dy = m_baseCenter.y - from->y;
+ length = sqrt( dx * dx + dy * dy );
+ if( length < 1.0f )
+ return FALSE;
+ }
+ dx /= length;
+ dy /= length;
+
+ const Int CANDIDATES = 7;
+ static const Real TURN[ CANDIDATES ] = { 0.0f, 0.45f, -0.45f, 0.9f, -0.9f, 1.35f, -1.35f }; // radians either side of straight back
+
+ Bool found = FALSE;
+ Real bestThreat = 0.0f;
+ Real bestZ = 0.0f;
+ for( Int i = 0; i < CANDIDATES; ++i )
+ {
+ const Real c = Cos( TURN[ i ] );
+ const Real s = Sin( TURN[ i ] );
+ Coord3D at;
+ at.x = awayFrom->x + (dx * c - dy * s) * distance;
+ at.y = awayFrom->y + (dx * s + dy * c) * distance;
+ at.z = TheTerrainLogic->getGroundHeight( at.x, at.y );
+
+ if( !groundLineClear( from, &at ) )
+ continue;
+ if( mustReach )
+ {
+ const Real reachFromThere = reach + Weapon_elevationRangeBonus( reach, at.z - mustReach->z );
+ if( sqr( at.x - mustReach->x ) + sqr( at.y - mustReach->y ) > sqr( reachFromThere ) )
+ continue;
+ }
+ const Real threat = m_influence.enemyAt( at.x, at.y );
+ // about as quiet: within a tenth, or both nothing
+ const Bool quieter = !found || threat < bestThreat * 0.9f;
+ const Bool asQuietAndHigher = found && threat <= bestThreat * 1.1f && at.z > bestZ;
+ if( quieter || asQuietAndHigher )
+ {
+ found = TRUE;
+ bestThreat = threat;
+ bestZ = at.z;
+ *spot = at;
+ }
+ }
+ return found;
+}
+
+//----------------------------------------------------------------------------------------------------------
+/** Hard's units, fought one at a time from the influence map. Deliberately at the player level: the
+ * unit's own AI still aims, picks targets and drives; this only decides where it stands, on the
+ * rung's own clock. */
+//----------------------------------------------------------------------------------------------------------
+void AIPlayer::doTactics( void )
+{
+ if( !getSkillProfile()->m_tacticalMicro )
+ return;
+ const UnsignedInt now = TheGameLogic->getFrame();
+ const Int me = m_player->getPlayerIndex();
+ if( TheGlobalData->m_noTacticsSlotParity >= 0 && TheGameLogic->isInSkirmishGame() &&
+ (ThePlayerList->getSlotIndex( me ) & 1) == TheGlobalData->m_noTacticsSlotParity )
+ return; // -notactics, the measuring half of a batch; the approaches then count the old way too
+
+ if( !m_influence.isBuilt() || (now + computeUpdatePhase( me, INFLUENCE_REBUILD_RATE )) % INFLUENCE_REBUILD_RATE == 0 )
+ rebuildInfluence();
+
+ if( !m_baseCenterSet )
+ return;
+ if( (now + computeUpdatePhase( me, TACTICS_RATE )) % TACTICS_RATE != 0 )
+ return;
+
+ std::vector<Object *> units;
+ m_player->iterateObjects( collectObject, &units );
+ for( size_t i = 0; i < units.size(); ++i )
+ tacticsFor( units[ i ] );
+
+ // ponytail: a linear list searched per unit, a few hundred rows at most; a map keyed on the ID if
+ // armies ever grow past that
+ for( size_t i = 0; i < m_tactics.size(); )
+ {
+ if( now - m_tactics[ i ].lastSeenFrame > TACTICAL_ROW_EXPIRY_FRAMES )
+ {
+ // one that is still alive (in a tunnel, garrisoned) keeps the mood its team gave it
+ Object *unit = TheGameLogic->findObjectByID( m_tactics[ i ].unit );
+ if( unit && unit->getAI() )
+ restoreMood( unit, &m_tactics[ i ] );
+ m_tactics[ i ] = m_tactics.back();
+ m_tactics.pop_back();
+ }
+ else
+ ++i;
+ }
+}
+
+//----------------------------------------------------------------------------------------------------------
+void AIPlayer::tacticsFor( Object *obj )
+{
+ // armed, not "able to attack" this frame: that reads false while a clip reloads, which is exactly
+ // when a Rocket Buggy has to step away, and it took every buggy out of here the moment it had fired
+ if( obj->isEffectivelyDead() || obj->isContained() || groundAttackRange( obj ) <= 0.0f )
+ return;
+ if( obj->isKindOf( KINDOF_STRUCTURE ) || obj->isKindOf( KINDOF_IMMOBILE ) || obj->isKindOf( KINDOF_AIRCRAFT ) ||
+ obj->isKindOf( KINDOF_DOZER ) || obj->isKindOf( KINDOF_HARVESTER ) || obj->isKindOf( KINDOF_PROJECTILE ) )
+ return;
+ AIUpdateInterface *ai = obj->getAI();
+ if( ai == NULL || ai->hasTunnelTrip() )
+ return;
+ // base defence stays where it was put, and the scouts, the capturer and the hijacker have their jobs
+ Team *team = obj->getTeam();
+ if( team == NULL || obj->isKindOf( KINDOF_MONEY_HACKER ) )
+ return;
+ const TeamTemplateInfo *info = team->getPrototype()->getTemplateInfo();
+ if( info && (info->m_isBaseDefense || info->m_isPerimeterDefense) )
+ return;
+ if( obj->getID() == m_capturerID || obj->getID() == m_hijackerID )
+ return;
+ for( Int i = 0; i < MAX_AI_SCOUTS; ++i )
+ {
+ if( obj->getID() == m_scoutID[ i ] )
+ return;
+ }
+
+ const Coord3D *pos = obj->getPosition();
+ const UnsignedInt now = TheGameLogic->getFrame();
+ const Real threatHere = m_influence.enemyAt( pos->x, pos->y );
+ Object *victim = ai->getCurrentVictim();
+ const TacticalStep *existing = findTacticalStep( obj->getID() );
+ if( threatHere <= 0.0f && victim == NULL &&
+ (existing == NULL || (existing->resumeFrame == 0 && !existing->rejoin && existing->savedAttitude == AI_INVALID)) )
+ return; // nothing can shoot it and it is shooting nothing: nothing to decide
+
+ TacticalStep *step = tacticalStepFor( obj->getID() );
+ step->lastSeenFrame = now;
+ if( now < step->leaveAloneUntil )
+ return;
+ if( step->resumeFrame == 0 )
+ restoreMood( obj, step ); // home from a lost fight: its own mood again
+
+ // a step under way ends when it gets there or runs out of time, and the unit goes back to work:
+ // the thing it was shooting if that still stands, otherwise back up the road it stepped off
+ if( step->resumeFrame != 0 )
+ {
+ if( now < step->resumeFrame && ai->isMoving() )
+ return;
+ step->resumeFrame = 0;
+ restoreMood( obj, step );
+ Object *target = TheGameLogic->findObjectByID( step->target );
+ if( target && !target->isEffectivelyDead() && observerKnowsAbout( target, m_player->getPlayerIndex() ) )
+ ai->aiAttackObject( target, NO_MAX_SHOTS_LIMIT, CMD_FROM_AI );
+ else
+ ai->aiAttackMoveToPosition( &step->origin, NO_MAX_SHOTS_LIMIT, CMD_FROM_AI );
+ return;
+ }
+
+ // a step replaced the order the team gave it, so once the fight it stepped for is over it is standing
+ // on its own in the middle of the map; it goes back to the rest of its team rather than wait there
+ // to be picked off
+ if( step->rejoin && victim == NULL && threatHere <= 0.0f && !ai->isMoving() )
+ {
+ step->rejoin = FALSE;
+ Coord3D centre;
+ centre.zero();
+ Real count = 0.0f;
+ for( DLINK_ITERATOR<Object> iter = team->iterate_TeamMemberList(); !iter.done(); iter.advance() )
+ {
+ const Object *mate = iter.cur();
+ if( mate == NULL || mate == obj || mate->isEffectivelyDead() || mate->isContained() )
+ continue;
+ centre.x += mate->getPosition()->x;
+ centre.y += mate->getPosition()->y;
+ count += 1.0f;
+ }
+ if( count > 0.0f )
+ {
+ centre.x /= count;
+ centre.y /= count;
+ centre.z = TheTerrainLogic->getGroundHeight( centre.x, centre.y );
+ ai->aiAttackMoveToPosition( &centre, NO_MAX_SHOTS_LIMIT, CMD_FROM_AI );
+ }
+ return;
+ }
+
+ const Real myRange = groundAttackRange( obj );
+ if( myRange <= 0.0f )
+ return;
+
+ // a hurt unit on ground it cannot win goes home, where the next wave will pick it up
+ const BodyModuleInterface *body = obj->getBodyModule();
+ const Real friendsHere = m_influence.friendAt( pos->x, pos->y );
+ if( body && body->getHealth() < body->getMaxHealth() * HURT_HEALTH_SHARE && threatHere > friendsHere )
+ {
+ DEBUG_LOG(("AI TACTICS frame %d player %d pulls a hurt '%s' out, %.0f against %.0f\n", now, m_player->getPlayerIndex(),
+ obj->getTemplate()->getName().str(), threatHere, friendsHere));
+ // out to the first ground on the way home that nothing known covers, not all the way home: on a
+ // big map the walk home crossed the ground it was pulled out of, and it stays near enough to
+ // guard the road behind the fight
+ Coord3D safe = m_baseCenter;
+ const Real homeX = m_baseCenter.x - pos->x;
+ const Real homeY = m_baseCenter.y - pos->y;
+ const Real homeDist = sqrt( homeX * homeX + homeY * homeY );
+ for( Real along = INFLUENCE_CELL_SIZE; along < homeDist; along += INFLUENCE_CELL_SIZE )
+ {
+ const Real x = pos->x + homeX * along / homeDist;
+ const Real y = pos->y + homeY * along / homeDist;
+ if( m_influence.enemyAt( x, y ) <= 0.0f )
+ {
+ safe.x = x + homeX * INFLUENCE_CELL_SIZE / homeDist; // a cell past the edge of the reach
+ safe.y = y + homeY * INFLUENCE_CELL_SIZE / homeDist;
+ safe.z = TheTerrainLogic->getGroundHeight( safe.x, safe.y );
+ break;
+ }
+ }
+ stepCalmly( obj, step, &safe );
+ step->rejoin = TRUE;
+ step->leaveAloneUntil = now + LEAVE_ALONE_FRAMES;
+ return;
+ }
+
+ // kite: the nearest thing that is about to reach it and that it outranges
+ Object *closing = NULL;
+ Real closingRange = 0.0f;
+ Real closingDistSqr = 0.0f;
+ Object *nearestArmed = NULL; // the closest armed thing in this unit's reach, whatever else it is
+ Real nearestArmedDistSqr = 0.0f;
+ {
+ PartitionFilterPlayerAffiliation enemies( m_player, ALLOW_ENEMIES, true );
+ PartitionFilterAlive alive;
+ PartitionFilter *filters[] = { &enemies, &alive, NULL };
+ ObjectIterator *iter = ThePartitionManager->iterateObjectsInRange( pos, myRange, FROM_CENTER_2D, filters );
+ MemoryPoolObjectHolder hold( iter );
+ for( Object *enemy = iter->first(); enemy; enemy = iter->next() )
+ {
+ // the affiliation filter lets the player's own objects through whatever it is asked for
+ if( enemy->getControllingPlayer() == m_player || m_player->getRelationship( enemy->getTeam() ) != ENEMIES )
+ continue;
+ if( enemy->isKindOf( KINDOF_PROJECTILE ) || !observerKnowsAbout( enemy, m_player->getPlayerIndex() ) )
+ continue;
+ const Real enemyRange = groundAttackRange( enemy );
+ if( enemyRange <= 0.0f )
+ continue;
+ const Real reach = enemyRange + Weapon_elevationRangeBonus( enemyRange, firingHeight( enemy ) - pos->z );
+ const Real distSqr = sqr( enemy->getPosition()->x - pos->x ) + sqr( enemy->getPosition()->y - pos->y );
+ if( nearestArmed == NULL || distSqr < nearestArmedDistSqr )
+ {
+ nearestArmed = enemy;
+ nearestArmedDistSqr = distSqr;
+ }
+ // watched from as far out as the unit drives while it turns round, since a vehicle cannot
+ // reverse: a buggy that started its turn at the enemy's reach finished it inside
+ if( distSqr > sqr( reach + KITE_WATCH_MARGIN + ai->getCurLocomotorSpeed() * KITE_TURN_FRAMES ) )
+ continue; // not close enough to hurt yet, nor soon
+ // running from something faster only means not shooting at it; a gun that cannot move is
+ // always worth standing off from
+ AIUpdateInterface *enemyAI = enemy->getAI();
+ const Bool enemyMoves = enemyAI && !enemy->isKindOf( KINDOF_IMMOBILE ) && !enemy->isKindOf( KINDOF_STRUCTURE );
+ const Real enemySpeed = enemyMoves ? enemyAI->getCurLocomotorSpeed() : 0.0f;
+ if( enemySpeed > ai->getCurLocomotorSpeed() )
+ continue;
+ // a gun that moves is worth stepping away from while it is fighting this player or already
+ // reaches this unit; one still out of reach and busy with somebody else is shot, not run from.
+ // Four tanks sent at one buggy of four drove through the other three.
+ const Object *enemyVictim = enemyAI ? enemyAI->getCurrentVictim() : NULL;
+ const Bool comingForUs = enemyVictim && enemyVictim->getControllingPlayer() == m_player;
+ if( enemyMoves && !comingForUs && distSqr > sqr( reach ) )
+ continue;
+ // a gun that walks is run from only by something that outranges it by a long way, a rocket
+ // launcher against a tank; a tank that hopped back from another tank's slightly shorter gun
+ // spent the hop turning round, and on Twilight Flame kiting like that lost more than it saved
+ if( enemyMoves && myRange < reach * KITE_MOBILE_RANGE_RATIO )
+ continue;
+ // and only from something worth running from: a tank that backs away from a rifleman it
+ // could have driven over was the commonest step the first version took
+ if( obj->getCrusherLevel() > enemy->getCrushableLevel() || aiCombatPower( enemy ) < KITE_WORTHY_SHARE * aiCombatPower( obj ) )
+ continue;
+ if( closing == NULL || distSqr < closingDistSqr )
+ {
+ closing = enemy;
+ closingRange = reach;
+ closingDistSqr = distSqr;
+ }
+ }
+ }
+ // fire, then step: a gun that is ready or aiming shoots first, and the hop happens while it reloads.
+ // Hopping on the clock alone had a Tomahawk step back every second and never finish a launch.
+ // Once the enemy's gun already reaches it, it steps whatever its own gun is doing: a Tomahawk that
+ // waited to finish aiming while four tanks drove up to it died aiming.
+ const Weapon *gun = obj->getCurrentWeapon();
+ // ... and only when what it is shooting at is in reach; a gun that is ready while it drives towards a
+ // target further off is not about to fire, and waiting on it let a buggy drive into the tanks
+ const Bool gunBusy = gun && (gun->getStatus() == READY_TO_FIRE || gun->getStatus() == PRE_ATTACK) && victim != NULL &&
+ sqr( victim->getPosition()->x - pos->x ) + sqr( victim->getPosition()->y - pos->y ) <= sqr( myRange );
+ const Bool alreadyHit = closing && closingDistSqr <= sqr( closingRange );
+ // Only what can aim without driving: infantry, or a gun on a turret. A Rocket Buggy's rack is fixed
+ // to the chassis and a car cannot turn on the spot, so every hop cost it a three-second circle to
+ // face the tank again, and it fired less kiting than standing.
+ const Bool aimsWithoutDriving = obj->isKindOf( KINDOF_INFANTRY ) || ai->getWhichTurretForCurWeapon() != TURRET_INVALID;
+ Real standoff = 0.0f;
+ if( aimsWithoutDriving && closing && (alreadyHit || !gunBusy) && AIKite_standoffDistance( myRange, closingRange, KITE_MARGIN, &standoff ) &&
+ closingDistSqr < sqr( standoff - KITE_MARGIN ) ) // already standing off: a step would only slide it sideways
+ {
+ Coord3D spot;
+ if( pickTacticalSpot( obj, pos, closing->getPosition(), standoff, closing->getPosition(), myRange, &spot ) )
+ {
+ // back to shooting the gun it stepped away from, which the spot keeps in reach; going back to a
+ // target further off drove the buggies through the tanks in front of it to get there
+ step->target = closing->getID();
+ DEBUG_LOG(("AI TACTICS frame %d player %d kites '%s' back from '%s', %.0f outranging %.0f, (%.0f,%.0f) to (%.0f,%.0f) away from (%.0f,%.0f)\n",
+ now, m_player->getPlayerIndex(), obj->getTemplate()->getName().str(), closing->getTemplate()->getName().str(), myRange, closingRange,
+ pos->x, pos->y, spot.x, spot.y, closing->getPosition()->x, closing->getPosition()->y));
+ step->origin = *pos;
+ // long enough to turn round and drive there; a vehicle given one second did not finish the turn
+ step->lastKiteFrame = now;
+ const Real speed = max( ai->getCurLocomotorSpeed(), 0.1f );
+ const Real walk = sqrt( sqr( spot.x - pos->x ) + sqr( spot.y - pos->y ) );
+ step->resumeFrame = now + min<UnsignedInt>( KITE_STEP_MAX_FRAMES, KITE_TURN_FRAMES + REAL_TO_INT_CEIL( walk / speed ) );
+ step->rejoin = TRUE;
+ stepCalmly( obj, step, &spot );
+ return;
+ }
+ }
+
+ // A target out of reach is walked to, through whatever is in reach on the way. Four buggies sent at
+ // the last of four tanks drove past the other three with their rockets loaded and died without one
+ // shot fired. With an armed enemy already in reach, that is the one it shoots.
+ if( victim && nearestArmed && nearestArmed != victim &&
+ sqr( victim->getPosition()->x - pos->x ) + sqr( victim->getPosition()->y - pos->y ) > sqr( myRange ) )
+ {
+ DEBUG_LOG(("AI TACTICS frame %d player %d turns '%s' on the '%s' in reach instead of walking to its target\n", now,
+ m_player->getPlayerIndex(), obj->getTemplate()->getName().str(), nearestArmed->getTemplate()->getName().str()));
+ ai->aiAttackObject( nearestArmed, NO_MAX_SHOTS_LIMIT, CMD_FROM_AI );
+ return;
+ }
+
+ /* The high ground. A climb is worth its walk only when it changes the exchange: the target can hit
+ this unit where it stands, and from a rise nearby this unit reaches the target while the target no
+ longer reaches it. Climbing whenever a rise was near measured worse on Twilight Flame than not
+ climbing at all - every walk mid-fight is time not shooting, and its ramps made the walk long. */
+ const Real victimRange = victim ? groundAttackRange( victim ) : 0.0f;
+ const Real victimReachHere = victimRange + (victim ? Weapon_elevationRangeBonus( victimRange, firingHeight( victim ) - pos->z ) : 0.0f);
+ const Bool victimHitsMe = victim && victimRange > 0.0f &&
+ sqr( victim->getPosition()->x - pos->x ) + sqr( victim->getPosition()->y - pos->y ) <= sqr( victimReachHere );
+ if( victimHitsMe && !ai->isMoving() && now >= step->nextClimbFrame )
+ {
+ step->nextClimbFrame = now + CLIMB_INTERVAL_FRAMES;
+ const Int DIRECTIONS = 8;
+ Coord3D best;
+ Bool found = FALSE;
+ Real bestZ = pos->z + CLIMB_MIN_GAIN;
+ for( Int ring = 1; ring <= 2; ++ring )
+ {
+ const Real radius = CLIMB_SEARCH_RADIUS * ring / 2.0f;
+ for( Int d = 0; d < DIRECTIONS; ++d )
+ {
+ const Real angle = 2.0f * PI * d / DIRECTIONS;
+ Coord3D at;
+ at.x = pos->x + radius * Cos( angle );
+ at.y = pos->y + radius * Sin( angle );
+ at.z = TheTerrainLogic->getGroundHeight( at.x, at.y );
+ if( at.z < bestZ )
+ continue;
+ ICoord2D cell;
+ TheAI->pathfinder()->worldToCell( &at, &cell );
+ const PathfindCell *pathCell = TheAI->pathfinder()->getCell( LAYER_GROUND, cell.x, cell.y );
+ if( pathCell == NULL || pathCell->getType() != PathfindCell::CELL_CLEAR )
+ continue;
+ const Coord3D *vpos = victim->getPosition();
+ const Real reachFromThere = myRange + Weapon_elevationRangeBonus( myRange, at.z - vpos->z );
+ const Real victimReachThere = victimRange + Weapon_elevationRangeBonus( victimRange, firingHeight( victim ) - at.z );
+ const Real distSqr = sqr( at.x - vpos->x ) + sqr( at.y - vpos->y );
+ if( distSqr > sqr( reachFromThere ) || distSqr <= sqr( victimReachThere + KITE_MARGIN ) )
+ continue; // out of its own reach, or still inside the target's
+ if( m_influence.enemyAt( at.x, at.y ) > threatHere || !groundLineClear( pos, &at ) )
+ continue;
+ best = at;
+ bestZ = at.z;
+ found = TRUE;
+ }
+ }
+ if( found )
+ {
+ DEBUG_LOG(("AI TACTICS frame %d player %d takes '%s' %.0f up onto (%.0f,%.0f)\n", now, m_player->getPlayerIndex(),
+ obj->getTemplate()->getName().str(), best.z - pos->z, best.x, best.y));
+ step->target = victim->getID();
+ step->origin = *pos;
+ step->resumeFrame = now + TACTICAL_STEP_MAX_FRAMES;
+ step->rejoin = TRUE;
+ stepCalmly( obj, step, &best );
+ }
+ }
+}
+
//----------------------------------------------------------------------------------------------------------
/** The cheapest thing this player could build that can walk somewhere and is not needed elsewhere.
* Faction-agnostic on purpose - it lands on the Ranger, the Red Guard, the Rebel and the
@@ -7386,7 +8047,7 @@ void AIPlayer::xfer( Xfer *xfer )
{
// version
- XferVersion currentVersion = 8; // 2: scout 3: rung and role 4: scouting stamps 5: the capturer 6: parked waves 7: superweapon aims 8: the hijacker
+ XferVersion currentVersion = 9; // 2: scout 3: rung and role 4: scouting stamps 5: the capturer 6: parked waves 7: superweapon aims 8: the hijacker 9: tactical steps
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
@@ -7601,6 +8262,32 @@ void AIPlayer::xfer( Xfer *xfer )
}
xfer->xferInt( &m_strikeNext );
}
+ // the units part way through a tactical step, above all the mood each was calmed from: a game saved
+ // in the middle of a kite would otherwise load a unit that stays calm for the rest of the match. And
+ // the influence map as it stands, since the next rebuild can be most of a second off and the lanes,
+ // the retreat and the steps all read it before then.
+ if( version >= 9 )
+ {
+ m_influence.xfer( xfer );
+ UnsignedShort rows = (UnsignedShort)m_tactics.size();
+ xfer->xferUnsignedShort( &rows );
+ if( xfer->getXferMode() == XFER_LOAD )
+ m_tactics.resize( rows );
+ for( UnsignedShort i = 0; i < rows; ++i )
+ {
+ TacticalStep &step = m_tactics[ i ];
+ xfer->xferObjectID( &step.unit );
+ xfer->xferObjectID( &step.target );
+ xfer->xferCoord3D( &step.origin );
+ xfer->xferUnsignedInt( &step.resumeFrame );
+ xfer->xferUnsignedInt( &step.nextClimbFrame );
+ xfer->xferUnsignedInt( &step.leaveAloneUntil );
+ xfer->xferUnsignedInt( &step.lastSeenFrame );
+ xfer->xferBool( &step.rejoin );
+ xfer->xferInt( &step.savedAttitude );
+ xfer->xferUnsignedInt( &step.lastKiteFrame );
+ }
+ }
// 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/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 2177c9914..1859a4f3a 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -8983,6 +8983,7 @@ TEST(the_difficulty_ladder_climbs_in_every_direction_it_should)
CHECK( upper.m_retreatTeams >= lower.m_retreatTeams );
CHECK( upper.m_useInfluenceMapForAttackLane >= lower.m_useInfluenceMapForAttackLane );
CHECK( upper.m_economyBuildings >= lower.m_economyBuildings );
+ CHECK( upper.m_tacticalMicro >= lower.m_tacticalMicro );
CHECK( upper.m_focusFire >= lower.m_focusFire );
CHECK( upper.m_savesSciencePoints >= lower.m_savesSciencePoints );
CHECK( upper.m_adaptiveHarvesters >= lower.m_adaptiveHarvesters );
@@ -9004,6 +9005,54 @@ TEST(the_difficulty_ladder_climbs_in_every_direction_it_should)
}
}
+/** The influence map is what every fighting decision of Hard's reads, so what it says about a patch of
+ ground has to be what the guns there can actually do: reach it flat, reach further from above, and
+ add up when two of them cover the same cell. */
+TEST(influence_map_covers_what_a_gun_reaches_and_the_high_ground_reaches_further)
+{
+ AIInfluenceMap map;
+ map.reset( 0.0f, 0.0f, 1000.0f, 1000.0f, 50.0f );
+ CHECK_EQ( 20, map.getCols() );
+
+ map.stampEnemy( 500.0f, 500.0f, 0.0f, 100.0f, 1000.0f );
+ CHECK_EQ( 1000.0f, map.enemyAt( 500.0f, 500.0f ) );
+ CHECK_EQ( 1000.0f, map.enemyAt( 575.0f, 525.0f ) ); // cell centre 575,525: 79 away
+ CHECK_EQ( 0.0f, map.enemyAt( 675.0f, 525.0f ) ); // 175 away, out of a 100 gun's reach
+ CHECK_EQ( 0.0f, map.friendAt( 500.0f, 500.0f ) );
+
+ // the same gun thirty units up reaches 90 further (three a unit), which covers the 175 cell
+ map.clear();
+ map.stampEnemy( 500.0f, 500.0f, 30.0f, 100.0f, 1000.0f );
+ CHECK_EQ( 1000.0f, map.enemyAt( 675.0f, 525.0f ) );
+ CHECK_EQ( 0.0f, map.enemyAt( 775.0f, 525.0f ) );
+
+ // ... and a cell on a hill as high as the gun gets no bonus against it
+ map.clear();
+ for( Int row = 0; row < map.getRows(); ++row )
+ for( Int col = 0; col < map.getCols(); ++col )
+ map.setCellHeight( col, row, 30.0f );
+ map.stampEnemy( 500.0f, 500.0f, 30.0f, 100.0f, 1000.0f );
+ CHECK_EQ( 0.0f, map.enemyAt( 675.0f, 525.0f ) );
+
+ map.stampEnemy( 500.0f, 500.0f, 30.0f, 100.0f, 500.0f );
+ CHECK_EQ( 1500.0f, map.enemyAt( 500.0f, 500.0f ) );
+ CHECK_EQ( 0.0f, map.enemyAt( -10.0f, 500.0f ) ); // off the map reads as nothing
+}
+
+/** Kiting: a unit steps back into the band between the enemy's reach and its own, and only when the
+ band is wide enough to stand in. */
+TEST(kite_standoff_sits_between_the_two_ranges)
+{
+ Real distance = 0.0f;
+ CHECK( AIKite_standoffDistance( 300.0f, 150.0f, 20.0f, &distance ) );
+ CHECK_EQ( 280.0f, distance ); // the far edge of its own 300, well out of the enemy's 150
+ CHECK( AIKite_standoffDistance( 200.0f, 150.0f, 20.0f, &distance ) );
+ CHECK_EQ( 180.0f, distance );
+ CHECK( distance > 150.0f + 20.0f );
+ CHECK( !AIKite_standoffDistance( 180.0f, 150.0f, 20.0f, &distance ) ); // 30 of band, 40 needed
+ CHECK( !AIKite_standoffDistance( 150.0f, 200.0f, 20.0f, &distance ) ); // outranged: nothing to kite
+}
+
/** 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