BattleEvaluator.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  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. avHexes.eraseIf([&](const BattleHex & hex)
  318. {
  319. return !cb->getBattle(battleID)->battleIsInsideWalls(hex);
  320. });
  321. }
  322. if(avHexes.empty() || hexes.empty()) //we are blocked or dest is blocked
  323. {
  324. return BattleAction::makeDefend(stack);
  325. }
  326. BattleHexArray targetHexes = hexes;
  327. targetHexes.sort([&reachability](const BattleHex & h1, const BattleHex & h2) -> bool
  328. {
  329. return reachability.distances[h1.toInt()] < reachability.distances[h2.toInt()];
  330. });
  331. BattleHex bestNeighbour = targetHexes.front();
  332. if(reachability.distances[bestNeighbour.toInt()] > GameConstants::BFIELD_SIZE)
  333. {
  334. logAi->trace("No reachable hexes.");
  335. return BattleAction::makeDefend(stack);
  336. }
  337. // this turn
  338. for(const auto & hex : targetHexes)
  339. {
  340. if(avHexes.contains(hex))
  341. {
  342. return moveOrAttack(stack, hex, targets);
  343. }
  344. if(stack->coversPos(hex))
  345. {
  346. logAi->warn("Warning: already standing on neighbouring hex!");
  347. //We shouldn't even be here...
  348. return BattleAction::makeDefend(stack);
  349. }
  350. }
  351. // not this turn
  352. scoreEvaluator.updateReachabilityMap(hb);
  353. if(stack->hasBonusOfType(BonusType::FLYING))
  354. {
  355. BattleHexArray obstacleHexes;
  356. const auto & obstacles = hb->battleGetAllObstacles();
  357. for (const auto & obst : obstacles)
  358. {
  359. if(obst->triggersEffects())
  360. {
  361. auto triggerAbility = VLC->spells()->getById(obst->getTrigger());
  362. auto triggerIsNegative = triggerAbility->isNegative() || triggerAbility->isDamage();
  363. if(triggerIsNegative)
  364. obstacleHexes.insert(obst->getAffectedTiles());
  365. }
  366. }
  367. // Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
  368. // We just check all available hexes and pick the one closest to the target.
  369. auto nearestAvailableHex = vstd::minElementByFun(avHexes, [this, &bestNeighbour, &stack, &obstacleHexes](const BattleHex & hex) -> int
  370. {
  371. const int NEGATIVE_OBSTACLE_PENALTY = 100; // avoid landing on negative obstacle (moat, fire wall, etc)
  372. const int BLOCKED_STACK_PENALTY = 100; // avoid landing on moat
  373. auto distance = BattleHex::getDistance(bestNeighbour, hex);
  374. if(obstacleHexes.contains(hex))
  375. distance += NEGATIVE_OBSTACLE_PENALTY;
  376. return scoreEvaluator.checkPositionBlocksOurStacks(*hb, stack, hex) ? BLOCKED_STACK_PENALTY + distance : distance;
  377. });
  378. return moveOrAttack(stack, *nearestAvailableHex, targets);
  379. }
  380. else
  381. {
  382. BattleHex currentDest = bestNeighbour;
  383. while(true)
  384. {
  385. if(!currentDest.isValid())
  386. {
  387. return BattleAction::makeDefend(stack);
  388. }
  389. if(avHexes.contains(currentDest)
  390. && !scoreEvaluator.checkPositionBlocksOurStacks(*hb, stack, currentDest))
  391. {
  392. return moveOrAttack(stack, currentDest, targets);
  393. }
  394. currentDest = reachability.predecessors[currentDest.toInt()];
  395. }
  396. }
  397. logAi->error("We should either detect that hexes are unreachable or make a move!");
  398. return BattleAction::makeDefend(stack);
  399. }
  400. bool BattleEvaluator::canCastSpell()
  401. {
  402. auto hero = cb->getBattle(battleID)->battleGetMyHero();
  403. if(!hero)
  404. return false;
  405. return cb->getBattle(battleID)->battleCanCastSpell(hero, spells::Mode::HERO) == ESpellCastProblem::OK;
  406. }
  407. bool BattleEvaluator::attemptCastingSpell(const CStack * activeStack)
  408. {
  409. auto hero = cb->getBattle(battleID)->battleGetMyHero();
  410. if(!hero)
  411. return false;
  412. LOGL("Casting spells sounds like fun. Let's see...");
  413. //Get all spells we can cast
  414. std::vector<const CSpell*> possibleSpells;
  415. for (auto const & s : VLC->spellh->objects)
  416. if (s->canBeCast(cb->getBattle(battleID).get(), spells::Mode::HERO, hero))
  417. possibleSpells.push_back(s.get());
  418. LOGFL("I can cast %d spells.", possibleSpells.size());
  419. vstd::erase_if(possibleSpells, [](const CSpell *s)
  420. {
  421. return spellType(s) != SpellTypes::BATTLE;
  422. });
  423. LOGFL("I know how %d of them works.", possibleSpells.size());
  424. //Get possible spell-target pairs
  425. std::vector<PossibleSpellcast> possibleCasts;
  426. for(auto spell : possibleSpells)
  427. {
  428. spells::BattleCast temp(cb->getBattle(battleID).get(), hero, spells::Mode::HERO, spell);
  429. const bool FAST = true;
  430. for(auto & target : temp.findPotentialTargets(FAST))
  431. {
  432. PossibleSpellcast ps;
  433. ps.dest = target;
  434. ps.spell = spell;
  435. possibleCasts.push_back(ps);
  436. }
  437. }
  438. LOGFL("Found %d spell-target combinations.", possibleCasts.size());
  439. if(possibleCasts.empty())
  440. return false;
  441. using ValueMap = PossibleSpellcast::ValueMap;
  442. auto evaluateQueue = [&](ValueMap & values, const std::vector<battle::Units> & queue, std::shared_ptr<HypotheticBattle> state, size_t minTurnSpan, bool * enemyHadTurnOut) -> bool
  443. {
  444. bool firstRound = true;
  445. bool enemyHadTurn = false;
  446. size_t ourTurnSpan = 0;
  447. bool stop = false;
  448. for(auto & round : queue)
  449. {
  450. if(!firstRound)
  451. state->nextRound();
  452. for(auto unit : round)
  453. {
  454. if(!vstd::contains(values, unit->unitId()))
  455. values[unit->unitId()] = 0;
  456. if(!unit->alive())
  457. continue;
  458. if(state->battleGetOwner(unit) != playerID)
  459. {
  460. enemyHadTurn = true;
  461. if(!firstRound || state->battleCastSpells(unit->unitSide()) == 0)
  462. {
  463. //enemy could counter our spell at this point
  464. //anyway, we do not know what enemy will do
  465. //just stop evaluation
  466. stop = true;
  467. break;
  468. }
  469. }
  470. else if(!enemyHadTurn)
  471. {
  472. ourTurnSpan++;
  473. }
  474. state->nextTurn(unit->unitId());
  475. PotentialTargets potentialTargets(unit, damageCache, state);
  476. if(!potentialTargets.possibleAttacks.empty())
  477. {
  478. AttackPossibility attackPossibility = potentialTargets.bestAction();
  479. auto stackWithBonuses = state->getForUpdate(unit->unitId());
  480. *stackWithBonuses = *attackPossibility.attackerState;
  481. if(attackPossibility.defenderDamageReduce > 0)
  482. {
  483. stackWithBonuses->removeUnitBonus(Bonus::UntilAttack);
  484. stackWithBonuses->removeUnitBonus(Bonus::UntilOwnAttack);
  485. }
  486. if(attackPossibility.attackerDamageReduce > 0)
  487. stackWithBonuses->removeUnitBonus(Bonus::UntilBeingAttacked);
  488. for(auto affected : attackPossibility.affectedUnits)
  489. {
  490. stackWithBonuses = state->getForUpdate(affected->unitId());
  491. *stackWithBonuses = *affected;
  492. if(attackPossibility.defenderDamageReduce > 0)
  493. stackWithBonuses->removeUnitBonus(Bonus::UntilBeingAttacked);
  494. if(attackPossibility.attackerDamageReduce > 0 && attackPossibility.attack.defender->unitId() == affected->unitId())
  495. stackWithBonuses->removeUnitBonus(Bonus::UntilAttack);
  496. }
  497. }
  498. auto bav = potentialTargets.bestActionValue();
  499. //best action is from effective owner`s point if view, we need to convert to our point if view
  500. if(state->battleGetOwner(unit) != playerID)
  501. bav = -bav;
  502. values[unit->unitId()] += bav;
  503. }
  504. firstRound = false;
  505. if(stop)
  506. break;
  507. }
  508. if(enemyHadTurnOut)
  509. *enemyHadTurnOut = enemyHadTurn;
  510. return ourTurnSpan >= minTurnSpan;
  511. };
  512. ValueMap valueOfStack;
  513. ValueMap healthOfStack;
  514. TStacks all = cb->getBattle(battleID)->battleGetAllStacks(false);
  515. size_t ourRemainingTurns = 0;
  516. for(auto unit : all)
  517. {
  518. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  519. valueOfStack[unit->unitId()] = 0;
  520. if(cb->getBattle(battleID)->battleGetOwner(unit) == playerID && unit->canMove() && !unit->moved())
  521. ourRemainingTurns++;
  522. }
  523. LOGFL("I have %d turns left in this round", ourRemainingTurns);
  524. const bool castNow = ourRemainingTurns <= 1;
  525. if(castNow)
  526. print("I should try to cast a spell now");
  527. else
  528. print("I could wait better moment to cast a spell");
  529. auto amount = all.size();
  530. std::vector<battle::Units> turnOrder;
  531. cb->getBattle(battleID)->battleGetTurnOrder(turnOrder, amount, 2); //no more than 1 turn after current, each unit at least once
  532. {
  533. bool enemyHadTurn = false;
  534. auto state = std::make_shared<HypotheticBattle>(env.get(), cb->getBattle(battleID));
  535. evaluateQueue(valueOfStack, turnOrder, state, 0, &enemyHadTurn);
  536. if(!enemyHadTurn)
  537. {
  538. auto battleIsFinishedOpt = state->battleIsFinished();
  539. if(battleIsFinishedOpt)
  540. {
  541. print("No need to cast a spell. Battle will finish soon.");
  542. return false;
  543. }
  544. }
  545. }
  546. CStopWatch timer;
  547. #if BATTLE_TRACE_LEVEL >= 1
  548. tbb::blocked_range<size_t> r(0, possibleCasts.size());
  549. #else
  550. tbb::parallel_for(tbb::blocked_range<size_t>(0, possibleCasts.size()), [&](const tbb::blocked_range<size_t> & r)
  551. {
  552. #endif
  553. for(auto i = r.begin(); i != r.end(); i++)
  554. {
  555. auto & ps = possibleCasts[i];
  556. #if BATTLE_TRACE_LEVEL >= 1
  557. if(ps.dest.empty())
  558. logAi->trace("Evaluating %s", ps.spell->getNameTranslated());
  559. else
  560. {
  561. auto psFirst = ps.dest.front();
  562. auto strWhere = psFirst.unitValue ? psFirst.unitValue->getDescription() : std::to_string(psFirst.hexValue.toInt());
  563. logAi->trace("Evaluating %s at %s", ps.spell->getNameTranslated(), strWhere);
  564. }
  565. #endif
  566. auto state = std::make_shared<HypotheticBattle>(env.get(), cb->getBattle(battleID));
  567. spells::BattleCast cast(state.get(), hero, spells::Mode::HERO, ps.spell);
  568. cast.castEval(state->getServerCallback(), ps.dest);
  569. auto allUnits = state->battleGetUnitsIf([](const battle::Unit * u) -> bool { return u->isValidTarget(true); });
  570. auto needFullEval = vstd::contains_if(allUnits, [&](const battle::Unit * u) -> bool
  571. {
  572. auto original = cb->getBattle(battleID)->battleGetUnitByID(u->unitId());
  573. return !original || u->getMovementRange() != original->getMovementRange();
  574. });
  575. DamageCache safeCopy = damageCache;
  576. DamageCache innerCache(&safeCopy);
  577. innerCache.buildDamageCache(state, side);
  578. if(cachedAttack.ap && cachedAttack.waited)
  579. {
  580. state->makeWait(activeStack);
  581. }
  582. float stackActionScore = 0;
  583. float damageToHostilesScore = 0;
  584. float damageToFriendliesScore = 0;
  585. if(needFullEval || !cachedAttack.ap)
  586. {
  587. #if BATTLE_TRACE_LEVEL >= 1
  588. logAi->trace("Full evaluation is started due to stack speed affected.");
  589. #endif
  590. PotentialTargets innerTargets(activeStack, innerCache, state);
  591. BattleExchangeEvaluator innerEvaluator(state, env, strengthRatio, simulationTurnsCount);
  592. innerEvaluator.updateReachabilityMap(state);
  593. auto moveTarget = innerEvaluator.findMoveTowardsUnreachable(activeStack, innerTargets, innerCache, state);
  594. if(!innerTargets.possibleAttacks.empty())
  595. {
  596. auto newStackAction = innerEvaluator.findBestTarget(activeStack, innerTargets, innerCache, state);
  597. stackActionScore = std::max(moveTarget.score, newStackAction.score);
  598. }
  599. else
  600. {
  601. stackActionScore = moveTarget.score;
  602. }
  603. }
  604. else
  605. {
  606. auto updatedAttacker = state->getForUpdate(cachedAttack.ap->attack.attacker->unitId());
  607. auto updatedDefender = state->getForUpdate(cachedAttack.ap->attack.defender->unitId());
  608. auto updatedBai = BattleAttackInfo(
  609. updatedAttacker.get(),
  610. updatedDefender.get(),
  611. cachedAttack.ap->attack.chargeDistance,
  612. cachedAttack.ap->attack.shooting);
  613. auto updatedAttack = AttackPossibility::evaluate(updatedBai, cachedAttack.ap->from, innerCache, state);
  614. BattleExchangeEvaluator innerEvaluator(scoreEvaluator);
  615. stackActionScore = innerEvaluator.evaluateExchange(updatedAttack, cachedAttack.turn, *targets, innerCache, state);
  616. }
  617. for(const auto & unit : allUnits)
  618. {
  619. if(!unit->isValidTarget(true))
  620. continue;
  621. auto newHealth = unit->getAvailableHealth();
  622. auto oldHealth = vstd::find_or(healthOfStack, unit->unitId(), 0); // old health value may not exist for newly summoned units
  623. if(oldHealth != newHealth)
  624. {
  625. auto damage = std::abs(oldHealth - newHealth);
  626. auto originalDefender = cb->getBattle(battleID)->battleGetUnitByID(unit->unitId());
  627. auto dpsReduce = AttackPossibility::calculateDamageReduce(
  628. nullptr,
  629. originalDefender && originalDefender->alive() ? originalDefender : unit,
  630. damage,
  631. innerCache,
  632. state);
  633. auto ourUnit = unit->unitSide() == side ? 1 : -1;
  634. auto goodEffect = newHealth > oldHealth ? 1 : -1;
  635. if(ourUnit * goodEffect == 1)
  636. {
  637. auto isMagical = state->getForUpdate(unit->unitId())->summoned
  638. || unit->isClone()
  639. || unit->isGhost();
  640. if(ourUnit && goodEffect && isMagical)
  641. continue;
  642. damageToHostilesScore += dpsReduce * scoreEvaluator.getPositiveEffectMultiplier();
  643. }
  644. else
  645. // discourage AI making collateral damage with spells
  646. damageToFriendliesScore -= 4 * dpsReduce * scoreEvaluator.getNegativeEffectMultiplier();
  647. #if BATTLE_TRACE_LEVEL >= 1
  648. // Ensure ps.dest is not empty before accessing the first element
  649. if (!ps.dest.empty())
  650. {
  651. logAi->trace(
  652. "Spell %s to %d affects %s (%d), dps: %2f oldHealth: %d newHealth: %d",
  653. ps.spell->getNameTranslated(),
  654. ps.dest.at(0).hexValue.toInt(), // Safe to access .at(0) now
  655. unit->creatureId().toCreature()->getNameSingularTranslated(),
  656. unit->getCount(),
  657. dpsReduce,
  658. oldHealth,
  659. newHealth);
  660. }
  661. else
  662. {
  663. // Handle the case where ps.dest is empty
  664. logAi->trace(
  665. "Spell %s has no destination, affects %s (%d), dps: %2f oldHealth: %d newHealth: %d",
  666. ps.spell->getNameTranslated(),
  667. unit->creatureId().toCreature()->getNameSingularTranslated(),
  668. unit->getCount(),
  669. dpsReduce,
  670. oldHealth,
  671. newHealth);
  672. }
  673. #endif
  674. }
  675. }
  676. if (vstd::isAlmostEqual(stackActionScore, static_cast<float>(EvaluationResult::INEFFECTIVE_SCORE)))
  677. {
  678. ps.value = damageToFriendliesScore + damageToHostilesScore;
  679. }
  680. else
  681. {
  682. ps.value = stackActionScore + damageToFriendliesScore + damageToHostilesScore;
  683. }
  684. #if BATTLE_TRACE_LEVEL >= 1
  685. logAi->trace("Total score for %s: %2f (action: %2f, friedly damage: %2f, hostile damage: %2f)", ps.spell->getJsonKey(), ps.value, stackActionScore, damageToFriendliesScore, damageToHostilesScore);
  686. #endif
  687. }
  688. #if BATTLE_TRACE_LEVEL == 0
  689. });
  690. #endif
  691. LOGFL("Evaluation took %d ms", timer.getDiff());
  692. auto castToPerform = *vstd::maxElementByFun(possibleCasts, [](const PossibleSpellcast & ps) -> float
  693. {
  694. return ps.value;
  695. });
  696. if(castToPerform.value > cachedAttack.score && !vstd::isAlmostEqual(castToPerform.value, cachedAttack.score))
  697. {
  698. LOGFL("Best spell is %s (value %d). Will cast.", castToPerform.spell->getNameTranslated() % castToPerform.value);
  699. BattleAction spellcast;
  700. spellcast.actionType = EActionType::HERO_SPELL;
  701. spellcast.spell = castToPerform.spell->id;
  702. spellcast.setTarget(castToPerform.dest);
  703. spellcast.side = side;
  704. spellcast.stackNumber = -1;
  705. cb->battleMakeSpellAction(battleID, spellcast);
  706. activeActionMade = true;
  707. return true;
  708. }
  709. LOGFL("Best spell is %s. But it is actually useless (value %d).", castToPerform.spell->getNameTranslated() % castToPerform.value);
  710. return false;
  711. }
  712. //Below method works only for offensive spells
  713. void BattleEvaluator::evaluateCreatureSpellcast(const CStack * stack, PossibleSpellcast & ps)
  714. {
  715. using ValueMap = PossibleSpellcast::ValueMap;
  716. RNGStub rngStub;
  717. HypotheticBattle state(env.get(), cb->getBattle(battleID));
  718. TStacks all = cb->getBattle(battleID)->battleGetAllStacks(false);
  719. ValueMap healthOfStack;
  720. ValueMap newHealthOfStack;
  721. for(auto unit : all)
  722. {
  723. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  724. }
  725. spells::BattleCast cast(&state, stack, spells::Mode::CREATURE_ACTIVE, ps.spell);
  726. cast.castEval(state.getServerCallback(), ps.dest);
  727. for(auto unit : all)
  728. {
  729. auto unitId = unit->unitId();
  730. auto localUnit = state.battleGetUnitByID(unitId);
  731. newHealthOfStack[unitId] = localUnit->getAvailableHealth();
  732. }
  733. int64_t totalGain = 0;
  734. for(auto unit : all)
  735. {
  736. auto unitId = unit->unitId();
  737. auto localUnit = state.battleGetUnitByID(unitId);
  738. auto healthDiff = newHealthOfStack[unitId] - healthOfStack[unitId];
  739. if(localUnit->unitOwner() != cb->getBattle(battleID)->getPlayerID())
  740. healthDiff = -healthDiff;
  741. if(healthDiff < 0)
  742. {
  743. ps.value = -1;
  744. return; //do not damage own units at all
  745. }
  746. totalGain += healthDiff;
  747. }
  748. ps.value = totalGain;
  749. }
  750. void BattleEvaluator::print(const std::string & text) const
  751. {
  752. logAi->trace("%s Battle AI[%p]: %s", playerID.toString(), this, text);
  753. }