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): skirmish ai pulls ranked units out to be mended
Olcay Seygan48fdcca96455
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 91985e17c..2f1c9c907 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -219,6 +219,7 @@ found and fixed — EA's own, not port damage.**- 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.- The retreat actually happens now, on Normal as well as Hard. 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. A unit that makes it home gets its mood back when it stops walking.- A beaten team stops running once it is out of range. It used to break off a fight at your front door and walk the whole map back to its base at full health, where nothing repaired it, then stand there until a script or the next wave remembered it. Now it falls back just past the reach of the guns it was losing to, waits, and goes straight back in as soon as that fight turns: your units leave or die, or enough of its own arrive. If the fight still looks lost half a minute later, it goes home and joins the next wave. A team only walks home first when your guns cover the whole road. In 32 Hard against Hard matches on Twilight Flame, 2,748 of 2,756 retreats stopped short of home, and the side doing it lost 92 units a match where it had lost 96, for the same number of kills; that difference is inside the noise of 32 matches. Replays recorded before this change play out differently.+- It looks after its veterans. A heroic tank cost the computer no more thought than one off the line, and it fought to the last chevron. Now a unit with a rank pulls out on its own health, whatever its team does: under 35% for a veteran, 45% for an elite, 55% for a heroic. It also leaves a fight its team is losing before the team gives up, the higher the rank the sooner, though never one it is even in. It goes to whatever of its side's buildings can mend it, a tank to its repair point or a soldier to his barracks, and home when there is none. The computer also counts a ranked unit for a quarter more per chevron when it weighs one army against another, yours included, since your chevrons are on show. Over eight Hard matches on Twilight Flame it pulled out 422 ranked units, 28 of them heroic, and 358 of those went to a building that mends them. Both sides lost 1,979 units where the same matches had cost them 2,080, and 3% less in value, with the same economy. Replays recorded before this change play out differently.- It no longer runs from a fight in its own base. Home was where the retreat went, so when you rushed a Normal or Hard computer early, every defender was outnumbered, read the fight as lost, and was ordered back to the middle of the base it was already standing in, walking and not shooting, again every second and a half. Sixteen rebels and four Scorpions sent into a Hard USA base a minute in went a full minute without losing one. A fight at home is now fought where it is. While the base is being hit the computer also keeps its attack groups at home: nothing it has gathered leaves on a wave, nothing waiting to leave gathers out on the road, and the groups guarding the base are no longer called away to join an attack. What was gathered goes once none of your units it knows of stands in its base, or half a minute after the last hit. And it spends on the fight. A minute in, its opening has gone on buildings: a Hard USA had two soldiers and 8,000 in the bank when that rush arrived. Now a base under attack trains fighters from every factory that has room, each one picked against whatever of yours it has the least answer to yet, so sixteen rebels and four Scorpions get Rangers as well as Missile Defenders. It stops buying income buildings and extra factories until the fight is over, puts a gun up between the middle of its base and your units when it finds the room, and sends what it has at home at you once there is enough of it to matter; a handful sent out by twos only feeds you. Over four matches the USA left 36 of those 64 rebels alive where it had left 49. China and GLA already train at the pace their barracks allow, and came out about where they were. Replays recorded before this change play out differently.## Hard fights each unit from where it is strongestdiff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.hindex 3b1572ebb..27e8ab015 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h@@ -671,6 +671,7 @@ protected:Real *enemyHealth, Real *enemyPower, std::vector<Real> *enemyGuns, Real *advantage = NULL);Real fightRatio(const Coord3D *centre, Bool countHolders, Real *enemyHealth, Real *enemyPower, std::vector<Real> *enemyGuns); ///< the exchange around centre, by the units in it when the rung weighs themBool doFallback(Team *team); ///< TRUE when it sent the team's holders back or home on this pass+ void pullOutRanked(Team *team, Bool inFight, Real ratio); ///< veterans and up leave earlier than the team, to a repair or heal padvoid stepCalmly(Object *obj, TacticalStep *step, const Coord3D *spot); ///< a move the unit's mood cannot turn into an attack movevoid restoreMood(Object *obj, TacticalStep *step);Bool pickTacticalSpot(const Object *obj, const Coord3D *from, const Coord3D *awayFrom, Real distance,diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cppindex e21f84e63..ea63522d4 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp@@ -159,12 +159,20 @@ static Real templateCombatPower( const ThingTemplate *tmpl, const Player *ownerreturn INT_TO_REAL( tmpl->calcCostToBuild( owner ) );}-/** The same figure for a unit on the field. */+/** What a rank adds to a unit's worth: a quarter of its price a chevron. A heroic tank hits harder,+ * takes more and heals itself, and the price alone weighed it the same as one off the line. */+Real AIRank_valueScale( Int rank )+{+ return 1.0f + 0.25f * (Real)rank;+}++/** The same figure for a unit on the field, its rank counted. Ranks are on show to every player, so+ * weighing an enemy's by them reads nothing a human could not. */static Real aiCombatPower( const Object *obj ){if( obj == NULL || obj->getTemplate() == NULL )return 0.0f;- return templateCombatPower( obj->getTemplate(), obj->getControllingPlayer() );+ return templateCombatPower( obj->getTemplate(), obj->getControllingPlayer() ) * AIRank_valueScale( (Int)obj->getVeterancyLevel() );}/** One of the map's own Player_N_Start waypoints, by 0-based position index. Where the start@@ -10060,6 +10068,103 @@ static Bool retreatCanOrderHome( const Object *obj )ai != NULL && ai->getJetAIUpdate() != NULL );}+//----------------------------------------------------------------------------------------------------------+/** A ranked unit is worth keeping. It hits harder and takes more, and it took a match of fighting to+ * earn: a new one off the line is a rookie again. So it leaves a fight on its own health, whatever+ * its team does, below RANK_HEALTH_BASE plus RANK_HEALTH_STEP a rank (35% for a veteran, 55% for a+ * heroic), and leaves a fight its team is losing before the team does, at the rung's ratio raised by+ * RANK_RATIO_STEP a rank and never above an even fight. A regular soldier is the retreat's as before.+ *+ * Split out with plain values so the rule is testable without a running game. */+static const Real RANK_HEALTH_BASE = 0.25f;+static const Real RANK_HEALTH_STEP = 0.1f;+static const Real RANK_RATIO_STEP = 0.25f;+/** How near a unit's own goal has to be to where pullOutRanked would send it to count as on its way. */+static const Real RANK_GOAL_SLACK = 50.0f;++Bool AIRetreat_rankPullsOut( Int rank, Real healthFraction, Bool inFight, Real ratio, Real retreatRatio )+{+ if( rank <= 0 )+ return FALSE;+ if( healthFraction < RANK_HEALTH_BASE + RANK_HEALTH_STEP * rank )+ return TRUE;+ return inFight && ratio < min( retreatRatio * (1.0f + RANK_RATIO_STEP * rank), 1.0f );+}++/** The nearest of our own buildings that mends this unit - a repair pad for a vehicle, a heal pad for+ * infantry - or NULL. Ties go to the first in the object list. */+static Object *findMender( Player *player, Object *unit )+{+ std::vector<Object *> owned;+ player->iterateObjects( collectOwned, &owned );+ Object *best = NULL;+ Real bestSqr = 0.0f;+ for( std::vector<Object *>::const_iterator o = owned.begin(); o != owned.end(); ++o )+ {+ if( !(*o)->isKindOf( KINDOF_STRUCTURE ) ||+ !(TheActionManager->canGetRepairedAt( unit, *o, CMD_FROM_AI ) || TheActionManager->canGetHealedAt( unit, *o, CMD_FROM_AI )) )+ continue;+ const Real distSqr = sqr( (*o)->getPosition()->x - unit->getPosition()->x ) + sqr( (*o)->getPosition()->y - unit->getPosition()->y );+ if( best == NULL || distSqr < bestSqr )+ {+ best = *o;+ bestSqr = distSqr;+ }+ }+ return best;+}++/** The ranked members of a team that AIRetreat_rankPullsOut says go, to the nearest building that mends+ * them, or home when there is none. Marked as a walk home, so neither this nor the team's retreat+ * turns them round for RETREAT_HOME_WALK_FRAMES. */+void AIPlayer::pullOutRanked( Team *team, Bool inFight, Real ratio )+{+ const UnsignedInt now = TheGameLogic->getFrame();+ for( DLINK_ITERATOR<Object> objIter = team->iterate_TeamMemberList(); !objIter.done(); objIter.advance() )+ {+ Object *obj = objIter.cur();+ const Int rank = (Int)obj->getVeterancyLevel();+ if( rank <= LEVEL_REGULAR || obj->isEffectivelyDead() || obj->isContained() || !retreatCanOrderHome( obj ) ||+ obj->getBodyModule() == NULL || obj->getAI()->hasTunnelTrip() )+ continue;+ const TacticalStep *row = findTacticalStep( obj->getID() );+ if( row && (row->fallingBack || (row->fallbackFrame != 0 && now - row->fallbackFrame < RETREAT_HOME_WALK_FRAMES)) )+ continue;+ // one already on its way into a dock or a building is being mended, or will be. So is one in a state+ // of its own module's (1000 and up): a Helix sent to its airfield flies there in ChinookAIUpdate's+ // states, and was sent again on every pass of a 3,600-foot flight+ const StateID state = obj->getAI()->getCurrentStateID();+ if( state == AI_DOCK || state == AI_ENTER || state >= 1000 )+ continue;+ const Real health = obj->getBodyModule()->getHealth() / obj->getBodyModule()->getMaxHealth();+ if( !AIRetreat_rankPullsOut( rank, health, inFight, ratio, getSkillProfile()->m_retreatTtkRatio ) )+ continue;+ Object *mender = findMender( m_player, obj );+ if( mender == NULL && isAtHome( obj->getPosition() ) )+ continue; // home already, and nothing there mends it+ // one already walking there from an earlier pass whose row has since gone+ const Coord3D *to = mender ? mender->getPosition() : &m_baseCenter;+ const Coord3D *goal = obj->getAI()->getGoalPosition();+ if( obj->getAI()->isMoving() && goal && sqr( goal->x - to->x ) + sqr( goal->y - to->y ) < sqr( RANK_GOAL_SLACK ) )+ continue;+ leaveTacticsAlone( obj->getID() );+ TacticalStep *step = tacticalStepFor( obj->getID() );+ step->fallingBack = FALSE;+ step->fallbackFrom = *obj->getPosition();+ step->fallbackFrame = now;+ stepCalmly( obj, step, to );+ if( mender && TheActionManager->canGetRepairedAt( obj, mender, CMD_FROM_AI ) )+ obj->getAI()->aiGetRepaired( mender, CMD_FROM_SCRIPT );+ else if( mender )+ obj->getAI()->aiGetHealed( mender, CMD_FROM_SCRIPT );+ DEBUG_LOG(("AI VETERAN frame %d player %d pulls '%s' %d rank %d out at %.0f%% health, fight %.2f%s, state %d, %.0f from %s, now state %d\n", now,+ m_player->getPlayerIndex(), obj->getTemplate()->getName().str(), obj->getID(), rank, health * 100.0f,+ inFight ? ratio : 0.0f, inFight ? "" : " (none)", (Int)state,+ (Real)sqrt( sqr( to->x - obj->getPosition()->x ) + sqr( to->y - obj->getPosition()->y ) ),+ mender ? mender->getTemplate()->getName().str() : "base", (Int)obj->getAI()->getCurrentStateID()));+ }+}+//----------------------------------------------------------------------------------------------------------/** Look at every fight this AI is in and break off the ones it is losing.*@@ -10128,13 +10233,15 @@ void AIPlayer::doRetreats( void )// A fight at home is not broken off: home is where the retreat goes. Ordered to the base// centre, the defenders of an early rush stopped shooting and walked, every decision tick,- // while sixteen rebels took the base apart untouched for a minute.- if( isAtHome( ¢re ) )- continue;-+ // while sixteen rebels took the base apart untouched for a minute. A ranked unit hurt badly+ // enough still goes to be mended, at home too+ const Bool home = isAtHome( ¢re );Real enemyHealth = 0.0f, enemyPower = 0.0f;std::vector<Real> enemyGuns;- const Real ratio = fightRatio( ¢re, FALSE, &enemyHealth, &enemyPower, &enemyGuns );+ const Real ratio = home ? 1.0f : fightRatio( ¢re, FALSE, &enemyHealth, &enemyPower, &enemyGuns );+ pullOutRanked( team, enemyPower > 0.0f, ratio );+ if( home )+ continue;if( enemyPower <= 0.0f )continue; // not in a fightdiff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex 035166559..3ac247566 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -11201,6 +11201,38 @@ TEST(the_retreat_never_orders_an_aircraft_home)}+/** AIPlayer.cpp: a ranked unit leaves a fight on its own health and before its team does, the higher+ the rank the sooner, and counts for more in every weighing of forces. */+extern Bool AIRetreat_rankPullsOut( Int rank, Real healthFraction, Bool inFight, Real ratio, Real retreatRatio );+extern Real AIRank_valueScale( Int rank );++TEST(the_ai_pulls_ranked_units_out_sooner_the_higher_the_rank)+{+ // a regular soldier is the team retreat's, however hurt or however the fight goes+ CHECK( !AIRetreat_rankPullsOut( 0, 0.05f, true, 0.1f, 0.5f ) );++ // on its own health, fight or no fight: a veteran at 30%, an elite at 40%, a heroic at 50%+ CHECK( AIRetreat_rankPullsOut( 1, 0.30f, false, 1.0f, 0.5f ) );+ CHECK( !AIRetreat_rankPullsOut( 1, 0.40f, false, 1.0f, 0.5f ) );+ CHECK( AIRetreat_rankPullsOut( 2, 0.40f, false, 1.0f, 0.5f ) );+ CHECK( AIRetreat_rankPullsOut( 3, 0.50f, false, 1.0f, 0.5f ) );+ CHECK( !AIRetreat_rankPullsOut( 3, 0.60f, false, 1.0f, 0.5f ) );++ // a fight read at 0.7, which a team quitting at 0.5 stays in: the veteran stays, the elite goes+ CHECK( !AIRetreat_rankPullsOut( 1, 1.0f, true, 0.7f, 0.5f ) );+ CHECK( AIRetreat_rankPullsOut( 2, 1.0f, true, 0.7f, 0.5f ) );+ // a fight read the same with no enemy in it is no reason to go+ CHECK( !AIRetreat_rankPullsOut( 3, 1.0f, false, 0.7f, 0.5f ) );+ // and nobody leaves a fight it is even in or winning, at any rank+ CHECK( !AIRetreat_rankPullsOut( 3, 1.0f, true, 1.0f, 0.9f ) );++ CHECK_NEAR( 1.0f, AIRank_valueScale( 0 ), 0.0001f );+ CHECK( AIRank_valueScale( 3 ) > AIRank_valueScale( 2 ) );+ CHECK( AIRank_valueScale( 2 ) > AIRank_valueScale( 1 ) );+ CHECK( AIRank_valueScale( 1 ) > 1.0f );+}++/** AI.cpp: a team that loses a fight stops at the first ground on its way home that none of thefight's guns reach, a step past it, rather than walking the whole map back to its base. */TEST(a_losing_team_falls_back_out_of_reach_not_home)