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.

fix(gameengine): ai sends a ranked unit to be mended once, not every 30 s

Olcay Seygan7df1283a8f2b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5b3227872..ec9ad9e95 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -231,7 +231,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. A unit sent off to be mended now leaves its squad on the way, so the squad's next order no longer drags it back into the fight half-repaired; it joins a new squad once it is fixed or home. Before, a Black Lotus at 67% health was sent to her barracks four times in a row and never arrived, and one unit was pulled out twelve times in a match. Over the same two 2v2 Hard matches on Twilight Flame the most any unit was pulled out fell from 12 and 8 to 5 and 2, and the ones still pulled out twice came back mended in between.
+- 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. A unit sent off to be mended now leaves its squad on the way, so the squad's next order no longer drags it back into the fight half-repaired; it joins a new squad once it is fixed or home. Before, a Black Lotus at 67% health was sent to her barracks four times in a row and never arrived, and one unit was pulled out twelve times in a match. Over the same two 2v2 Hard matches on Twilight Flame the most any unit was pulled out fell from 12 and 8 to 5 and 2, and the ones still pulled out twice came back mended in between. It still sent some again every thirty seconds from wherever they stood: a GLA Angry Mob member that its mob kept marching off was ordered to the barracks eight times, and a Scorpion on its way to the Arms Dealer was turned back into the fight at a third of its health, because the computer's fight logic saw a hurt tank standing still in the queue and sent it back to its squad. A unit sent off to be mended now gets no other order until it is fixed or home. Over six Hard against Medium matches between GLA and the USA on Twilight Flame, the thirty-second repeats went from 13 to none, every unit pulled out twice had come back at full health in between, and 78 of the 89 that came back did so at full health. It also stops pulling out a unit that is not hurt because its squad is losing: Colonel Burton was walked off at full health. A losing fight now pulls a ranked unit only once it is below 90%; in the same matches, 25 pulled at 90% or more became none.
- 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 strongest
@@ -323,7 +323,7 @@ found and fixed — EA's own, not port damage.**
- Campaign reinforcements flown in by Chinook land again. That one-at-a-time unloading sent a mission's scripted Chinooks home with their cargo still aboard, so on the second American mission the dozers announced at the docks never got off, and neither did the next one.
- A guarding unit no longer fights itself between returning to post and shooting back.
- Guard covers the circle you choose. How far a guard reached used to come from each unit's own eyesight, so Rangers and Missile Defenders posted on the same spot held circles of 180 and 270 and a raider standing between the two was only shot by half the group. Now one guard order gives the whole group one circle, the widest any of them had. Roll the mouse wheel while the guard key or the guard button is armed and the circle grows or shrinks before you click, drawn on the ground under the pointer as you go. Select a guarding group and its circle is drawn round the post, and every unit of yours on guard carries a small steel shield over its head, selected or not, in place of the blocky "G" it used to wear. The shield has smooth edges and a lit and a shaded half, and it shrinks as you zoom out the way the health bars do: at 1080p it was 24 pixels tall over every unit at every zoom, and it is now 18 up close and 11 from the opening camera, about the height of an infantryman's head.
-- An Ambulance cleans up the toxins around it without being told. Its hose reaches 100, and that was all it ever looked at, so one parked a truck's length from a toxin pool sat and watched it. Standing idle or on guard, it now notices a pool, an anthrax cloud or a radiation field up to 300 away, drives over, washes off every one in that circle, and goes back to where it stood; one that was on guard is back on guard. A unit you are moving is never pulled off its order, and any order you give while it is cleaning ends the cleanup. Put down 150 to 250 from two Ambulances, one idle and one guarding, three poison fields were gone inside 16 seconds, both trucks were back on their spots, and a third Ambulance driving past a fourth field went straight on to where it was sent. The Cleanup Area button works better for it too: an Ambulance sent to clean an area used to shoot only at what was already in reach once it got there and stood still in front of the rest, and once the area was clean it never counted as idle again, so it ignored the next spill. Replays recorded before this change play out differently.
+- An Ambulance cleans up the toxins around it without being told. Its hose reaches 100, and that was all it ever looked at, so one parked a truck's length from a toxin pool sat and watched it. Standing idle or on guard, it now notices a pool, an anthrax cloud or a radiation field up to 300 away, drives over, washes off every one in that circle, and goes back to where it stood; one that was on guard is back on guard. A unit you are moving is never pulled off its order, and any order you give while it is cleaning ends the cleanup. Put down 150 to 250 from two Ambulances, one idle and one guarding, three poison fields were gone inside 16 seconds, both trucks were back on their spots, and a third Ambulance driving past a fourth field went straight on to where it was sent. The Cleanup Area button works better for it too: an Ambulance sent to clean an area used to shoot only at what was already in reach once it got there and stood still in front of the rest, and once the area was clean it never counted as idle again, so it ignored the next spill. An Ambulance guarding a tank goes back to guarding the tank after a cleanup, not the patch of ground it left from, so it follows the tank again: with the tank driven 600 away after the cleanup, the Ambulance reached it 17 seconds later. One that gives up on a spill it cannot drive up to no longer goes back for the same spill every time it stands idle; telling it to clean the area yourself still sends it. Replays recorded before this change play out differently.
- Jets on guard attack what is inside the circle you drew. A plane on guard flies to its post and circles it, and since guards stopped shooting at enemies hidden in fog it only went after what that loop brought into its own sight: a Raptor guarding a circle of 700 hung over the post for the whole 80 seconds of the test with a power plant 550 out, and an Aurora circled for ten seconds before it found the same one. Aircraft are back on the original rule and take anything in the circle, fog or not. The Raptor's first missiles now land 11 seconds after the order and the Aurora's bomb after 9, and neither flies over the post first. Ground units still leave alone what they cannot see. A replay recorded before this change plays back differently.
- H now sets a stance for the group. Defensive is how your units have always behaved: they fire on what comes into range and stay put. Aggressive lets them go after anything they can see, the way the computer's own units do, so a group left on aggressive clears the ground around it without being told. The button shows the stance the selection holds.
- A queued attack move finishes its fights before the next order on the list goes out. The first enemy it met used to count as arriving, so a list of attack moves round a town skipped ahead a step at every skirmish and the group was off to the last point while the first was still contested. Replays recorded before this version play back differently.
diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifest
index 5df5fb3a3..c01057f67 100644
--- a/GeneralsMD/Code/BuildFingerprint.manifest
+++ b/GeneralsMD/Code/BuildFingerprint.manifest
@@ -128,6 +128,7 @@ Data/Scenarios/airbelow.txt
Data/Scenarios/airbelowfar.txt
Data/Scenarios/alphaaurora.txt
Data/Scenarios/ambulanceclean.txt
+Data/Scenarios/ambulanceguard.txt
Data/Scenarios/aurorafog.txt
Data/Scenarios/avengerlasers.txt
Data/Scenarios/beambase.txt
diff --git a/GeneralsMD/Code/Data/Scenarios/ambulanceguard.txt b/GeneralsMD/Code/Data/Scenarios/ambulanceguard.txt
new file mode 100644
index 000000000..c3629d678
--- /dev/null
+++ b/GeneralsMD/Code/Data/Scenarios/ambulanceguard.txt
@@ -0,0 +1,23 @@
+# Does an Ambulance guarding a tank come back to the tank after a cleanup?
+#
+# The Ambulance guards a Crusader, notices a medium poison field 200 from it, cleans it and should be
+# back on guard on the Crusader, not on the spot it left from. The Crusader then drives 600 east, and
+# the "arrive" line says whether the Ambulance followed it. Measured 2026-10-12: back on guard at
+# frame 340, at the Crusader 505 frames after it set off.
+#
+# generals.exe -headless -quickstart -noshellmap -observer -multiInstance -noFPSLimit
+# -randommap 1 2 small -autoskirmish 2 -takeover
+# -side 0 FactionAmerica -side 1 FactionGLA -seed 1 -maxframes 1800
+# -scenario ambulanceguard -logPrefix ambulanceguard_
+#
+# See mobstress.txt for the line grammar.
+
+30 spawn 0 AirF_AmericaVehicleMedic 1 700 1500
+30 spawn 0 AmericaTankCrusader 1 760 1500
+
+60 guard 0 AirF_AmericaVehicleMedic 0 AmericaTankCrusader
+
+90 spawn 1 PoisonFieldMedium 1 700 1700
+
+600 move 0 AmericaTankCrusader 1360 1500
+601 arrive 0 AirF_AmericaVehicleMedic 1360 1500 200
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
index 5da8d2489..e64bbe288 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
@@ -475,6 +475,7 @@ public:
Bool isDutyHelix( const Object *obj ) const; ///< a Helix this AI bought to heal or to raid, which nothing else gives orders
Bool isDutyAmbulance( const Object *obj ) const; ///< an Ambulance this AI bought to follow the army, which nothing else gives orders
Bool isWalkingToAmbulance( const Object *obj ) const; ///< a patient on its way into a duty Ambulance, which nothing else gives orders either
+ Bool isOutToMend( const Object *obj ) const; ///< a pulled-out veteran or a patient, out of its team until releaseMended frees it
protected:
/**
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CleanupHazardUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CleanupHazardUpdate.h
index 59684c8df..1a488b255 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CleanupHazardUpdate.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CleanupHazardUpdate.h
@@ -100,6 +100,8 @@ protected:
Int m_resumeGuardMode; ///< a GuardMode
Bool m_returning; ///< the area is clean and the walk back to m_pos has been ordered
Int m_approaches; ///< scans in a row standing out of reach of the hazard it is after
+ ObjectID m_resumeGuardObject; ///< the object it was guarding when a cleanup took it off guard, or INVALID_ID for a spot
+ ObjectID m_givenUpID; ///< the last hazard it gave up on as out of reach, never gone for again
};
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h
index c8f519b81..642ecd03f 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h
@@ -88,7 +88,8 @@ enum ScenarioActionType
SCENARIO_ACTION_WEAPONAT, ///< weaponat <slot> <selector> <position> [primary|secondary|tertiary]; a FIRE_WEAPON button's click on the ground, as MSG_DO_WEAPON_AT_LOCATION; tertiary when left out
SCENARIO_ACTION_FORCEGROUND, ///< forceground <slot> <selector> <position>; the attack key's click on the ground, as MSG_DO_FORCE_ATTACK_GROUND
SCENARIO_ACTION_REAIM, ///< reaim <slot> <selector> <position>; a right click that moves a running power's aim (the Spectre Gunship's), as MSG_DO_SPECIAL_POWER_OVERRIDE_DESTINATION
- SCENARIO_ACTION_RESPOND ///< respond <slot> <selector> <position>; from now, how long each unit takes to point its gun at the position, fire with it pointed there, and get closer to it
+ SCENARIO_ACTION_RESPOND, ///< respond <slot> <selector> <position>; from now, how long each unit takes to point its gun at the position, fire with it pointed there, and get closer to it
+ SCENARIO_ACTION_GUARD ///< guard <slot> <selector> <targetSlot> <targetSelector>; a guard order on one object, as a script gives it
};
/// ScenarioAction::atStart when the position is plain numbers
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
index 961ac8fc8..82365ab84 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
@@ -2816,6 +2816,18 @@ void AIPlayer::logEngage( const char *cause, const std::vector<Object *> &units
void AIPlayer::onUnitLost( const Object *obj )
{
const Team *team = obj->getTeam();
+ // AI DEFLOSS: killed by a building's gun or its garrison, for the count of units thrown at defences
+ const DamageInfo *last = obj->getBodyModule()->getLastDamageInfo();
+ const Object *killer = last ? TheGameLogic->findObjectByID( last->in.m_sourceID ) : NULL;
+ if( killer && killer->getContainedBy() )
+ killer = killer->getContainedBy();
+ if( isSkirmishAI() && !obj->isKindOf( KINDOF_STRUCTURE ) && killer && killer->isKindOf( KINDOF_STRUCTURE ) &&
+ m_player->getRelationship( killer->getTeam() ) == ENEMIES )
+ DEBUG_LOG(("AI DEFLOSS frame %d player %d '%s' worth %.0f to '%s'\n", TheGameLogic->getFrame(), m_player->getPlayerIndex(),
+ obj->getTemplate()->getName().str(), aiCombatPower( obj ), killer->getTemplate()->getName().str()));
+ if( isSkirmishAI() && obj->isKindOf( KINDOF_STRUCTURE ) && aiCombatPower( obj ) > 0.0f )
+ DEBUG_LOG(("AI DEFDEAD frame %d player %d '%s' worth %.0f\n", TheGameLogic->getFrame(), m_player->getPlayerIndex(),
+ obj->getTemplate()->getName().str(), aiCombatPower( obj )));
if( !isSkirmishAI() || obj->isKindOf( KINDOF_STRUCTURE ) || team == NULL || team == m_player->getDefaultTeam() )
return;
const Real NEAR_SQR = 300.0f * 300.0f;
@@ -10921,6 +10933,12 @@ Bool AIPlayer::isWalkingToAmbulance( const Object *obj ) const
return ai && ai->getCurrentStateID() == AI_ENTER && ai->getGoalObject() && isDutyAmbulance( ai->getGoalObject() );
}
+Bool AIPlayer::isOutToMend( const Object *obj ) const
+{
+ const AIUpdateInterface *ai = obj->getAI();
+ return ai && !ai->isRecruitable() && obj->getTeam() == m_player->getDefaultTeam();
+}
+
/** For the log only: what became of each patient an Ambulance called in. It climbs in, then is let out
* or dies inside; or it dies on the way; or something else gives it an order first and it walks off. */
void AIPlayer::followPatients( void )
@@ -11318,6 +11336,9 @@ static Bool retreatCanOrderHome( const Object *obj )
static const Real RANK_HEALTH_BASE = 0.25f;
static const Real RANK_HEALTH_STEP = 0.1f;
static const Real RANK_RATIO_STEP = 0.25f;
+/** A losing fight pulls only one that has been hurt in it. Colonel Burton was walked out of one at full
+ * health, and a whole one has nothing to mend: canGetRepairedAt and canGetHealedAt refuse it. */
+static const Real RANK_UNHURT = 0.9f;
/** 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;
@@ -11327,7 +11348,7 @@ Bool AIRetreat_rankPullsOut( Int rank, Real healthFraction, Bool inFight, Real r
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 );
+ return inFight && healthFraction < RANK_UNHURT && 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
@@ -11375,6 +11396,11 @@ void AIPlayer::pullOutRanked( Team *team, Bool inFight, Real ratio )
const TacticalStep *row = findTacticalStep( obj->getID() );
if( row && (row->fallingBack || (row->fallbackFrame != 0 && now - row->fallbackFrame < RETREAT_HOME_WALK_FRAMES)) )
continue;
+ // one already out stays out until releaseMended frees it. Out of its team it is in the default
+ // one, which doRetreats walks too, and every RETREAT_HOME_WALK_FRAMES it was sent again from
+ // wherever it stood: an Angry Mob member that its mob kept walking was pulled 8 times, every 30 s
+ if( isOutToMend( obj ) )
+ 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
@@ -11434,6 +11460,8 @@ void AIPlayer::releaseMended( void )
if( state == AI_DOCK || state == AI_ENTER || state >= 1000 || ai->isMoving() )
continue;
ai->setIsRecruitable( TRUE );
+ DEBUG_LOG(("AI VETERAN frame %d player %d frees '%s' %d at %.0f%% health\n", TheGameLogic->getFrame(), m_player->getPlayerIndex(),
+ obj->getTemplate()->getName().str(), obj->getID(), obj->getBodyModule()->getHealth() / obj->getBodyModule()->getMaxHealth() * 100.0f));
}
}
@@ -11573,7 +11601,7 @@ void AIPlayer::doRetreats( void )
continue;
// nor one walking to an Ambulance that called it in: sent home instead, it left the Ambulance
// hurt (the other 2 of the 4 walk-offs in six Hard USA mirrors)
- if( isWalkingToAmbulance( obj ) )
+ if( isWalkingToAmbulance( obj ) || isOutToMend( obj ) )
continue;
// 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
@@ -12356,8 +12384,10 @@ void AIPlayer::tacticsFor( Object *obj )
return;
// nor a patient on its way into an Ambulance: past leaveTacticsAlone's ten seconds the pull-out and the
// rejoin walked 2 of 4 such patients off in six Hard USA mirrors on Twilight Flame (2026-10-11)
+ // nor one pulled out to be mended: waiting its turn at an Arms Dealer's dock it stood still, and the
+ // rejoin walked it back to the fight still hurt
if( obj->getID() == m_capturerID || obj->getID() == m_hijackerID || isDutyHelix( obj ) || isDutyAmbulance( obj ) ||
- isWalkingToAmbulance( obj ) )
+ isWalkingToAmbulance( obj ) || isOutToMend( obj ) )
return;
for( Int i = 0; i < MAX_AI_SCOUTS; ++i )
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/CleanupHazardUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/CleanupHazardUpdate.cpp
index a5b955f29..941ca4aea 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/CleanupHazardUpdate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/CleanupHazardUpdate.cpp
@@ -58,6 +58,18 @@
/** Scans in a row an area cleaner stands out of reach of its hazard before it gives the area up. */
static const Int MAX_CLEANUP_APPROACHES = 5;
+/** Every hazard but the one given up on. */
+class PartitionFilterRejectGivenUp : public PartitionFilter
+{
+ ObjectID m_id;
+public:
+ PartitionFilterRejectGivenUp( ObjectID id ) : m_id( id ) {}
+ virtual Bool allow( Object *objOther ) { return objOther->getID() != m_id; }
+#if defined(_DEBUG) || defined(_INTERNAL)
+ virtual const char* debugGetName() { return "PartitionFilterRejectGivenUp"; }
+#endif
+};
+
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
CleanupHazardUpdateModuleData::CleanupHazardUpdateModuleData()
@@ -96,8 +108,10 @@ CleanupHazardUpdate::CleanupHazardUpdate( Thing *thing, const ModuleData* module
m_resumeGuardMode = GUARDMODE_NORMAL;
m_returning = FALSE;
m_approaches = 0;
+ m_resumeGuardObject = INVALID_ID;
+ m_givenUpID = INVALID_ID;
-}
+}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
@@ -186,9 +200,9 @@ UpdateSleepTime CleanupHazardUpdate::update()
{
m_returning = FALSE;
// Cleaning an area: standing still out of the weapon's reach on a scan, scan after scan, is a hazard
- // it cannot drive up to. It gives the area up rather than order the same drive for good.
- // ponytail: it may notice the same hazard again from home and try once more, bounded by the
- // hazard's own lifetime; a list of hazards given up on would end that
+ // it cannot drive up to. It gives the area up rather than order the same drive for good, and does
+ // not go for that hazard again: noticed from home, it drove the same way for the hazard's lifetime.
+ // ponytail: one hazard remembered; two out of reach side by side would take turns
AIUpdateInterface *ai = obj->getAI();
WeaponBonus bonus;
bonus.clear();
@@ -197,6 +211,7 @@ UpdateSleepTime CleanupHazardUpdate::update()
{
if( ++m_approaches > MAX_CLEANUP_APPROACHES )
{
+ m_givenUpID = found->getID();
finishArea( "gave up on a hazard it cannot reach", TRUE );
return UPDATE_SLEEP_NONE;
}
@@ -323,7 +338,8 @@ Object* CleanupHazardUpdate::scanClosestTarget()
PartitionFilterAcceptByKindOf kindFilter(MAKE_KINDOF_MASK(KINDOF_CLEANUP_HAZARD), KINDOFMASK_NONE);
PartitionFilterSameMapStatus filterMapStatus(getObject());
- PartitionFilter* filters[] = { &kindFilter, &filterMapStatus, NULL };
+ PartitionFilterRejectGivenUp givenUpFilter( m_givenUpID );
+ PartitionFilter* filters[] = { &kindFilter, &filterMapStatus, &givenUpFilter, NULL };
if( m_moveRange > 0.0f )
{
@@ -361,7 +377,13 @@ void CleanupHazardUpdate::finishArea( const char *why, Bool goHome )
if( m_resumeGuard )
{
m_resumeGuard = FALSE;
- ai->aiGuardPosition( &m_pos, (GuardMode)m_resumeGuardMode, CMD_FROM_AI );
+ // back on the object it guarded, not the spot it stood on when it left; on the spot if that is gone
+ Object *guarded = TheGameLogic->findObjectByID( m_resumeGuardObject );
+ m_resumeGuardObject = INVALID_ID;
+ if( guarded && !guarded->isEffectivelyDead() )
+ ai->aiGuardObject( guarded, (GuardMode)m_resumeGuardMode, CMD_FROM_AI );
+ else
+ ai->aiGuardPosition( &m_pos, (GuardMode)m_resumeGuardMode, CMD_FROM_AI );
}
else if( goHome )
ai->aiMoveToPosition( &m_pos, CMD_FROM_AI );
@@ -398,16 +420,17 @@ void CleanupHazardUpdate::startAutoCleanup()
PartitionFilterAcceptByKindOf kindFilter(MAKE_KINDOF_MASK(KINDOF_CLEANUP_HAZARD), KINDOFMASK_NONE);
PartitionFilterSameMapStatus filterMapStatus(obj);
- PartitionFilter* filters[] = { &kindFilter, &filterMapStatus, NULL };
+ PartitionFilterRejectGivenUp givenUpFilter( m_givenUpID );
+ PartitionFilter* filters[] = { &kindFilter, &filterMapStatus, &givenUpFilter, NULL };
if( !ThePartitionManager->getClosestObject( obj->getPosition(), data->m_scanRange + AUTO_CLEANUP_MOVE_RANGE, FROM_CENTER_2D, filters ) )
return;
m_pos = *obj->getPosition();
m_moveRange = AUTO_CLEANUP_MOVE_RANGE;
- // ponytail: an object guard comes back as a guard on the spot it stood, since EA's guard target type
- // keeps the first guard order ever given rather than the current one
+ // read before aiBusy below, whose exit from the guard state clears the guard target type
m_resumeGuard = guarding;
m_resumeGuardMode = ai->getGuardMode();
+ m_resumeGuardObject = guarding && ai->getGuardTargetType() == GUARDTARGET_OBJECT ? ai->getGuardObject() : INVALID_ID;
ai->aiBusy( CMD_FROM_AI );
DEBUG_LOG(("CLEANUP frame %d '%s' %d of player %d goes to clean by itself round (%.0f,%.0f)%s\n", TheGameLogic->getFrame(),
obj->getTemplate()->getName().str(), obj->getID(), obj->getControllingPlayer() ? obj->getControllingPlayer()->getPlayerIndex() : -1,
@@ -429,6 +452,7 @@ void CleanupHazardUpdate::setCleanupAreaParameters( const Coord3D *pos, Real ran
m_resumeGuard = FALSE;
m_returning = FALSE;
m_approaches = 0;
+ m_givenUpID = INVALID_ID; // sent on purpose, it tries every hazard there again
if( ai )
{
@@ -454,13 +478,14 @@ void CleanupHazardUpdate::crc( Xfer *xfer )
/** Xfer method
* Version Info:
* 1: Initial version
- * 2: the guard a cleanup it started by itself gives back, the walk back, the drives toward a hazard */
+ * 2: the guard a cleanup it started by itself gives back, the walk back, the drives toward a hazard
+ * 3: the object that guard was on, the hazard given up on */
// ------------------------------------------------------------------------------------------------
void CleanupHazardUpdate::xfer( Xfer *xfer )
{
// version
- XferVersion currentVersion = 2;
+ XferVersion currentVersion = 3;
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
@@ -495,6 +520,11 @@ void CleanupHazardUpdate::xfer( Xfer *xfer )
xfer->xferBool( &m_returning );
xfer->xferInt( &m_approaches );
}
+ if( version >= 3 )
+ {
+ xfer->xferObjectID( &m_resumeGuardObject );
+ xfer->xferObjectID( &m_givenUpID );
+ }
} // end xfer
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp
index a3d082096..a4b8ccd84 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp
@@ -224,6 +224,8 @@ static Bool parseActionType( const AsciiString &token, ScenarioActionType *actio
*action = SCENARIO_ACTION_REAIM;
else if (token == "respond")
*action = SCENARIO_ACTION_RESPOND;
+ else if (token == "guard")
+ *action = SCENARIO_ACTION_GUARD;
else
return FALSE;
@@ -318,6 +320,7 @@ static Int tokensNeededFor( ScenarioActionType action )
case SCENARIO_ACTION_ATTACK: return SCENARIO_TOKENS_ATTACK;
case SCENARIO_ACTION_ENTER: return SCENARIO_TOKENS_ATTACK;
case SCENARIO_ACTION_DOCK: return SCENARIO_TOKENS_ATTACK;
+ case SCENARIO_ACTION_GUARD: return SCENARIO_TOKENS_ATTACK;
case SCENARIO_ACTION_PRODUCE: return SCENARIO_TOKENS_ATTACK;
case SCENARIO_ACTION_STOP: return SCENARIO_TOKENS_STOP;
case SCENARIO_ACTION_TALLY: return SCENARIO_TOKENS_STOP;
@@ -419,6 +422,7 @@ ScenarioParseResult ScenarioDrill_parseLine( const char *line, ScenarioAction *a
case SCENARIO_ACTION_ATTACK:
case SCENARIO_ACTION_ENTER:
case SCENARIO_ACTION_DOCK:
+ case SCENARIO_ACTION_GUARD:
case SCENARIO_ACTION_SHIFTATTACK:
case SCENARIO_ACTION_FORCEATTACK:
case SCENARIO_ACTION_SHIFTPOWER:
@@ -1600,9 +1604,11 @@ static Bool executeOrder( const ScenarioAction &action, Player *player, const Co
case SCENARIO_ACTION_ATTACK:
case SCENARIO_ACTION_ENTER:
case SCENARIO_ACTION_DOCK:
+ case SCENARIO_ACTION_GUARD:
{
const char *verb = (action.action == SCENARIO_ACTION_ATTACK) ? "attack"
- : (action.action == SCENARIO_ACTION_DOCK) ? "dock" : "enter";
+ : (action.action == SCENARIO_ACTION_DOCK) ? "dock"
+ : (action.action == SCENARIO_ACTION_GUARD) ? "guard" : "enter";
Player *targetPlayer = findPlayerForSlot( action.targetSlot );
Object *target = (targetPlayer != NULL)
? findFirstMatching( targetPlayer, action.targetSelector )
@@ -1619,6 +1625,8 @@ static Bool executeOrder( const ScenarioAction &action, Player *player, const Co
group->groupAttackObject( target, SCENARIO_ATTACK_SHOTS, CMD_FROM_SCRIPT );
else if (action.action == SCENARIO_ACTION_DOCK)
group->groupDock( target, CMD_FROM_SCRIPT );
+ else if (action.action == SCENARIO_ACTION_GUARD)
+ group->groupGuardObject( target, GUARDMODE_NORMAL, CMD_FROM_SCRIPT );
else
group->groupEnter( target, CMD_FROM_SCRIPT );
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 29eb53c60..0328a960b 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -11219,8 +11219,11 @@ TEST(the_ai_pulls_ranked_units_out_sooner_the_higher_the_rank)
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 ) );
+ CHECK( !AIRetreat_rankPullsOut( 1, 0.8f, true, 0.7f, 0.5f ) );
+ CHECK( AIRetreat_rankPullsOut( 2, 0.8f, true, 0.7f, 0.5f ) );
+ // but only once the fight has hurt it: Colonel Burton was walked out of one at full health
+ CHECK( !AIRetreat_rankPullsOut( 3, 1.0f, true, 0.1f, 0.5f ) );
+ CHECK( !AIRetreat_rankPullsOut( 2, 0.95f, 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