BattleAI.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  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::init(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. auto & target = bestAttack;
  158. score = evaluationResult.score;
  159. std::string action;
  160. if(evaluationResult.wait)
  161. {
  162. result = BattleAction::makeWait(stack);
  163. action = "wait";
  164. }
  165. else if(bestAttack.attack.shooting)
  166. {
  167. result = BattleAction::makeShotAttack(stack, bestAttack.attack.defender);
  168. action = "shot";
  169. }
  170. else
  171. {
  172. result = BattleAction::makeMeleeAttack(stack, bestAttack.attack.defender->getPosition(), bestAttack.from);
  173. action = "melee";
  174. }
  175. logAi->debug("BattleAI: %s -> %s x %d, %s, from %d curpos %d dist %d speed %d: +%lld -%lld = %lld",
  176. bestAttack.attackerState->unitType()->identifier,
  177. bestAttack.affectedUnits[0]->unitType()->identifier,
  178. (int)bestAttack.affectedUnits[0]->getCount(), action, (int)bestAttack.from, (int)bestAttack.attack.attacker->getPosition().hex,
  179. bestAttack.attack.chargedFields, bestAttack.attack.attacker->Speed(0, true),
  180. bestAttack.defenderDamageReduce, bestAttack.attackerDamageReduce, bestAttack.attackValue()
  181. );
  182. }
  183. }
  184. else if(bestSpellcast.is_initialized())
  185. {
  186. return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
  187. }
  188. //ThreatMap threatsToUs(stack); // These lines may be usefull but they are't used in the code.
  189. if(moveTarget.score > score)
  190. {
  191. score = moveTarget.score;
  192. if(stack->waited())
  193. {
  194. result = goTowardsNearest(stack, moveTarget.positions);
  195. }
  196. else
  197. {
  198. result = BattleAction::makeWait(stack);
  199. }
  200. }
  201. if(score > EvaluationResult::INEFFECTIVE_SCORE)
  202. {
  203. return result;
  204. }
  205. if(!stack->hasBonusOfType(Bonus::FLYING)
  206. && stack->unitSide() == BattleSide::ATTACKER
  207. && cb->battleGetSiegeLevel() >= CGTownInstance::CITADEL)
  208. {
  209. auto brokenWallMoat = getBrokenWallMoatHexes();
  210. if(brokenWallMoat.size())
  211. {
  212. if(stack->doubleWide() && vstd::contains(brokenWallMoat, stack->getPosition()))
  213. return BattleAction::makeMove(stack, stack->getPosition().cloneInDirection(BattleHex::RIGHT));
  214. else
  215. return goTowardsNearest(stack, brokenWallMoat);
  216. }
  217. }
  218. }
  219. catch(boost::thread_interrupted &)
  220. {
  221. throw;
  222. }
  223. catch(std::exception &e)
  224. {
  225. logAi->error("Exception occurred in %s %s",__FUNCTION__, e.what());
  226. }
  227. return result;
  228. }
  229. BattleAction CBattleAI::goTowardsNearest(const CStack * stack, std::vector<BattleHex> hexes) const
  230. {
  231. auto reachability = cb->getReachability(stack);
  232. auto avHexes = cb->battleGetAvailableHexes(reachability, stack);
  233. if(!avHexes.size() || !hexes.size()) //we are blocked or dest is blocked
  234. {
  235. return BattleAction::makeDefend(stack);
  236. }
  237. std::sort(hexes.begin(), hexes.end(), [&](BattleHex h1, BattleHex h2) -> bool
  238. {
  239. return reachability.distances[h1] < reachability.distances[h2];
  240. });
  241. for(auto hex : hexes)
  242. {
  243. if(vstd::contains(avHexes, hex))
  244. return BattleAction::makeMove(stack, hex);
  245. if(stack->coversPos(hex))
  246. {
  247. logAi->warn("Warning: already standing on neighbouring tile!");
  248. //We shouldn't even be here...
  249. return BattleAction::makeDefend(stack);
  250. }
  251. }
  252. BattleHex bestNeighbor = hexes.front();
  253. if(reachability.distances[bestNeighbor] > GameConstants::BFIELD_SIZE)
  254. {
  255. return BattleAction::makeDefend(stack);
  256. }
  257. BattleExchangeEvaluator scoreEvaluator(cb, env);
  258. HypotheticBattle hb(env.get(), cb);
  259. scoreEvaluator.updateReachabilityMap(hb);
  260. if(stack->hasBonusOfType(Bonus::FLYING))
  261. {
  262. std::set<BattleHex> moatHexes;
  263. if(hb.battleGetSiegeLevel() >= BuildingID::CITADEL)
  264. {
  265. auto townMoat = hb.getDefendedTown()->town->moatHexes;
  266. moatHexes = std::set<BattleHex>(townMoat.begin(), townMoat.end());
  267. }
  268. // Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
  269. // We just check all available hexes and pick the one closest to the target.
  270. auto nearestAvailableHex = vstd::minElementByFun(avHexes, [&](BattleHex hex) -> int
  271. {
  272. const int MOAT_PENALTY = 100; // avoid landing on moat
  273. const int BLOCKED_STACK_PENALTY = 100; // avoid landing on moat
  274. auto distance = BattleHex::getDistance(bestNeighbor, hex);
  275. if(vstd::contains(moatHexes, hex))
  276. distance += MOAT_PENALTY;
  277. return scoreEvaluator.checkPositionBlocksOurStacks(hb, stack, hex) ? BLOCKED_STACK_PENALTY + distance : distance;
  278. });
  279. return BattleAction::makeMove(stack, *nearestAvailableHex);
  280. }
  281. else
  282. {
  283. BattleHex currentDest = bestNeighbor;
  284. while(1)
  285. {
  286. if(!currentDest.isValid())
  287. {
  288. return BattleAction::makeDefend(stack);
  289. }
  290. if(vstd::contains(avHexes, currentDest)
  291. && !scoreEvaluator.checkPositionBlocksOurStacks(hb, stack, currentDest))
  292. return BattleAction::makeMove(stack, currentDest);
  293. currentDest = reachability.predecessors[currentDest];
  294. }
  295. }
  296. }
  297. BattleAction CBattleAI::useCatapult(const CStack * stack)
  298. {
  299. BattleAction attack;
  300. BattleHex targetHex = BattleHex::INVALID;
  301. if(cb->battleGetGateState() == EGateState::CLOSED)
  302. {
  303. targetHex = cb->wallPartToBattleHex(EWallPart::GATE);
  304. }
  305. else
  306. {
  307. EWallPart::EWallPart wallParts[] = {
  308. EWallPart::KEEP,
  309. EWallPart::BOTTOM_TOWER,
  310. EWallPart::UPPER_TOWER,
  311. EWallPart::BELOW_GATE,
  312. EWallPart::OVER_GATE,
  313. EWallPart::BOTTOM_WALL,
  314. EWallPart::UPPER_WALL
  315. };
  316. for(auto wallPart : wallParts)
  317. {
  318. auto wallState = cb->battleGetWallState(wallPart);
  319. if(wallState == EWallState::INTACT || wallState == EWallState::DAMAGED)
  320. {
  321. targetHex = cb->wallPartToBattleHex(wallPart);
  322. break;
  323. }
  324. }
  325. }
  326. if(!targetHex.isValid())
  327. {
  328. return BattleAction::makeDefend(stack);
  329. }
  330. attack.aimToHex(targetHex);
  331. attack.actionType = EActionType::CATAPULT;
  332. attack.side = side;
  333. attack.stackNumber = stack->ID;
  334. return attack;
  335. }
  336. void CBattleAI::attemptCastingSpell()
  337. {
  338. auto hero = cb->battleGetMyHero();
  339. if(!hero)
  340. return;
  341. if(cb->battleCanCastSpell(hero, spells::Mode::HERO) != ESpellCastProblem::OK)
  342. return;
  343. LOGL("Casting spells sounds like fun. Let's see...");
  344. //Get all spells we can cast
  345. std::vector<const CSpell*> possibleSpells;
  346. vstd::copy_if(VLC->spellh->objects, std::back_inserter(possibleSpells), [hero, this](const CSpell *s) -> bool
  347. {
  348. return s->canBeCast(cb.get(), spells::Mode::HERO, hero);
  349. });
  350. LOGFL("I can cast %d spells.", possibleSpells.size());
  351. vstd::erase_if(possibleSpells, [](const CSpell *s)
  352. {
  353. return spellType(s) != SpellTypes::BATTLE;
  354. });
  355. LOGFL("I know how %d of them works.", possibleSpells.size());
  356. //Get possible spell-target pairs
  357. std::vector<PossibleSpellcast> possibleCasts;
  358. for(auto spell : possibleSpells)
  359. {
  360. spells::BattleCast temp(cb.get(), hero, spells::Mode::HERO, spell);
  361. for(auto & target : temp.findPotentialTargets())
  362. {
  363. PossibleSpellcast ps;
  364. ps.dest = target;
  365. ps.spell = spell;
  366. possibleCasts.push_back(ps);
  367. }
  368. }
  369. LOGFL("Found %d spell-target combinations.", possibleCasts.size());
  370. if(possibleCasts.empty())
  371. return;
  372. using ValueMap = PossibleSpellcast::ValueMap;
  373. auto evaluateQueue = [&](ValueMap & values, const std::vector<battle::Units> & queue, HypotheticBattle & state, size_t minTurnSpan, bool * enemyHadTurnOut) -> bool
  374. {
  375. bool firstRound = true;
  376. bool enemyHadTurn = false;
  377. size_t ourTurnSpan = 0;
  378. bool stop = false;
  379. for(auto & round : queue)
  380. {
  381. if(!firstRound)
  382. state.nextRound(0);//todo: set actual value?
  383. for(auto unit : round)
  384. {
  385. if(!vstd::contains(values, unit->unitId()))
  386. values[unit->unitId()] = 0;
  387. if(!unit->alive())
  388. continue;
  389. if(state.battleGetOwner(unit) != playerID)
  390. {
  391. enemyHadTurn = true;
  392. if(!firstRound || state.battleCastSpells(unit->unitSide()) == 0)
  393. {
  394. //enemy could counter our spell at this point
  395. //anyway, we do not know what enemy will do
  396. //just stop evaluation
  397. stop = true;
  398. break;
  399. }
  400. }
  401. else if(!enemyHadTurn)
  402. {
  403. ourTurnSpan++;
  404. }
  405. state.nextTurn(unit->unitId());
  406. PotentialTargets pt(unit, state);
  407. if(!pt.possibleAttacks.empty())
  408. {
  409. AttackPossibility ap = pt.bestAction();
  410. auto swb = state.getForUpdate(unit->unitId());
  411. *swb = *ap.attackerState;
  412. if(ap.defenderDamageReduce > 0)
  413. swb->removeUnitBonus(Bonus::UntilAttack);
  414. if(ap.attackerDamageReduce > 0)
  415. swb->removeUnitBonus(Bonus::UntilBeingAttacked);
  416. for(auto affected : ap.affectedUnits)
  417. {
  418. swb = state.getForUpdate(affected->unitId());
  419. *swb = *affected;
  420. if(ap.defenderDamageReduce > 0)
  421. swb->removeUnitBonus(Bonus::UntilBeingAttacked);
  422. if(ap.attackerDamageReduce > 0 && ap.attack.defender->unitId() == affected->unitId())
  423. swb->removeUnitBonus(Bonus::UntilAttack);
  424. }
  425. }
  426. auto bav = pt.bestActionValue();
  427. //best action is from effective owner`s point if view, we need to convert to our point if view
  428. if(state.battleGetOwner(unit) != playerID)
  429. bav = -bav;
  430. values[unit->unitId()] += bav;
  431. }
  432. firstRound = false;
  433. if(stop)
  434. break;
  435. }
  436. if(enemyHadTurnOut)
  437. *enemyHadTurnOut = enemyHadTurn;
  438. return ourTurnSpan >= minTurnSpan;
  439. };
  440. ValueMap valueOfStack;
  441. ValueMap healthOfStack;
  442. TStacks all = cb->battleGetAllStacks(false);
  443. size_t ourRemainingTurns = 0;
  444. for(auto unit : all)
  445. {
  446. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  447. valueOfStack[unit->unitId()] = 0;
  448. if(cb->battleGetOwner(unit) == playerID && unit->canMove() && !unit->moved())
  449. ourRemainingTurns++;
  450. }
  451. LOGFL("I have %d turns left in this round", ourRemainingTurns);
  452. const bool castNow = ourRemainingTurns <= 1;
  453. if(castNow)
  454. print("I should try to cast a spell now");
  455. else
  456. print("I could wait better moment to cast a spell");
  457. auto amount = all.size();
  458. std::vector<battle::Units> turnOrder;
  459. cb->battleGetTurnOrder(turnOrder, amount, 2); //no more than 1 turn after current, each unit at least once
  460. {
  461. bool enemyHadTurn = false;
  462. HypotheticBattle state(env.get(), cb);
  463. evaluateQueue(valueOfStack, turnOrder, state, 0, &enemyHadTurn);
  464. if(!enemyHadTurn)
  465. {
  466. auto battleIsFinishedOpt = state.battleIsFinished();
  467. if(battleIsFinishedOpt)
  468. {
  469. print("No need to cast a spell. Battle will finish soon.");
  470. return;
  471. }
  472. }
  473. }
  474. struct ScriptsCache
  475. {
  476. //todo: re-implement scripts context cache
  477. };
  478. auto evaluateSpellcast = [&] (PossibleSpellcast * ps, std::shared_ptr<ScriptsCache>)
  479. {
  480. HypotheticBattle state(env.get(), cb);
  481. spells::BattleCast cast(&state, hero, spells::Mode::HERO, ps->spell);
  482. cast.castEval(state.getServerCallback(), ps->dest);
  483. ValueMap newHealthOfStack;
  484. ValueMap newValueOfStack;
  485. size_t ourUnits = 0;
  486. for(auto unit : all)
  487. {
  488. auto unitId = unit->unitId();
  489. auto localUnit = state.battleGetUnitByID(unitId);
  490. newHealthOfStack[unitId] = localUnit->getAvailableHealth();
  491. newValueOfStack[unitId] = 0;
  492. if(state.battleGetOwner(localUnit) == playerID && localUnit->alive() && localUnit->willMove())
  493. ourUnits++;
  494. }
  495. size_t minTurnSpan = ourUnits/3; //todo: tweak this
  496. std::vector<battle::Units> newTurnOrder;
  497. state.battleGetTurnOrder(newTurnOrder, amount, 2);
  498. const bool turnSpanOK = evaluateQueue(newValueOfStack, newTurnOrder, state, minTurnSpan, nullptr);
  499. if(turnSpanOK || castNow)
  500. {
  501. int64_t totalGain = 0;
  502. for(auto unit : all)
  503. {
  504. auto unitId = unit->unitId();
  505. auto localUnit = state.battleGetUnitByID(unitId);
  506. auto newValue = getValOr(newValueOfStack, unitId, 0);
  507. auto oldValue = getValOr(valueOfStack, unitId, 0);
  508. auto healthDiff = newHealthOfStack[unitId] - healthOfStack[unitId];
  509. if(localUnit->unitOwner() != playerID)
  510. healthDiff = -healthDiff;
  511. if(healthDiff < 0)
  512. {
  513. ps->value = -1;
  514. return; //do not damage own units at all
  515. }
  516. totalGain += (newValue - oldValue + healthDiff);
  517. }
  518. ps->value = totalGain;
  519. }
  520. else
  521. {
  522. ps->value = -1;
  523. }
  524. };
  525. using EvalRunner = ThreadPool<ScriptsCache>;
  526. EvalRunner::Tasks tasks;
  527. for(PossibleSpellcast & psc : possibleCasts)
  528. tasks.push_back(std::bind(evaluateSpellcast, &psc, _1));
  529. uint32_t threadCount = boost::thread::hardware_concurrency();
  530. if(threadCount == 0)
  531. {
  532. logGlobal->warn("No information of CPU cores available");
  533. threadCount = 1;
  534. }
  535. CStopWatch timer;
  536. std::vector<std::shared_ptr<ScriptsCache>> scriptsPool;
  537. for(uint32_t idx = 0; idx < threadCount; idx++)
  538. {
  539. scriptsPool.emplace_back();
  540. }
  541. EvalRunner runner(&tasks, scriptsPool);
  542. runner.run();
  543. LOGFL("Evaluation took %d ms", timer.getDiff());
  544. auto pscValue = [](const PossibleSpellcast &ps) -> int64_t
  545. {
  546. return ps.value;
  547. };
  548. auto castToPerform = *vstd::maxElementByFun(possibleCasts, pscValue);
  549. if(castToPerform.value > 0)
  550. {
  551. LOGFL("Best spell is %s (value %d). Will cast.", castToPerform.spell->name % castToPerform.value);
  552. BattleAction spellcast;
  553. spellcast.actionType = EActionType::HERO_SPELL;
  554. spellcast.actionSubtype = castToPerform.spell->id;
  555. spellcast.setTarget(castToPerform.dest);
  556. spellcast.side = side;
  557. spellcast.stackNumber = (!side) ? -1 : -2;
  558. cb->battleMakeAction(&spellcast);
  559. }
  560. else
  561. {
  562. LOGFL("Best spell is %s. But it is actually useless (value %d).", castToPerform.spell->name % castToPerform.value);
  563. }
  564. }
  565. //Below method works only for offensive spells
  566. void CBattleAI::evaluateCreatureSpellcast(const CStack * stack, PossibleSpellcast & ps)
  567. {
  568. using ValueMap = PossibleSpellcast::ValueMap;
  569. RNGStub rngStub;
  570. HypotheticBattle state(env.get(), cb);
  571. TStacks all = cb->battleGetAllStacks(false);
  572. ValueMap healthOfStack;
  573. ValueMap newHealthOfStack;
  574. for(auto unit : all)
  575. {
  576. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  577. }
  578. spells::BattleCast cast(&state, stack, spells::Mode::CREATURE_ACTIVE, ps.spell);
  579. cast.castEval(state.getServerCallback(), ps.dest);
  580. for(auto unit : all)
  581. {
  582. auto unitId = unit->unitId();
  583. auto localUnit = state.battleGetUnitByID(unitId);
  584. newHealthOfStack[unitId] = localUnit->getAvailableHealth();
  585. }
  586. int64_t totalGain = 0;
  587. for(auto unit : all)
  588. {
  589. auto unitId = unit->unitId();
  590. auto localUnit = state.battleGetUnitByID(unitId);
  591. auto healthDiff = newHealthOfStack[unitId] - healthOfStack[unitId];
  592. if(localUnit->unitOwner() != getCbc()->getPlayerID())
  593. healthDiff = -healthDiff;
  594. if(healthDiff < 0)
  595. {
  596. ps.value = -1;
  597. return; //do not damage own units at all
  598. }
  599. totalGain += healthDiff;
  600. }
  601. ps.value = totalGain;
  602. }
  603. void CBattleAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool Side)
  604. {
  605. LOG_TRACE(logAi);
  606. side = Side;
  607. }
  608. void CBattleAI::print(const std::string &text) const
  609. {
  610. logAi->trace("%s Battle AI[%p]: %s", playerID.getStr(), this, text);
  611. }
  612. boost::optional<BattleAction> CBattleAI::considerFleeingOrSurrendering()
  613. {
  614. BattleStateInfoForRetreat bs;
  615. bs.canFlee = cb->battleCanFlee();
  616. bs.canSurrender = cb->battleCanSurrender(playerID);
  617. bs.ourSide = cb->battleGetMySide();
  618. bs.ourHero = cb->battleGetMyHero();
  619. bs.enemyHero = nullptr;
  620. for(auto stack : cb->battleGetAllStacks(false))
  621. {
  622. if(stack->alive())
  623. {
  624. if(stack->side == bs.ourSide)
  625. bs.ourStacks.push_back(stack);
  626. else
  627. {
  628. bs.enemyStacks.push_back(stack);
  629. bs.enemyHero = cb->battleGetOwnerHero(stack);
  630. }
  631. }
  632. }
  633. if(!bs.canFlee || !bs.canSurrender)
  634. {
  635. return boost::none;
  636. }
  637. return cb->makeSurrenderRetreatDecision(bs);
  638. }