BattleAI.cpp 20 KB

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