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): AI places defences by field of fire, faster pace

Olcay Seygan89cefae745bb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 136e9dbb2..8636d5efa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -181,9 +181,10 @@ found and fixed — EA's own, not port damage.**
- It puts more harvesters on a supply centre with more piles around it, instead of the same three numbers everywhere.
- USA's Chinooks stop collecting over the command center. When the pile beside a supply centre ran out, its Chinooks flew home and hovered, and the computer went on buying new ones for its other centres while those sat idle. It only looked for an idle gatherer when a pile stood right next to the centre, a fraction of how far a Chinook looks. An idle gatherer is now sent to any of its supply centres with a pile inside that gatherer's own range, and nothing new is bought while one stands idle beside a pile that has no room for it.
- It keeps its lights on, and keeps them out of reach. Its plan carries a fixed number of power plants and nothing ever adds one, so a raid that took two of them left the base underpowered - radar dark, base defences off, superweapon clock stopped - until a rebuild timer came round and put the new plant back on the spot the raid already knew the way to. It now buys a plant when the margin gets thin rather than when the meter reads zero, and puts it on the far side of the base from whoever it is fighting.
-- Spare cash also buys a gun on the side the trouble comes from. Production and income go up around the middle of the base, the power goes behind it, and base defences go out in front, so money that keeps arriving thickens the base in the order a base wants to be thick in. Front means towards the nearest enemy, which is not the same as the one it has decided to attack - that one can be across the map, and a wall built facing it has its back to the neighbour. The walls grow with the army. One gun every minute and a half, never more than ten, used to be the rule; now the computer may stand one gun for every four fighting units it has, so a big army comes home to a fortress and a beaten one rebuilds its tanks before its bunkers. Letting it buy guns on every pass instead was tried first: 241 guns over twelve four-player matches, and they ate the army, down to 60 kills a match from 73. Tied to the army, 71 guns, and the army is the biggest of any version tried, 78 kills a match. A small army no longer means a bare base, though: one more gun is allowed every 40 seconds of the match on top of what the army earns, up to 24, and the computer buys them as soon as its bank clears its saving threshold rather than twice that. When there is no room out in front, the next gun goes 45 degrees round to either side, then 90, and when the whole front is taken it goes up inside the base.
-- Its guns come as a mix. It used to put up whichever defence came first on the worker's build bar, every time: a Hard USA base put up 22 Patriots for every Fire Base, a GLA one Stinger Sites, and China's own spare-cash guns were bunkers. Now each new gun is the type the base has fewest of, so Patriots and Fire Bases go up in turn, Stinger Sites alternate with Tunnel Networks, and China's Gattling Cannons get bunkers and Speaker Towers beside them. Those two shoot at nothing on their own, so the computer keeps about one of each for every three cannons. A type lost in a raid is the one rebuilt first. Every general's own versions count, and the planned defences its build scripts ask for follow the same rule. Over 48 one-on-one matches between Hard and Normal computers and 24 between two Hards, the same seeds before and after, a Hard USA side built 4.0 guns a match where it built 2.4, 1.3 of them Fire Bases where it built 0.1. China went from 4.0 to 6.2, GLA held at 4.9. Hard won 25 of those 48 matches against Normal, as it did before. Replays recorded before this change play out differently.
-- Hard builds its superweapon as soon as it can pay for one and has the guns to stand it on, and then another. Its scripts held the first one back behind a clock that ran for twelve and a half minutes, seven and a half if you had built your own tech building first, and then allowed exactly one: a player who took on seven Hard computers at once saw a single nuke all match. There is no clock now. The tech building that unlocks it goes up first, and the superweapon follows once the money is in the bank and twelve of its guns stand finished, a rule only the computer plays by (see the lobby section). More follow as the base grows, one for every twelve guns, so a computer holding twenty-four guns can stand two superweapons. The numbers below were measured when four guns were enough. With twelve, a one-on-one between computers rarely lasts long enough: over 96 Hard sides in the same 72 matches, 11 had a superweapon up before and 5 after, the first at 6.8 minutes where it had been 4.6. Before that rule it put its first particle cannon up at 4.3 minutes on Twilight Flame and its first nuke at 4.9, without a gun to its name. Over 24 matches between two Hard computers on the same map, the first nuke now goes up at 6.2 minutes as a rule, anywhere from 4.4 to 9.8, and the first Particle Cannon at 7.4. The Scud Storm comes last at 7.6 but never later than 8.7, and every GLA side had one inside ten minutes, where 4 of the 32 China and USA sides were still waiting for theirs. The lobby's superweapon limit and Pro Rules still apply to the computer exactly as they do to you.
+- Spare cash also buys a gun on the side the trouble comes from. Production and income go up around the middle of the base, the power goes behind it, and base defences go out in front, so money that keeps arriving thickens the base in the order a base wants to be thick in. Front means towards the nearest enemy, which is not the same as the one it has decided to attack - that one can be across the map, and a wall built facing it has its back to the neighbour. The walls grow with the army. One gun every minute and a half, never more than ten, used to be the rule; now the computer may stand one gun for every four fighting units it has, so a big army comes home to a fortress and a beaten one rebuilds its tanks before its bunkers. Letting it buy guns on every pass instead was tried first: 241 guns over twelve four-player matches, and they ate the army, down to 60 kills a match from 73. Tied to the army, 71 guns, and the army is the biggest of any version tried, 78 kills a match. A small army no longer means a bare base, though: one gun for every three fighting units, and however small the army, one more every 30 seconds of the match up to 24, so the twelfth is allowed six minutes in. The computer buys them as soon as its bank clears its saving threshold rather than twice that, and a base three or more guns short of its allowance orders two at a time.
+- Each gun goes where it sees the most of the way in. The computer used to aim one spot at the enemy's side of the base and, when that was taken, put the gun down wherever it fitted, which on a crowded map meant behind its own factories with nothing to shoot at. Now it looks at nearly a hundred spots around the base and scores each one by the open ground inside the gun's reach that lies between the base and the enemy. Ground hidden behind its own buildings or a cliff counts for nothing, ground at the back of the base counts for very little, and every gun already standing nearby halves the score, so the guns spread along the front instead of piling up on one corner. It only asks the build rules about the best dozen of those spots, and a spot under a building, on unbuildable ground or within reach of the enemy's own base is crossed off first, so the gun usually goes on the first spot it asks about: 296 of 349 did over 72 matches.
+- Its guns come as a mix. It used to put up whichever defence came first on the worker's build bar, every time: a Hard USA base put up 22 Patriots for every Fire Base, a GLA one Stinger Sites, and China's own spare-cash guns were bunkers. Now each new gun is the type the base has fewest of, so Patriots and Fire Bases go up in turn, Stinger Sites alternate with Tunnel Networks, and China's Gattling Cannons get bunkers and Speaker Towers beside them. Those two shoot at nothing on their own, so the computer keeps about one of each for every three cannons. A type lost in a raid is the one rebuilt first. Every general's own versions count, and the planned defences its build scripts ask for follow the same rule. Over 48 one-on-one matches between Hard and Normal computers and 24 between two Hards, the same seeds each time, a Hard USA side built 4.9 guns a match where it built 2.4, 1.6 of them Fire Bases where it built 0.1. China went from 4.0 to 9.9 and GLA from 4.9 to 6.9. Hard won 29 of those 48 matches against Normal, where it won 25. Replays recorded before this change play out differently.
+- Hard builds its superweapon as soon as it can pay for one and has the guns to stand it on, and then another. Its scripts held the first one back behind a clock that ran for twelve and a half minutes, seven and a half if you had built your own tech building first, and then allowed exactly one: a player who took on seven Hard computers at once saw a single nuke all match. There is no clock now. The tech building that unlocks it goes up first, and the superweapon follows once the money is in the bank and twelve of its guns stand finished, a rule only the computer plays by (see the lobby section). More follow as the base grows, one for every twelve guns, so a computer holding twenty-four guns can stand two superweapons. The numbers below were measured when four guns were enough. With twelve, a one-on-one between computers rarely lasts long enough: over 96 Hard sides in the same 72 matches, 11 had a superweapon up with four guns and 7 with twelve, the first at 5.4 minutes and most between 8 and 9. Before that rule it put its first particle cannon up at 4.3 minutes on Twilight Flame and its first nuke at 4.9, without a gun to its name. Over 24 matches between two Hard computers on the same map, the first nuke now goes up at 6.2 minutes as a rule, anywhere from 4.4 to 9.8, and the first Particle Cannon at 7.4. The Scud Storm comes last at 7.6 but never later than 8.7, and every GLA side had one inside ten minutes, where 4 of the 32 China and USA sides were still waiting for theirs. The lobby's superweapon limit and Pro Rules still apply to the computer exactly as they do to you.
- Hard trains more builders when it has work for them. It only ever made a new dozer after losing all of them, so it played every match on the two it had, and every building it bought queued behind those two. On Twilight Flame a third of the China Tank computers never got round to a war factory, never sent an attack, and ended up sitting in a ring of bunkers on a pile of cash. Now, with money in the bank and every dozer busy, it trains another, up to four. Over six four-player matches on that map, every computer built its war factories, the attack waves went from 39 to 82, and each one spent half as much again.
- Hard no longer rebuilds its factories inside your base. A busy computer puts its next war factory beside its newest expansion, and it remembered that expansion forever: after you destroyed the supply centre there, even one it had built right next to your base, it kept putting the factory back up on the same spot. It now only builds beside an expansion it still holds, and only one nearer its own base than yours.
- Hard keeps its lights on. It asked for a new power plant before running out, and the request then sat in a queue behind everything else its plan wanted: one China waited 95 seconds for a plant with 26,000 in the bank, every builder busy, and went dark halfway. A plant now jumps that queue once the margin is thin, a busy builder is taken off whatever it is doing to put it up, and while the base is dark the computer buys nothing else. Over eight four-player matches the time its bases spent without power fell by a third, from 42 minutes to 28 across all of them.
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
index 789b9f3cd..c6ec1a936 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
@@ -340,9 +340,11 @@ Bool aiWantsAnotherTechBuilding( Int standing, Int onTheWay );
/** Base defences a Hard computer may stand: one per AI_ARMY_PER_DEFENSE fighting units, and however
* small the army, one more every AI_DEFENSE_PACE_SECONDS of the match until two superweapons' worth
* stand. The army ration alone left a 1v1 base on two or three guns, short of the
- * DEFENSES_PER_SUPERWEAPON a superweapon asks for. */
-static const Int AI_ARMY_PER_DEFENSE = 4;
-static const Int AI_DEFENSE_PACE_SECONDS = 40;
+ * DEFENSES_PER_SUPERWEAPON a superweapon asks for. At 30 seconds the clock allows the twelfth
+ * gun at six minutes, under the seven a Hard-against-Hard 1v1 lasts on average; 40 seconds and
+ * four units a gun, the first try, put a superweapon up on 5 of 96 Hard sides. */
+static const Int AI_ARMY_PER_DEFENSE = 3;
+static const Int AI_DEFENSE_PACE_SECONDS = 30;
Int aiDefenseAllowance( Int army, UnsignedInt frame );
/** Which of the base defences a dozer can build goes up next, as an index into the candidates: the
@@ -350,6 +352,12 @@ Int aiDefenseAllowance( Int army, UnsignedInt frame );
* sits first. A defence with no gun or spawn of its own (an empty bunker, a speaker tower) counts
* AI_SUPPORT_DEFENSE_WEIGHT times what it has standing. Ties go to an armed one, then to the first
* candidate. -1 when there are none. */
+/** What one point of open ground inside a defence's reach is worth to the spot it is scored for:
+ * how much nearer the enemy it lies than the middle of the base does, in reaches, never below
+ * zero, plus a tenth for lying outside the base. Ground behind the base counts only that tenth,
+ * so a spot at the back scores a fraction of one at the front, and none inside the base. */
+Real aiFireSampleWeight( Real baseToThreat, Real sampleToThreat, Real reach, Bool outsideBase );
+
static const Int AI_SUPPORT_DEFENSE_WEIGHT = 3;
Int aiPickBaseDefense( const Int *standing, const Bool *armed, Int count );
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
index b6157c6fa..205c220c9 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
@@ -346,6 +346,7 @@ protected:
Bool placeNear(const ThingTemplate *tmpl, const Coord3D *center, Real innerRadius, Bool walkOutward); ///< a legal, safe spot on a ring round center, queued for a dozer. walkOutward keeps searching further out as the inner rings fill
Bool queueExtraFactory(Object *dozer, KindOfType kind, Bool unlimited); ///< one more of this factory, beside a held expansion or around the base
const ThingTemplate *nextBaseDefense(Object *dozer); ///< the base defence off this dozer's buttons that the base has fewest of, NULL for none
+ Bool placeDefense(const ThingTemplate *defense); ///< queue it on the ring spot whose clear field of fire covers the most ground toward the enemy
Real knownFirepowerAlongPath(Waypoint *way); ///< what this AI has seen that can shoot, along an approach
AsciiString secondApproachLabel(const Coord3D *from, const AsciiString &taken, Int pathSuffix); ///< the quietest other road, or empty
Bool loadGunships(void); ///< infantry boards the transports it can shoot out of: the wave's anything at home, a team's its own; TRUE while a firing gunship is still filling
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
index 274e45c07..74a2d1764 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
@@ -1264,6 +1264,15 @@ Int aiDefenseAllowance( Int army, UnsignedInt frame )
return byArmy > byClock ? byArmy : byClock;
}
+//-------------------------------------------------------------------------------------------------
+Real aiFireSampleWeight( Real baseToThreat, Real sampleToThreat, Real reach, Bool outsideBase )
+{
+ Real weight = reach > 0.0f ? ( baseToThreat - sampleToThreat ) / reach : 0.0f;
+ if( weight < 0.0f )
+ weight = 0.0f;
+ return outsideBase ? weight + 0.1f : weight;
+}
+
//-------------------------------------------------------------------------------------------------
Int aiPickBaseDefense( const Int *standing, const Bool *armed, Int count )
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
index 8848369fb..27b77c53f 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
@@ -4926,6 +4926,250 @@ const ThingTemplate *AIPlayer::nextBaseDefense( Object *dozer )
return pick < 0 ? NULL : candidates[ pick ];
}
+/** Where a defence's own guns reach, off its default weapon set. A Stinger Site's soldiers, an empty
+ * bunker and a speaker tower have none, and are scored as if they reached DEFENSE_REACH_UNARMED. */
+static const Real DEFENSE_REACH_UNARMED = 250.0f;
+
+static Real defenseReach( const ThingTemplate *tmpl )
+{
+ Real reach = 0.0f;
+ const WeaponTemplateSet *set = tmpl->getWeaponTemplateSets().empty() ? NULL : tmpl->findWeaponTemplateSet( WeaponSetFlags() );
+ for( Int slot = 0; set && slot < WEAPONSLOT_COUNT; ++slot )
+ {
+ const WeaponTemplate *weapon = set->getNth( (WeaponSlotType)slot );
+ if( weapon && weapon->getUnmodifiedAttackRange() > reach )
+ reach = weapon->getUnmodifiedAttackRange();
+ }
+ return reach > 0.0f ? reach : DEFENSE_REACH_UNARMED;
+}
+
+static void collectDefensePositions( Object *obj, void *userData )
+{
+ if( obj->isKindOf( KINDOF_FS_BASE_DEFENSE ) && !obj->isEffectivelyDead() )
+ ((std::vector<Coord3D> *)userData)->push_back( *obj->getPosition() );
+}
+
+/** Rings round the base center a defence may go on, in base radii, and spots per ring. */
+static const Int DEFENSE_RINGS = 4;
+static const Real DEFENSE_RING_RADII[ DEFENSE_RINGS ] = { 0.75f, 1.0f, 1.25f, 1.5f };
+static const Int DEFENSE_SPOTS_PER_RING = 24;
+/** Ground looked at round each spot: this many directions, at half and nine tenths of the reach. */
+static const Int DEFENSE_FIRE_SAMPLES = 16;
+/** Best-scored spots asked for legality, each about a millisecond. */
+static const Int DEFENSE_PLACE_TRIES = 12;
+
+//----------------------------------------------------------------------------------------------------------
+/** A defence goes where its guns see the most of the ground an enemy comes over. A spot on a ring
+ * round the base is scored by the open ground inside its reach: each sample point on clear,
+ * drivable ground counts for how much nearer the enemy it lies than the middle of the base does
+ * (aiFireSampleWeight), plus a little for being outside the base at all, and counts nothing when a building of ours or a cliff stands
+ * between it and the spot. Every defence already standing or queued within three quarters of the
+ * reach divides the score, so the guns spread along the front instead of stacking. The enemy is
+ * where enemyStartGuess says, the same knowledge every other decision here uses. The spot that went
+ * up in front of a fixed point used to land behind the base's own buildings on a crowded map, and a
+ * missed spot fell back to the middle of the base; one with no score is not built at all now. */
+//----------------------------------------------------------------------------------------------------------
+Bool AIPlayer::placeDefense( const ThingTemplate *defense )
+{
+ if( !m_baseCenterSet )
+ return FALSE;
+
+ Coord3D threats[ MAX_PLAYER_COUNT ];
+ Int threatCount = 0;
+ for( Int i = 0; i < ThePlayerList->getPlayerCount() && threatCount < MAX_PLAYER_COUNT; ++i )
+ {
+ Player *them = ThePlayerList->getNthPlayer( i );
+ if( them == m_player || m_player->getRelationship( them->getDefaultTeam() ) != ENEMIES || !them->hasAnyObjects() )
+ continue;
+ if( enemyStartGuess( i, &threats[ threatCount ] ) )
+ ++threatCount;
+ }
+ if( threatCount == 0 )
+ {
+ Coord3D dir;
+ if( !enemyDirection( &dir ) )
+ return FALSE;
+ threats[ 0 ].x = m_baseCenter.x + dir.x * 4.0f * m_baseRadius;
+ threats[ 0 ].y = m_baseCenter.y + dir.y * 4.0f * m_baseRadius;
+ threats[ 0 ].z = 0.0f;
+ threatCount = 1;
+ }
+
+ std::vector<Coord3D> guns;
+ m_player->iterateObjects( collectDefensePositions, &guns );
+ for( BuildListInfo *info = m_player->getBuildList(); info; info = info->getNext() )
+ {
+ const ThingTemplate *planned = info->isPriorityBuild() && info->getObjectID() == INVALID_ID
+ ? TheThingFactory->findTemplate( info->getTemplateName(), FALSE ) : NULL;
+ if( planned && planned->isKindOf( KINDOF_FS_BASE_DEFENSE ) )
+ guns.push_back( *info->getLocation() );
+ }
+
+ const Real reach = defenseReach( defense );
+ const Real spacingSqr = sqr( 0.75f * reach );
+ const Real footprint = defense->getTemplateGeometryInfo().getBoundingCircleRadius();
+ const Real footprintSqr = sqr( 2.0f * footprint );
+ Region3D extent;
+ TheTerrainLogic->getMaximumPathfindExtent( &extent );
+
+ const Int SPOTS = DEFENSE_RINGS * DEFENSE_SPOTS_PER_RING;
+ Coord3D spot[ SPOTS ];
+ Real score[ SPOTS ];
+ Int clear[ SPOTS ];
+ Int blocked[ SPOTS ];
+ Int order[ SPOTS ];
+ for( Int s = 0; s < SPOTS; ++s )
+ {
+ const Real angle = 2.0f * PI * ( s % DEFENSE_SPOTS_PER_RING ) / DEFENSE_SPOTS_PER_RING;
+ const Real radius = DEFENSE_RING_RADII[ s / DEFENSE_SPOTS_PER_RING ] * m_baseRadius;
+ spot[ s ].x = m_baseCenter.x + radius * Cos( angle );
+ spot[ s ].y = m_baseCenter.y + radius * Sin( angle );
+ spot[ s ].z = 0.0f;
+ score[ s ] = 0.0f;
+ clear[ s ] = 0;
+ blocked[ s ] = 0;
+ order[ s ] = s;
+ if( spot[ s ].x < extent.lo.x || spot[ s ].x > extent.hi.x || spot[ s ].y < extent.lo.y || spot[ s ].y > extent.hi.y )
+ continue;
+
+ // a spot that cannot be legal is not worth a legality check: on a building, a cliff or water,
+ // or on top of a gun already there or queued. Without this 11 of every 12 checks failed, most
+ // of them on restricted terrain under the footprint's edge, so the corners are looked at too
+ {
+ Bool open = TRUE;
+ for( Int corner = 0; corner < 9 && open; ++corner )
+ {
+ Coord3D at = spot[ s ];
+ at.x += footprint * ( corner % 3 - 1 );
+ at.y += footprint * ( corner / 3 - 1 );
+ ICoord2D cell;
+ TheAI->pathfinder()->worldToCell( &at, &cell );
+ const PathfindCell *pathCell = TheAI->pathfinder()->getCell( LAYER_GROUND, cell.x, cell.y );
+ open = pathCell != NULL && pathCell->getType() == PathfindCell::CELL_CLEAR;
+ }
+ if( !open )
+ continue;
+ // the rest failed on the clearance kept round another building, ours or anybody's
+ PartitionFilterAcceptByKindOf structuresOnly( MAKE_KINDOF_MASK( KINDOF_STRUCTURE ), KINDOFMASK_NONE );
+ PartitionFilter *structureFilters[] = { &structuresOnly, NULL };
+ if( ThePartitionManager->getClosestObject( &spot[ s ], footprint + PATHFIND_CELL_SIZE_F * 2.0f,
+ FROM_BOUNDINGSPHERE_2D, structureFilters ) != NULL )
+ continue;
+ Bool onGun = FALSE;
+ for( std::vector<Coord3D>::const_iterator g = guns.begin(); g != guns.end() && !onGun; ++g )
+ onGun = sqr( g->x - spot[ s ].x ) + sqr( g->y - spot[ s ].y ) < footprintSqr;
+ if( onGun )
+ continue;
+ // and ground the build rules refuse - a tile marked unbuildable, a slope - fails most of
+ // what is left, and the terrain half of the legality test alone is a footprint walk
+ if( TheBuildAssistant->isLocationLegalToBuild( &spot[ s ], defense, defense->getPlacementViewAngle(),
+ BuildAssistant::TERRAIN_RESTRICTIONS, NULL, m_player ) != LBC_OK )
+ continue;
+ // an enemy within reach of the dozer: on a small map the front ring sat that close to the
+ // enemy's own base, and the best spots were refused on every pass for the whole match
+ if( !isLocationSafe( &spot[ s ], defense ) )
+ continue;
+ }
+
+
+ for( Int k = 0; k < 2 * DEFENSE_FIRE_SAMPLES; ++k )
+ {
+ const Real sampleAngle = 2.0f * PI * ( k % DEFENSE_FIRE_SAMPLES ) / DEFENSE_FIRE_SAMPLES;
+ const Real sampleReach = ( k < DEFENSE_FIRE_SAMPLES ? 0.5f : 0.9f ) * reach;
+ Coord3D at;
+ at.x = spot[ s ].x + sampleReach * Cos( sampleAngle );
+ at.y = spot[ s ].y + sampleReach * Sin( sampleAngle );
+ 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 )
+ continue; // not ground anything drives over
+
+ // measured against the enemy nearest this ground, from the middle of the base: ground the
+ // enemy has to cross to reach us, not merely ground in front of this spot
+ Real sampleToThreat = -1.0f;
+ Int nearest = 0;
+ for( Int t = 0; t < threatCount; ++t )
+ {
+ const Real d = sqrt( sqr( threats[ t ].x - at.x ) + sqr( threats[ t ].y - at.y ) );
+ if( sampleToThreat < 0.0f || d < sampleToThreat )
+ {
+ sampleToThreat = d;
+ nearest = t;
+ }
+ }
+ const Real baseToThreat = sqrt( sqr( threats[ nearest ].x - m_baseCenter.x ) + sqr( threats[ nearest ].y - m_baseCenter.y ) );
+ const Real weight = aiFireSampleWeight( baseToThreat, sampleToThreat, reach,
+ sqr( at.x - m_baseCenter.x ) + sqr( at.y - m_baseCenter.y ) > sqr( m_baseRadius ) );
+ if( weight <= 0.0f )
+ continue;
+ if( !groundLineClear( &spot[ s ], &at ) )
+ {
+ ++blocked[ s ];
+ continue;
+ }
+ ++clear[ s ];
+ score[ s ] += weight;
+ }
+
+ Int neighbours = 0;
+ for( std::vector<Coord3D>::const_iterator g = guns.begin(); g != guns.end(); ++g )
+ if( sqr( g->x - spot[ s ].x ) + sqr( g->y - spot[ s ].y ) < spacingSqr )
+ ++neighbours;
+ score[ s ] /= INT_TO_REAL( 1 + neighbours );
+ }
+
+ // best first, the lower index of two alike
+ for( Int i = 1; i < SPOTS; ++i )
+ for( Int j = i; j > 0 && score[ order[ j ] ] > score[ order[ j - 1 ] ]; --j )
+ {
+ const Int swap = order[ j ];
+ order[ j ] = order[ j - 1 ];
+ order[ j - 1 ] = swap;
+ }
+
+ const Real placeAngle = defense->getPlacementViewAngle();
+ Int illegal = 0;
+ LegalBuildCode lastCode = LBC_OK;
+ // a pass whose best dozen all failed asked the same dozen again ten seconds later, all match long.
+ // Half the tries go to the best spots, the other half to a window further down the ranking that
+ // moves on every pass, round to the top again every fourth
+ const Int HALF = DEFENSE_PLACE_TRIES / 2;
+ const Int window = HALF + (Int)( ( TheGameLogic->getFrame() / ECONOMY_CHECK_RATE ) % 4 ) * HALF;
+ for( Int t = 0; t < DEFENSE_PLACE_TRIES; ++t )
+ {
+ const Int n = t < HALF ? t : window + t - HALF;
+ if( n >= SPOTS )
+ break;
+ const Int s = order[ n ];
+ if( score[ s ] <= 0.0f )
+ continue; // ranked after every spot worth anything; the window may have run into them
+ const LegalBuildCode code = TheBuildAssistant->isLocationLegalToBuild( &spot[ s ], defense, placeAngle,
+ BuildAssistant::CLEAR_PATH | BuildAssistant::TERRAIN_RESTRICTIONS | BuildAssistant::NO_OBJECT_OVERLAP,
+ NULL, m_player );
+ TheTerrainVisual->removeAllBibs(); // isLocationLegalToBuild adds bib feedback
+ if( code != LBC_OK )
+ {
+ ++illegal;
+ lastCode = code;
+ }
+ else
+ {
+ DEBUG_LOG(("AI DEFENSE frame %d player %d places '%s' at (%.0f,%.0f), rank %d, score %.2f, fire clear %d blocked %d, %d guns near\n",
+ TheGameLogic->getFrame(), m_player->getPlayerIndex(), defense->getName().str(), spot[ s ].x, spot[ s ].y, n + 1,
+ score[ s ], clear[ s ], blocked[ s ], (Int)guns.size()));
+ m_player->addToPriorityBuildList( defense->getName(), &spot[ s ], placeAngle );
+ return TRUE;
+ }
+ }
+ DEBUG_LOG(("AI DEFENSE frame %d player %d has no spot for '%s', best score %.2f, fire clear %d blocked %d, %d illegal (last code %d)\n",
+ TheGameLogic->getFrame(), m_player->getPlayerIndex(), defense->getName().str(), score[ order[ 0 ] ], clear[ order[ 0 ] ], blocked[ order[ 0 ] ],
+ illegal, (Int)lastCode));
+ return FALSE;
+}
+
/** How loaded this player's factories of one kind are. Counted off the objects, because a factory
* bought past the build list is still a factory. */
struct FactoryLoad
@@ -5371,37 +5615,24 @@ void AIPlayer::doEconomy( void )
more than ten. Bought whenever the bank allowed, they took the money from the army: over twelve
four-player matches 23 guns became 241, and attack waves fell from 223 to 187. So the guns grow
with the army, and with the clock up to two superweapons' worth (aiDefenseAllowance), one at a
- time, each the type the base has fewest of. They go round the front: straight at the enemy,
- then 45 degrees either side, then 90, so the flanks are covered too, and a pass that finds one
- arc full tries the next arc on the next pass. They wait only for the hoard, like the income
- buildings: behind twice the hoard, a 1v1 Hard side built two to five a match. */
+ time, each the type the base has fewest of, each on the spot with the widest field of fire
+ (placeDefense). They wait only for the hoard, like the income buildings: behind twice the
+ hoard, a 1v1 Hard side built two to five a match. A base three or more behind its allowance
+ queues two a pass, of different types, since one a pass left most of the allowance unspent. */
const BaseTally tally = tallyBase( m_player );
- const ThingTemplate *defense = nextBaseDefense( dozer );
- if( defense && tally.defenses < aiDefenseAllowance( tally.army, TheGameLogic->getFrame() )
- && !priorityBuildPending( m_player, defense ) )
- {
- // cos and sin of 0, +45, -45, +90 and -90 degrees, written out so no trig runs in logic
- const Int ARCS = 5;
- static const Real ARC_COS[ ARCS ] = { 1.0f, 0.70710678f, 0.70710678f, 0.0f, 0.0f };
- static const Real ARC_SIN[ ARCS ] = { 0.0f, 0.70710678f, -0.70710678f, 1.0f, -1.0f };
- Coord3D spot = m_baseCenter;
- Coord3D dir;
- if( enemyDirection( &dir ) )
- {
- const Int arc = (Int)( ( (UnsignedInt)tally.defenses + TheGameLogic->getFrame() / ECONOMY_CHECK_RATE ) % ARCS );
- const Real x = dir.x * ARC_COS[ arc ] - dir.y * ARC_SIN[ arc ];
- const Real y = dir.y * ARC_COS[ arc ] + dir.x * ARC_SIN[ arc ];
- spot.x += x * m_baseRadius * DEFENSE_STANDOFF;
- spot.y += y * m_baseRadius * DEFENSE_STANDOFF;
- }
- // a base on a small map has its arc off the edge or on a cliff: 680 of 790 tries missed over
- // 72 1v1 matches, so a miss goes round the middle of the base instead
- Bool placed = placeNear( defense, &spot, 0.0f, FALSE );
- if( !placed )
- placed = placeNear( defense, &m_baseCenter, 0.5f * m_baseRadius, FALSE );
+ const Int allowance = aiDefenseAllowance( tally.army, TheGameLogic->getFrame() );
+ const Int perPass = allowance - tally.defenses >= 3 ? 2 : 1;
+ for( Int k = 0; k < perPass && tally.defenses + k < allowance; ++k )
+ {
+ const ThingTemplate *defense = nextBaseDefense( dozer );
+ if( defense == NULL || priorityBuildPending( m_player, defense ) )
+ break;
+ const Bool placed = placeDefense( defense );
DEBUG_LOG(("AI ECONOMY frame %d player %d %s defense '%s', %d of %d standing, army %d\n", TheGameLogic->getFrame(),
m_player->getPlayerIndex(), placed ? "puts up" : "has no room for", defense->getName().str(),
- tally.defenses, aiDefenseAllowance( tally.army, TheGameLogic->getFrame() ), tally.army));
+ tally.defenses + k, allowance, tally.army));
+ if( !placed )
+ break;
}
// ... and what does not pay back for twice it, so the opening build order is not what pays for it
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp
index cb5d90b08..4b959e348 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp
@@ -681,7 +681,9 @@ void AISkirmishPlayer::buildAIBaseDefense(Bool flank)
Object *dozer = findNearestDozer(&m_baseCenter);
const ThingTemplate *mix = dozer ? nextBaseDefense(dozer) : NULL;
if (mix) {
- buildAIBaseDefenseStructure(mix->getName(), flank);
+ // the spot with the widest field of fire first; the approach-path ring when none scores
+ if (!placeDefense(mix))
+ buildAIBaseDefenseStructure(mix->getName(), flank);
} else if (resInfo) {
buildAIBaseDefenseStructure(resInfo->m_baseDefenseStructure1, flank);
}
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 00a0814a9..da0f9c46f 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -11290,6 +11290,13 @@ TEST(ai_base_defenses_rotate_through_the_sides_types)
CHECK_EQ( standing[ 1 ], 2 );
}
+ // a spot is scored by the ground it sees toward the enemy: ground half a reach nearer him than the
+ // middle of the base is worth a half, ground behind the base nothing, and outside the base a tenth on top
+ CHECK_NEAR( aiFireSampleWeight( 1000.0f, 850.0f, 300.0f, FALSE ), 0.5f, 0.001f );
+ CHECK_NEAR( aiFireSampleWeight( 1000.0f, 1200.0f, 300.0f, FALSE ), 0.0f, 0.001f );
+ CHECK_NEAR( aiFireSampleWeight( 1000.0f, 1200.0f, 300.0f, TRUE ), 0.1f, 0.001f );
+ CHECK_NEAR( aiFireSampleWeight( 1000.0f, 700.0f, 300.0f, TRUE ), 1.1f, 0.001f );
+
// one type lost in a raid is the one put back
{
const Int standing[ 2 ] = { 5, 2 };