BattleAI.cpp 20 KB

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