BattleEvaluator.cpp 27 KB

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