BattleEvaluator.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  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(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)->getRandomCastedSpell(CRandomGenerator::getDefault(), stack);
  60. if(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. bestAttack.affectedUnits[0]->getCount(),
  121. (int)bestAttack.from,
  122. (int)bestAttack.attack.attacker->getPosition().hex,
  123. bestAttack.attack.chargeDistance,
  124. bestAttack.attack.attacker->getMovementRange(0),
  125. bestAttack.defenderDamageReduce,
  126. bestAttack.attackerDamageReduce,
  127. score
  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. logAi->debug(
  166. "Moving %s towards hex %s[%d], score: %2f/%2f",
  167. stack->getDescription(),
  168. moveTarget.cachedAttack->attack.defender->getDescription(),
  169. moveTarget.cachedAttack->attack.defender->getPosition().hex,
  170. moveTarget.score,
  171. moveTarget.scorePerTurn);
  172. return goTowardsNearest(stack, moveTarget.positions);
  173. }
  174. else
  175. {
  176. return BattleAction::makeWait(stack);
  177. }
  178. }
  179. if(score <= EvaluationResult::INEFFECTIVE_SCORE
  180. && !stack->hasBonusOfType(BonusType::FLYING)
  181. && stack->unitSide() == BattleSide::ATTACKER
  182. && cb->getBattle(battleID)->battleGetSiegeLevel() >= CGTownInstance::CITADEL)
  183. {
  184. auto brokenWallMoat = getBrokenWallMoatHexes();
  185. if(brokenWallMoat.size())
  186. {
  187. activeActionMade = true;
  188. if(stack->doubleWide() && vstd::contains(brokenWallMoat, stack->getPosition()))
  189. return BattleAction::makeMove(stack, stack->getPosition().cloneInDirection(BattleHex::RIGHT));
  190. else
  191. return goTowardsNearest(stack, brokenWallMoat);
  192. }
  193. }
  194. return stack->waited() ? BattleAction::makeDefend(stack) : BattleAction::makeWait(stack);
  195. }
  196. uint64_t timeElapsed(std::chrono::time_point<std::chrono::high_resolution_clock> start)
  197. {
  198. auto end = std::chrono::high_resolution_clock::now();
  199. return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
  200. }
  201. BattleAction BattleEvaluator::goTowardsNearest(const CStack * stack, std::vector<BattleHex> hexes)
  202. {
  203. auto reachability = cb->getBattle(battleID)->getReachability(stack);
  204. auto avHexes = cb->getBattle(battleID)->battleGetAvailableHexes(reachability, stack, false);
  205. if(!avHexes.size() || !hexes.size()) //we are blocked or dest is blocked
  206. {
  207. return BattleAction::makeDefend(stack);
  208. }
  209. std::sort(hexes.begin(), hexes.end(), [&](BattleHex h1, BattleHex h2) -> bool
  210. {
  211. return reachability.distances[h1] < reachability.distances[h2];
  212. });
  213. for(auto hex : hexes)
  214. {
  215. if(vstd::contains(avHexes, hex))
  216. {
  217. return BattleAction::makeMove(stack, hex);
  218. }
  219. if(stack->coversPos(hex))
  220. {
  221. logAi->warn("Warning: already standing on neighbouring tile!");
  222. //We shouldn't even be here...
  223. return BattleAction::makeDefend(stack);
  224. }
  225. }
  226. BattleHex bestNeighbor = hexes.front();
  227. if(reachability.distances[bestNeighbor] > GameConstants::BFIELD_SIZE)
  228. {
  229. return BattleAction::makeDefend(stack);
  230. }
  231. scoreEvaluator.updateReachabilityMap(hb);
  232. if(stack->hasBonusOfType(BonusType::FLYING))
  233. {
  234. std::set<BattleHex> obstacleHexes;
  235. auto insertAffected = [](const CObstacleInstance & spellObst, std::set<BattleHex> obstacleHexes) {
  236. auto affectedHexes = spellObst.getAffectedTiles();
  237. obstacleHexes.insert(affectedHexes.cbegin(), affectedHexes.cend());
  238. };
  239. const auto & obstacles = hb->battleGetAllObstacles();
  240. for (const auto & obst: obstacles) {
  241. if(obst->triggersEffects())
  242. {
  243. auto triggerAbility = VLC->spells()->getById(obst->getTrigger());
  244. auto triggerIsNegative = triggerAbility->isNegative() || triggerAbility->isDamage();
  245. if(triggerIsNegative)
  246. insertAffected(*obst, obstacleHexes);
  247. }
  248. }
  249. // Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
  250. // We just check all available hexes and pick the one closest to the target.
  251. auto nearestAvailableHex = vstd::minElementByFun(avHexes, [&](BattleHex hex) -> int
  252. {
  253. const int NEGATIVE_OBSTACLE_PENALTY = 100; // avoid landing on negative obstacle (moat, fire wall, etc)
  254. const int BLOCKED_STACK_PENALTY = 100; // avoid landing on moat
  255. auto distance = BattleHex::getDistance(bestNeighbor, hex);
  256. if(vstd::contains(obstacleHexes, hex))
  257. distance += NEGATIVE_OBSTACLE_PENALTY;
  258. return scoreEvaluator.checkPositionBlocksOurStacks(*hb, stack, hex) ? BLOCKED_STACK_PENALTY + distance : distance;
  259. });
  260. return BattleAction::makeMove(stack, *nearestAvailableHex);
  261. }
  262. else
  263. {
  264. BattleHex currentDest = bestNeighbor;
  265. while(true)
  266. {
  267. if(!currentDest.isValid())
  268. {
  269. return BattleAction::makeDefend(stack);
  270. }
  271. if(vstd::contains(avHexes, currentDest)
  272. && !scoreEvaluator.checkPositionBlocksOurStacks(*hb, stack, currentDest))
  273. return BattleAction::makeMove(stack, currentDest);
  274. currentDest = reachability.predecessors[currentDest];
  275. }
  276. }
  277. }
  278. bool BattleEvaluator::canCastSpell()
  279. {
  280. auto hero = cb->getBattle(battleID)->battleGetMyHero();
  281. if(!hero)
  282. return false;
  283. return cb->getBattle(battleID)->battleCanCastSpell(hero, spells::Mode::HERO) == ESpellCastProblem::OK;
  284. }
  285. bool BattleEvaluator::attemptCastingSpell(const CStack * activeStack)
  286. {
  287. auto hero = cb->getBattle(battleID)->battleGetMyHero();
  288. if(!hero)
  289. return false;
  290. LOGL("Casting spells sounds like fun. Let's see...");
  291. //Get all spells we can cast
  292. std::vector<const CSpell*> possibleSpells;
  293. for (auto const & s : VLC->spellh->objects)
  294. if (s->canBeCast(cb->getBattle(battleID).get(), spells::Mode::HERO, hero))
  295. possibleSpells.push_back(s.get());
  296. LOGFL("I can cast %d spells.", possibleSpells.size());
  297. vstd::erase_if(possibleSpells, [](const CSpell *s)
  298. {
  299. return spellType(s) != SpellTypes::BATTLE || s->getTargetType() == spells::AimType::LOCATION;
  300. });
  301. LOGFL("I know how %d of them works.", possibleSpells.size());
  302. //Get possible spell-target pairs
  303. std::vector<PossibleSpellcast> possibleCasts;
  304. for(auto spell : possibleSpells)
  305. {
  306. spells::BattleCast temp(cb->getBattle(battleID).get(), hero, spells::Mode::HERO, spell);
  307. if(spell->getTargetType() == spells::AimType::LOCATION)
  308. continue;
  309. const bool FAST = true;
  310. for(auto & target : temp.findPotentialTargets(FAST))
  311. {
  312. PossibleSpellcast ps;
  313. ps.dest = target;
  314. ps.spell = spell;
  315. possibleCasts.push_back(ps);
  316. }
  317. }
  318. LOGFL("Found %d spell-target combinations.", possibleCasts.size());
  319. if(possibleCasts.empty())
  320. return false;
  321. using ValueMap = PossibleSpellcast::ValueMap;
  322. auto evaluateQueue = [&](ValueMap & values, const std::vector<battle::Units> & queue, std::shared_ptr<HypotheticBattle> state, size_t minTurnSpan, bool * enemyHadTurnOut) -> bool
  323. {
  324. bool firstRound = true;
  325. bool enemyHadTurn = false;
  326. size_t ourTurnSpan = 0;
  327. bool stop = false;
  328. for(auto & round : queue)
  329. {
  330. if(!firstRound)
  331. state->nextRound();
  332. for(auto unit : round)
  333. {
  334. if(!vstd::contains(values, unit->unitId()))
  335. values[unit->unitId()] = 0;
  336. if(!unit->alive())
  337. continue;
  338. if(state->battleGetOwner(unit) != playerID)
  339. {
  340. enemyHadTurn = true;
  341. if(!firstRound || state->battleCastSpells(unit->unitSide()) == 0)
  342. {
  343. //enemy could counter our spell at this point
  344. //anyway, we do not know what enemy will do
  345. //just stop evaluation
  346. stop = true;
  347. break;
  348. }
  349. }
  350. else if(!enemyHadTurn)
  351. {
  352. ourTurnSpan++;
  353. }
  354. state->nextTurn(unit->unitId());
  355. PotentialTargets potentialTargets(unit, damageCache, state);
  356. if(!potentialTargets.possibleAttacks.empty())
  357. {
  358. AttackPossibility attackPossibility = potentialTargets.bestAction();
  359. auto stackWithBonuses = state->getForUpdate(unit->unitId());
  360. *stackWithBonuses = *attackPossibility.attackerState;
  361. if(attackPossibility.defenderDamageReduce > 0)
  362. {
  363. stackWithBonuses->removeUnitBonus(Bonus::UntilAttack);
  364. stackWithBonuses->removeUnitBonus(Bonus::UntilOwnAttack);
  365. }
  366. if(attackPossibility.attackerDamageReduce > 0)
  367. stackWithBonuses->removeUnitBonus(Bonus::UntilBeingAttacked);
  368. for(auto affected : attackPossibility.affectedUnits)
  369. {
  370. stackWithBonuses = state->getForUpdate(affected->unitId());
  371. *stackWithBonuses = *affected;
  372. if(attackPossibility.defenderDamageReduce > 0)
  373. stackWithBonuses->removeUnitBonus(Bonus::UntilBeingAttacked);
  374. if(attackPossibility.attackerDamageReduce > 0 && attackPossibility.attack.defender->unitId() == affected->unitId())
  375. stackWithBonuses->removeUnitBonus(Bonus::UntilAttack);
  376. }
  377. }
  378. auto bav = potentialTargets.bestActionValue();
  379. //best action is from effective owner`s point if view, we need to convert to our point if view
  380. if(state->battleGetOwner(unit) != playerID)
  381. bav = -bav;
  382. values[unit->unitId()] += bav;
  383. }
  384. firstRound = false;
  385. if(stop)
  386. break;
  387. }
  388. if(enemyHadTurnOut)
  389. *enemyHadTurnOut = enemyHadTurn;
  390. return ourTurnSpan >= minTurnSpan;
  391. };
  392. ValueMap valueOfStack;
  393. ValueMap healthOfStack;
  394. TStacks all = cb->getBattle(battleID)->battleGetAllStacks(false);
  395. size_t ourRemainingTurns = 0;
  396. for(auto unit : all)
  397. {
  398. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  399. valueOfStack[unit->unitId()] = 0;
  400. if(cb->getBattle(battleID)->battleGetOwner(unit) == playerID && unit->canMove() && !unit->moved())
  401. ourRemainingTurns++;
  402. }
  403. LOGFL("I have %d turns left in this round", ourRemainingTurns);
  404. const bool castNow = ourRemainingTurns <= 1;
  405. if(castNow)
  406. print("I should try to cast a spell now");
  407. else
  408. print("I could wait better moment to cast a spell");
  409. auto amount = all.size();
  410. std::vector<battle::Units> turnOrder;
  411. cb->getBattle(battleID)->battleGetTurnOrder(turnOrder, amount, 2); //no more than 1 turn after current, each unit at least once
  412. {
  413. bool enemyHadTurn = false;
  414. auto state = std::make_shared<HypotheticBattle>(env.get(), cb->getBattle(battleID));
  415. evaluateQueue(valueOfStack, turnOrder, state, 0, &enemyHadTurn);
  416. if(!enemyHadTurn)
  417. {
  418. auto battleIsFinishedOpt = state->battleIsFinished();
  419. if(battleIsFinishedOpt)
  420. {
  421. print("No need to cast a spell. Battle will finish soon.");
  422. return false;
  423. }
  424. }
  425. }
  426. CStopWatch timer;
  427. #if BATTLE_TRACE_LEVEL >= 1
  428. tbb::blocked_range<size_t> r(0, possibleCasts.size());
  429. #else
  430. tbb::parallel_for(tbb::blocked_range<size_t>(0, possibleCasts.size()), [&](const tbb::blocked_range<size_t> & r)
  431. {
  432. #endif
  433. for(auto i = r.begin(); i != r.end(); i++)
  434. {
  435. auto & ps = possibleCasts[i];
  436. #if BATTLE_TRACE_LEVEL >= 1
  437. logAi->trace("Evaluating %s", ps.spell->getNameTranslated());
  438. #endif
  439. auto state = std::make_shared<HypotheticBattle>(env.get(), cb->getBattle(battleID));
  440. spells::BattleCast cast(state.get(), hero, spells::Mode::HERO, ps.spell);
  441. cast.castEval(state->getServerCallback(), ps.dest);
  442. auto allUnits = state->battleGetUnitsIf([](const battle::Unit * u) -> bool { return true; });
  443. auto needFullEval = vstd::contains_if(allUnits, [&](const battle::Unit * u) -> bool
  444. {
  445. auto original = cb->getBattle(battleID)->battleGetUnitByID(u->unitId());
  446. return !original || u->getMovementRange() != original->getMovementRange();
  447. });
  448. DamageCache safeCopy = damageCache;
  449. DamageCache innerCache(&safeCopy);
  450. innerCache.buildDamageCache(state, side);
  451. if(needFullEval || !cachedAttack)
  452. {
  453. #if BATTLE_TRACE_LEVEL >= 1
  454. logAi->trace("Full evaluation is started due to stack speed affected.");
  455. #endif
  456. PotentialTargets innerTargets(activeStack, innerCache, state);
  457. BattleExchangeEvaluator innerEvaluator(state, env, strengthRatio);
  458. if(!innerTargets.possibleAttacks.empty())
  459. {
  460. innerEvaluator.updateReachabilityMap(state);
  461. auto newStackAction = innerEvaluator.findBestTarget(activeStack, innerTargets, innerCache, state);
  462. ps.value = newStackAction.score;
  463. }
  464. else
  465. {
  466. ps.value = 0;
  467. }
  468. }
  469. else
  470. {
  471. ps.value = scoreEvaluator.evaluateExchange(*cachedAttack, 0, *targets, innerCache, state);
  472. }
  473. for(auto unit : allUnits)
  474. {
  475. auto newHealth = unit->getAvailableHealth();
  476. auto oldHealth = healthOfStack[unit->unitId()];
  477. if(oldHealth != newHealth)
  478. {
  479. auto damage = std::abs(oldHealth - newHealth);
  480. auto originalDefender = cb->getBattle(battleID)->battleGetUnitByID(unit->unitId());
  481. auto dpsReduce = AttackPossibility::calculateDamageReduce(
  482. nullptr,
  483. originalDefender && originalDefender->alive() ? originalDefender : unit,
  484. damage,
  485. innerCache,
  486. state);
  487. auto ourUnit = unit->unitSide() == side ? 1 : -1;
  488. auto goodEffect = newHealth > oldHealth ? 1 : -1;
  489. if(ourUnit * goodEffect == 1)
  490. {
  491. if(ourUnit && goodEffect && (unit->isClone() || unit->isGhost()))
  492. continue;
  493. ps.value += dpsReduce * scoreEvaluator.getPositiveEffectMultiplier();
  494. }
  495. else
  496. ps.value -= dpsReduce * scoreEvaluator.getNegativeEffectMultiplier();
  497. #if BATTLE_TRACE_LEVEL >= 1
  498. logAi->trace(
  499. "Spell affects %s (%d), dps: %2f",
  500. unit->creatureId().toCreature()->getNameSingularTranslated(),
  501. unit->getCount(),
  502. dpsReduce);
  503. #endif
  504. }
  505. }
  506. #if BATTLE_TRACE_LEVEL >= 1
  507. logAi->trace("Total score: %2f", ps.value);
  508. #endif
  509. }
  510. #if BATTLE_TRACE_LEVEL == 0
  511. });
  512. #endif
  513. LOGFL("Evaluation took %d ms", timer.getDiff());
  514. auto pscValue = [](const PossibleSpellcast &ps) -> float
  515. {
  516. return ps.value;
  517. };
  518. auto castToPerform = *vstd::maxElementByFun(possibleCasts, pscValue);
  519. if(castToPerform.value > cachedScore)
  520. {
  521. LOGFL("Best spell is %s (value %d). Will cast.", castToPerform.spell->getNameTranslated() % castToPerform.value);
  522. BattleAction spellcast;
  523. spellcast.actionType = EActionType::HERO_SPELL;
  524. spellcast.spell = castToPerform.spell->id;
  525. spellcast.setTarget(castToPerform.dest);
  526. spellcast.side = side;
  527. spellcast.stackNumber = (!side) ? -1 : -2;
  528. cb->battleMakeSpellAction(battleID, spellcast);
  529. activeActionMade = true;
  530. return true;
  531. }
  532. LOGFL("Best spell is %s. But it is actually useless (value %d).", castToPerform.spell->getNameTranslated() % castToPerform.value);
  533. return false;
  534. }
  535. //Below method works only for offensive spells
  536. void BattleEvaluator::evaluateCreatureSpellcast(const CStack * stack, PossibleSpellcast & ps)
  537. {
  538. using ValueMap = PossibleSpellcast::ValueMap;
  539. RNGStub rngStub;
  540. HypotheticBattle state(env.get(), cb->getBattle(battleID));
  541. TStacks all = cb->getBattle(battleID)->battleGetAllStacks(false);
  542. ValueMap healthOfStack;
  543. ValueMap newHealthOfStack;
  544. for(auto unit : all)
  545. {
  546. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  547. }
  548. spells::BattleCast cast(&state, stack, spells::Mode::CREATURE_ACTIVE, ps.spell);
  549. cast.castEval(state.getServerCallback(), ps.dest);
  550. for(auto unit : all)
  551. {
  552. auto unitId = unit->unitId();
  553. auto localUnit = state.battleGetUnitByID(unitId);
  554. newHealthOfStack[unitId] = localUnit->getAvailableHealth();
  555. }
  556. int64_t totalGain = 0;
  557. for(auto unit : all)
  558. {
  559. auto unitId = unit->unitId();
  560. auto localUnit = state.battleGetUnitByID(unitId);
  561. auto healthDiff = newHealthOfStack[unitId] - healthOfStack[unitId];
  562. if(localUnit->unitOwner() != cb->getBattle(battleID)->getPlayerID())
  563. healthDiff = -healthDiff;
  564. if(healthDiff < 0)
  565. {
  566. ps.value = -1;
  567. return; //do not damage own units at all
  568. }
  569. totalGain += healthDiff;
  570. }
  571. ps.value = totalGain;
  572. }
  573. void BattleEvaluator::print(const std::string & text) const
  574. {
  575. logAi->trace("%s Battle AI[%p]: %s", playerID.toString(), this, text);
  576. }