BattleEvaluator.cpp 25 KB

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