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): attack move scans instead of driving past enemies

Olcay Seygance447be220a9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4078522b3..09ac90ecd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -59,6 +59,7 @@ found and fixed — EA's own, not port damage.**
- Which enemy it goes after was the nearest one and nothing else, plus a rule with its sign the wrong way round: an opponent who had lost his units or his production had his distance treated as half the map, so the computer ignored the one it was about to beat. That is what dragged matches out.
- It now weighs distance, whether the target is crippled - an opportunity, not a distraction - and how much of what it can see that player is worth. Only a genuinely finished enemy is skipped.
- It still refuses to gang up with another computer opponent on one victim, and still gently prefers whoever is already shooting at it.
+- An aggressive computer team is supposed to fight its way to where it is sent rather than walk there. It never did. The order to fight was being reissued every frame, and each reissue pushed the moment that unit next looks for a target one step further into the future, so the look never came at all and the team crossed the map through the enemy without firing. Over four and a half minutes of one test match that order was restarted 2,240 times. It is restarted 15 times now.
## The computer knows when to quit
- Its teams fought to the last man. The word "retreat" appeared nowhere in the opponent's code - the single most visible thing that made it look stupid.
@@ -96,6 +97,7 @@ found and fixed — EA's own, not port damage.**
- Attack-moving through a base shoots the base; buildings were filtered out.
- Aircraft make their pass, fly home, rearm and resume your order.
- Nothing walks off the map chasing a target that keeps retreating.
+- Being pulled off a chase no longer blinds a unit on the way back. It owes the order a stretch of ground before it is allowed to drive to another fight, and it used to spend that stretch refusing to see anything at all - so a tank rolled past an enemy parked beside it without firing a shot. It still will not go chasing during that stretch. It will shoot whatever is already in front of its gun, which costs the advance nothing.
- A unit turns onto whatever is actually shooting it, then resumes the advance.
- Otherwise it picks the worst thing in range: anything armed before anything that is not, then the more dangerous of the two, and worth fades with distance so it is never the far one it walks the field for. A group ordered through a base no longer stops for the first dozer it passes while the artillery beside it keeps firing.
- Ctrl on the attack-move click no longer shells the ground instead.
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIStateMachine.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIStateMachine.h
index 014d6032f..e1c10d35f 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIStateMachine.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIStateMachine.h
@@ -599,10 +599,11 @@ protected:
enum {ATTACK_MOVE_REACQUIRE_DELAY=30}; ///< frames of pure movement after a dud fight or a broken leash
enum {ATTACK_MOVE_RETALIATE_FRAMES=30}; ///< how recently we must have been hit to turn on whoever hit us
- void startEngaging( Object *victim ); ///< stop here and hand the victim to the attack sub-machine
+ void startEngaging( Object *victim, Bool allowChase ); ///< stop here and hand the victim to the attack sub-machine
void stopEngaging( void ); ///< the fight is over; put back what startEngaging changed
Bool hasLeftTheLeash( void ); ///< has the victim dragged us too far off the attack move?
Object *findRetaliationTarget( void ); ///< whoever is shooting us right now, if we can shoot back
+ Bool canHitFromHere( const Object *victim ); ///< can we shoot it without moving an inch?
Bool mayEngageYet( void ); ///< has the required progress toward the goal been made?
void requireProgressTowardGoal( void ); ///< refuse to fight again until we are closer to the goal
void applyGroupSpeed( void ); ///< hold this unit to the ordered group's speed
@@ -615,6 +616,7 @@ protected:
ObjectID m_victimID; ///< who we picked
UnsignedInt m_engageStartFrame; ///< when we picked it
UnsignedInt m_frameToScanOn; ///< next frame we may look for a target
+ UnsignedInt m_frameToApproachOn; ///< until this frame we only take targets we can already shoot
Real m_reengageGoalDistSqr; ///< no new fight until we are this close to the goal (0 = no gate)
Real m_groupSpeed; ///< speed of the slowest member of the ordered group
Bool m_isEngaging; ///< true while the attack sub-machine owns us
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
index 2fee1a578..4cfce2167 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
@@ -607,8 +607,10 @@ public:
///< States that are doing idle checks should call with calledDuringIdle set true so that they check their
///< States that will actually close with what they find (attack move) should call with allowOutOfWeaponRangeTargets
///< set true, which searches vision range instead of only what is already within weapon range.
+ ///< requireWithinWeaponRange narrows that back to what can be shot without moving an inch, whoever
+ ///< is playing - an attack move whose approach is suspended still fires at what it can reach.
- Object *getNextMoodTarget( Bool calledByAI, Bool calledDuringIdle, Bool allowOutOfWeaponRangeTargets = FALSE );
+ Object *getNextMoodTarget( Bool calledByAI, Bool calledDuringIdle, Bool allowOutOfWeaponRangeTargets = FALSE, Bool requireWithinWeaponRange = FALSE );
UnsignedInt getNextMoodCheckTime() const { return m_nextMoodCheckTime; }
// This function will return a combination of MoodMatrixParameter flags.
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
index 1c1efc6bd..c2f8a14b0 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
@@ -2085,8 +2085,21 @@ StateReturnType AIMoveToState::update()
blah++;
}
+ //
+ // An aggressive mood turns a plain move order into an attack move - but only a real move order.
+ // This same AIMoveToState instance is also handed out as the machine's *temporary* state, parked
+ // on top of another order by an internally generated move (AIUpdate.cpp,
+ // privateMoveToPosition), and its update runs every frame while the order underneath is held
+ // still. Converting from there did two wrong things at once: it clobbered the very order the
+ // temporary state exists to protect, and it re-entered AI_ATTACK_MOVE_TO every frame, whose
+ // onEnter pushes the target scan clock forward by design. A unit caught in that loop never
+ // scanned once in its life - an attack move walked it straight past everything it was pointed
+ // at, which is the bug this guard fixes. AssaultTransportAIUpdate already guards its own
+ // re-issue the same way.
+ //
UnsignedInt adjustment = ai->getMoodMatrixActionAdjustment(MM_Action_Move);
- if (m_isMoveTo && (adjustment & MAA_Action_To_AttackMove))
+ if (m_isMoveTo && (adjustment & MAA_Action_To_AttackMove)
+ && getMachine()->getCurrentStateID() == AI_MOVE_TO)
ai->aiAttackMoveToPosition(&m_goalPosition, NO_MAX_SHOTS_LIMIT, CMD_FROM_AI);
// if we have a goal object, move to it, as it may have moved
@@ -3528,6 +3541,7 @@ AIAttackMoveToState::AIAttackMoveToState( StateMachine *machine ) : AIMoveToStat
m_engageStartFrame = 0;
m_ammoAtEngage = 0;
m_frameToScanOn = 0;
+ m_frameToApproachOn = 0;
m_reengageGoalDistSqr = 0.0f;
m_groupSpeed = FAST_AS_POSSIBLE;
m_isEngaging = FALSE;
@@ -3555,7 +3569,7 @@ void AIAttackMoveToState::crc( Xfer *xfer )
void AIAttackMoveToState::xfer( Xfer *xfer )
{
// version
- XferVersion currentVersion = 5;
+ XferVersion currentVersion = 6;
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
@@ -3584,6 +3598,9 @@ void AIAttackMoveToState::xfer( Xfer *xfer )
// fight was real, which sets m_frameToScanOn. Uninitialized memory driving a logic clock.
xfer->xferInt(&m_ammoAtEngage);
}
+ if (version>=6) {
+ xfer->xferUnsignedInt(&m_frameToApproachOn);
+ }
xfer->xferSnapshot(m_attackMoveMachine);
} // end xfer
@@ -3623,6 +3640,7 @@ StateReturnType AIAttackMoveToState::onEnter()
m_engageStartFrame = 0;
m_engageOrigin = *owner->getPosition();
m_reengageGoalDistSqr = 0.0f;
+ m_frameToApproachOn = 0;
// spread the scans of a group that was all ordered on the same frame over the scan interval.
m_frameToScanOn = TheGameLogic->getFrame() + ((UnsignedInt)owner->getID() % ATTACK_MOVE_SCAN_RATE);
@@ -3690,7 +3708,7 @@ static Int countRemainingAmmo( const Object *obj )
return total;
}
-void AIAttackMoveToState::startEngaging( Object *victim )
+void AIAttackMoveToState::startEngaging( Object *victim, Bool allowChase )
{
Object *owner = getMachineOwner();
AIUpdateInterface *ai = owner->getAI();
@@ -3718,7 +3736,11 @@ void AIAttackMoveToState::startEngaging( Object *victim )
// AIAttackApproachTargetState::onEnter), so on attack move it used to lock onto a target it
// never closed with and keep driving to the goal instead. Attack move is an explicit order to
// engage, so let it approach; hasLeftTheLeash() bounds how far the victim can drag it.
- if (owner->getControllingPlayer()->getPlayerType() == PLAYER_HUMAN)
+ //
+ // allowChase is FALSE for a fight taken during the stretch of pure movement a dud fight or a
+ // broken leash buys (see update()): that fight was only allowed because the target was already
+ // in range, and letting it be chased is exactly the walk-off those windows exist to prevent.
+ if (allowChase && owner->getControllingPlayer()->getPlayerType() == PLAYER_HUMAN)
ai->setAllowedToChase(TRUE);
@@ -3793,9 +3815,16 @@ void AIAttackMoveToState::stopEngaging( void )
m_engageStartFrame, now, ATTACK_MOVE_DUD_ENGAGE_FRAMES ))
{
// we could not touch it (unreachable, cannot attack it, out of ammo) - move on for a second.
- m_frameToScanOn = now + ATTACK_MOVE_REACQUIRE_DELAY;
+ // m_victimID is deliberately left standing: it is who we failed on, and the scan refuses to
+ // pick it again until the window is up. Without that, a unit that cannot hurt what is
+ // standing next to it - out of ammo is the common one - re-picks it every scan and stops
+ // there for good, since a target already in range is otherwise always worth taking.
+ m_frameToApproachOn = now + ATTACK_MOVE_REACQUIRE_DELAY;
+ }
+ else
+ {
+ m_victimID = INVALID_ID;
}
- m_victimID = INVALID_ID;
}
//----------------------------------------------------------------------------------------------------------
@@ -3896,14 +3925,69 @@ Object *AIAttackMoveToState::findRetaliationTarget( void )
canShootBack = (result == ATTACKRESULT_POSSIBLE || result == ATTACKRESULT_POSSIBLE_AFTER_MOVING);
}
+ // m_victimID outlives a fight that ended as a dud (see stopEngaging), so "already fighting them"
+ // has to ask whether we are in fact fighting, not just who we last picked.
if (!AIAttackMove_shouldRetaliate( body->getLastDamageTimestamp(), TheGameLogic->getFrame(),
ATTACK_MOVE_RETALIATE_FRAMES,
- attacker->getID() == m_victimID, canShootBack ))
+ m_isEngaging && attacker->getID() == m_victimID, canShootBack ))
return NULL;
return attacker;
}
+//----------------------------------------------------------------------------------------------------------
+/**
+ * Can we shoot it from exactly where we stand? ATTACKRESULT_POSSIBLE is the in-range answer;
+ * ATTACKRESULT_POSSIBLE_AFTER_MOVING means we would have to drive to it first (WeaponSet.cpp:706).
+ */
+Bool AIAttackMoveToState::canHitFromHere( const Object *victim )
+{
+ if (victim == NULL)
+ return FALSE;
+
+ Object *owner = getMachineOwner();
+
+ // An empty clip is the one thing getAbleToAttackSpecificObject does not ask about, and it is
+ // what a dud fight is usually made of: the unit stops for something it cannot presently shoot,
+ // the attack state exits within a few frames, and the whole thing repeats on the next scan.
+ // Nothing is lost by driving on and reloading.
+ if (owner->isOutOfAmmo())
+ return FALSE;
+
+ return owner->getAbleToAttackSpecificObject( ATTACK_NEW_TARGET, victim, CMD_FROM_AI ) == ATTACKRESULT_POSSIBLE;
+}
+
+//----------------------------------------------------------------------------------------------------------
+/**
+ * May this target be taken now? With no Object involved so test_gameengine can link straight to it
+ * - the same trick as AIAttackMove_leashBroken above.
+ *
+ * A dud fight and a broken leash each buy the attack move a stretch of pure movement: the first a
+ * second of it, the second a leash length of progress toward the goal. Both exist to stop a target
+ * we would have to drive to from walking the unit off its path, so both bound the *approach* - and
+ * a target already inside our weapon range needs no approach at all. They used to stop the scan
+ * itself, and the unit spent those stretches blind, driving straight past whatever was standing
+ * next to it. Shooting what we can already reach costs the attack move nothing, so nothing here
+ * refuses it.
+ *
+ * The one exception is the target the dud fight was against: we just failed to touch it (out of
+ * ammo is the usual reason) and it is usually still in range, so taking it again every scan would
+ * park the unit there for good.
+ */
+Bool AIAttackMove_mayTakeTarget( Bool targetIsInRangeNow, Bool targetIsTheLastDud,
+ Bool owesProgressToGoal, UnsignedInt now, UnsignedInt frameToApproachOn )
+{
+ Bool inTheReacquireWindow = (now < frameToApproachOn);
+
+ if (targetIsTheLastDud && inTheReacquireWindow)
+ return FALSE;
+
+ if (targetIsInRangeNow)
+ return TRUE;
+
+ return !owesProgressToGoal && !inTheReacquireWindow;
+}
+
//----------------------------------------------------------------------------------------------------------
/**
* The leash alone does not bound a chase: it is measured from wherever the fight started, so a
@@ -3966,7 +4050,7 @@ StateReturnType AIAttackMoveToState::update()
m_attackMoveMachine->setState( AI_IDLE );
stopEngaging();
ai->friend_setLastCommandSource(m_commandSrc);
- m_frameToScanOn = TheGameLogic->getFrame() + ATTACK_MOVE_REACQUIRE_DELAY;
+ m_frameToApproachOn = TheGameLogic->getFrame() + ATTACK_MOVE_REACQUIRE_DELAY;
requireProgressTowardGoal();
shouldRepathThisFrame = true;
}
@@ -3984,7 +4068,7 @@ StateReturnType AIAttackMoveToState::update()
{
stopEngaging();
m_frameToScanOn = now + ATTACK_MOVE_SCAN_RATE;
- startEngaging(shooter);
+ startEngaging(shooter, TRUE);
return STATE_CONTINUE;
}
}
@@ -4019,20 +4103,42 @@ StateReturnType AIAttackMoveToState::update()
}
UnsignedInt now = TheGameLogic->getFrame();
- if (now >= m_frameToScanOn && mayEngageYet())
+ if (now >= m_frameToScanOn)
{
m_frameToScanOn = now + ATTACK_MOVE_SCAN_RATE;
// Scan on our own clock rather than the unit's idle mood clock (seconds apart, long
// enough to drive right past an enemy), and take anything in vision range, not just what
// is already within weapon range - we stop and close with whatever we find.
ai->setNextMoodCheckTime(now);
+
+ // The scan itself never stops: what a dud fight or a broken leash suspends is the
+ // approach, so the unit still shoots anything it can already reach. See
+ // AIAttackMove_mayTakeTarget.
+ Bool owesProgress = !mayEngageYet();
+ // ...which is the same question asked of a target we would have to drive to.
+ Bool mayApproach = AIAttackMove_mayTakeTarget( FALSE, FALSE, owesProgress, now, m_frameToApproachOn );
+
// whoever is shooting us beats whatever the scan would have picked (usually the nearest)
Object* nextObjectToAttack = findRetaliationTarget();
- if (nextObjectToAttack == NULL)
- nextObjectToAttack = ai->getNextMoodTarget( true, false, true );
+ if (nextObjectToAttack != NULL &&
+ !AIAttackMove_mayTakeTarget( canHitFromHere(nextObjectToAttack),
+ nextObjectToAttack->getID() == m_victimID,
+ owesProgress, now, m_frameToApproachOn ))
+ nextObjectToAttack = NULL;
+
+ // While the approach is suspended the search is narrowed to what is already in range, so a
+ // distant high-threat target cannot crowd out the enemy standing next to us - and an empty
+ // clip means there is nothing worth stopping for at all (see canHitFromHere).
+ if (nextObjectToAttack == NULL && (mayApproach || !owner->isOutOfAmmo()))
+ {
+ nextObjectToAttack = ai->getNextMoodTarget( true, false, true, !mayApproach );
+ if (nextObjectToAttack != NULL && !mayApproach && nextObjectToAttack->getID() == m_victimID)
+ nextObjectToAttack = NULL; // the one we just failed on
+ }
+
if (nextObjectToAttack != NULL)
{
- startEngaging(nextObjectToAttack);
+ startEngaging(nextObjectToAttack, mayApproach);
// we don't want an update to take place 'till next frame.
return STATE_CONTINUE;
}
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
index 30ed68028..09a1f793e 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
@@ -6210,7 +6210,7 @@ public:
#endif
};
-Object* AIUpdateInterface::getNextMoodTarget( Bool calledByAI, Bool calledDuringIdle, Bool allowOutOfWeaponRangeTargets )
+Object* AIUpdateInterface::getNextMoodTarget( Bool calledByAI, Bool calledDuringIdle, Bool allowOutOfWeaponRangeTargets, Bool requireWithinWeaponRange )
{
Object *obj = getObject();
@@ -6311,7 +6311,7 @@ Object* AIUpdateInterface::getNextMoodTarget( Bool calledByAI, Bool calledDuring
{
const Real weaponRange = obj->getLargestWeaponRange();
if (weaponRange > 0.0f)
- rangeToFindWithin = weaponRange * ATTACK_MOVE_SEARCH_SCALE;
+ rangeToFindWithin = weaponRange * (requireWithinWeaponRange ? 1.0f : ATTACK_MOVE_SEARCH_SCALE);
}
if (rangeToFindWithin <= 0.0f)
@@ -6372,6 +6372,13 @@ Object* AIUpdateInterface::getNextMoodTarget( Bool calledByAI, Bool calledDuring
{
flags |= AI::WITHIN_ATTACK_RANGE;
}
+
+ // ... and a caller that has been told not to move at all right now takes only what it can shoot
+ // from where it stands, whoever is playing.
+ if (requireWithinWeaponRange)
+ {
+ flags |= AI::WITHIN_ATTACK_RANGE;
+ }
//
// Instead of shroud affecting the ability to attack, it affects the ability to target.
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 414b26395..288f32ba0 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -1126,6 +1126,36 @@ TEST(attack_move_turns_on_whoever_is_shooting_it)
CHECK( !AIAttackMove_shouldRetaliate( 0xffffffff, 0xfffffff0, WINDOW, false, true ) );
}
+/* AIStates.cpp: a dud fight and a broken leash suspend the approach, never the shooting -
+ a unit on attack move drove past whatever stood next to it during those windows. */
+extern Bool AIAttackMove_mayTakeTarget( Bool targetIsInRangeNow, Bool targetIsTheLastDud,
+ Bool owesProgressToGoal, UnsignedInt now, UnsignedInt frameToApproachOn );
+
+TEST(attack_move_still_shoots_what_it_can_already_reach)
+{
+ /* nothing owed: take anything, in range or not. */
+ CHECK( AIAttackMove_mayTakeTarget( true, false, false, 1000, 0 ) );
+ CHECK( AIAttackMove_mayTakeTarget( false, false, false, 1000, 0 ) );
+
+ /* inside the reacquire window after a dud fight: what we can shoot from here is still
+ taken, what we would have to drive to is not. This is the bug being fixed. */
+ CHECK( AIAttackMove_mayTakeTarget( true, false, false, 1000, 1030 ) );
+ CHECK( !AIAttackMove_mayTakeTarget( false, false, false, 1000, 1030 ) );
+
+ /* owing the goal a leash length of progress after a broken leash: same answer. */
+ CHECK( AIAttackMove_mayTakeTarget( true, false, true, 1000, 0 ) );
+ CHECK( !AIAttackMove_mayTakeTarget( false, false, true, 1000, 0 ) );
+
+ /* the window is over the moment the frame arrives. */
+ CHECK( AIAttackMove_mayTakeTarget( false, false, false, 1030, 1030 ) );
+
+ /* the one target the window does refuse is the one we just failed on - it is usually
+ still in range (out of ammo, cannot hurt it), so taking it again every scan would
+ park the unit there for the rest of the match. */
+ CHECK( !AIAttackMove_mayTakeTarget( true, true, false, 1000, 1030 ) );
+ CHECK( AIAttackMove_mayTakeTarget( true, true, false, 1030, 1030 ) );
+}
+
/* AI.cpp: on attack move the scan ranks what it finds by threat instead of handing
back the nearest thing. */
extern Int AI_threatScore( Int templateThreatValue, Int buildCost, Bool threatensMe,