BattleAI.cpp 7.9 KB

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