BattleAI.cpp 22 KB

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