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