BattleAI.cpp 22 KB

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