BattleEvaluator.cpp 21 KB

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