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): make an attack move arrive as a group and bound its chase

Olcay Seyganbd8363b47236
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIStateMachine.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIStateMachine.h
index 256e50b2d..6fe44f700 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIStateMachine.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIStateMachine.h
@@ -599,6 +599,9 @@ protected:
void startEngaging( Object *victim ); ///< 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?
+ 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
CommandSourceType m_commandSrc; // Original command source. We switch to CMD_FROM_AI when auto-acquiring.
StateMachine *m_attackMoveMachine;
@@ -608,6 +611,8 @@ 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
+ 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
Bool m_chaseWasAllowed; ///< the owner's chase flag, saved while we engage
protected:
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
index 40300cf68..e41f7c1a8 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
@@ -2283,17 +2283,65 @@ void AIGroup::groupAttackPosition( const Coord3D *pos, Int maxShotsToFire, Comma
*/
void AIGroup::groupAttackMoveToPosition( const Coord3D *pos, Int maxShotsToFire, CommandSourceType cmdSource )
{
+ //
+ // This used to hand every member the same single coordinate, so a group attack move arrived as
+ // a queue rather than a group: everyone pathed to one point, at their own top speed. Spread the
+ // destination the way groupMoveToPosition does (each member keeps its offset from the group
+ // centroid) and hold the ground units to the speed of the slowest one so the group stays
+ // together on the way in - the whole point of an attack move is arriving able to fight.
+ //
+ if (m_dirty)
+ recompute();
+
+ Coord3D center;
+ Coord2D min;
+ Coord2D max;
+ getMinMaxAndCenter( &min, &max, &center );
+
+ // path the members closest to the goal first; it leaves fewer of them to collide on arrival.
+ MemoryPoolObjectHolder iterHolder;
+ SimpleObjectIterator *iter = newInstance(SimpleObjectIterator);
+ iterHolder.hold(iter);
std::list<Object *>::iterator i;
for( i = m_memberList.begin(); i != m_memberList.end(); ++i )
{
- AIUpdateInterface *ai = (*i)->getAIUpdateInterface();
- if (ai)
+ Object *member = *i;
+ if (member->isDisabledByType( DISABLED_HELD ))
+ continue; // don't bother telling the occupants to move
+ if (member->isKindOf( KINDOF_IMMOBILE ))
+ continue;
+ if (member->getAIUpdateInterface() == NULL)
+ continue;
+
+ TheAI->pathfinder()->removeGoal( member );
+ Real dx = member->getPosition()->x - pos->x;
+ Real dy = member->getPosition()->y - pos->y;
+ iter->insert( member, dx*dx + dy*dy );
+ }
+ iter->sort( ITER_SORTED_NEAR_TO_FAR );
+
+ Coord3D goalPos = *pos;
+ Bool firstUnit = true;
+ Object *theUnit;
+ for( theUnit = iter->first(); theUnit; theUnit = iter->next() )
+ {
+ AIUpdateInterface *ai = theUnit->getAIUpdateInterface();
+ if (firstUnit)
{
- if ((*i)->isAbleToAttack())
- ai->aiAttackMoveToPosition( pos, maxShotsToFire, cmdSource );
- else
- ai->aiMoveToPosition( pos, cmdSource );
+ // the member nearest the goal defines the shape; everyone else keeps its offset from it.
+ center = *theUnit->getPosition();
+ firstUnit = false;
}
+
+ Coord3D dest;
+ computeIndividualDestination( &dest, &goalPos, theUnit, &center, FALSE );
+
+ // the speed of the slowest member is picked up by AIAttackMoveToState::onEnter, which runs
+ // inside this order - the move state resets the desired speed, so it cannot be set here.
+ if (theUnit->isAbleToAttack())
+ ai->aiAttackMoveToPosition( &dest, maxShotsToFire, cmdSource );
+ else
+ ai->aiMoveToPosition( &dest, cmdSource );
}
}
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
index 4fbe755eb..c761553c2 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
@@ -3519,6 +3519,8 @@ AIAttackMoveToState::AIAttackMoveToState( StateMachine *machine ) : AIMoveToStat
m_victimID = INVALID_ID;
m_engageStartFrame = 0;
m_frameToScanOn = 0;
+ m_reengageGoalDistSqr = 0.0f;
+ m_groupSpeed = FAST_AS_POSSIBLE;
m_isEngaging = FALSE;
m_chaseWasAllowed = FALSE;
m_attackMoveMachine = newInstance(AIAttackMoveStateMachine)(getMachineOwner(), "AIAttackMoveMachine");
@@ -3544,7 +3546,7 @@ void AIAttackMoveToState::crc( Xfer *xfer )
void AIAttackMoveToState::xfer( Xfer *xfer )
{
// version
- XferVersion currentVersion = 3;
+ XferVersion currentVersion = 4;
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
@@ -3563,6 +3565,10 @@ void AIAttackMoveToState::xfer( Xfer *xfer )
xfer->xferBool(&m_isEngaging);
xfer->xferBool(&m_chaseWasAllowed);
}
+ if (version>=4) {
+ xfer->xferReal(&m_reengageGoalDistSqr);
+ xfer->xferReal(&m_groupSpeed);
+ }
xfer->xferSnapshot(m_attackMoveMachine);
} // end xfer
@@ -3601,10 +3607,41 @@ StateReturnType AIAttackMoveToState::onEnter()
m_victimID = INVALID_ID;
m_engageStartFrame = 0;
m_engageOrigin = *owner->getPosition();
+ m_reengageGoalDistSqr = 0.0f;
// 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);
- return AIMoveToState::onEnter();
+ // An attack move arrives as a group or it arrives as a queue of single units, so the ground
+ // units go at the pace of the slowest one. The order is still running inside the AIGroup that
+ // issued it, so the group is still reachable here; it is gone by the next update.
+ m_groupSpeed = FAST_AS_POSSIBLE;
+ AIGroup *group = ai->getGroup();
+ if (group != NULL && ai->isDoingGroundMovement())
+ {
+ Real speed = group->getSpeed();
+ if (speed > 0.0f && speed < FAST_AS_POSSIBLE)
+ m_groupSpeed = speed;
+ }
+
+ StateReturnType ret = AIMoveToState::onEnter();
+ // AIInternalMoveToState::onEnter resets the desired speed, so this has to follow it.
+ applyGroupSpeed();
+ return ret;
+}
+
+//----------------------------------------------------------------------------------------------------------
+/**
+ * Hold this unit to the group's speed. Called after every (re)path, since entering the move state
+ * puts the speed back to FAST_AS_POSSIBLE.
+ */
+void AIAttackMoveToState::applyGroupSpeed( void )
+{
+ if (m_groupSpeed >= FAST_AS_POSSIBLE)
+ return;
+
+ AIUpdateInterface *ai = getMachineOwner()->getAI();
+ if (ai != NULL)
+ ai->setDesiredSpeed(m_groupSpeed);
}
//----------------------------------------------------------------------------------------------------------
@@ -3701,33 +3738,42 @@ Bool AIAttackMoveToState::hasLeftTheLeash( void )
return (dx*dx + dy*dy) > sqr(ATTACK_MOVE_LEASH_CELLS*PATHFIND_CELL_SIZE_F);
}
+//----------------------------------------------------------------------------------------------------------
+/**
+ * The leash alone does not bound a chase: it is measured from wherever the fight started, so a
+ * victim that keeps backing off is re-acquired from a leash length further along every time and
+ * walks the unit off the map one leash at a time. After a broken leash the unit therefore owes the
+ * attack move a leash length of progress toward its goal before it may pick another fight.
+ */
+void AIAttackMoveToState::requireProgressTowardGoal( void )
+{
+ Object *owner = getMachineOwner();
+ Real dx = owner->getPosition()->x - m_goalPosition.x;
+ Real dy = owner->getPosition()->y - m_goalPosition.y;
+ Real distToGoal = sqrt(dx*dx + dy*dy) - ATTACK_MOVE_LEASH_CELLS*PATHFIND_CELL_SIZE_F;
+ m_reengageGoalDistSqr = (distToGoal > 0.0f) ? sqr(distToGoal) : 0.0f;
+}
-// ---------------------------------------------------------------------------
-// TEMPORARY DIAGNOSTIC (jet reload/resume). Remove with the matching probes
-// in JetAIUpdate.cpp; every line is prefixed JETRELOAD:.
-// ---------------------------------------------------------------------------
-static void jetStateTrace(const Object *obj, const char *what, const char *detail)
+//----------------------------------------------------------------------------------------------------------
+/**
+ * True unless a broken leash left us owing the attack move some progress toward its goal.
+ */
+Bool AIAttackMoveToState::mayEngageYet( void )
{
- AIUpdateInterface *ai = ((Object *)obj)->getAI();
- if (ai == NULL || ai->getJetAIUpdate() == NULL)
- return; // only trace jets
+ if (m_reengageGoalDistSqr <= 0.0f)
+ return TRUE;
- AsciiString ammo;
- for (Int i = 0; i < WEAPONSLOT_COUNT; ++i)
- {
- const Weapon *w = obj->getWeaponInWeaponSlot((WeaponSlotType)i);
- if (w == NULL)
- continue;
- AsciiString one;
- one.format(" w%d[ammo=%d/%d status=%d max=%d]", i,
- w->getRemainingAmmo(), w->getClipSize(), (Int)w->getStatus(), w->getMaxShotCount());
- ammo.concat(one);
- }
- DEBUG_LOG(("JETRELOAD: obj %d %s %s frame=%d outOfAmmo=%d%s\n",
- (Int)obj->getID(), what, detail, (Int)TheGameLogic->getFrame(),
- (Int)((Object *)obj)->isOutOfAmmo(), ammo.str()));
+ Object *owner = getMachineOwner();
+ Real dx = owner->getPosition()->x - m_goalPosition.x;
+ Real dy = owner->getPosition()->y - m_goalPosition.y;
+ if ((dx*dx + dy*dy) > m_reengageGoalDistSqr)
+ return FALSE;
+
+ m_reengageGoalDistSqr = 0.0f; // paid up
+ return TRUE;
}
+
//----------------------------------------------------------------------------------------------------------
StateReturnType AIAttackMoveToState::update()
{
@@ -3740,8 +3786,6 @@ StateReturnType AIAttackMoveToState::update()
JetAIUpdate *jetAI = ai->getJetAIUpdate();
if( jetAI && jetAI->isOutOfSpecialReloadAmmo() )
{
- if ((TheGameLogic->getFrame() % 30) == 0)
- jetStateTrace(owner, "ATTACKMOVE-OUT-OF-RELOAD-AMMO", "(returning STATE_SUCCESS)");
//We need to return to base to reload!
return STATE_SUCCESS;
}
@@ -3755,14 +3799,15 @@ StateReturnType AIAttackMoveToState::update()
stopEngaging();
ai->friend_setLastCommandSource(m_commandSrc);
m_frameToScanOn = TheGameLogic->getFrame() + ATTACK_MOVE_REACQUIRE_DELAY;
+ requireProgressTowardGoal();
shouldRepathThisFrame = true;
}
else
{
- // we shoot standing still: the move goal is cleared every frame, and only the attack
- // machine's own approach may set a new one.
- ai->setLocomotorGoalNone();
- owner->clearModelConditionState(MODELCONDITION_MOVING);
+ // The move stopped once, in startEngaging; from here the attack machine owns the
+ // locomotor, so that its approach can close with the victim and its own arrival can stop
+ // it. (Clearing the goal and the MOVING condition every frame - as this state used to -
+ // fights the approach for the locomotor and strobes the walk animation.)
m_attackMoveMachine->updateStateMachine();
// if the machine is now idling, then we need to attempt to get a new target
@@ -3789,7 +3834,7 @@ StateReturnType AIAttackMoveToState::update()
}
UnsignedInt now = TheGameLogic->getFrame();
- if (now >= m_frameToScanOn)
+ if (now >= m_frameToScanOn && mayEngageYet())
{
m_frameToScanOn = now + ATTACK_MOVE_SCAN_RATE;
// Scan on our own clock rather than the unit's idle mood clock (seconds apart, long
@@ -3797,14 +3842,6 @@ StateReturnType AIAttackMoveToState::update()
// is already within weapon range - we stop and close with whatever we find.
ai->setNextMoodCheckTime(now);
Object* nextObjectToAttack = ai->getNextMoodTarget( true, false, true );
- if ((now % 30) == 0 || nextObjectToAttack != NULL)
- {
- AsciiString dbg;
- dbg.format("(target=%d, mood=%d)",
- nextObjectToAttack ? (Int)nextObjectToAttack->getID() : 0,
- (Int)(ai->getMoodMatrixActionAdjustment(MM_Action_Attack) & MAA_Action_Ok));
- jetStateTrace(owner, "ATTACKMOVE-PICK-TARGET", dbg.str());
- }
if (nextObjectToAttack != NULL)
{
startEngaging(nextObjectToAttack);
@@ -3820,10 +3857,11 @@ StateReturnType AIAttackMoveToState::update()
shouldRepathThisFrame = true;
}
- if (shouldRepathThisFrame)
+ if (shouldRepathThisFrame)
{
AIMoveToState::onEnter();
forceRepath();
+ applyGroupSpeed(); // re-entering the move state put the speed back to FAST_AS_POSSIBLE
}
StateReturnType ret = AIMoveToState::update();
@@ -5672,7 +5710,6 @@ StateReturnType AIAttackState::onEnter()
//from ever happening, but failed in two cases which I fixed. This is an extra check to mitigate cheats.
if( source->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ) )
{
- jetStateTrace(source, "ATTACK-ENTER-FAIL", "(under construction)");
return STATE_FAILURE;
}
@@ -5680,7 +5717,6 @@ StateReturnType AIAttackState::onEnter()
// (this can happen for units which never auto-reload, like the Raptor)
if (source->isOutOfAmmo() && !source->isKindOf(KINDOF_PROJECTILE))
{
- jetStateTrace(source, "ATTACK-ENTER-FAIL", "(isOutOfAmmo)");
return STATE_FAILURE;
}
@@ -5715,7 +5751,6 @@ StateReturnType AIAttackState::onEnter()
Bool weaponPicked = chooseWeapon();
if( !weaponPicked )
{
- jetStateTrace(source, "ATTACK-ENTER-FAIL", "(chooseWeapon failed)");
return STATE_FAILURE;
}
@@ -5731,12 +5766,6 @@ StateReturnType AIAttackState::onEnter()
m_lockedWeaponOnEnter = source->isCurWeaponLocked() ? curWeapon : NULL;
StateReturnType retType = m_attackMachine->initDefaultState();
- {
- AsciiString dbg;
- dbg.format("(initDefaultState=%d, weapon=%s)", (Int)retType,
- source->getCurrentWeapon() ? source->getCurrentWeapon()->getName().str() : "<none>");
- jetStateTrace(source, "ATTACK-ENTER", dbg.str());
- }
if( retType == STATE_CONTINUE )
{
source->setStatus( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_IS_ATTACKING ) );
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
index 7d7e7c1a1..47c0d72f1 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
@@ -4610,7 +4610,17 @@ Object* AIUpdateInterface::getNextMoodTarget( Bool calledByAI, Bool calledDuring
// Use Guard Outer, which typically corresponds to the total range
Real rangeToFindWithin = TheAI->getAdjustedVisionRangeForObject(obj, AI_VISIONFACTOR_OWNERTYPE | AI_VISIONFACTOR_MOOD);
- if (rangeToFindWithin <= 0.0f)
+ // A caller that closes with what it finds (attack move) is not limited by what the unit can see:
+ // a unit whose weapon outranges its vision - artillery, rocket infantry, a Scud launcher - found
+ // nothing at all this way and walked past everything it was ordered to kill.
+ if (allowOutOfWeaponRangeTargets)
+ {
+ Real weaponRange = obj->getLargestWeaponRange();
+ if (weaponRange > rangeToFindWithin)
+ rangeToFindWithin = weaponRange;
+ }
+
+ if (rangeToFindWithin <= 0.0f)
return NULL;
//If we are contained by an object, add it's bounding radius so that large buildings can auto acquire everything in
@@ -4647,7 +4657,14 @@ Object* AIUpdateInterface::getNextMoodTarget( Bool calledByAI, Bool calledDuring
flags |= AI::IGNORE_INSIGNIFICANT_BUILDINGS;
}
- if( d->m_autoAcquireEnemiesWhenIdle & AAS_Idle_Attack_Buildings )
+ //
+ // Idle auto-acquire ignores buildings unless the unit is one of the few with AttackBuildings in
+ // its AutoAcquireEnemiesWhenIdle, which is right for a unit standing around, and wrong for an
+ // attack move: the player pointed at the enemy base and the group walked through it without
+ // firing at a single structure. A caller that closes with what it finds takes buildings too;
+ // the CAN_ATTACK filter still rejects the ones this unit's weapons cannot hurt.
+ //
+ if( (d->m_autoAcquireEnemiesWhenIdle & AAS_Idle_Attack_Buildings) || allowOutOfWeaponRangeTargets )
{
flags |= AI::ATTACK_BUILDINGS;
}