BattleAI.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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 <vstd/RNG.h>
  13. #include "StackWithBonuses.h"
  14. #include "EnemyInfo.h"
  15. #include "PossibleSpellcast.h"
  16. #include "../../lib/CStopWatch.h"
  17. #include "../../lib/CThreadHelper.h"
  18. #include "../../lib/spells/CSpellHandler.h"
  19. #include "../../lib/spells/ISpellMechanics.h"
  20. #include "../../lib/CStack.h"//todo: remove
  21. #define LOGL(text) print(text)
  22. #define LOGFL(text, formattingEl) print(boost::str(boost::format(text) % formattingEl))
  23. class RNGStub : public vstd::RNG
  24. {
  25. public:
  26. vstd::TRandI64 getInt64Range(int64_t lower, int64_t upper) override
  27. {
  28. return [=]()->int64_t
  29. {
  30. return (lower + upper)/2;
  31. };
  32. }
  33. vstd::TRand getDoubleRange(double lower, double upper) override
  34. {
  35. return [=]()->double
  36. {
  37. return (lower + upper)/2;
  38. };
  39. }
  40. };
  41. enum class SpellTypes
  42. {
  43. ADVENTURE, BATTLE, OTHER
  44. };
  45. SpellTypes spellType(const CSpell * spell)
  46. {
  47. if(!spell->isCombatSpell() || spell->isCreatureAbility())
  48. return SpellTypes::OTHER;
  49. if(spell->isOffensiveSpell() || spell->hasEffects() || spell->hasBattleEffects())
  50. return SpellTypes::BATTLE;
  51. return SpellTypes::OTHER;
  52. }
  53. CBattleAI::CBattleAI()
  54. : side(-1), wasWaitingForRealize(false), wasUnlockingGs(false)
  55. {
  56. }
  57. CBattleAI::~CBattleAI()
  58. {
  59. if(cb)
  60. {
  61. //Restore previous state of CB - it may be shared with the main AI (like VCAI)
  62. cb->waitTillRealize = wasWaitingForRealize;
  63. cb->unlockGsWhenWaiting = wasUnlockingGs;
  64. }
  65. }
  66. void CBattleAI::init(std::shared_ptr<CBattleCallback> CB)
  67. {
  68. setCbc(CB);
  69. cb = CB;
  70. playerID = *CB->getPlayerID(); //TODO should be sth in callback
  71. wasWaitingForRealize = cb->waitTillRealize;
  72. wasUnlockingGs = CB->unlockGsWhenWaiting;
  73. CB->waitTillRealize = true;
  74. CB->unlockGsWhenWaiting = false;
  75. }
  76. BattleAction CBattleAI::activeStack( const CStack * stack )
  77. {
  78. LOG_TRACE_PARAMS(logAi, "stack: %s", stack->nodeName()) ;
  79. setCbc(cb); //TODO: make solid sure that AIs always use their callbacks (need to take care of event handlers too)
  80. try
  81. {
  82. if(stack->type->idNumber == CreatureID::CATAPULT)
  83. return useCatapult(stack);
  84. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON) && stack->hasBonusOfType(Bonus::HEALER))
  85. {
  86. auto healingTargets = cb->battleGetStacks(CBattleInfoEssentials::ONLY_MINE);
  87. std::map<int, const CStack*> woundHpToStack;
  88. for(auto stack : healingTargets)
  89. if(auto woundHp = stack->MaxHealth() - stack->getFirstHPleft())
  90. woundHpToStack[woundHp] = stack;
  91. if(woundHpToStack.empty())
  92. return BattleAction::makeDefend(stack);
  93. else
  94. return BattleAction::makeHeal(stack, woundHpToStack.rbegin()->second); //last element of the woundHpToStack is the most wounded stack
  95. }
  96. attemptCastingSpell();
  97. if(auto ret = getCbc()->battleIsFinished())
  98. {
  99. //spellcast may finish battle
  100. //send special preudo-action
  101. BattleAction cancel;
  102. cancel.actionType = EActionType::CANCEL;
  103. return cancel;
  104. }
  105. if(auto action = considerFleeingOrSurrendering())
  106. return *action;
  107. //best action is from effective owner point if view, we are effective owner as we received "activeStack"
  108. HypotheticBattle hb(getCbc());
  109. PotentialTargets targets(stack, &hb);
  110. if(targets.possibleAttacks.size())
  111. {
  112. auto hlp = targets.bestAction();
  113. if(hlp.attack.shooting)
  114. return BattleAction::makeShotAttack(stack, hlp.attack.defender);
  115. else
  116. return BattleAction::makeMeleeAttack(stack, hlp.attack.defender->getPosition(), hlp.tile);
  117. }
  118. else
  119. {
  120. if(stack->waited())
  121. {
  122. //ThreatMap threatsToUs(stack); // These lines may be usefull but they are't used in the code.
  123. auto dists = getCbc()->battleGetDistances(stack, stack->getPosition());
  124. if(!targets.unreachableEnemies.empty())
  125. {
  126. const EnemyInfo &ei= *range::min_element(targets.unreachableEnemies, std::bind(isCloser, _1, _2, std::ref(dists)));
  127. if(distToNearestNeighbour(ei.s->getPosition(), dists) < GameConstants::BFIELD_SIZE)
  128. {
  129. return goTowards(stack, ei.s->getPosition());
  130. }
  131. }
  132. }
  133. else
  134. {
  135. return BattleAction::makeWait(stack);
  136. }
  137. }
  138. }
  139. catch(boost::thread_interrupted &)
  140. {
  141. throw;
  142. }
  143. catch(std::exception &e)
  144. {
  145. logAi->error("Exception occurred in %s %s",__FUNCTION__, e.what());
  146. }
  147. return BattleAction::makeDefend(stack);
  148. }
  149. BattleAction CBattleAI::goTowards(const CStack * stack, BattleHex destination)
  150. {
  151. if(!destination.isValid())
  152. {
  153. logAi->error("CBattleAI::goTowards: invalid destination");
  154. return BattleAction::makeDefend(stack);
  155. }
  156. auto reachability = cb->getReachability(stack);
  157. auto avHexes = cb->battleGetAvailableHexes(reachability, stack);
  158. if(vstd::contains(avHexes, destination))
  159. return BattleAction::makeMove(stack, destination);
  160. auto destNeighbours = destination.neighbouringTiles();
  161. if(vstd::contains_if(destNeighbours, [&](BattleHex n) { return stack->coversPos(destination); }))
  162. {
  163. logAi->warn("Warning: already standing on neighbouring tile!");
  164. //We shouldn't even be here...
  165. return BattleAction::makeDefend(stack);
  166. }
  167. vstd::erase_if(destNeighbours, [&](BattleHex hex){ return !reachability.accessibility.accessible(hex, stack); });
  168. if(!avHexes.size() || !destNeighbours.size()) //we are blocked or dest is blocked
  169. {
  170. return BattleAction::makeDefend(stack);
  171. }
  172. if(stack->hasBonusOfType(Bonus::FLYING))
  173. {
  174. // Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
  175. // We just check all available hexes and pick the one closest to the target.
  176. auto distToDestNeighbour = [&](BattleHex hex) -> int
  177. {
  178. auto nearestNeighbourToHex = vstd::minElementByFun(destNeighbours, [&](BattleHex a)
  179. {return BattleHex::getDistance(a, hex);});
  180. return BattleHex::getDistance(*nearestNeighbourToHex, hex);
  181. };
  182. auto nearestAvailableHex = vstd::minElementByFun(avHexes, distToDestNeighbour);
  183. return BattleAction::makeMove(stack, *nearestAvailableHex);
  184. }
  185. else
  186. {
  187. BattleHex bestNeighbor = destination;
  188. if(distToNearestNeighbour(destination, reachability.distances, &bestNeighbor) > GameConstants::BFIELD_SIZE)
  189. {
  190. return BattleAction::makeDefend(stack);
  191. }
  192. BattleHex currentDest = bestNeighbor;
  193. while(1)
  194. {
  195. if(!currentDest.isValid())
  196. {
  197. logAi->error("CBattleAI::goTowards: internal error");
  198. return BattleAction::makeDefend(stack);
  199. }
  200. if(vstd::contains(avHexes, currentDest))
  201. return BattleAction::makeMove(stack, currentDest);
  202. currentDest = reachability.predecessors[currentDest];
  203. }
  204. }
  205. }
  206. BattleAction CBattleAI::useCatapult(const CStack * stack)
  207. {
  208. throw std::runtime_error("CBattleAI::useCatapult is not implemented.");
  209. }
  210. void CBattleAI::attemptCastingSpell()
  211. {
  212. auto hero = cb->battleGetMyHero();
  213. if(!hero)
  214. return;
  215. if(cb->battleCanCastSpell(hero, spells::Mode::HERO) != ESpellCastProblem::OK)
  216. return;
  217. LOGL("Casting spells sounds like fun. Let's see...");
  218. //Get all spells we can cast
  219. std::vector<const CSpell*> possibleSpells;
  220. vstd::copy_if(VLC->spellh->objects, std::back_inserter(possibleSpells), [this, hero] (const CSpell *s) -> bool
  221. {
  222. return s->canBeCast(getCbc().get(), spells::Mode::HERO, hero);
  223. });
  224. LOGFL("I can cast %d spells.", possibleSpells.size());
  225. vstd::erase_if(possibleSpells, [](const CSpell *s)
  226. {
  227. return spellType(s) != SpellTypes::BATTLE;
  228. });
  229. LOGFL("I know how %d of them works.", possibleSpells.size());
  230. //Get possible spell-target pairs
  231. std::vector<PossibleSpellcast> possibleCasts;
  232. for(auto spell : possibleSpells)
  233. {
  234. spells::BattleCast temp(getCbc().get(), hero, spells::Mode::HERO, spell);
  235. for(auto & target : temp.findPotentialTargets())
  236. {
  237. PossibleSpellcast ps;
  238. ps.dest = target;
  239. ps.spell = spell;
  240. possibleCasts.push_back(ps);
  241. }
  242. }
  243. LOGFL("Found %d spell-target combinations.", possibleCasts.size());
  244. if(possibleCasts.empty())
  245. return;
  246. using ValueMap = PossibleSpellcast::ValueMap;
  247. auto evaluateQueue = [&](ValueMap & values, const std::vector<battle::Units> & queue, HypotheticBattle * state, size_t minTurnSpan, bool * enemyHadTurnOut) -> bool
  248. {
  249. bool firstRound = true;
  250. bool enemyHadTurn = false;
  251. size_t ourTurnSpan = 0;
  252. bool stop = false;
  253. for(auto & round : queue)
  254. {
  255. if(!firstRound)
  256. state->nextRound(0);//todo: set actual value?
  257. for(auto unit : round)
  258. {
  259. if(!vstd::contains(values, unit->unitId()))
  260. values[unit->unitId()] = 0;
  261. if(!unit->alive())
  262. continue;
  263. if(state->battleGetOwner(unit) != playerID)
  264. {
  265. enemyHadTurn = true;
  266. if(!firstRound || state->battleCastSpells(unit->unitSide()) == 0)
  267. {
  268. //enemy could counter our spell at this point
  269. //anyway, we do not know what enemy will do
  270. //just stop evaluation
  271. stop = true;
  272. break;
  273. }
  274. }
  275. else if(!enemyHadTurn)
  276. {
  277. ourTurnSpan++;
  278. }
  279. state->nextTurn(unit->unitId());
  280. PotentialTargets pt(unit, state);
  281. if(!pt.possibleAttacks.empty())
  282. {
  283. AttackPossibility ap = pt.bestAction();
  284. auto swb = state->getForUpdate(unit->unitId());
  285. *swb = *ap.attackerState;
  286. if(ap.damageDealt > 0)
  287. swb->removeUnitBonus(Bonus::UntilAttack);
  288. if(ap.damageReceived > 0)
  289. swb->removeUnitBonus(Bonus::UntilBeingAttacked);
  290. for(auto affected : ap.affectedUnits)
  291. {
  292. swb = state->getForUpdate(affected->unitId());
  293. *swb = *affected;
  294. if(ap.damageDealt > 0)
  295. swb->removeUnitBonus(Bonus::UntilBeingAttacked);
  296. if(ap.damageReceived > 0 && ap.attack.defender->unitId() == affected->unitId())
  297. swb->removeUnitBonus(Bonus::UntilAttack);
  298. }
  299. }
  300. auto bav = pt.bestActionValue();
  301. //best action is from effective owner`s point if view, we need to convert to our point if view
  302. if(state->battleGetOwner(unit) != playerID)
  303. bav = -bav;
  304. values[unit->unitId()] += bav;
  305. }
  306. firstRound = false;
  307. if(stop)
  308. break;
  309. }
  310. if(enemyHadTurnOut)
  311. *enemyHadTurnOut = enemyHadTurn;
  312. return ourTurnSpan > minTurnSpan;
  313. };
  314. RNGStub rngStub;
  315. ValueMap valueOfStack;
  316. ValueMap healthOfStack;
  317. TStacks all = cb->battleGetAllStacks(false);
  318. for(auto unit : all)
  319. {
  320. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  321. valueOfStack[unit->unitId()] = 0;
  322. }
  323. auto amount = all.size();
  324. std::vector<battle::Units> turnOrder;
  325. cb->battleGetTurnOrder(turnOrder, amount, 2); //no more than 1 turn after current, each unit at least once
  326. {
  327. bool enemyHadTurn = false;
  328. HypotheticBattle state(cb);
  329. evaluateQueue(valueOfStack, turnOrder, &state, 0, &enemyHadTurn);
  330. if(!enemyHadTurn)
  331. {
  332. auto battleIsFinishedOpt = state.battleIsFinished();
  333. if(battleIsFinishedOpt)
  334. {
  335. print("No need to cast a spell. Battle will finish soon.");
  336. return;
  337. }
  338. }
  339. }
  340. auto evaluateSpellcast = [&] (PossibleSpellcast * ps)
  341. {
  342. int64_t totalGain = 0;
  343. HypotheticBattle state(cb);
  344. spells::BattleCast cast(&state, hero, spells::Mode::HERO, ps->spell);
  345. cast.target = ps->dest;
  346. cast.cast(&state, rngStub);
  347. ValueMap newHealthOfStack;
  348. ValueMap newValueOfStack;
  349. size_t ourUnits = 0;
  350. for(auto unit : all)
  351. {
  352. newHealthOfStack[unit->unitId()] = unit->getAvailableHealth();
  353. newValueOfStack[unit->unitId()] = 0;
  354. if(state.battleGetOwner(unit) == playerID && unit->alive() && unit->willMove())
  355. ourUnits++;
  356. }
  357. size_t minTurnSpan = ourUnits/3; //todo: tweak this
  358. std::vector<battle::Units> newTurnOrder;
  359. state.battleGetTurnOrder(newTurnOrder, amount, 2);
  360. if(evaluateQueue(newValueOfStack, newTurnOrder, &state, minTurnSpan, nullptr))
  361. {
  362. for(auto unit : all)
  363. {
  364. auto newValue = getValOr(newValueOfStack, unit->unitId(), 0);
  365. auto oldValue = getValOr(valueOfStack, unit->unitId(), 0);
  366. auto healthDiff = newHealthOfStack[unit->unitId()] - healthOfStack[unit->unitId()];
  367. if(unit->unitOwner() != playerID)
  368. healthDiff = -healthDiff;
  369. auto gain = newValue - oldValue + healthDiff;
  370. if(gain != 0)
  371. totalGain += gain;
  372. }
  373. ps->value = totalGain;
  374. }
  375. else
  376. {
  377. ps->value = -1;
  378. }
  379. };
  380. std::vector<std::function<void()>> tasks;
  381. for(PossibleSpellcast & psc : possibleCasts)
  382. {
  383. tasks.push_back(std::bind(evaluateSpellcast, &psc));
  384. }
  385. uint32_t threadCount = boost::thread::hardware_concurrency();
  386. if(threadCount == 0)
  387. {
  388. logGlobal->warn("No information of CPU cores available");
  389. threadCount = 1;
  390. }
  391. CStopWatch timer;
  392. CThreadHelper threadHelper(&tasks, threadCount);
  393. threadHelper.run();
  394. LOGFL("Evaluation took %d ms", timer.getDiff());
  395. auto pscValue = [] (const PossibleSpellcast &ps) -> int64_t
  396. {
  397. return ps.value;
  398. };
  399. auto castToPerform = *vstd::maxElementByFun(possibleCasts, pscValue);
  400. if(castToPerform.value > 0)
  401. {
  402. LOGFL("Best spell is %s (value %d). Will cast.", castToPerform.spell->name % castToPerform.value);
  403. BattleAction spellcast;
  404. spellcast.actionType = EActionType::HERO_SPELL;
  405. spellcast.actionSubtype = castToPerform.spell->id;
  406. spellcast.setTarget(castToPerform.dest);
  407. spellcast.side = side;
  408. spellcast.stackNumber = (!side) ? -1 : -2;
  409. cb->battleMakeAction(&spellcast);
  410. }
  411. else
  412. {
  413. LOGFL("Best spell is %s. But it is actually useless (value %d).", castToPerform.spell->name % castToPerform.value);
  414. }
  415. }
  416. int CBattleAI::distToNearestNeighbour(BattleHex hex, const ReachabilityInfo::TDistances &dists, BattleHex *chosenHex)
  417. {
  418. int ret = 1000000;
  419. for(BattleHex n : hex.neighbouringTiles())
  420. {
  421. if(dists[n] >= 0 && dists[n] < ret)
  422. {
  423. ret = dists[n];
  424. if(chosenHex)
  425. *chosenHex = n;
  426. }
  427. }
  428. return ret;
  429. }
  430. void CBattleAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool Side)
  431. {
  432. LOG_TRACE(logAi);
  433. side = Side;
  434. }
  435. bool CBattleAI::isCloser(const EnemyInfo &ei1, const EnemyInfo &ei2, const ReachabilityInfo::TDistances &dists)
  436. {
  437. return distToNearestNeighbour(ei1.s->getPosition(), dists) < distToNearestNeighbour(ei2.s->getPosition(), dists);
  438. }
  439. void CBattleAI::print(const std::string &text) const
  440. {
  441. logAi->trace("%s Battle AI[%p]: %s", playerID.getStr(), this, text);
  442. }
  443. boost::optional<BattleAction> CBattleAI::considerFleeingOrSurrendering()
  444. {
  445. if(cb->battleCanSurrender(playerID))
  446. {
  447. }
  448. if(cb->battleCanFlee())
  449. {
  450. }
  451. return boost::none;
  452. }