BattleEvaluator.cpp 28 KB

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