BattleEvaluator.cpp 19 KB

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