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.

feat(gameengine): ambulances clean hazards and the ai fields them

Olcay Seygan468063ff9c6a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a1dab1aca..095c3f06e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -197,6 +197,7 @@ found and fixed — EA's own, not port damage.**
- Its buildings have men in them. The computer built Bunkers and Fire Bases, put up its Palace as GLA, and left every one of them empty for the whole match. Now the soldiers guarding its base and the ones standing idle at home climb into its own buildings they can shoot out of, and on Medium and Hard it trains more for the empty seats once it has money to spare. While its base is being hit, the men at home also take any empty civilian building in the base. The soldiers gathered for an attack are never taken off it for this. Over eight Hard matches on Twilight Flame, 173 soldiers went in, each of them once, 88 of them into a Palace and the rest into Fire Bases and Bunkers, with the matches' economy and number of attacks where they were. A first version bought five Red Guards for China's first Bunker a minute into the match, and the computer's own plan, finding the bank empty, sold the whole base in two of eight matches; it now waits for spare money. Replays recorded before this change play out differently.
- Its Chinooks fly the army. A USA attack walked the whole road, at the pace of its slowest tank. Medium and Hard now buy plain Chinooks for nothing but lift, more of them the bigger the attack and the longer the road: they load tanks and soldiers at home, put them down on the attack's road short of anything the computer has seen that can shoot, and go home for the next load while the attack is under way. The drop is one a straight flight from the base reaches over quiet ground, after the first version flew seven loaded Chinooks in one match straight at a drop beyond an enemy base and lost every one. A Chinook hit hard on the way puts its load down where it is. Neither these nor the Air Force General's Combat Chinooks go on the supply runs unless nothing else is left to gather and nothing else can be bought, and the Combat Chinook is no longer ever bought as a gatherer.
- Its Helixes have jobs. Every Helix the computer owned bought its upgrades in button order, so each one carried a battle bunker whatever it was up against, with napalm on top. A Helix in one of its attack or guard groups now looks at what it knows of your army first and takes the gattling cannon when most of your strength is on foot, the bunker when most of it is in vehicles, and the soldiers trained to sit in that bunker are Tank Hunters rather than Red Guards. Against GLA over four Hard matches that came out 15 bunkers to 6 cannons, each decided on the split at that moment. China on Medium and Hard also buys two Helixes as healers, a third once its army passes thirty units, each under a Propaganda Tower. They hang behind the attack over whichever of its units is most hurt, carry nobody, and pull away when they are hit or when anti-air they know of comes near; over twelve Hard matches they spent 93% of their time out of the base further from the nearest enemy gun than it could shoot. They used to bunch up over the same tank, which got nothing out of it: a unit inside two towers heals no faster than inside one. Each healer now keeps its spot at least a tower's reach, 150, from the others', going to the most hurt unit nobody else's tower already covers, or stepping sideways behind the attack until it is clear of theirs. Two more Helixes take the napalm bomb, or the Nuke General's nuclear one, and raid your base, a factory first and otherwise whatever pays for it or powers it. A raid comes in from the side your known anti-air does not cover, looks for a new way in when a gun turns up ahead, and turns for home when it is hit below half health. Over the same twelve matches 126 raids went out, 23 dropped their bomb, five buildings fell after a drop, and 31 raiders were shot down on a raid. A raider also stops bombing once its run is over. A Helix told to bomb a spot drops another bomb under itself every ten seconds until it gets a different order, and the computer's own orders never counted as one, so a raider that had bombed your base went on dropping napalm all the way home, over your soldiers on the way, and then on its own base for the rest of the match. Over eight Hard matches against America, 104 of 121 bombs fell nowhere near the building they were meant for. On the same matches now, each of the 14 bombs dropped lands on its building, and a raid that turns back before its drop no longer flies out again to finish it once it is home. The Infantry General's Helix has no tower, so it only raids. Replays recorded before this change play out differently.
+- The USA computer fields Ambulances. It never built one before. On Medium and Hard it buys one once eight fighting units stand and a second at twenty, and keeps them a little behind the middle of its army, short of every gun of yours it knows about. A soldier of its own under half health who stands near one walks over and climbs in, and gets out again once he is whole. Toxins, anthrax and radiation on its own side of the map get driven to and washed off. Over six Hard matches against GLA on Twilight Flame it ordered 26 Ambulances, called 10 wounded men in and sent them on 19 cleanups of its own ground. They also die a lot: 24 of the 25 that rolled out were lost, and those six matches went no better for the USA than the same six without them (no win either way, 57 kills a match where it had 66). Replays recorded before this change play out differently.
- It comes at you from two sides. An attack big enough to be two sends a third of its strength down the second-quietest road, so you cannot meet the whole thing in one place.
- It holds ground between attacks. Hard gathers its next wave a third of the way along the road to you, not in front of its own base, as long as nothing it has seen can shoot at that spot; otherwise it gathers at home.
@@ -310,6 +311,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.
- 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/Data/Scenarios/ambulanceclean.txt b/GeneralsMD/Code/Data/Scenarios/ambulanceclean.txt
new file mode 100644
index 000000000..e5f628445
--- /dev/null
+++ b/GeneralsMD/Code/Data/Scenarios/ambulanceclean.txt
@@ -0,0 +1,34 @@
+# Does an Ambulance clean a toxin field near it without being told to?
+#
+# Three Ambulances on the open middle of the small generated map mobopen.txt uses, each with medium
+# poison fields (30 seconds of life, 900 frames) put down 150 to 250 from it, past the 100 its
+# cleanup weapon reaches. The north one stands idle, the middle one has a guard order on its own
+# spot, and the south one is ordered across to 1500,1800 past a field 100 off its road. The first
+# two should drive over, clean every field, and come back (the middle one on guard again); the
+# third should arrive without stopping and leave its field alone. The tallies at 120 and 600 count
+# the fields left, the second well before any could have run out on its own. The log's CLEANUP
+# lines say who went and when its area was clean.
+#
+# generals.exe -headless -quickstart -noshellmap -observer -multiInstance -noFPSLimit
+# -randommap 1 2 small -autoskirmish 2 -takeover
+# -side 0 FactionAmerica -side 1 FactionGLA -seed 1 -maxframes 900
+# -scenario ambulanceclean -logPrefix ambulanceclean_
+#
+# See mobstress.txt for the line grammar.
+
+30 spawn 0 AmericaVehicleMedic 1 700 500
+30 spawn 0 AirF_AmericaVehicleMedic 1 700 1200
+30 spawn 0 SupW_AmericaVehicleMedic 1 700 1800
+
+60 shiftguard 0 AirF_AmericaVehicleMedic 700 1200
+
+90 spawn 1 PoisonFieldMedium 1 900 500
+90 spawn 1 PoisonFieldMedium 1 850 650
+90 spawn 1 PoisonFieldMedium 1 920 1250
+90 spawn 1 PoisonFieldMedium 1 1000 1900
+
+90 move 0 SupW_AmericaVehicleMedic 1500 1800
+91 arrive 0 SupW_AmericaVehicleMedic 1500 1800 80
+
+120 tally 1 PoisonFieldMedium
+600 tally 1 PoisonFieldMedium
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
index 27e8ab015..f5786b2b3 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
@@ -369,6 +369,8 @@ protected:
void buyDutyHelix(void); ///< Medium and up buy the healers and raiders their Helixes' buttons allow
Int helixRoleWanted(const ThingTemplate *tmpl) const; ///< the job a Helix of this kind would take now, -1 for none
void takeDutyHelix(Object *helix); ///< a Helix buyDutyHelix ordered comes out and takes its job
+ void doAmbulances(void); ///< the USA's Ambulances: bought once there is an army, kept behind it, taking in the hurt and cleaning our side
+ void steerAmbulance(Int slot, const std::vector<AIKnownGun> &guns); ///< one Ambulance's job this pass
void upgradeHelix(Object *helix, Int role, AIEnemyComposition *enemy, Bool *enemyRead); ///< the upgrade this Helix's job or the enemy army calls for
void collectKnownGuns(std::vector<AIKnownGun> *guns) const; ///< every enemy gun this AI knows of, in object list order
void steerHealer(Int slot, const std::vector<AIKnownGun> &guns); ///< a healer over our hurt behind the line, clear of every known gun
@@ -439,6 +441,7 @@ public:
Bool isTransportChinook( const Object *obj ) const; ///< a plain Chinook this AI bought to fly its wave, not to gather
Bool isDutyChinook( const Object *obj ) const; ///< either of those, which the gatherer counts leave out
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
protected:
/**
@@ -523,6 +526,14 @@ protected:
};
enum { MAX_DUTY_HELIXES = 5 };
DutyHelix m_dutyHelix[ MAX_DUTY_HELIXES ];
+ /// An Ambulance bought to follow the army: the hurt infantry climb in, and it cleans hazards on our side
+ struct DutyAmbulance
+ {
+ ObjectID id; ///< INVALID_ID for a free slot
+ Coord3D spot; ///< where it was last sent
+ };
+ enum { MAX_DUTY_AMBULANCES = 2 };
+ DutyAmbulance m_ambulance[ MAX_DUTY_AMBULANCES ];
Int m_healerSeconds; ///< for the log only, not saved: healer seconds counted, and those clear of the nearest gun's reach
Int m_healerClearSeconds;
Int m_captureTimer; ///< frames until the next look for something to capture
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CleanupHazardUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CleanupHazardUpdate.h
index 9f7f4381e..59684c8df 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CleanupHazardUpdate.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CleanupHazardUpdate.h
@@ -78,9 +78,13 @@ public:
void fireWhenReady();
void setCleanupAreaParameters( const Coord3D *pos, Real range ); //This allows the unit to cleanup an area until clean, then the AI goes idle.
+ Bool isCleaningArea() const { return m_moveRange > 0.0f; } ///< out cleaning an area, the cleanup ability's or one it noticed by itself
protected:
+ void startAutoCleanup(); ///< idle or on guard with a hazard near: clean it, then come back
+ void finishArea( const char *why, Bool goHome ); ///< the area is done with: back on guard, home, or idle
+
ObjectID m_bestTargetID;
Bool m_inRange;
Int m_nextScanFrames;
@@ -90,6 +94,12 @@ protected:
//Cleanup area (temporary values).
Coord3D m_pos;
Real m_moveRange;
+
+ //A cleanup it started by itself took the unit off guard: it guards m_pos again when the area is clean.
+ Bool m_resumeGuard;
+ 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
};
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
index a006ed051..5162eeb6a 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
@@ -81,6 +81,7 @@
#include "GameLogic/Module/OpenContain.h" // a seat's own shoot-out flag, asked before a rider exists
#include "GameLogic/Module/TransportContain.h" // ... and a template's hold, before one exists
#include "GameLogic/Module/JetAIUpdate.h" // a Comanche is a jet with no runway
+#include "GameLogic/Module/CleanupHazardUpdate.h" // an Ambulance out cleaning is left to it
#include <map>
#include "Platform/MsvcFloatCasts.h"
@@ -373,6 +374,11 @@ m_role(AIROLE_AGGRESSIVE)
m_dutyHelix[ helix ].spot.zero();
m_dutyHelix[ helix ].targetHealth = 0.0f;
}
+ for( Int slot = 0; slot < MAX_DUTY_AMBULANCES; ++slot )
+ {
+ m_ambulance[ slot ].id = INVALID_ID;
+ m_ambulance[ slot ].spot.zero();
+ }
m_healerSeconds = 0;
m_healerClearSeconds = 0;
m_captureTimer = 1;
@@ -646,6 +652,7 @@ static Bool hasSuppliesNear( Player *player, const Object *supplyCenter, Real re
}
static const TransportContainModuleData *transportContainOf( const ThingTemplate *tmpl );
+static Bool isAmbulanceTemplate( const ThingTemplate *tmpl );
static Bool passengersFireFrom( const ThingTemplate *tmpl );
static Bool isHelicopter( const Object *obj );
@@ -1793,6 +1800,18 @@ void AIPlayer::onUnitProduced( Object *factory, Object *unit )
// a Helix buyDutyHelix ordered; a team's Helix comes out of a team order, not a support one
if (order->m_isScout && isHelicopter(unit))
takeDutyHelix(unit);
+ // ... and an Ambulance doAmbulances ordered
+ if (order->m_isScout && isAmbulanceTemplate(unit->getTemplate())) {
+ for (Int slot = 0; slot < MAX_DUTY_AMBULANCES; ++slot) {
+ if (m_ambulance[slot].id == INVALID_ID) {
+ m_ambulance[slot].id = unit->getID();
+ m_ambulance[slot].spot = *unit->getPosition();
+ DEBUG_LOG(("AI AMBULANCE frame %d player %d '%s' %d comes out\n", TheGameLogic->getFrame(),
+ m_player->getPlayerIndex(), unit->getTemplate()->getName().str(), unit->getID()));
+ break;
+ }
+ }
+ }
found = true;
break;
}
@@ -4777,6 +4796,7 @@ void AIPlayer::update( void )
AI_PHASE( AIP_TACTICS, doTransports() ); // Put the helicopters' riders down at the fight.
AI_PHASE( AIP_TACTICS, doShuttles() ); // Fly the wave's ground units up its road.
AI_PHASE( AIP_TACTICS, doHelixes() ); // Helix upgrades by the enemy army, healers, bomb raids.
+ AI_PHASE( AIP_TACTICS, doAmbulances() ); // Ambulances behind the army, for the hurt and the hazards.
#ifdef DEBUG_LOGGING
Int64 playerEnd;
@@ -7613,7 +7633,7 @@ Bool AIPlayer::leavesToFinish( const Object *obj ) const
for( Int slot = 0; slot < MAX_AI_SCOUTS; ++slot )
if( m_scoutID[ slot ] == id )
return FALSE;
- return id != m_capturerID && id != m_ferryID && id != m_hijackerID && !isDutyHelix( obj );
+ return id != m_capturerID && id != m_ferryID && id != m_hijackerID && !isDutyHelix( obj ) && !isDutyAmbulance( obj );
}
//----------------------------------------------------------------------------------------------------------
@@ -10011,6 +10031,248 @@ void AIPlayer::doHelixes( void )
now, m_player->getPlayerIndex(), healers, m_healerClearSeconds, m_healerSeconds));
}
+//----------------------------------------------------------------------------------------------------------
+/** The USA's Ambulance carries three infantry, heals them a quarter of their health a second, and
+ * cleans toxins, anthrax and radiation off the ground. The computer never built one. Medium and up
+ * now buy one once AMBULANCE_FIRST_ARMY fighting units stand and a second at AMBULANCE_SECOND_ARMY,
+ * through the support-unit queue. An Ambulance waits
+ * AMBULANCE_BEHIND back from the middle of whoever is out, toward home and clear of every known gun,
+ * or at home with nobody out. The cash hoard does not hold it back, since a USA at war banks under
+ * the hoard all match. Our infantry within AMBULANCE_CALL_REACH of it and under half health
+ * walk over and climb in, and it lets them out once they are whole. It drives to the nearest hazard
+ * on our side of the map that no known gun covers; one beside it it notices by itself
+ * (CleanupHazardUpdate::startAutoCleanup). Split out with plain values so the rules are testable
+ * without a running game. */
+//----------------------------------------------------------------------------------------------------------
+static const Int AMBULANCE_CHECK_RATE = LOGICFRAMES_PER_SECOND;
+static const Int AMBULANCE_FIRST_ARMY = 8;
+static const Int AMBULANCE_SECOND_ARMY = 20;
+static const Real AMBULANCE_PATIENT_HEALTH = 0.5f;
+static const Real AMBULANCE_CALL_REACH = 450.0f;
+static const Real AMBULANCE_BEHIND = 150.0f;
+static const Real AMBULANCE_HAZARD_REACH = 1500.0f;
+/** The cleanup ability's MaxMoveDistanceFromLocation in retail AmericaVehicle.ini. */
+static const Real AMBULANCE_CLEANUP_RANGE = 300.0f;
+static const Real AMBULANCE_REORDER_DISTANCE = 100.0f;
+
+Int AIAmbulance_wanted( Int army )
+{
+ if( army >= AMBULANCE_SECOND_ARMY )
+ return 2;
+ return army >= AMBULANCE_FIRST_ARMY ? 1 : 0;
+}
+
+Bool AIAmbulance_callsPatient( Real healthFraction, Real distance )
+{
+ return healthFraction < AMBULANCE_PATIENT_HEALTH && distance <= AMBULANCE_CALL_REACH;
+}
+
+/** A vehicle with a hold that cleans hazards: the Ambulance, and each general's copy of it. */
+static Bool isAmbulanceTemplate( const ThingTemplate *tmpl )
+{
+ if( !tmpl->isKindOf( KINDOF_VEHICLE ) || transportContainOf( tmpl ) == NULL )
+ return FALSE;
+ const ModuleInfo &modules = tmpl->getBehaviorModuleInfo();
+ for( Int m = 0; m < modules.getCount(); ++m )
+ if( modules.getNthName( m ).compare( "CleanupHazardUpdate" ) == 0 )
+ return TRUE;
+ return FALSE;
+}
+
+Bool AIPlayer::isDutyAmbulance( const Object *obj ) const
+{
+ for( Int slot = 0; slot < MAX_DUTY_AMBULANCES; ++slot )
+ if( m_ambulance[ slot ].id == obj->getID() )
+ return TRUE;
+ return FALSE;
+}
+
+void AIPlayer::doAmbulances( void )
+{
+ if( !isSkirmishAI() || !m_baseCenterSet || m_skillLevel == AISKILL_EASY || measuringWithoutTactics() )
+ return;
+ if( (TheGameLogic->getFrame() + computeUpdatePhase( m_player->getPlayerIndex(), AMBULANCE_CHECK_RATE )) % AMBULANCE_CHECK_RATE != 0 )
+ return;
+ Int owned = 0;
+ for( Int slot = 0; slot < MAX_DUTY_AMBULANCES; ++slot )
+ {
+ DutyAmbulance &duty = m_ambulance[ slot ];
+ if( duty.id == INVALID_ID )
+ continue;
+ const Object *ambulance = TheGameLogic->findObjectByID( duty.id );
+ if( ambulance && !ambulance->isEffectivelyDead() && ambulance->getControllingPlayer() == m_player )
+ {
+ ++owned;
+ continue;
+ }
+ DEBUG_LOG(("AI AMBULANCE frame %d player %d loses %d\n", TheGameLogic->getFrame(), m_player->getPlayerIndex(), duty.id));
+ duty.id = INVALID_ID;
+ }
+
+ const Int wanted = AIAmbulance_wanted( tallyBase( m_player ).army );
+ // no cash hoard to clear: an Ambulance is 600, and a USA at war banks under the hoard all match long.
+ // queueSupportUnit still waits for twice its price
+ if( owned < wanted && !isBaseUnderAttack() && !scoutInQueue() )
+ {
+ std::vector<Object *> factories;
+ m_player->iterateObjects( collectFactories, &factories );
+ Bool ordered = FALSE;
+ for( size_t f = 0; f < factories.size() && !ordered; ++f )
+ {
+ const CommandSet *commandSet = TheControlBar->findCommandSet( factories[ f ]->getCommandSetString() );
+ if( commandSet == NULL )
+ continue;
+ for( Int i = 0; i < MAX_COMMANDS_PER_SET && !ordered; ++i )
+ {
+ const CommandButton *button = commandSet->getCommandButton( i );
+ if( button == NULL || button->getCommandType() != GUI_COMMAND_UNIT_BUILD || button->getThingTemplate() == NULL ||
+ !isAmbulanceTemplate( button->getThingTemplate() ) || TheBuildAssistant->canMakeUnit( factories[ f ], button->getThingTemplate() ) != CANMAKE_OK )
+ continue;
+ queueSupportUnit( button->getThingTemplate(), "AMBULANCE" );
+ ordered = TRUE;
+ if( scoutInQueue() )
+ DEBUG_LOG(("AI AMBULANCE frame %d player %d orders '%s', %d owned of %d wanted, %d in the bank\n", TheGameLogic->getFrame(),
+ m_player->getPlayerIndex(), button->getThingTemplate()->getName().str(), owned, wanted, m_player->getMoney()->countMoney()));
+ }
+ }
+ }
+
+ std::vector<AIKnownGun> guns;
+ Bool gunsRead = FALSE;
+ for( Int slot = 0; slot < MAX_DUTY_AMBULANCES; ++slot )
+ {
+ if( m_ambulance[ slot ].id == INVALID_ID )
+ continue;
+ if( !gunsRead )
+ {
+ collectKnownGuns( &guns );
+ gunsRead = TRUE;
+ }
+ steerAmbulance( slot, guns );
+ }
+}
+
+void AIPlayer::steerAmbulance( Int slot, const std::vector<AIKnownGun> &guns )
+{
+ DutyAmbulance &duty = m_ambulance[ slot ];
+ Object *ambulance = TheGameLogic->findObjectByID( duty.id );
+ static NameKeyType key_CleanupHazardUpdate = NAMEKEY( "CleanupHazardUpdate" );
+ CleanupHazardUpdate *cleaner = (CleanupHazardUpdate *)ambulance->findUpdateModule( key_CleanupHazardUpdate );
+ if( ambulance->isContained() )
+ return;
+ AIUpdateInterface *ai = ambulance->getAI();
+ ContainModuleInterface *hold = ambulance->getContain();
+ const Coord3D *pos = ambulance->getPosition();
+ const UnsignedInt now = TheGameLogic->getFrame();
+
+ // whole again: out they get
+ if( hold->getContainCount() > 0 )
+ {
+ Bool whole = TRUE;
+ const ContainedItemsList *riders = hold->getContainedItemsList();
+ for( ContainedItemsList::const_iterator r = riders->begin(); r != riders->end(); ++r )
+ if( (*r)->getBodyModule()->getHealth() < (*r)->getBodyModule()->getMaxHealth() )
+ whole = FALSE;
+ if( whole )
+ {
+ DEBUG_LOG(("AI AMBULANCE frame %d player %d '%s' %d lets %d out whole at (%.0f,%.0f)\n", now, m_player->getPlayerIndex(),
+ ambulance->getTemplate()->getName().str(), duty.id, (Int)hold->getContainCount(), pos->x, pos->y));
+ ai->aiEvacuate( FALSE, CMD_FROM_AI );
+ return;
+ }
+ }
+ if( cleaner->isCleaningArea() )
+ return; // its own module drives it until the ground is clean and brings it back
+
+ // the hurt nearby climb in, while there is room, and the middle of whoever is out
+ BoardingSearch boarding;
+ boarding.transport = ambulance;
+ boarding.found = FALSE;
+ m_player->iterateObjects( findBoarder, &boarding );
+ Int room = hold->getContainMax() - (Int)hold->getContainCount() - hold->getExtraSlotsInUse();
+ Int called = 0;
+ std::vector<Object *> owned;
+ m_player->iterateObjects( collectOwned, &owned );
+ Coord3D middle;
+ middle.zero();
+ Int out = 0;
+ for( size_t o = 0; o < owned.size(); ++o )
+ {
+ Object *obj = owned[ o ];
+ if( obj->isEffectivelyDead() || obj->isContained() || obj->getAI() == NULL || obj->isKindOf( KINDOF_STRUCTURE ) ||
+ obj->isKindOf( KINDOF_AIRCRAFT ) || isDutyAmbulance( obj ) )
+ continue;
+ if( (obj->isKindOf( KINDOF_INFANTRY ) || obj->isKindOf( KINDOF_VEHICLE )) && aiCombatPower( obj ) > 0.0f && !isAtHome( obj->getPosition() ) )
+ {
+ middle.x += obj->getPosition()->x;
+ middle.y += obj->getPosition()->y;
+ ++out;
+ }
+ if( room <= 0 || !obj->isKindOf( KINDOF_INFANTRY ) )
+ continue;
+ const StateID state = obj->getAI()->getCurrentStateID();
+ const BodyModuleInterface *body = obj->getBodyModule();
+ const Real distance = (Real)sqrt( sqr( obj->getPosition()->x - pos->x ) + sqr( obj->getPosition()->y - pos->y ) );
+ if( state == AI_ENTER || state == AI_DOCK || state >= 1000 || !hold->isValidContainerFor( obj, TRUE ) ||
+ !AIAmbulance_callsPatient( body->getHealth() / body->getMaxHealth(), distance ) )
+ continue;
+ leaveTacticsAlone( obj->getID() );
+ obj->getAI()->aiEnter( ambulance, CMD_FROM_AI );
+ --room;
+ ++called;
+ DEBUG_LOG(("AI AMBULANCE frame %d player %d '%s' %d calls in '%s' %d at %.0f%% health, %.0f away\n", now, m_player->getPlayerIndex(),
+ ambulance->getTemplate()->getName().str(), duty.id, obj->getTemplate()->getName().str(), obj->getID(),
+ body->getHealth() * 100.0f / body->getMaxHealth(), distance));
+ }
+ if( called > 0 || boarding.found )
+ return; // no new spot while they walk over
+
+ // the nearest hazard, if it is on our side and out of every known gun's reach
+ PartitionFilterAcceptByKindOf kindFilter( MAKE_KINDOF_MASK( KINDOF_CLEANUP_HAZARD ), KINDOFMASK_NONE );
+ PartitionFilterSameMapStatus filterMapStatus( ambulance );
+ PartitionFilter *filters[] = { &kindFilter, &filterMapStatus, NULL };
+ Object *hazard = ThePartitionManager->getClosestObject( pos, AMBULANCE_HAZARD_REACH, FROM_CENTER_2D, filters );
+ if( hazard && isOurSideOfMap( hazard->getPosition() ) && deepestReach( guns, hazard->getPosition()->x, hazard->getPosition()->y, FALSE ) < 0.0f )
+ {
+ DEBUG_LOG(("AI AMBULANCE frame %d player %d '%s' %d goes to clean '%s' %d at (%.0f,%.0f), %.0f away\n", now, m_player->getPlayerIndex(),
+ ambulance->getTemplate()->getName().str(), duty.id, hazard->getTemplate()->getName().str(), hazard->getID(),
+ hazard->getPosition()->x, hazard->getPosition()->y,
+ (Real)sqrt( sqr( hazard->getPosition()->x - pos->x ) + sqr( hazard->getPosition()->y - pos->y ) )));
+ cleaner->setCleanupAreaParameters( hazard->getPosition(), AMBULANCE_CLEANUP_RANGE );
+ duty.spot = *hazard->getPosition();
+ return;
+ }
+
+ // behind whoever is out, or home
+ Coord3D spot = m_baseCenter;
+ if( out > 0 )
+ {
+ middle.x /= out;
+ middle.y /= out;
+ const Real dx = m_baseCenter.x - middle.x;
+ const Real dy = m_baseCenter.y - middle.y;
+ const Real length = (Real)sqrt( dx * dx + dy * dy );
+ if( length > AMBULANCE_BEHIND )
+ {
+ middle.x += dx * AMBULANCE_BEHIND / length;
+ middle.y += dy * AMBULANCE_BEHIND / length;
+ spot = rearOf( &middle, guns );
+ }
+ }
+ else if( isAtHome( pos ) )
+ spot = *pos;
+ spot.z = TheTerrainLogic->getGroundHeight( spot.x, spot.y );
+ const Bool moved = sqr( spot.x - duty.spot.x ) + sqr( spot.y - duty.spot.y ) > sqr( AMBULANCE_REORDER_DISTANCE );
+ const Bool away = sqr( spot.x - pos->x ) + sqr( spot.y - pos->y ) > sqr( AMBULANCE_REORDER_DISTANCE );
+ if( !moved && !(ai->isIdle() && away) )
+ return;
+ if( moved )
+ DEBUG_LOG(("AI AMBULANCE frame %d player %d '%s' %d waits at (%.0f,%.0f), %d units out\n", now, m_player->getPlayerIndex(),
+ ambulance->getTemplate()->getName().str(), duty.id, spot.x, spot.y, out));
+ ai->aiMoveToPosition( &spot, CMD_FROM_AI );
+ duty.spot = spot;
+}
+
//----------------------------------------------------------------------------------------------------------
/** How far around a fight to look for what is in it. Wide enough to catch the base defences and
* the second rank shooting into it, not so wide that a skirmish at the front counts the garrison
@@ -11000,7 +11262,7 @@ void AIPlayer::tacticsFor( Object *obj )
const TeamTemplateInfo *info = team->getPrototype()->getTemplateInfo();
if( info && (info->m_isBaseDefense || info->m_isPerimeterDefense) )
return;
- if( obj->getID() == m_capturerID || obj->getID() == m_hijackerID || isDutyHelix( obj ) )
+ if( obj->getID() == m_capturerID || obj->getID() == m_hijackerID || isDutyHelix( obj ) || isDutyAmbulance( obj ) )
return;
for( Int i = 0; i < MAX_AI_SCOUTS; ++i )
{
@@ -11349,7 +11611,7 @@ Object *AIPlayer::findScout( void )
continue;
if( obj->getAI() == NULL )
continue;
- if( obj->getID() == m_capturerID || obj->getID() == m_hijackerID )
+ if( obj->getID() == m_capturerID || obj->getID() == m_hijackerID || isDutyAmbulance( obj ) )
continue; // it has a job; two owners giving one unit orders is how both jobs stall
Bool alreadyScouting = FALSE;
@@ -12675,7 +12937,7 @@ void AIPlayer::xfer( Xfer *xfer )
{
// version
- XferVersion currentVersion = 18; // 2: scout 3: rung and role 4: scouting stamps 5: the capturer 6: parked waves 7: superweapon aims 8: the hijacker 9: tactical steps 10: the ferry and dropped riders 11: the outward placement ring 12: the pressure level 13: falling back 14: gunship Chinooks and the boarding wait 15: transport Chinooks and the lent one 16: healer and raider Helixes 17: the seen-enemy ledger 18: the fist
+ XferVersion currentVersion = 19; // 2: scout 3: rung and role 4: scouting stamps 5: the capturer 6: parked waves 7: superweapon aims 8: the hijacker 9: tactical steps 10: the ferry and dropped riders 11: the outward placement ring 12: the pressure level 13: falling back 14: gunship Chinooks and the boarding wait 15: transport Chinooks and the lent one 16: healer and raider Helixes 17: the seen-enemy ledger 18: the fist 19: the Ambulances
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
@@ -13047,6 +13309,14 @@ void AIPlayer::xfer( Xfer *xfer )
for( UnsignedShort i = 0; i < held; ++i )
xfer->xferObjectID( &m_massUnits[ i ] );
}
+ if( version >= 19 )
+ {
+ for( Int slot = 0; slot < MAX_DUTY_AMBULANCES; ++slot )
+ {
+ xfer->xferObjectID( &m_ambulance[ slot ].id );
+ xfer->xferCoord3D( &m_ambulance[ slot ].spot );
+ }
+ }
// the ladder rung and the role, which are rolled once and must come back the same way
if( version >= 3 )
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/CleanupHazardUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/CleanupHazardUpdate.cpp
index 5adef4fd5..dcaba0ef1 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/CleanupHazardUpdate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/CleanupHazardUpdate.cpp
@@ -34,6 +34,7 @@
#define DEFINE_WEAPONSLOTTYPE_NAMES
+#include "Common/Player.h"
#include "Common/RandomValue.h"
#include "Common/ThingTemplate.h"
#include "Common/Xfer.h"
@@ -54,6 +55,9 @@
//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes")
#endif
+/** 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;
+
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
CleanupHazardUpdateModuleData::CleanupHazardUpdateModuleData()
@@ -88,6 +92,10 @@ CleanupHazardUpdate::CleanupHazardUpdate( Thing *thing, const ModuleData* module
m_weaponTemplate = NULL;
m_moveRange = 0.0f;
m_pos.zero();
+ m_resumeGuard = FALSE;
+ m_resumeGuardMode = GUARDMODE_NORMAL;
+ m_returning = FALSE;
+ m_approaches = 0;
}
@@ -152,6 +160,9 @@ UpdateSleepTime CleanupHazardUpdate::update()
{
//Either the player or a script gave a NEW order so abandon the cleanup area cause.
m_moveRange = 0.0f;
+ m_resumeGuard = FALSE;
+ m_returning = FALSE;
+ m_approaches = 0;
return UPDATE_SLEEP_NONE;
}
}
@@ -166,9 +177,32 @@ UpdateSleepTime CleanupHazardUpdate::update()
}
m_nextScanFrames = data->m_scanFrames;
+ if( m_moveRange == 0.0f )
+ startAutoCleanup();
+
//Periodic scanning (expensive)
- if( scanClosestTarget() )
+ Object *found = scanClosestTarget();
+ if( found )
{
+ 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
+ AIUpdateInterface *ai = obj->getAI();
+ WeaponBonus bonus;
+ bonus.clear();
+ if( m_moveRange > 0.0f && ai && (ai->isIdle() || ai->isBusy()) &&
+ ThePartitionManager->getDistanceSquared( obj, found, FROM_CENTER_2D ) > sqr( m_weaponTemplate->getAttackRange( bonus ) ) )
+ {
+ if( ++m_approaches > MAX_CLEANUP_APPROACHES )
+ {
+ finishArea( "gave up on a hazard it cannot reach", TRUE );
+ return UPDATE_SLEEP_NONE;
+ }
+ }
+ else
+ m_approaches = 0;
//1 frame can make a big difference so fire ASAP!
fireWhenReady();
}
@@ -180,15 +214,18 @@ UpdateSleepTime CleanupHazardUpdate::update()
if( ai && (ai->isIdle() || ai->isBusy()) )
{
Real fDist = sqrt( ThePartitionManager->getDistanceSquared( obj, &m_pos, FROM_CENTER_2D ) );
- if( fDist < 25.0f )
+ // the walk back counts as done once it has stopped: a unit parked on the spot used to send it
+ // back there every second for good
+ if( fDist < 25.0f || m_returning )
{
//Abort clean area because there's nothing left to clean!
- m_moveRange = 0.0f;
+ finishArea( "area clean", FALSE );
}
else
{
//Abort clean area AFTER we move back to our initial position!
ai->aiMoveToPosition( &m_pos, CMD_FROM_AI );
+ m_returning = TRUE;
}
}
}
@@ -254,7 +291,19 @@ void CleanupHazardUpdate::fireWhenReady()
AIUpdateInterface *ai = self->getAI();
if( ai )
{
- if( ai->isIdle() || ai->isBusy() )
+ WeaponBonus bonus;
+ bonus.clear();
+ if( (ai->isIdle() || ai->isBusy()) && m_moveRange > 0.0f &&
+ ThePartitionManager->getDistanceSquared( self, target, FROM_CENTER_2D ) > sqr( m_weaponTemplate->getAttackRange( bonus ) ) )
+ {
+ // cleaning an area, with the hazard out of reach: drive up to it first, since the attack's own
+ // approach never moved the unit and it stood shooting at nothing until the area was given up.
+ // Out of the busy state first: an AI move given to a busy unit is only a temporary state laid
+ // over it, ordered again every frame, and the unit crept at a step a frame
+ ai->aiIdle( CMD_FROM_AI );
+ ai->aiMoveToPosition( target->getPosition(), CMD_FROM_AI );
+ }
+ else if( ai->isIdle() || ai->isBusy() )
{
// lock it just till the weapon is empty or the attack is "done"
self->setWeaponLock( data->m_weaponSlot, LOCKED_TEMPORARILY );
@@ -295,6 +344,71 @@ Object* CleanupHazardUpdate::scanClosestTarget()
return bestTargetInRange;
}
+//-------------------------------------------------------------------------------------------------
+/** The area is done with: back on guard if a cleanup it started took it off guard, otherwise out of
+ the busy state the area kept it in, which has no way out of its own. Left busy, it never read as
+ idle again, so scripts waiting on it stalled and it never noticed another hazard. goHome walks it
+ back to where the area started, for an area given up away from there. */
+void CleanupHazardUpdate::finishArea( const char *why, Bool goHome )
+{
+ Object *obj = getObject();
+ AIUpdateInterface *ai = obj->getAI();
+ DEBUG_LOG(("CLEANUP frame %d '%s' %d %s%s\n", TheGameLogic->getFrame(), obj->getTemplate()->getName().str(), obj->getID(),
+ why, m_resumeGuard ? ", back on guard" : ""));
+ m_moveRange = 0.0f;
+ m_returning = FALSE;
+ m_approaches = 0;
+ if( m_resumeGuard )
+ {
+ m_resumeGuard = FALSE;
+ ai->aiGuardPosition( &m_pos, (GuardMode)m_resumeGuardMode, CMD_FROM_AI );
+ }
+ else if( goHome )
+ ai->aiMoveToPosition( &m_pos, CMD_FROM_AI );
+ else
+ ai->aiIdle( CMD_FROM_AI );
+}
+
+//-------------------------------------------------------------------------------------------------
+/** How far past its own scan range a cleaner standing idle or on guard goes for a hazard by itself.
+ The scan range is the weapon's reach, so before this an Ambulance cleaned only what it was parked
+ on and watched a toxin field a truck's length away. With the Ambulance's 100 it notices up to 300,
+ the reach its cleanup ability is given around the point it is sent to. */
+static const Real AUTO_CLEANUP_MOVE_RANGE = 200.0f;
+
+/** Idle, or on a guard order, with a hazard in reach: clean the area round where it stands the way the
+ cleanup ability does, which brings it back here when nothing is left, and guard here again if it
+ was guarding. Any other order, the player's or a script's, is left alone, and one given while it is
+ cleaning ends the cleanup as it ends the ability's. */
+void CleanupHazardUpdate::startAutoCleanup()
+{
+ const CleanupHazardUpdateModuleData *data = getCleanupHazardUpdateModuleData();
+ Object *obj = getObject();
+ AIUpdateInterface *ai = obj->getAI();
+ if( !ai || obj->isContained() )
+ return;
+ const Bool guarding = ai->getCurrentStateID() == AI_GUARD;
+ if( !guarding && !ai->isIdle() )
+ return;
+
+ PartitionFilterAcceptByKindOf kindFilter(MAKE_KINDOF_MASK(KINDOF_CLEANUP_HAZARD), KINDOFMASK_NONE);
+ PartitionFilterSameMapStatus filterMapStatus(obj);
+ PartitionFilter* filters[] = { &kindFilter, &filterMapStatus, 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
+ m_resumeGuard = guarding;
+ m_resumeGuardMode = ai->getGuardMode();
+ 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,
+ m_pos.x, m_pos.y, guarding ? ", off guard" : ""));
+}
+
//-------------------------------------------------------------------------------------------------
//This allows the unit to cleanup an area until clean, then the AI goes idle.
//-------------------------------------------------------------------------------------------------
@@ -307,6 +421,9 @@ void CleanupHazardUpdate::setCleanupAreaParameters( const Coord3D *pos, Real ran
//from the specified position.
m_moveRange = range;
m_pos = *pos;
+ m_resumeGuard = FALSE;
+ m_returning = FALSE;
+ m_approaches = 0;
if( ai )
{
@@ -331,13 +448,14 @@ void CleanupHazardUpdate::crc( Xfer *xfer )
// ------------------------------------------------------------------------------------------------
/** Xfer method
* Version Info:
- * 1: Initial version */
+ * 1: Initial version
+ * 2: the guard a cleanup it started by itself gives back, the walk back, the drives toward a hazard */
// ------------------------------------------------------------------------------------------------
void CleanupHazardUpdate::xfer( Xfer *xfer )
{
// version
- XferVersion currentVersion = 1;
+ XferVersion currentVersion = 2;
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
@@ -365,6 +483,14 @@ void CleanupHazardUpdate::xfer( Xfer *xfer )
// move range
xfer->xferReal( &m_moveRange );
+ if( version >= 2 )
+ {
+ xfer->xferBool( &m_resumeGuard );
+ xfer->xferInt( &m_resumeGuardMode );
+ xfer->xferBool( &m_returning );
+ xfer->xferInt( &m_approaches );
+ }
+
} // end xfer
// ------------------------------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 3ac247566..9bb5373e7 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -11233,6 +11233,29 @@ TEST(the_ai_pulls_ranked_units_out_sooner_the_higher_the_rank)
}
+/** AIPlayer.cpp: the computer buys its first Ambulance once it has an army and a second once the army
+ is big, and calls in the badly hurt from near it only. */
+extern Int AIAmbulance_wanted( Int army );
+extern Bool AIAmbulance_callsPatient( Real healthFraction, Real distance );
+
+TEST(the_ai_buys_ambulances_by_army_and_calls_in_the_hurt_nearby)
+{
+ CHECK_EQ( 0, AIAmbulance_wanted( 0 ) );
+ CHECK_EQ( 0, AIAmbulance_wanted( 7 ) );
+ CHECK_EQ( 1, AIAmbulance_wanted( 8 ) );
+ CHECK_EQ( 1, AIAmbulance_wanted( 19 ) );
+ CHECK_EQ( 2, AIAmbulance_wanted( 20 ) );
+ CHECK_EQ( 2, AIAmbulance_wanted( 200 ) );
+
+ CHECK( AIAmbulance_callsPatient( 0.3f, 100.0f ) );
+ CHECK( AIAmbulance_callsPatient( 0.49f, 450.0f ) );
+ // half health or more stays in the fight
+ CHECK( !AIAmbulance_callsPatient( 0.5f, 100.0f ) );
+ // too far off to walk over
+ CHECK( !AIAmbulance_callsPatient( 0.1f, 451.0f ) );
+}
+
+
/** AI.cpp: a team that loses a fight stops at the first ground on its way home that none of the
fight'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)