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.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
feat(gameengine): aim AI superweapons at threats, and not twice at one crater
Olcay Seygan9ff58d93eef8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 195aa6024..5d69466b9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -41,6 +41,14 @@ found and fixed — EA's own, not port damage.**- Nor does it know which start position you took. It used to read that straight off the lobby, for every player, from the first second. Now it works it out: each position it has not looked at is a suspect, and the odds are simply how many opponents are still unaccounted for over how many places they could be - three of you on an eight-position map is 3 in 7 for each. Every empty position its scout crosses off makes the rest likelier, 3 in 6, then 3 in 5. When the numbers meet, it stops looking: three opponents with three places left to be is not a guess, and walking over to confirm it would waste the trip. On a two-player map that is true from the start, so nothing changed there - it never wastes a second hunting for an address it can work out by subtraction. Where it has not worked you out yet, it attacks the position you are most likely to be on, and finds out on arrival.- Nor does it read your base off the map. Where your base is, what it is worth, which supply dock to expand to and where to aim a superweapon all came off a walk of your object list, in the shroud, from the first second of the match. The computer now only counts what it can see, plus the buildings it has already found - buildings do not walk away. Before it has scouted you, all it knows is where you started, which is on the map preview anyway.+## Superweapons that go where the damage is++- The computer picked its superweapon target by adding up what your things cost inside the blast, so a supply stash outranked the tank column parked next to it. Anything that can shoot back is now worth several times its price, and base defences and massed armour are what the shot goes looking for.+- It could only aim inside the rectangle your buildings sit in. An attack wave sitting on its doorstep was never a target at all; now your army counts wherever it is standing.+- Two silos ready on the same second fired at the same spot, because nothing that was already in the air was on the map yet. A spot that has just been aimed at is worth nothing to the next shot and climbs back over ten minutes, so the salvo spreads across your base instead of digging one crater.+- Measured over a half-hour match: a Particle Cannon that fired at the identical spot three times running now spreads six shots over five parts of the map, and comes back to the first one at the end, when what you rebuilt there is worth twice what it killed.+- The spy satellite goes through the same targeting, and it was scanning one cell of one base seventeen times a match. It sweeps now.+## Generals powers the computer actually meant to buy- It spent every promotion point the moment it had one, on whatever in its list happened to be cheap enough. The strong three-point ability at the end of the list was never reached, because the points were always already gone.diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.hindex 001ccf467..8305edfd4 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h@@ -330,6 +330,19 @@ Real aiStartOccupiedOdds( Int unlocatedEnemies, Int uncheckedPositions );* building in the way. */Bool aiIsIncomeNotATarget( Bool isTechBuilding, Bool isCapturable, Bool isTechBaseDefense );+/** What a superweapon target is still worth, given one shot already aimed at it - 1.0 untouched,+ * 0.0 right on top of a shot aimed this frame, climbing back over 'window' frames and with+ * distance from that shot.+ *+ * A superweapon is in the air for several seconds and everything it is about to kill is standing+ * the whole time, so a scan that reads the object list hands every ready superweapon, and every+ * script pass until the first one lands, the identical point: three nukes in one crater. The+ * recovery is deliberately gradual rather than a ban - the ground an enemy rebuilt on is worth+ * hitting again, and a base with nothing else left in it should still be shot at.+ *+ * Two shots further apart than the blast radius do not cover the same ground, so nothing fades. */+Real aiStrikeFade( Real distanceSqr, Real radiusSqr, UnsignedInt age, UnsignedInt window );+/** How attractive an enemy player is to go after, as a cost - lower is better, and it is a squared* distance with the other terms folded into it so the units stay comparable.*diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.hindex 8c89a04b5..9adfb3349 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h@@ -403,7 +403,11 @@ protected:Object *findSupplyCenter(Int minSupplies);void getPlayerStructureBounds(Region2D *bounds, Int playerNdx, Bool conservative = FALSE, Int observerNdx = -1 );-protected:+ /// what a superweapon aimed here is worth, with the shots already on their way taken off+ Int superweaponScore( Coord3D *center, Int playerNdx, Real radius, Bool targetMilitaryUnits );+ void noteSuperweaponAim( const Coord3D *pos ); ///< remember a spot, so the next shot goes elsewhere++protected:Player *m_player; ///< the Player we represent@@ -475,6 +479,13 @@ protected:AsciiString m_heldLabel[ MAX_HELD_TEAMS ]; ///< the approach the script asked forInt m_heldSuffix[ MAX_HELD_TEAMS ]; ///< the enemy start index its path name ends inUnsignedInt m_heldSince; ///< frame the first of the parked teams arrived++ /** Where the last few superweapons were aimed, so the next one does not land in the same crater+ * while the one before it is still in the air. */+ enum { MAX_REMEMBERED_STRIKES = 4 };+ 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};#endif // _AI_PLAYER_H_diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cppindex 1beafc0ea..17bd6ba16 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp@@ -1113,6 +1113,31 @@ Real aiRetreatRatio( Real myHealth, Real myPower, Real enemyHealth, Real enemyPoreturn (ratio > NOT_A_FIGHT) ? NOT_A_FIGHT : ratio;}+//-------------------------------------------------------------------------------------------------+/** What a spot is still worth to aim a superweapon at, after one already aimed near it.+ *+ * Nothing outside the blast fades, and nothing older than the window does. Inside both, how much+ * the two shots overlap decides: on top of the old aim the worth is the share of the window that+ * has passed, at the rim it is untouched, and it slides between the two.+ *+ * The grading is the part that does the work, and the flat version that came first is why. A+ * fade that took the same amount off every point inside the blast left the ranking among them+ * exactly as it was, so the second shot picked the same winner as the first and only the+ * reported worth moved - measured, seventeen scans of one cell in one match. Grading it makes+ * the next shot slide off the crater and cover ground the last one did not. */+//-------------------------------------------------------------------------------------------------+Real aiStrikeFade( Real distanceSqr, Real radiusSqr, UnsignedInt age, UnsignedInt window )+{+ if( window == 0 || age >= window )+ return 1.0f;+ if( radiusSqr <= 0.0f || distanceSqr >= radiusSqr )+ return 1.0f;++ const Real overlap = 1.0f - sqrt( distanceSqr / radiusSqr ); // 1 on top of the old aim, 0 at the rim+ const Real recovered = INT_TO_REAL( age ) / INT_TO_REAL( window );+ return 1.0f - overlap * (1.0f - recovered);+}+//-------------------------------------------------------------------------------------------------Bool aiShouldMass( Real waitingThreat, Real enemyVisibleThreat, Real massFraction,Bool timeExpired, Bool baseUnderAttack )diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cppindex bf0636eb0..cad2a6179 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp@@ -307,6 +307,13 @@ m_role(AIROLE_AGGRESSIVE)}m_heldSince = 0;+ for( Int strike = 0; strike < MAX_REMEMBERED_STRIKES; ++strike )+ {+ m_strikeAim[ strike ].zero();+ m_strikeFrame[ strike ] = 0; // 0 == nothing aimed here yet, which fades nothing+ }+ m_strikeNext = 0;+m_frameLastBuildingBuilt = TheGameLogic->getFrame();p->setCanBuildUnits(false); // turn off ai production by default.@@ -1564,6 +1571,68 @@ void AIPlayer::onUnitProduced( Object *factory, Object *unit )m_teamDelay = 0; // Cause the update queues & selection to happen immediately.}+/** How long a spot stays spoken for after a superweapon has been aimed at it.+ *+ * It has to outlast a recharge or it buys nothing: the first cut was a minute, and the spy+ * satellite - which goes through this same script action - recharges in 1801 frames and found+ * its memory expired by one frame every single time, so it scanned the identical cell of the+ * identical base seventeen times in a match. One recharge is not enough either: a Particle+ * Uplink Cannon comes back in 8400 frames and at a window of 9000 the crater has recovered 93%+ * of its worth, which moves nothing - measured, three shots into the same spot. Two recharges+ * is the number, so the shot after this one has to find somewhere half as good before it will+ * come back here.+ *+ * Coming back is deliberate. The same three shots were at a cluster he kept rebuilding, worth+ * 6859, then 7300, then 8900 - a target that grows back past the fade is one worth hitting+ * again, and the fade recovering the whole way is what allows it. */+enum { SUPERWEAPON_REAIM_FRAMES = 600 * LOGICFRAMES_PER_SECOND };++//----------------------------------------------------------------------------------------------------------+/** What a superweapon aimed at this spot is worth to this player right now.+ *+ * The score itself is EA's - the price of everything inside the blast - and the fade on top of it+ * is what stops the salvo. A negative score belongs to a sneak attack, which reads defended ground+ * as a cost rather than a prize; fading that would flatter exactly the ground it is avoiding.+ */+//----------------------------------------------------------------------------------------------------------+Int AIPlayer::superweaponScore( Coord3D *center, Int playerNdx, Real radius, Bool targetMilitaryUnits )+{+ const Int value = getPlayerSuperweaponValue( center, playerNdx, radius, targetMilitaryUnits, m_player->getPlayerIndex() );+ if( value <= 0 )+ return value;++ const UnsignedInt now = TheGameLogic->getFrame();+ Real worth = 1.0f;+ for( Int strike = 0; strike < MAX_REMEMBERED_STRIKES; ++strike )+ {+ if( m_strikeFrame[ strike ] == 0 )+ continue;++ const Real dx = center->x - m_strikeAim[ strike ].x;+ const Real dy = center->y - m_strikeAim[ strike ].y;+ const Real fade = aiStrikeFade( dx*dx + dy*dy, sqr( radius ), now - m_strikeFrame[ strike ],+ SUPERWEAPON_REAIM_FRAMES );+ if( fade < worth )+ worth = fade; // the freshest shot covering this spot decides+ }++ return REAL_TO_INT( value * worth );+}++//----------------------------------------------------------------------------------------------------------+/** Remember a spot the next shot should leave alone.+ *+ * ponytail: recorded where the target is picked rather than where the shot leaves the silo - the+ * one caller fires immediately after a successful compute, and nothing else in the tree aims one.+ */+//----------------------------------------------------------------------------------------------------------+void AIPlayer::noteSuperweaponAim( const Coord3D *pos )+{+ m_strikeAim[ m_strikeNext ] = *pos;+ m_strikeFrame[ m_strikeNext ] = TheGameLogic->getFrame();+ m_strikeNext = (m_strikeNext + 1) % MAX_REMEMBERED_STRIKES;+}+//----------------------------------------------------------------------------------------------------------/*** Find a good spot to fire a superweapon.@@ -1661,8 +1730,8 @@ Bool AIPlayer::computeSuperweaponTarget(const SpecialPowerTemplate *power, Coordpos.x = bounds.lo.x + ( bounds.width() * xIndex ) / xCount;pos.y = bounds.lo.y + ( bounds.height() * yIndex ) / yCount;pos.z = 0;- Int curCash = getPlayerSuperweaponValue( &pos, playerNdx, 2*weaponRadius, targetMilitaryUnits, m_player->getPlayerIndex() );- if ( curCash > cash)+ Int curCash = superweaponScore( &pos, playerNdx, 2*weaponRadius, targetMilitaryUnits );+ if ( curCash > cash){cash = curCash;bestPos = pos;@@ -1670,6 +1739,50 @@ Bool AIPlayer::computeSuperweaponTarget(const SpecialPowerTemplate *power, Coord}}+ //+ // An army is a threat point wherever it happens to be standing, and the grid above only covers+ // the ground his buildings are on: getPlayerStructureBounds measures structures, so the wave+ // parked on our own doorstep was never a candidate at all - the AI could only ever shoot at+ // real estate. Offer what we can see of his army as centres too and let the same score choose.+ // ponytail: a value pass per armed unit, which is only paid on a frame a superweapon is ready.+ //+ Player *enemy = ThePlayerList->getNthPlayer( playerNdx );+ if( targetMilitaryUnits && enemy != NULL )+ {+ const Int observerNdx = m_player->getPlayerIndex();+ Player::PlayerTeamList::const_iterator teamIt;+ for( teamIt = enemy->getPlayerTeams()->begin(); teamIt != enemy->getPlayerTeams()->end(); ++teamIt )+ {+ for( DLINK_ITERATOR<Team> instanceIt = (*teamIt)->iterate_TeamInstanceList(); !instanceIt.done(); instanceIt.advance() )+ {+ Team *team = instanceIt.cur();+ if( !team )+ continue;+ for( DLINK_ITERATOR<Object> memberIt = team->iterate_TeamMemberList(); !memberIt.done(); memberIt.advance() )+ {+ Object *pObj = memberIt.cur();+ if( !pObj || pObj->isKindOf( KINDOF_STRUCTURE ) )+ continue; // his buildings are what the grid above already walked+ if( !pObj->isKindOf( KINDOF_CAN_ATTACK ) )+ continue; // a harvester is not a threat point; it is already worth its price in the grid+ if( pObj->isSignificantlyAboveTerrain() )+ continue; // same rule as the value function: nothing is aimed at a plane in the air+ if( !observerKnowsAbout( pObj, observerNdx ) )+ continue;++ Coord3D pos = *pObj->getPosition();+ pos.z = 0;+ Int curCash = superweaponScore( &pos, playerNdx, 2*weaponRadius, targetMilitaryUnits );+ if( curCash > cash )+ {+ cash = curCash;+ bestPos = pos;+ }+ }+ }+ }+ }+//Fine tune that position by looking at a even smaller radius.Coord3D veryBestPos;xCount = 11;@@ -1683,7 +1796,7 @@ Bool AIPlayer::computeSuperweaponTarget(const SpecialPowerTemplate *power, Coordpos.x = bestPos.x + (x-5)*(weaponRadius/10);pos.y = bestPos.y + (y-5)*(weaponRadius/10); // was (x-5): only the diagonal was scannedpos.z = 0;- Int curCash = getPlayerSuperweaponValue( &pos, playerNdx, weaponRadius, targetMilitaryUnits, m_player->getPlayerIndex() );+ Int curCash = superweaponScore( &pos, playerNdx, weaponRadius, targetMilitaryUnits );if ( curCash > cash){cash = curCash;@@ -1707,12 +1820,22 @@ Bool AIPlayer::computeSuperweaponTarget(const SpecialPowerTemplate *power, Coordsuccess = ( cash > -1 );+ if( success )+ {+ DEBUG_LOG(("AI SUPERWEAPON frame %d player %d aims '%s' at (%.0f,%.0f), worth %d\n", TheGameLogic->getFrame(),+ m_player->getPlayerIndex(), power->getName().str(), veryBestPos.x, veryBestPos.y, cash));+ noteSuperweaponAim( &veryBestPos );+ }+return success;}+/** How much an armed target is worth on top of its price, so the shot goes where the threat is. */+const Real SUPERWEAPON_THREAT_WEIGHT = 2.0f;+//----------------------------------------------------------------------------------------------------------/*** Get the target value for structures in an area.@@ -1790,9 +1913,19 @@ Int AIPlayer::getPlayerSuperweaponValue(Coord3D *center, Int playerNdx, Real radelsevalue = value / 10; // Superweapons cannot be killed by any superweapon, so we don't want to target them as highly. jba.}+ //+ // What a superweapon is for. Price alone ranks a supply stash above the tank+ // column parked beside it, which is why these shots landed in the money and not+ // in the army. What can shoot is worth several times its price to be rid of:+ // aiCombatPower reads ThingTemplate's ThreatValue where the data sets it and+ // falls back on cost, the same weighing the retreat and the counter score use.+ //+ if( includeMilitaryUnits )+ value += aiCombatPower( pObj ) * SUPERWEAPON_THREAT_WEIGHT;+if( applyNegValue ){- cash -= factor * value * 5.0f; //Extremely undesired+ cash -= factor * value * 5.0f; //Extremely undesired}else{@@ -6761,7 +6894,7 @@ void AIPlayer::xfer( Xfer *xfer ){// version- XferVersion currentVersion = 6; // 2: scout 3: rung and role 4: scouting stamps 5: the capturer 6: parked waves+ XferVersion currentVersion = 7; // 2: scout 3: rung and role 4: scouting stamps 5: the capturer 6: parked waves 7: superweapon aimsXferVersion version = currentVersion;xfer->xferVersion( &version, currentVersion );@@ -6960,6 +7093,16 @@ void AIPlayer::xfer( Xfer *xfer )}xfer->xferUnsignedInt( &m_heldSince );}+ // where the last shots were aimed, so a loaded game does not put the next one in the same crater+ if( version >= 7 )+ {+ for( Int strike = 0; strike < MAX_REMEMBERED_STRIKES; ++strike )+ {+ xfer->xferCoord3D( &m_strikeAim[ strike ] );+ xfer->xferUnsignedInt( &m_strikeFrame[ strike ] );+ }+ xfer->xferInt( &m_strikeNext );+ }// the ladder rung and the role, which are rolled once and must come back the same wayif( version >= 3 )diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex dd330e874..f8886f57c 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -9073,6 +9073,45 @@ TEST(retreat_ratio_measures_the_exchange_not_the_health_bar)}+/** A superweapon takes seconds to arrive and everything it is about to kill stands there the whole+ time, so the scan that picks the target says the same thing to the second silo and to the next+ script pass. Two AIs with three Scud Storms between them put all three in one crater. */+TEST(a_superweapon_does_not_aim_where_one_is_already_falling)+{+ const Real RADIUS_SQR = 100.0f * 100.0f;+ const UnsignedInt WINDOW = 60 * LOGICFRAMES_PER_SECOND;++ // the spot one is falling on right now is worth nothing to the next one+ CHECK_NEAR( 0.0f, aiStrikeFade( 0.0f, RADIUS_SQR, 0, WINDOW ), 0.0001f );++ // and it comes back, so ground he has rebuilt on is a target again rather than banned forever+ CHECK_NEAR( 0.5f, aiStrikeFade( 0.0f, RADIUS_SQR, WINDOW/2, WINDOW ), 0.0001f );+ CHECK_NEAR( 1.0f, aiStrikeFade( 0.0f, RADIUS_SQR, WINDOW, WINDOW ), 0.0001f );+ CHECK_NEAR( 1.0f, aiStrikeFade( 0.0f, RADIUS_SQR, 10*WINDOW, WINDOW ), 0.0001f );++ // the rest of his base is not in that crater, whatever is landing in it+ CHECK_NEAR( 1.0f, aiStrikeFade( RADIUS_SQR, RADIUS_SQR, 0, WINDOW ), 0.0001f );+ CHECK_NEAR( 1.0f, aiStrikeFade( 4.0f*RADIUS_SQR, RADIUS_SQR, 0, WINDOW ), 0.0001f );++ //+ // The grading is what moves the next shot, and a flat fade is the version that did not: taking+ // the same amount off every point in the blast leaves them in the same order, so the scan hands+ // back the same winner and only the number changes. Half a radius off the crater keeps half its+ // worth, so the second shot slides over and covers ground the first one did not.+ //+ CHECK_NEAR( 0.5f, aiStrikeFade( 0.25f*RADIUS_SQR, RADIUS_SQR, 0, WINDOW ), 0.0001f );+ CHECK( aiStrikeFade( 0.0f, RADIUS_SQR, 0, WINDOW ) < aiStrikeFade( 0.25f*RADIUS_SQR, RADIUS_SQR, 0, WINDOW ) );+ CHECK( aiStrikeFade( 0.25f*RADIUS_SQR, RADIUS_SQR, 0, WINDOW ) < aiStrikeFade( 0.81f*RADIUS_SQR, RADIUS_SQR, 0, WINDOW ) );++ // ... and both halves of it fade together: older and further off are both worth more+ CHECK( aiStrikeFade( 0.25f*RADIUS_SQR, RADIUS_SQR, 0, WINDOW )+ < aiStrikeFade( 0.25f*RADIUS_SQR, RADIUS_SQR, WINDOW/2, WINDOW ) );++ // no window is no memory: this is what every caller that does not want the fade gets+ CHECK_NEAR( 1.0f, aiStrikeFade( 0.0f, RADIUS_SQR, 0, 0 ), 0.0001f );+}++/** AIPlayer.cpp: who the retreat is allowed to order home. Aircraft are not: a move order is whatstarts a jet's or a helicopter's own round trip, so one handed to a parked aircraft everydecision interval took it off the deck, flew it at the base centre, idled it and landed it