BattleAI.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. /*
  2. * BattleAI.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "BattleAI.h"
  12. #include "BattleEvaluator.h"
  13. #include "BattleExchangeVariant.h"
  14. #include "StackWithBonuses.h"
  15. #include "EnemyInfo.h"
  16. #include "tbb/parallel_for.h"
  17. #include "../../lib/CStopWatch.h"
  18. #include "../../lib/CThreadHelper.h"
  19. #include "../../lib/mapObjects/CGTownInstance.h"
  20. #include "../../lib/spells/CSpellHandler.h"
  21. #include "../../lib/spells/ISpellMechanics.h"
  22. #include "../../lib/battle/BattleAction.h"
  23. #include "../../lib/battle/BattleStateInfoForRetreat.h"
  24. #include "../../lib/battle/CObstacleInstance.h"
  25. #include "../../lib/CStack.h" // TODO: remove
  26. // Eventually only IBattleInfoCallback and battle::Unit should be used,
  27. // CUnitState should be private and CStack should be removed completely
  28. #define LOGL(text) print(text)
  29. #define LOGFL(text, formattingEl) print(boost::str(boost::format(text) % formattingEl))
  30. CBattleAI::CBattleAI()
  31. : side(-1),
  32. wasWaitingForRealize(false),
  33. wasUnlockingGs(false)
  34. {
  35. }
  36. CBattleAI::~CBattleAI()
  37. {
  38. if(cb)
  39. {
  40. //Restore previous state of CB - it may be shared with the main AI (like VCAI)
  41. cb->waitTillRealize = wasWaitingForRealize;
  42. cb->unlockGsWhenWaiting = wasUnlockingGs;
  43. }
  44. }
  45. void CBattleAI::initBattleInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CBattleCallback> CB)
  46. {
  47. env = ENV;
  48. cb = CB;
  49. playerID = *CB->getPlayerID();
  50. wasWaitingForRealize = CB->waitTillRealize;
  51. wasUnlockingGs = CB->unlockGsWhenWaiting;
  52. CB->waitTillRealize = false;
  53. CB->unlockGsWhenWaiting = false;
  54. movesSkippedByDefense = 0;
  55. }
  56. void CBattleAI::initBattleInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CBattleCallback> CB, AutocombatPreferences autocombatPreferences)
  57. {
  58. initBattleInterface(ENV, CB);
  59. autobattlePreferences = autocombatPreferences;
  60. }
  61. BattleAction CBattleAI::useHealingTent(const BattleID & battleID, const CStack *stack)
  62. {
  63. auto healingTargets = cb->getBattle(battleID)->battleGetStacks(CBattleInfoEssentials::ONLY_MINE);
  64. std::map<int, const CStack*> woundHpToStack;
  65. for(const auto * stack : healingTargets)
  66. {
  67. if(auto woundHp = stack->getMaxHealth() - stack->getFirstHPleft())
  68. woundHpToStack[woundHp] = stack;
  69. }
  70. if(woundHpToStack.empty())
  71. return BattleAction::makeDefend(stack);
  72. else
  73. return BattleAction::makeHeal(stack, woundHpToStack.rbegin()->second); //last element of the woundHpToStack is the most wounded stack
  74. }
  75. void CBattleAI::yourTacticPhase(const BattleID & battleID, int distance)
  76. {
  77. cb->battleMakeTacticAction(battleID, BattleAction::makeEndOFTacticPhase(cb->getBattle(battleID)->battleGetTacticsSide()));
  78. }
  79. static float getStrengthRatio(std::shared_ptr<CBattleInfoCallback> cb, int side)
  80. {
  81. auto stacks = cb->battleGetAllStacks();
  82. auto our = 0;
  83. auto enemy = 0;
  84. for(auto stack : stacks)
  85. {
  86. auto creature = stack->creatureId().toCreature();
  87. if(!creature)
  88. continue;
  89. if(stack->unitSide() == side)
  90. our += stack->getCount() * creature->getAIValue();
  91. else
  92. enemy += stack->getCount() * creature->getAIValue();
  93. }
  94. return enemy == 0 ? 1.0f : static_cast<float>(our) / enemy;
  95. }
  96. void CBattleAI::activeStack(const BattleID & battleID, const CStack * stack )
  97. {
  98. LOG_TRACE_PARAMS(logAi, "stack: %s", stack->nodeName());
  99. auto timeElapsed = [](std::chrono::time_point<std::chrono::high_resolution_clock> start) -> uint64_t
  100. {
  101. auto end = std::chrono::high_resolution_clock::now();
  102. return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
  103. };
  104. BattleAction result = BattleAction::makeDefend(stack);
  105. auto start = std::chrono::high_resolution_clock::now();
  106. try
  107. {
  108. if(stack->creatureId() == CreatureID::CATAPULT)
  109. {
  110. cb->battleMakeUnitAction(battleID, useCatapult(battleID, stack));
  111. return;
  112. }
  113. if(stack->hasBonusOfType(BonusType::SIEGE_WEAPON) && stack->hasBonusOfType(BonusType::HEALER))
  114. {
  115. cb->battleMakeUnitAction(battleID, useHealingTent(battleID, stack));
  116. return;
  117. }
  118. #if BATTLE_TRACE_LEVEL>=1
  119. logAi->trace("Build evaluator and targets");
  120. #endif
  121. BattleEvaluator evaluator(env, cb, stack, playerID, battleID, side, getStrengthRatio(cb->getBattle(battleID), side));
  122. result = evaluator.selectStackAction(stack);
  123. if(autobattlePreferences.enableSpellsUsage && !skipCastUntilNextBattle && evaluator.canCastSpell())
  124. {
  125. auto spelCasted = evaluator.attemptCastingSpell(stack);
  126. if(spelCasted)
  127. return;
  128. skipCastUntilNextBattle = true;
  129. }
  130. logAi->trace("Spellcast attempt completed in %lld", timeElapsed(start));
  131. if(auto action = considerFleeingOrSurrendering(battleID))
  132. {
  133. cb->battleMakeUnitAction(battleID, *action);
  134. return;
  135. }
  136. }
  137. catch(boost::thread_interrupted &)
  138. {
  139. throw;
  140. }
  141. catch(std::exception &e)
  142. {
  143. logAi->error("Exception occurred in %s %s",__FUNCTION__, e.what());
  144. }
  145. if(result.actionType == EActionType::DEFEND)
  146. {
  147. movesSkippedByDefense++;
  148. }
  149. else if(result.actionType != EActionType::WAIT)
  150. {
  151. movesSkippedByDefense = 0;
  152. }
  153. logAi->trace("BattleAI decission made in %lld", timeElapsed(start));
  154. cb->battleMakeUnitAction(battleID, result);
  155. }
  156. BattleAction CBattleAI::useCatapult(const BattleID & battleID, const CStack * stack)
  157. {
  158. BattleAction attack;
  159. BattleHex targetHex = BattleHex::INVALID;
  160. if(cb->getBattle(battleID)->battleGetGateState() == EGateState::CLOSED)
  161. {
  162. targetHex = cb->getBattle(battleID)->wallPartToBattleHex(EWallPart::GATE);
  163. }
  164. else
  165. {
  166. std::array wallParts {
  167. EWallPart::KEEP,
  168. EWallPart::BOTTOM_TOWER,
  169. EWallPart::UPPER_TOWER,
  170. EWallPart::BELOW_GATE,
  171. EWallPart::OVER_GATE,
  172. EWallPart::BOTTOM_WALL,
  173. EWallPart::UPPER_WALL
  174. };
  175. for(auto wallPart : wallParts)
  176. {
  177. auto wallState = cb->getBattle(battleID)->battleGetWallState(wallPart);
  178. if(wallState == EWallState::REINFORCED || wallState == EWallState::INTACT || wallState == EWallState::DAMAGED)
  179. {
  180. targetHex = cb->getBattle(battleID)->wallPartToBattleHex(wallPart);
  181. break;
  182. }
  183. }
  184. }
  185. if(!targetHex.isValid())
  186. {
  187. return BattleAction::makeDefend(stack);
  188. }
  189. attack.aimToHex(targetHex);
  190. attack.actionType = EActionType::CATAPULT;
  191. attack.side = side;
  192. attack.stackNumber = stack->unitId();
  193. movesSkippedByDefense = 0;
  194. return attack;
  195. }
  196. void CBattleAI::battleStart(const BattleID & battleID, const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool Side, bool replayAllowed)
  197. {
  198. LOG_TRACE(logAi);
  199. side = Side;
  200. skipCastUntilNextBattle = false;
  201. }
  202. void CBattleAI::print(const std::string &text) const
  203. {
  204. logAi->trace("%s Battle AI[%p]: %s", playerID.toString(), this, text);
  205. }
  206. std::optional<BattleAction> CBattleAI::considerFleeingOrSurrendering(const BattleID & battleID)
  207. {
  208. BattleStateInfoForRetreat bs;
  209. bs.canFlee = cb->getBattle(battleID)->battleCanFlee();
  210. bs.canSurrender = cb->getBattle(battleID)->battleCanSurrender(playerID);
  211. bs.ourSide = cb->getBattle(battleID)->battleGetMySide();
  212. bs.ourHero = cb->getBattle(battleID)->battleGetMyHero();
  213. bs.enemyHero = nullptr;
  214. for(auto stack : cb->getBattle(battleID)->battleGetAllStacks(false))
  215. {
  216. if(stack->alive())
  217. {
  218. if(stack->unitSide() == bs.ourSide)
  219. bs.ourStacks.push_back(stack);
  220. else
  221. {
  222. bs.enemyStacks.push_back(stack);
  223. bs.enemyHero = cb->getBattle(battleID)->battleGetOwnerHero(stack);
  224. }
  225. }
  226. }
  227. bs.turnsSkippedByDefense = movesSkippedByDefense / bs.ourStacks.size();
  228. if(!bs.canFlee && !bs.canSurrender)
  229. {
  230. return std::nullopt;
  231. }
  232. auto result = cb->makeSurrenderRetreatDecision(battleID, bs);
  233. if(!result && bs.canFlee && bs.turnsSkippedByDefense > 30)
  234. {
  235. return BattleAction::makeRetreat(bs.ourSide);
  236. }
  237. return result;
  238. }