BattleAI.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  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 "StackWithBonuses.h"
  13. #include "EnemyInfo.h"
  14. #include "../../lib/CStopWatch.h"
  15. #include "../../lib/CThreadHelper.h"
  16. #include "../../lib/mapObjects/CGTownInstance.h"
  17. #include "../../lib/spells/CSpellHandler.h"
  18. #include "../../lib/spells/ISpellMechanics.h"
  19. #include "../../lib/battle/BattleStateInfoForRetreat.h"
  20. #include "../../lib/CStack.h" // TODO: remove
  21. // Eventually only IBattleInfoCallback and battle::Unit should be used,
  22. // CUnitState should be private and CStack should be removed completely
  23. #define LOGL(text) print(text)
  24. #define LOGFL(text, formattingEl) print(boost::str(boost::format(text) % formattingEl))
  25. enum class SpellTypes
  26. {
  27. ADVENTURE, BATTLE, OTHER
  28. };
  29. SpellTypes spellType(const CSpell * spell)
  30. {
  31. if(!spell->isCombat() || spell->isCreatureAbility())
  32. return SpellTypes::OTHER;
  33. if(spell->isOffensive() || spell->hasEffects() || spell->hasBattleEffects())
  34. return SpellTypes::BATTLE;
  35. return SpellTypes::OTHER;
  36. }
  37. std::vector<BattleHex> CBattleAI::getBrokenWallMoatHexes() const
  38. {
  39. std::vector<BattleHex> result;
  40. for(int wallPart = EWallPart::BOTTOM_WALL; wallPart < EWallPart::UPPER_WALL; wallPart++)
  41. {
  42. auto state = cb->battleGetWallState(wallPart);
  43. if(state != EWallState::DESTROYED)
  44. continue;
  45. auto wallHex = cb->wallPartToBattleHex((EWallPart::EWallPart)wallPart);
  46. auto moatHex = wallHex.cloneInDirection(BattleHex::LEFT);
  47. result.push_back(moatHex);
  48. }
  49. return result;
  50. }
  51. CBattleAI::CBattleAI()
  52. : side(-1),
  53. wasWaitingForRealize(false),
  54. 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<Environment> ENV, std::shared_ptr<CBattleCallback> CB)
  67. {
  68. setCbc(CB);
  69. env = ENV;
  70. cb = CB;
  71. playerID = *CB->getPlayerID(); //TODO should be sth in callback
  72. wasWaitingForRealize = CB->waitTillRealize;
  73. wasUnlockingGs = CB->unlockGsWhenWaiting;
  74. CB->waitTillRealize = true;
  75. CB->unlockGsWhenWaiting = false;
  76. }
  77. BattleAction CBattleAI::activeStack( const CStack * stack )
  78. {
  79. LOG_TRACE_PARAMS(logAi, "stack: %s", stack->nodeName()) ;
  80. setCbc(cb); //TODO: make solid sure that AIs always use their callbacks (need to take care of event handlers too)
  81. try
  82. {
  83. if(stack->type->idNumber == CreatureID::CATAPULT)
  84. return useCatapult(stack);
  85. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON) && stack->hasBonusOfType(Bonus::HEALER))
  86. {
  87. auto healingTargets = cb->battleGetStacks(CBattleInfoEssentials::ONLY_MINE);
  88. std::map<int, const CStack*> woundHpToStack;
  89. for(auto stack : healingTargets)
  90. if(auto woundHp = stack->MaxHealth() - stack->getFirstHPleft())
  91. woundHpToStack[woundHp] = stack;
  92. if(woundHpToStack.empty())
  93. return BattleAction::makeDefend(stack);
  94. else
  95. return BattleAction::makeHeal(stack, woundHpToStack.rbegin()->second); //last element of the woundHpToStack is the most wounded stack
  96. }
  97. attemptCastingSpell();
  98. if(auto ret = cb->battleIsFinished())
  99. {
  100. //spellcast may finish battle
  101. //send special preudo-action
  102. BattleAction cancel;
  103. cancel.actionType = EActionType::CANCEL;
  104. return cancel;
  105. }
  106. if(auto action = considerFleeingOrSurrendering())
  107. return *action;
  108. //best action is from effective owner point if view, we are effective owner as we received "activeStack"
  109. //evaluate casting spell for spellcasting stack
  110. boost::optional<PossibleSpellcast> bestSpellcast(boost::none);
  111. //TODO: faerie dragon type spell should be selected by server
  112. SpellID creatureSpellToCast = cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), stack, CBattleInfoCallback::RANDOM_AIMED);
  113. if(stack->hasBonusOfType(Bonus::SPELLCASTER) && stack->canCast() && creatureSpellToCast != SpellID::NONE)
  114. {
  115. const CSpell * spell = creatureSpellToCast.toSpell();
  116. if(spell->canBeCast(getCbc().get(), spells::Mode::CREATURE_ACTIVE, stack))
  117. {
  118. std::vector<PossibleSpellcast> possibleCasts;
  119. spells::BattleCast temp(getCbc().get(), stack, spells::Mode::CREATURE_ACTIVE, spell);
  120. for(auto & target : temp.findPotentialTargets())
  121. {
  122. PossibleSpellcast ps;
  123. ps.dest = target;
  124. ps.spell = spell;
  125. evaluateCreatureSpellcast(stack, ps);
  126. possibleCasts.push_back(ps);
  127. }
  128. std::sort(possibleCasts.begin(), possibleCasts.end(), [&](const PossibleSpellcast & lhs, const PossibleSpellcast & rhs) { return lhs.value > rhs.value; });
  129. if(!possibleCasts.empty() && possibleCasts.front().value > 0)
  130. {
  131. bestSpellcast = boost::optional<PossibleSpellcast>(possibleCasts.front());
  132. }
  133. }
  134. }
  135. HypotheticBattle hb(env.get(), cb);
  136. PotentialTargets targets(stack, &hb);
  137. if(!targets.possibleAttacks.empty())
  138. {
  139. AttackPossibility bestAttack = targets.bestAction();
  140. //TODO: consider more complex spellcast evaluation, f.e. because "re-retaliation" during enemy move in same turn for melee attack etc.
  141. if(bestSpellcast.is_initialized() && bestSpellcast->value > bestAttack.damageDiff())
  142. return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
  143. else if(bestAttack.attack.shooting)
  144. {
  145. auto &target = bestAttack;
  146. logAi->debug("BattleAI: %s -> %s x %d, shot, from %d curpos %d dist %d speed %d: %lld %lld %lld",
  147. target.attackerState->unitType()->identifier,
  148. target.affectedUnits[0]->unitType()->identifier,
  149. (int)target.affectedUnits.size(), (int)target.from, (int)bestAttack.attack.attacker->getPosition().hex,
  150. bestAttack.attack.chargedFields, bestAttack.attack.attacker->Speed(0, true),
  151. target.damageDealt, target.damageReceived, target.attackValue()
  152. );
  153. return BattleAction::makeShotAttack(stack, bestAttack.attack.defender);
  154. }
  155. else
  156. {
  157. auto &target = bestAttack;
  158. logAi->debug("BattleAI: %s -> %s x %d, mellee, from %d curpos %d dist %d speed %d: %lld %lld %lld",
  159. target.attackerState->unitType()->identifier,
  160. target.affectedUnits[0]->unitType()->identifier,
  161. (int)target.affectedUnits.size(), (int)target.from, (int)bestAttack.attack.attacker->getPosition().hex,
  162. bestAttack.attack.chargedFields, bestAttack.attack.attacker->Speed(0, true),
  163. target.damageDealt, target.damageReceived, target.attackValue()
  164. );
  165. return BattleAction::makeMeleeAttack(stack, bestAttack.attack.defender->getPosition(), bestAttack.from);
  166. }
  167. }
  168. else if(bestSpellcast.is_initialized())
  169. {
  170. return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
  171. }
  172. else
  173. {
  174. if(stack->waited())
  175. {
  176. //ThreatMap threatsToUs(stack); // These lines may be usefull but they are't used in the code.
  177. auto dists = cb->getReachability(stack);
  178. if(!targets.unreachableEnemies.empty())
  179. {
  180. auto closestEnemy = vstd::minElementByFun(targets.unreachableEnemies, [&](const battle::Unit * enemy) -> int
  181. {
  182. return dists.distToNearestNeighbour(stack, enemy);
  183. });
  184. if(dists.distToNearestNeighbour(stack, *closestEnemy) < GameConstants::BFIELD_SIZE)
  185. {
  186. return goTowardsNearest(stack, (*closestEnemy)->getAttackableHexes(stack));
  187. }
  188. }
  189. }
  190. else
  191. {
  192. return BattleAction::makeWait(stack);
  193. }
  194. }
  195. if(!stack->hasBonusOfType(Bonus::FLYING)
  196. && stack->unitSide() == BattleSide::ATTACKER
  197. && cb->battleGetSiegeLevel() >= CGTownInstance::CITADEL)
  198. {
  199. auto brokenWallMoat = getBrokenWallMoatHexes();
  200. if(brokenWallMoat.size())
  201. {
  202. if(stack->doubleWide() && vstd::contains(brokenWallMoat, stack->getPosition()))
  203. return BattleAction::makeMove(stack, stack->getPosition().cloneInDirection(BattleHex::RIGHT));
  204. else
  205. return goTowardsNearest(stack, brokenWallMoat);
  206. }
  207. }
  208. }
  209. catch(boost::thread_interrupted &)
  210. {
  211. throw;
  212. }
  213. catch(std::exception &e)
  214. {
  215. logAi->error("Exception occurred in %s %s",__FUNCTION__, e.what());
  216. }
  217. return BattleAction::makeDefend(stack);
  218. }
  219. BattleAction CBattleAI::goTowardsNearest(const CStack * stack, std::vector<BattleHex> hexes) const
  220. {
  221. auto reachability = cb->getReachability(stack);
  222. auto avHexes = cb->battleGetAvailableHexes(reachability, stack);
  223. if(!avHexes.size() || !hexes.size()) //we are blocked or dest is blocked
  224. {
  225. return BattleAction::makeDefend(stack);
  226. }
  227. std::sort(hexes.begin(), hexes.end(), [&](BattleHex h1, BattleHex h2) -> bool
  228. {
  229. return reachability.distances[h1] < reachability.distances[h2];
  230. });
  231. for(auto hex : hexes)
  232. {
  233. if(vstd::contains(avHexes, hex))
  234. return BattleAction::makeMove(stack, hex);
  235. if(stack->coversPos(hex))
  236. {
  237. logAi->warn("Warning: already standing on neighbouring tile!");
  238. //We shouldn't even be here...
  239. return BattleAction::makeDefend(stack);
  240. }
  241. }
  242. BattleHex bestNeighbor = hexes.front();
  243. if(reachability.distances[bestNeighbor] > GameConstants::BFIELD_SIZE)
  244. {
  245. return BattleAction::makeDefend(stack);
  246. }
  247. if(stack->hasBonusOfType(Bonus::FLYING))
  248. {
  249. // Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
  250. // We just check all available hexes and pick the one closest to the target.
  251. auto nearestAvailableHex = vstd::minElementByFun(avHexes, [&](BattleHex hex) -> int
  252. {
  253. return BattleHex::getDistance(bestNeighbor, hex);
  254. });
  255. return BattleAction::makeMove(stack, *nearestAvailableHex);
  256. }
  257. else
  258. {
  259. BattleHex currentDest = bestNeighbor;
  260. while(1)
  261. {
  262. if(!currentDest.isValid())
  263. {
  264. logAi->error("CBattleAI::goTowards: internal error");
  265. return BattleAction::makeDefend(stack);
  266. }
  267. if(vstd::contains(avHexes, currentDest))
  268. return BattleAction::makeMove(stack, currentDest);
  269. currentDest = reachability.predecessors[currentDest];
  270. }
  271. }
  272. }
  273. BattleAction CBattleAI::useCatapult(const CStack * stack)
  274. {
  275. BattleAction attack;
  276. BattleHex targetHex = BattleHex::INVALID;
  277. if(cb->battleGetGateState() == EGateState::CLOSED)
  278. {
  279. targetHex = cb->wallPartToBattleHex(EWallPart::GATE);
  280. }
  281. else
  282. {
  283. EWallPart::EWallPart wallParts[] = {
  284. EWallPart::KEEP,
  285. EWallPart::BOTTOM_TOWER,
  286. EWallPart::UPPER_TOWER,
  287. EWallPart::BELOW_GATE,
  288. EWallPart::OVER_GATE,
  289. EWallPart::BOTTOM_WALL,
  290. EWallPart::UPPER_WALL
  291. };
  292. for(auto wallPart : wallParts)
  293. {
  294. auto wallState = cb->battleGetWallState(wallPart);
  295. if(wallState == EWallState::INTACT || wallState == EWallState::DAMAGED)
  296. {
  297. targetHex = cb->wallPartToBattleHex(wallPart);
  298. break;
  299. }
  300. }
  301. }
  302. if(!targetHex.isValid())
  303. {
  304. return BattleAction::makeDefend(stack);
  305. }
  306. attack.aimToHex(targetHex);
  307. attack.actionType = EActionType::CATAPULT;
  308. attack.side = side;
  309. attack.stackNumber = stack->ID;
  310. return attack;
  311. }
  312. void CBattleAI::attemptCastingSpell()
  313. {
  314. auto hero = cb->battleGetMyHero();
  315. if(!hero)
  316. return;
  317. if(cb->battleCanCastSpell(hero, spells::Mode::HERO) != ESpellCastProblem::OK)
  318. return;
  319. LOGL("Casting spells sounds like fun. Let's see...");
  320. //Get all spells we can cast
  321. std::vector<const CSpell*> possibleSpells;
  322. vstd::copy_if(VLC->spellh->objects, std::back_inserter(possibleSpells), [hero, this](const CSpell *s) -> bool
  323. {
  324. return s->canBeCast(cb.get(), spells::Mode::HERO, hero);
  325. });
  326. LOGFL("I can cast %d spells.", possibleSpells.size());
  327. vstd::erase_if(possibleSpells, [](const CSpell *s)
  328. {
  329. return spellType(s) != SpellTypes::BATTLE;
  330. });
  331. LOGFL("I know how %d of them works.", possibleSpells.size());
  332. //Get possible spell-target pairs
  333. std::vector<PossibleSpellcast> possibleCasts;
  334. for(auto spell : possibleSpells)
  335. {
  336. spells::BattleCast temp(cb.get(), hero, spells::Mode::HERO, spell);
  337. for(auto & target : temp.findPotentialTargets())
  338. {
  339. PossibleSpellcast ps;
  340. ps.dest = target;
  341. ps.spell = spell;
  342. possibleCasts.push_back(ps);
  343. }
  344. }
  345. LOGFL("Found %d spell-target combinations.", possibleCasts.size());
  346. if(possibleCasts.empty())
  347. return;
  348. using ValueMap = PossibleSpellcast::ValueMap;
  349. auto evaluateQueue = [&](ValueMap & values, const std::vector<battle::Units> & queue, HypotheticBattle * state, size_t minTurnSpan, bool * enemyHadTurnOut) -> bool
  350. {
  351. bool firstRound = true;
  352. bool enemyHadTurn = false;
  353. size_t ourTurnSpan = 0;
  354. bool stop = false;
  355. for(auto & round : queue)
  356. {
  357. if(!firstRound)
  358. state->nextRound(0);//todo: set actual value?
  359. for(auto unit : round)
  360. {
  361. if(!vstd::contains(values, unit->unitId()))
  362. values[unit->unitId()] = 0;
  363. if(!unit->alive())
  364. continue;
  365. if(state->battleGetOwner(unit) != playerID)
  366. {
  367. enemyHadTurn = true;
  368. if(!firstRound || state->battleCastSpells(unit->unitSide()) == 0)
  369. {
  370. //enemy could counter our spell at this point
  371. //anyway, we do not know what enemy will do
  372. //just stop evaluation
  373. stop = true;
  374. break;
  375. }
  376. }
  377. else if(!enemyHadTurn)
  378. {
  379. ourTurnSpan++;
  380. }
  381. state->nextTurn(unit->unitId());
  382. PotentialTargets pt(unit, state);
  383. if(!pt.possibleAttacks.empty())
  384. {
  385. AttackPossibility ap = pt.bestAction();
  386. auto swb = state->getForUpdate(unit->unitId());
  387. *swb = *ap.attackerState;
  388. if(ap.damageDealt > 0)
  389. swb->removeUnitBonus(Bonus::UntilAttack);
  390. if(ap.damageReceived > 0)
  391. swb->removeUnitBonus(Bonus::UntilBeingAttacked);
  392. for(auto affected : ap.affectedUnits)
  393. {
  394. swb = state->getForUpdate(affected->unitId());
  395. *swb = *affected;
  396. if(ap.damageDealt > 0)
  397. swb->removeUnitBonus(Bonus::UntilBeingAttacked);
  398. if(ap.damageReceived > 0 && ap.attack.defender->unitId() == affected->unitId())
  399. swb->removeUnitBonus(Bonus::UntilAttack);
  400. }
  401. }
  402. auto bav = pt.bestActionValue();
  403. //best action is from effective owner`s point if view, we need to convert to our point if view
  404. if(state->battleGetOwner(unit) != playerID)
  405. bav = -bav;
  406. values[unit->unitId()] += bav;
  407. }
  408. firstRound = false;
  409. if(stop)
  410. break;
  411. }
  412. if(enemyHadTurnOut)
  413. *enemyHadTurnOut = enemyHadTurn;
  414. return ourTurnSpan >= minTurnSpan;
  415. };
  416. ValueMap valueOfStack;
  417. ValueMap healthOfStack;
  418. TStacks all = cb->battleGetAllStacks(false);
  419. size_t ourRemainingTurns = 0;
  420. for(auto unit : all)
  421. {
  422. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  423. valueOfStack[unit->unitId()] = 0;
  424. if(cb->battleGetOwner(unit) == playerID && unit->canMove() && !unit->moved())
  425. ourRemainingTurns++;
  426. }
  427. LOGFL("I have %d turns left in this round", ourRemainingTurns);
  428. const bool castNow = ourRemainingTurns <= 1;
  429. if(castNow)
  430. print("I should try to cast a spell now");
  431. else
  432. print("I could wait better moment to cast a spell");
  433. auto amount = all.size();
  434. std::vector<battle::Units> turnOrder;
  435. cb->battleGetTurnOrder(turnOrder, amount, 2); //no more than 1 turn after current, each unit at least once
  436. {
  437. bool enemyHadTurn = false;
  438. HypotheticBattle state(env.get(), cb);
  439. evaluateQueue(valueOfStack, turnOrder, &state, 0, &enemyHadTurn);
  440. if(!enemyHadTurn)
  441. {
  442. auto battleIsFinishedOpt = state.battleIsFinished();
  443. if(battleIsFinishedOpt)
  444. {
  445. print("No need to cast a spell. Battle will finish soon.");
  446. return;
  447. }
  448. }
  449. }
  450. struct ScriptsCache
  451. {
  452. //todo: re-implement scripts context cache
  453. };
  454. auto evaluateSpellcast = [&] (PossibleSpellcast * ps, std::shared_ptr<ScriptsCache>)
  455. {
  456. HypotheticBattle state(env.get(), cb);
  457. spells::BattleCast cast(&state, hero, spells::Mode::HERO, ps->spell);
  458. cast.castEval(state.getServerCallback(), ps->dest);
  459. ValueMap newHealthOfStack;
  460. ValueMap newValueOfStack;
  461. size_t ourUnits = 0;
  462. for(auto unit : all)
  463. {
  464. auto unitId = unit->unitId();
  465. auto localUnit = state.battleGetUnitByID(unitId);
  466. newHealthOfStack[unitId] = localUnit->getAvailableHealth();
  467. newValueOfStack[unitId] = 0;
  468. if(state.battleGetOwner(localUnit) == playerID && localUnit->alive() && localUnit->willMove())
  469. ourUnits++;
  470. }
  471. size_t minTurnSpan = ourUnits/3; //todo: tweak this
  472. std::vector<battle::Units> newTurnOrder;
  473. state.battleGetTurnOrder(newTurnOrder, amount, 2);
  474. const bool turnSpanOK = evaluateQueue(newValueOfStack, newTurnOrder, &state, minTurnSpan, nullptr);
  475. if(turnSpanOK || castNow)
  476. {
  477. int64_t totalGain = 0;
  478. for(auto unit : all)
  479. {
  480. auto unitId = unit->unitId();
  481. auto localUnit = state.battleGetUnitByID(unitId);
  482. auto newValue = getValOr(newValueOfStack, unitId, 0);
  483. auto oldValue = getValOr(valueOfStack, unitId, 0);
  484. auto healthDiff = newHealthOfStack[unitId] - healthOfStack[unitId];
  485. if(localUnit->unitOwner() != playerID)
  486. healthDiff = -healthDiff;
  487. if(healthDiff < 0)
  488. {
  489. ps->value = -1;
  490. return; //do not damage own units at all
  491. }
  492. totalGain += (newValue - oldValue + healthDiff);
  493. }
  494. ps->value = totalGain;
  495. }
  496. else
  497. {
  498. ps->value = -1;
  499. }
  500. };
  501. using EvalRunner = ThreadPool<ScriptsCache>;
  502. EvalRunner::Tasks tasks;
  503. for(PossibleSpellcast & psc : possibleCasts)
  504. tasks.push_back(std::bind(evaluateSpellcast, &psc, _1));
  505. uint32_t threadCount = boost::thread::hardware_concurrency();
  506. if(threadCount == 0)
  507. {
  508. logGlobal->warn("No information of CPU cores available");
  509. threadCount = 1;
  510. }
  511. CStopWatch timer;
  512. std::vector<std::shared_ptr<ScriptsCache>> scriptsPool;
  513. for(uint32_t idx = 0; idx < threadCount; idx++)
  514. {
  515. scriptsPool.emplace_back();
  516. }
  517. EvalRunner runner(&tasks, scriptsPool);
  518. runner.run();
  519. LOGFL("Evaluation took %d ms", timer.getDiff());
  520. auto pscValue = [](const PossibleSpellcast &ps) -> int64_t
  521. {
  522. return ps.value;
  523. };
  524. auto castToPerform = *vstd::maxElementByFun(possibleCasts, pscValue);
  525. if(castToPerform.value > 0)
  526. {
  527. LOGFL("Best spell is %s (value %d). Will cast.", castToPerform.spell->name % castToPerform.value);
  528. BattleAction spellcast;
  529. spellcast.actionType = EActionType::HERO_SPELL;
  530. spellcast.actionSubtype = castToPerform.spell->id;
  531. spellcast.setTarget(castToPerform.dest);
  532. spellcast.side = side;
  533. spellcast.stackNumber = (!side) ? -1 : -2;
  534. cb->battleMakeAction(&spellcast);
  535. }
  536. else
  537. {
  538. LOGFL("Best spell is %s. But it is actually useless (value %d).", castToPerform.spell->name % castToPerform.value);
  539. }
  540. }
  541. //Below method works only for offensive spells
  542. void CBattleAI::evaluateCreatureSpellcast(const CStack * stack, PossibleSpellcast & ps)
  543. {
  544. using ValueMap = PossibleSpellcast::ValueMap;
  545. RNGStub rngStub;
  546. HypotheticBattle state(env.get(), cb);
  547. TStacks all = cb->battleGetAllStacks(false);
  548. ValueMap healthOfStack;
  549. ValueMap newHealthOfStack;
  550. for(auto unit : all)
  551. {
  552. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  553. }
  554. spells::BattleCast cast(&state, stack, spells::Mode::CREATURE_ACTIVE, ps.spell);
  555. cast.castEval(state.getServerCallback(), ps.dest);
  556. for(auto unit : all)
  557. {
  558. auto unitId = unit->unitId();
  559. auto localUnit = state.battleGetUnitByID(unitId);
  560. newHealthOfStack[unitId] = localUnit->getAvailableHealth();
  561. }
  562. int64_t totalGain = 0;
  563. for(auto unit : all)
  564. {
  565. auto unitId = unit->unitId();
  566. auto localUnit = state.battleGetUnitByID(unitId);
  567. auto healthDiff = newHealthOfStack[unitId] - healthOfStack[unitId];
  568. if(localUnit->unitOwner() != getCbc()->getPlayerID())
  569. healthDiff = -healthDiff;
  570. if(healthDiff < 0)
  571. {
  572. ps.value = -1;
  573. return; //do not damage own units at all
  574. }
  575. totalGain += healthDiff;
  576. }
  577. ps.value = totalGain;
  578. }
  579. void CBattleAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool Side)
  580. {
  581. LOG_TRACE(logAi);
  582. side = Side;
  583. }
  584. void CBattleAI::print(const std::string &text) const
  585. {
  586. logAi->trace("%s Battle AI[%p]: %s", playerID.getStr(), this, text);
  587. }
  588. boost::optional<BattleAction> CBattleAI::considerFleeingOrSurrendering()
  589. {
  590. BattleStateInfoForRetreat bs;
  591. bs.canFlee = cb->battleCanFlee();
  592. bs.canSurrender = cb->battleCanSurrender(playerID);
  593. bs.ourSide = cb->battleGetMySide();
  594. bs.ourHero = cb->battleGetMyHero();
  595. bs.enemyHero = nullptr;
  596. for(auto stack : cb->battleGetAllStacks(false))
  597. {
  598. if(stack->alive())
  599. {
  600. if(stack->side == bs.ourSide)
  601. bs.ourStacks.push_back(stack);
  602. else
  603. {
  604. bs.enemyStacks.push_back(stack);
  605. bs.enemyHero = cb->battleGetOwnerHero(stack);
  606. }
  607. }
  608. }
  609. if(!bs.canFlee || !bs.canSurrender)
  610. {
  611. return boost::none;
  612. }
  613. return cb->makeSurrenderRetreatDecision(bs);
  614. }