BattleEvaluator.cpp 29 KB

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