BattleEvaluator.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  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 "BattleEvaluator.h"
  12. #include "BattleExchangeVariant.h"
  13. #include "StackWithBonuses.h"
  14. #include "EnemyInfo.h"
  15. #include "tbb/parallel_for.h"
  16. #include "../../lib/CStopWatch.h"
  17. #include "../../lib/CThreadHelper.h"
  18. #include "../../lib/mapObjects/CGTownInstance.h"
  19. #include "../../lib/spells/CSpellHandler.h"
  20. #include "../../lib/spells/ISpellMechanics.h"
  21. #include "../../lib/battle/BattleStateInfoForRetreat.h"
  22. #include "../../lib/battle/CObstacleInstance.h"
  23. #include "../../lib/battle/BattleAction.h"
  24. // TODO: remove
  25. // Eventually only IBattleInfoCallback and battle::Unit should be used,
  26. // CUnitState should be private and CStack should be removed completely
  27. #include "../../lib/CStack.h"
  28. #define LOGL(text) print(text)
  29. #define LOGFL(text, formattingEl) print(boost::str(boost::format(text) % formattingEl))
  30. enum class SpellTypes
  31. {
  32. ADVENTURE, BATTLE, OTHER
  33. };
  34. SpellTypes spellType(const CSpell * spell)
  35. {
  36. if(!spell->isCombat() || spell->isCreatureAbility())
  37. return SpellTypes::OTHER;
  38. if(spell->isOffensive() || spell->hasEffects() || spell->hasBattleEffects())
  39. return SpellTypes::BATTLE;
  40. return SpellTypes::OTHER;
  41. }
  42. std::vector<BattleHex> BattleEvaluator::getBrokenWallMoatHexes() const
  43. {
  44. std::vector<BattleHex> result;
  45. for(EWallPart wallPart : { EWallPart::BOTTOM_WALL, EWallPart::BELOW_GATE, EWallPart::OVER_GATE, EWallPart::UPPER_WALL })
  46. {
  47. auto state = cb->getBattle(battleID)->battleGetWallState(wallPart);
  48. if(state != EWallState::DESTROYED)
  49. continue;
  50. auto wallHex = cb->getBattle(battleID)->wallPartToBattleHex((EWallPart)wallPart);
  51. auto moatHex = wallHex.cloneInDirection(BattleHex::LEFT);
  52. result.push_back(moatHex);
  53. }
  54. return result;
  55. }
  56. std::optional<PossibleSpellcast> BattleEvaluator::findBestCreatureSpell(const CStack *stack)
  57. {
  58. //TODO: faerie dragon type spell should be selected by server
  59. SpellID creatureSpellToCast = cb->getBattle(battleID)->battleGetRandomStackSpell(CRandomGenerator::getDefault(), stack, CBattleInfoCallback::RANDOM_AIMED);
  60. if(stack->hasBonusOfType(BonusType::SPELLCASTER) && stack->canCast() && creatureSpellToCast != SpellID::NONE)
  61. {
  62. const CSpell * spell = creatureSpellToCast.toSpell();
  63. if(spell->canBeCast(cb->getBattle(battleID).get(), spells::Mode::CREATURE_ACTIVE, stack))
  64. {
  65. std::vector<PossibleSpellcast> possibleCasts;
  66. spells::BattleCast temp(cb->getBattle(battleID).get(), stack, spells::Mode::CREATURE_ACTIVE, spell);
  67. for(auto & target : temp.findPotentialTargets())
  68. {
  69. PossibleSpellcast ps;
  70. ps.dest = target;
  71. ps.spell = spell;
  72. evaluateCreatureSpellcast(stack, ps);
  73. possibleCasts.push_back(ps);
  74. }
  75. std::sort(possibleCasts.begin(), possibleCasts.end(), [&](const PossibleSpellcast & lhs, const PossibleSpellcast & rhs) { return lhs.value > rhs.value; });
  76. if(!possibleCasts.empty() && possibleCasts.front().value > 0)
  77. {
  78. return possibleCasts.front();
  79. }
  80. }
  81. }
  82. return std::nullopt;
  83. }
  84. BattleAction BattleEvaluator::selectStackAction(const CStack * stack)
  85. {
  86. #if BATTLE_TRACE_LEVEL >= 1
  87. logAi->trace("Select stack action");
  88. #endif
  89. //evaluate casting spell for spellcasting stack
  90. std::optional<PossibleSpellcast> bestSpellcast = findBestCreatureSpell(stack);
  91. auto moveTarget = scoreEvaluator.findMoveTowardsUnreachable(stack, *targets, damageCache, hb);
  92. float score = EvaluationResult::INEFFECTIVE_SCORE;
  93. if(targets->possibleAttacks.empty() && bestSpellcast.has_value())
  94. {
  95. activeActionMade = true;
  96. return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
  97. }
  98. if(!targets->possibleAttacks.empty())
  99. {
  100. #if BATTLE_TRACE_LEVEL>=1
  101. logAi->trace("Evaluating attack for %s", stack->getDescription());
  102. #endif
  103. auto evaluationResult = scoreEvaluator.findBestTarget(stack, *targets, damageCache, hb);
  104. auto & bestAttack = evaluationResult.bestAttack;
  105. cachedAttack = bestAttack;
  106. cachedScore = evaluationResult.score;
  107. //TODO: consider more complex spellcast evaluation, f.e. because "re-retaliation" during enemy move in same turn for melee attack etc.
  108. if(bestSpellcast.has_value() && bestSpellcast->value > bestAttack.damageDiff())
  109. {
  110. // return because spellcast value is damage dealt and score is dps reduce
  111. activeActionMade = true;
  112. return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
  113. }
  114. if(evaluationResult.score > score)
  115. {
  116. score = evaluationResult.score;
  117. logAi->debug("BattleAI: %s -> %s x %d, from %d curpos %d dist %d speed %d: +%2f -%2f = %2f",
  118. bestAttack.attackerState->unitType()->getJsonKey(),
  119. bestAttack.affectedUnits[0]->unitType()->getJsonKey(),
  120. (int)bestAttack.affectedUnits[0]->getCount(),
  121. (int)bestAttack.from,
  122. (int)bestAttack.attack.attacker->getPosition().hex,
  123. bestAttack.attack.chargeDistance,
  124. bestAttack.attack.attacker->speed(0, true),
  125. bestAttack.defenderDamageReduce,
  126. bestAttack.attackerDamageReduce,
  127. bestAttack.attackValue()
  128. );
  129. if (moveTarget.scorePerTurn <= score)
  130. {
  131. if(evaluationResult.wait)
  132. {
  133. return BattleAction::makeWait(stack);
  134. }
  135. else if(bestAttack.attack.shooting)
  136. {
  137. activeActionMade = true;
  138. return BattleAction::makeShotAttack(stack, bestAttack.attack.defender);
  139. }
  140. else
  141. {
  142. if(bestAttack.collateralDamageReduce
  143. && bestAttack.collateralDamageReduce >= bestAttack.defenderDamageReduce / 2
  144. && score < 0)
  145. {
  146. return BattleAction::makeDefend(stack);
  147. }
  148. else
  149. {
  150. activeActionMade = true;
  151. return BattleAction::makeMeleeAttack(stack, bestAttack.attack.defender->getPosition(), bestAttack.from);
  152. }
  153. }
  154. }
  155. }
  156. }
  157. //ThreatMap threatsToUs(stack); // These lines may be usefull but they are't used in the code.
  158. if(moveTarget.scorePerTurn > score)
  159. {
  160. score = moveTarget.score;
  161. cachedAttack = moveTarget.cachedAttack;
  162. cachedScore = score;
  163. if(stack->waited())
  164. {
  165. return goTowardsNearest(stack, moveTarget.positions);
  166. }
  167. else
  168. {
  169. return BattleAction::makeWait(stack);
  170. }
  171. }
  172. if(score <= EvaluationResult::INEFFECTIVE_SCORE
  173. && !stack->hasBonusOfType(BonusType::FLYING)
  174. && stack->unitSide() == BattleSide::ATTACKER
  175. && cb->getBattle(battleID)->battleGetSiegeLevel() >= CGTownInstance::CITADEL)
  176. {
  177. auto brokenWallMoat = getBrokenWallMoatHexes();
  178. if(brokenWallMoat.size())
  179. {
  180. activeActionMade = true;
  181. if(stack->doubleWide() && vstd::contains(brokenWallMoat, stack->getPosition()))
  182. return BattleAction::makeMove(stack, stack->getPosition().cloneInDirection(BattleHex::RIGHT));
  183. else
  184. return goTowardsNearest(stack, brokenWallMoat);
  185. }
  186. }
  187. return BattleAction::makeDefend(stack);
  188. }
  189. uint64_t timeElapsed(std::chrono::time_point<std::chrono::high_resolution_clock> start)
  190. {
  191. auto end = std::chrono::high_resolution_clock::now();
  192. return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
  193. }
  194. BattleAction BattleEvaluator::goTowardsNearest(const CStack * stack, std::vector<BattleHex> hexes)
  195. {
  196. auto reachability = cb->getBattle(battleID)->getReachability(stack);
  197. auto avHexes = cb->getBattle(battleID)->battleGetAvailableHexes(reachability, stack, false);
  198. if(!avHexes.size() || !hexes.size()) //we are blocked or dest is blocked
  199. {
  200. return BattleAction::makeDefend(stack);
  201. }
  202. std::sort(hexes.begin(), hexes.end(), [&](BattleHex h1, BattleHex h2) -> bool
  203. {
  204. return reachability.distances[h1] < reachability.distances[h2];
  205. });
  206. for(auto hex : hexes)
  207. {
  208. if(vstd::contains(avHexes, hex))
  209. {
  210. return BattleAction::makeMove(stack, hex);
  211. }
  212. if(stack->coversPos(hex))
  213. {
  214. logAi->warn("Warning: already standing on neighbouring tile!");
  215. //We shouldn't even be here...
  216. return BattleAction::makeDefend(stack);
  217. }
  218. }
  219. BattleHex bestNeighbor = hexes.front();
  220. if(reachability.distances[bestNeighbor] > GameConstants::BFIELD_SIZE)
  221. {
  222. return BattleAction::makeDefend(stack);
  223. }
  224. scoreEvaluator.updateReachabilityMap(hb);
  225. if(stack->hasBonusOfType(BonusType::FLYING))
  226. {
  227. std::set<BattleHex> obstacleHexes;
  228. auto insertAffected = [](const CObstacleInstance & spellObst, std::set<BattleHex> obstacleHexes) {
  229. auto affectedHexes = spellObst.getAffectedTiles();
  230. obstacleHexes.insert(affectedHexes.cbegin(), affectedHexes.cend());
  231. };
  232. const auto & obstacles = hb->battleGetAllObstacles();
  233. for (const auto & obst: obstacles) {
  234. if(obst->triggersEffects())
  235. {
  236. auto triggerAbility = VLC->spells()->getById(obst->getTrigger());
  237. auto triggerIsNegative = triggerAbility->isNegative() || triggerAbility->isDamage();
  238. if(triggerIsNegative)
  239. insertAffected(*obst, obstacleHexes);
  240. }
  241. }
  242. // Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
  243. // We just check all available hexes and pick the one closest to the target.
  244. auto nearestAvailableHex = vstd::minElementByFun(avHexes, [&](BattleHex hex) -> int
  245. {
  246. const int NEGATIVE_OBSTACLE_PENALTY = 100; // avoid landing on negative obstacle (moat, fire wall, etc)
  247. const int BLOCKED_STACK_PENALTY = 100; // avoid landing on moat
  248. auto distance = BattleHex::getDistance(bestNeighbor, hex);
  249. if(vstd::contains(obstacleHexes, hex))
  250. distance += NEGATIVE_OBSTACLE_PENALTY;
  251. return scoreEvaluator.checkPositionBlocksOurStacks(*hb, stack, hex) ? BLOCKED_STACK_PENALTY + distance : distance;
  252. });
  253. return BattleAction::makeMove(stack, *nearestAvailableHex);
  254. }
  255. else
  256. {
  257. BattleHex currentDest = bestNeighbor;
  258. while(1)
  259. {
  260. if(!currentDest.isValid())
  261. {
  262. return BattleAction::makeDefend(stack);
  263. }
  264. if(vstd::contains(avHexes, currentDest)
  265. && !scoreEvaluator.checkPositionBlocksOurStacks(*hb, stack, currentDest))
  266. return BattleAction::makeMove(stack, currentDest);
  267. currentDest = reachability.predecessors[currentDest];
  268. }
  269. }
  270. }
  271. bool BattleEvaluator::canCastSpell()
  272. {
  273. auto hero = cb->getBattle(battleID)->battleGetMyHero();
  274. if(!hero)
  275. return false;
  276. return cb->getBattle(battleID)->battleCanCastSpell(hero, spells::Mode::HERO) == ESpellCastProblem::OK;
  277. }
  278. bool BattleEvaluator::attemptCastingSpell(const CStack * activeStack)
  279. {
  280. auto hero = cb->getBattle(battleID)->battleGetMyHero();
  281. if(!hero)
  282. return false;
  283. LOGL("Casting spells sounds like fun. Let's see...");
  284. //Get all spells we can cast
  285. std::vector<const CSpell*> possibleSpells;
  286. vstd::copy_if(VLC->spellh->objects, std::back_inserter(possibleSpells), [hero, this](const CSpell *s) -> bool
  287. {
  288. return s->canBeCast(cb->getBattle(battleID).get(), spells::Mode::HERO, hero);
  289. });
  290. LOGFL("I can cast %d spells.", possibleSpells.size());
  291. vstd::erase_if(possibleSpells, [](const CSpell *s)
  292. {
  293. return spellType(s) != SpellTypes::BATTLE || s->getTargetType() == spells::AimType::LOCATION;
  294. });
  295. LOGFL("I know how %d of them works.", possibleSpells.size());
  296. //Get possible spell-target pairs
  297. std::vector<PossibleSpellcast> possibleCasts;
  298. for(auto spell : possibleSpells)
  299. {
  300. spells::BattleCast temp(cb->getBattle(battleID).get(), hero, spells::Mode::HERO, spell);
  301. if(spell->getTargetType() == spells::AimType::LOCATION)
  302. continue;
  303. const bool FAST = true;
  304. for(auto & target : temp.findPotentialTargets(FAST))
  305. {
  306. PossibleSpellcast ps;
  307. ps.dest = target;
  308. ps.spell = spell;
  309. possibleCasts.push_back(ps);
  310. }
  311. }
  312. LOGFL("Found %d spell-target combinations.", possibleCasts.size());
  313. if(possibleCasts.empty())
  314. return false;
  315. using ValueMap = PossibleSpellcast::ValueMap;
  316. auto evaluateQueue = [&](ValueMap & values, const std::vector<battle::Units> & queue, std::shared_ptr<HypotheticBattle> state, size_t minTurnSpan, bool * enemyHadTurnOut) -> bool
  317. {
  318. bool firstRound = true;
  319. bool enemyHadTurn = false;
  320. size_t ourTurnSpan = 0;
  321. bool stop = false;
  322. for(auto & round : queue)
  323. {
  324. if(!firstRound)
  325. state->nextRound();
  326. for(auto unit : round)
  327. {
  328. if(!vstd::contains(values, unit->unitId()))
  329. values[unit->unitId()] = 0;
  330. if(!unit->alive())
  331. continue;
  332. if(state->battleGetOwner(unit) != playerID)
  333. {
  334. enemyHadTurn = true;
  335. if(!firstRound || state->battleCastSpells(unit->unitSide()) == 0)
  336. {
  337. //enemy could counter our spell at this point
  338. //anyway, we do not know what enemy will do
  339. //just stop evaluation
  340. stop = true;
  341. break;
  342. }
  343. }
  344. else if(!enemyHadTurn)
  345. {
  346. ourTurnSpan++;
  347. }
  348. state->nextTurn(unit->unitId());
  349. PotentialTargets pt(unit, damageCache, state);
  350. if(!pt.possibleAttacks.empty())
  351. {
  352. AttackPossibility ap = pt.bestAction();
  353. auto swb = state->getForUpdate(unit->unitId());
  354. *swb = *ap.attackerState;
  355. if(ap.defenderDamageReduce > 0)
  356. swb->removeUnitBonus(Bonus::UntilAttack);
  357. if(ap.attackerDamageReduce > 0)
  358. swb->removeUnitBonus(Bonus::UntilBeingAttacked);
  359. for(auto affected : ap.affectedUnits)
  360. {
  361. swb = state->getForUpdate(affected->unitId());
  362. *swb = *affected;
  363. if(ap.defenderDamageReduce > 0)
  364. swb->removeUnitBonus(Bonus::UntilBeingAttacked);
  365. if(ap.attackerDamageReduce > 0 && ap.attack.defender->unitId() == affected->unitId())
  366. swb->removeUnitBonus(Bonus::UntilAttack);
  367. }
  368. }
  369. auto bav = pt.bestActionValue();
  370. //best action is from effective owner`s point if view, we need to convert to our point if view
  371. if(state->battleGetOwner(unit) != playerID)
  372. bav = -bav;
  373. values[unit->unitId()] += bav;
  374. }
  375. firstRound = false;
  376. if(stop)
  377. break;
  378. }
  379. if(enemyHadTurnOut)
  380. *enemyHadTurnOut = enemyHadTurn;
  381. return ourTurnSpan >= minTurnSpan;
  382. };
  383. ValueMap valueOfStack;
  384. ValueMap healthOfStack;
  385. TStacks all = cb->getBattle(battleID)->battleGetAllStacks(false);
  386. size_t ourRemainingTurns = 0;
  387. for(auto unit : all)
  388. {
  389. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  390. valueOfStack[unit->unitId()] = 0;
  391. if(cb->getBattle(battleID)->battleGetOwner(unit) == playerID && unit->canMove() && !unit->moved())
  392. ourRemainingTurns++;
  393. }
  394. LOGFL("I have %d turns left in this round", ourRemainingTurns);
  395. const bool castNow = ourRemainingTurns <= 1;
  396. if(castNow)
  397. print("I should try to cast a spell now");
  398. else
  399. print("I could wait better moment to cast a spell");
  400. auto amount = all.size();
  401. std::vector<battle::Units> turnOrder;
  402. cb->getBattle(battleID)->battleGetTurnOrder(turnOrder, amount, 2); //no more than 1 turn after current, each unit at least once
  403. {
  404. bool enemyHadTurn = false;
  405. auto state = std::make_shared<HypotheticBattle>(env.get(), cb->getBattle(battleID));
  406. evaluateQueue(valueOfStack, turnOrder, state, 0, &enemyHadTurn);
  407. if(!enemyHadTurn)
  408. {
  409. auto battleIsFinishedOpt = state->battleIsFinished();
  410. if(battleIsFinishedOpt)
  411. {
  412. print("No need to cast a spell. Battle will finish soon.");
  413. return false;
  414. }
  415. }
  416. }
  417. CStopWatch timer;
  418. #if BATTLE_TRACE_LEVEL >= 1
  419. tbb::blocked_range<size_t> r(0, possibleCasts.size());
  420. #else
  421. tbb::parallel_for(tbb::blocked_range<size_t>(0, possibleCasts.size()), [&](const tbb::blocked_range<size_t> & r)
  422. {
  423. #endif
  424. for(auto i = r.begin(); i != r.end(); i++)
  425. {
  426. auto & ps = possibleCasts[i];
  427. #if BATTLE_TRACE_LEVEL >= 1
  428. logAi->trace("Evaluating %s", ps.spell->getNameTranslated());
  429. #endif
  430. auto state = std::make_shared<HypotheticBattle>(env.get(), cb->getBattle(battleID));
  431. spells::BattleCast cast(state.get(), hero, spells::Mode::HERO, ps.spell);
  432. cast.castEval(state->getServerCallback(), ps.dest);
  433. auto allUnits = state->battleGetUnitsIf([](const battle::Unit * u) -> bool { return true; });
  434. auto needFullEval = vstd::contains_if(allUnits, [&](const battle::Unit * u) -> bool
  435. {
  436. auto original = cb->getBattle(battleID)->battleGetUnitByID(u->unitId());
  437. return !original || u->speed() != original->speed();
  438. });
  439. DamageCache safeCopy = damageCache;
  440. DamageCache innerCache(&safeCopy);
  441. innerCache.buildDamageCache(state, side);
  442. if(needFullEval || !cachedAttack)
  443. {
  444. #if BATTLE_TRACE_LEVEL >= 1
  445. logAi->trace("Full evaluation is started due to stack speed affected.");
  446. #endif
  447. PotentialTargets innerTargets(activeStack, innerCache, state);
  448. BattleExchangeEvaluator innerEvaluator(state, env, strengthRatio);
  449. if(!innerTargets.possibleAttacks.empty())
  450. {
  451. innerEvaluator.updateReachabilityMap(state);
  452. auto newStackAction = innerEvaluator.findBestTarget(activeStack, innerTargets, innerCache, state);
  453. ps.value = newStackAction.score;
  454. }
  455. else
  456. {
  457. ps.value = 0;
  458. }
  459. }
  460. else
  461. {
  462. ps.value = scoreEvaluator.calculateExchange(*cachedAttack, *targets, innerCache, state);
  463. }
  464. for(auto unit : allUnits)
  465. {
  466. auto newHealth = unit->getAvailableHealth();
  467. auto oldHealth = healthOfStack[unit->unitId()];
  468. if(oldHealth != newHealth)
  469. {
  470. auto damage = std::abs(oldHealth - newHealth);
  471. auto originalDefender = cb->getBattle(battleID)->battleGetUnitByID(unit->unitId());
  472. auto dpsReduce = AttackPossibility::calculateDamageReduce(
  473. nullptr,
  474. originalDefender && originalDefender->alive() ? originalDefender : unit,
  475. damage,
  476. innerCache,
  477. state);
  478. auto ourUnit = unit->unitSide() == side ? 1 : -1;
  479. auto goodEffect = newHealth > oldHealth ? 1 : -1;
  480. if(ourUnit * goodEffect == 1)
  481. {
  482. if(ourUnit && goodEffect && (unit->isClone() || unit->isGhost() || !unit->unitSlot().validSlot()))
  483. continue;
  484. ps.value += dpsReduce * scoreEvaluator.getPositiveEffectMultiplier();
  485. }
  486. else
  487. ps.value -= dpsReduce * scoreEvaluator.getNegativeEffectMultiplier();
  488. #if BATTLE_TRACE_LEVEL >= 1
  489. logAi->trace(
  490. "Spell affects %s (%d), dps: %2f",
  491. unit->creatureId().toCreature()->getNameSingularTranslated(),
  492. unit->getCount(),
  493. dpsReduce);
  494. #endif
  495. }
  496. }
  497. #if BATTLE_TRACE_LEVEL >= 1
  498. logAi->trace("Total score: %2f", ps.value);
  499. #endif
  500. }
  501. #if BATTLE_TRACE_LEVEL == 0
  502. });
  503. #endif
  504. LOGFL("Evaluation took %d ms", timer.getDiff());
  505. auto pscValue = [](const PossibleSpellcast &ps) -> float
  506. {
  507. return ps.value;
  508. };
  509. auto castToPerform = *vstd::maxElementByFun(possibleCasts, pscValue);
  510. if(castToPerform.value > cachedScore)
  511. {
  512. LOGFL("Best spell is %s (value %d). Will cast.", castToPerform.spell->getNameTranslated() % castToPerform.value);
  513. BattleAction spellcast;
  514. spellcast.actionType = EActionType::HERO_SPELL;
  515. spellcast.spell = castToPerform.spell->id;
  516. spellcast.setTarget(castToPerform.dest);
  517. spellcast.side = side;
  518. spellcast.stackNumber = (!side) ? -1 : -2;
  519. cb->battleMakeSpellAction(battleID, spellcast);
  520. activeActionMade = true;
  521. return true;
  522. }
  523. LOGFL("Best spell is %s. But it is actually useless (value %d).", castToPerform.spell->getNameTranslated() % castToPerform.value);
  524. return false;
  525. }
  526. //Below method works only for offensive spells
  527. void BattleEvaluator::evaluateCreatureSpellcast(const CStack * stack, PossibleSpellcast & ps)
  528. {
  529. using ValueMap = PossibleSpellcast::ValueMap;
  530. RNGStub rngStub;
  531. HypotheticBattle state(env.get(), cb->getBattle(battleID));
  532. TStacks all = cb->getBattle(battleID)->battleGetAllStacks(false);
  533. ValueMap healthOfStack;
  534. ValueMap newHealthOfStack;
  535. for(auto unit : all)
  536. {
  537. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  538. }
  539. spells::BattleCast cast(&state, stack, spells::Mode::CREATURE_ACTIVE, ps.spell);
  540. cast.castEval(state.getServerCallback(), ps.dest);
  541. for(auto unit : all)
  542. {
  543. auto unitId = unit->unitId();
  544. auto localUnit = state.battleGetUnitByID(unitId);
  545. newHealthOfStack[unitId] = localUnit->getAvailableHealth();
  546. }
  547. int64_t totalGain = 0;
  548. for(auto unit : all)
  549. {
  550. auto unitId = unit->unitId();
  551. auto localUnit = state.battleGetUnitByID(unitId);
  552. auto healthDiff = newHealthOfStack[unitId] - healthOfStack[unitId];
  553. if(localUnit->unitOwner() != cb->getBattle(battleID)->getPlayerID())
  554. healthDiff = -healthDiff;
  555. if(healthDiff < 0)
  556. {
  557. ps.value = -1;
  558. return; //do not damage own units at all
  559. }
  560. totalGain += healthDiff;
  561. }
  562. ps.value = totalGain;
  563. }
  564. void BattleEvaluator::print(const std::string & text) const
  565. {
  566. logAi->trace("%s Battle AI[%p]: %s", playerID.toString(), this, text);
  567. }