BattleAI.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  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 "BattleAI.h"
  12. #include "BattleExchangeVariant.h"
  13. #include "StackWithBonuses.h"
  14. #include "EnemyInfo.h"
  15. #include "../../lib/CStopWatch.h"
  16. #include "../../lib/CThreadHelper.h"
  17. #include "../../lib/mapObjects/CGTownInstance.h"
  18. #include "../../lib/spells/CSpellHandler.h"
  19. #include "../../lib/spells/ISpellMechanics.h"
  20. #include "../../lib/battle/BattleStateInfoForRetreat.h"
  21. #include "../../lib/battle/CObstacleInstance.h"
  22. #include "../../lib/CStack.h" // TODO: remove
  23. // Eventually only IBattleInfoCallback and battle::Unit should be used,
  24. // CUnitState should be private and CStack should be removed completely
  25. #define LOGL(text) print(text)
  26. #define LOGFL(text, formattingEl) print(boost::str(boost::format(text) % formattingEl))
  27. enum class SpellTypes
  28. {
  29. ADVENTURE, BATTLE, OTHER
  30. };
  31. SpellTypes spellType(const CSpell * spell)
  32. {
  33. if(!spell->isCombat() || spell->isCreatureAbility())
  34. return SpellTypes::OTHER;
  35. if(spell->isOffensive() || spell->hasEffects() || spell->hasBattleEffects())
  36. return SpellTypes::BATTLE;
  37. return SpellTypes::OTHER;
  38. }
  39. std::vector<BattleHex> CBattleAI::getBrokenWallMoatHexes() const
  40. {
  41. std::vector<BattleHex> result;
  42. for(EWallPart wallPart : { EWallPart::BOTTOM_WALL, EWallPart::BELOW_GATE, EWallPart::OVER_GATE, EWallPart::UPPER_WALL })
  43. {
  44. auto state = cb->battleGetWallState(wallPart);
  45. if(state != EWallState::DESTROYED)
  46. continue;
  47. auto wallHex = cb->wallPartToBattleHex((EWallPart)wallPart);
  48. auto moatHex = wallHex.cloneInDirection(BattleHex::LEFT);
  49. result.push_back(moatHex);
  50. }
  51. return result;
  52. }
  53. CBattleAI::CBattleAI()
  54. : side(-1),
  55. wasWaitingForRealize(false),
  56. wasUnlockingGs(false)
  57. {
  58. }
  59. CBattleAI::~CBattleAI()
  60. {
  61. if(cb)
  62. {
  63. //Restore previous state of CB - it may be shared with the main AI (like VCAI)
  64. cb->waitTillRealize = wasWaitingForRealize;
  65. cb->unlockGsWhenWaiting = wasUnlockingGs;
  66. }
  67. }
  68. void CBattleAI::initBattleInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CBattleCallback> CB)
  69. {
  70. setCbc(CB);
  71. env = ENV;
  72. cb = CB;
  73. playerID = *CB->getPlayerID(); //TODO should be sth in callback
  74. wasWaitingForRealize = CB->waitTillRealize;
  75. wasUnlockingGs = CB->unlockGsWhenWaiting;
  76. CB->waitTillRealize = false;
  77. CB->unlockGsWhenWaiting = false;
  78. movesSkippedByDefense = 0;
  79. }
  80. void CBattleAI::initBattleInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CBattleCallback> CB, AutocombatPreferences autocombatPreferences)
  81. {
  82. initBattleInterface(ENV, CB);
  83. autobattlePreferences = autocombatPreferences;
  84. }
  85. BattleAction CBattleAI::useHealingTent(const CStack *stack)
  86. {
  87. auto healingTargets = cb->battleGetStacks(CBattleInfoEssentials::ONLY_MINE);
  88. std::map<int, const CStack*> woundHpToStack;
  89. for(const auto * stack : healingTargets)
  90. {
  91. if(auto woundHp = stack->getMaxHealth() - stack->getFirstHPleft())
  92. woundHpToStack[woundHp] = stack;
  93. }
  94. if(woundHpToStack.empty())
  95. return BattleAction::makeDefend(stack);
  96. else
  97. return BattleAction::makeHeal(stack, woundHpToStack.rbegin()->second); //last element of the woundHpToStack is the most wounded stack
  98. }
  99. std::optional<PossibleSpellcast> CBattleAI::findBestCreatureSpell(const CStack *stack)
  100. {
  101. //TODO: faerie dragon type spell should be selected by server
  102. SpellID creatureSpellToCast = cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), stack, CBattleInfoCallback::RANDOM_AIMED);
  103. if(stack->hasBonusOfType(BonusType::SPELLCASTER) && stack->canCast() && creatureSpellToCast != SpellID::NONE)
  104. {
  105. const CSpell * spell = creatureSpellToCast.toSpell();
  106. if(spell->canBeCast(getCbc().get(), spells::Mode::CREATURE_ACTIVE, stack))
  107. {
  108. std::vector<PossibleSpellcast> possibleCasts;
  109. spells::BattleCast temp(getCbc().get(), stack, spells::Mode::CREATURE_ACTIVE, spell);
  110. for(auto & target : temp.findPotentialTargets())
  111. {
  112. PossibleSpellcast ps;
  113. ps.dest = target;
  114. ps.spell = spell;
  115. evaluateCreatureSpellcast(stack, ps);
  116. possibleCasts.push_back(ps);
  117. }
  118. std::sort(possibleCasts.begin(), possibleCasts.end(), [&](const PossibleSpellcast & lhs, const PossibleSpellcast & rhs) { return lhs.value > rhs.value; });
  119. if(!possibleCasts.empty() && possibleCasts.front().value > 0)
  120. {
  121. return possibleCasts.front();
  122. }
  123. }
  124. }
  125. return std::nullopt;
  126. }
  127. BattleAction CBattleAI::selectStackAction(const CStack * stack)
  128. {
  129. //evaluate casting spell for spellcasting stack
  130. std::optional<PossibleSpellcast> bestSpellcast = findBestCreatureSpell(stack);
  131. HypotheticBattle hb(env.get(), cb);
  132. PotentialTargets targets(stack, hb);
  133. BattleExchangeEvaluator scoreEvaluator(cb, env);
  134. auto moveTarget = scoreEvaluator.findMoveTowardsUnreachable(stack, targets, hb);
  135. int64_t score = EvaluationResult::INEFFECTIVE_SCORE;
  136. if(targets.possibleAttacks.empty() && bestSpellcast.has_value())
  137. {
  138. movesSkippedByDefense = 0;
  139. return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
  140. }
  141. if(!targets.possibleAttacks.empty())
  142. {
  143. #if BATTLE_TRACE_LEVEL>=1
  144. logAi->trace("Evaluating attack for %s", stack->getDescription());
  145. #endif
  146. auto evaluationResult = scoreEvaluator.findBestTarget(stack, targets, hb);
  147. auto & bestAttack = evaluationResult.bestAttack;
  148. //TODO: consider more complex spellcast evaluation, f.e. because "re-retaliation" during enemy move in same turn for melee attack etc.
  149. if(bestSpellcast.has_value() && bestSpellcast->value > bestAttack.damageDiff())
  150. {
  151. // return because spellcast value is damage dealt and score is dps reduce
  152. movesSkippedByDefense = 0;
  153. return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
  154. }
  155. if(evaluationResult.score > score)
  156. {
  157. score = evaluationResult.score;
  158. logAi->debug("BattleAI: %s -> %s x %d, from %d curpos %d dist %d speed %d: +%lld -%lld = %lld",
  159. bestAttack.attackerState->unitType()->getJsonKey(),
  160. bestAttack.affectedUnits[0]->unitType()->getJsonKey(),
  161. (int)bestAttack.affectedUnits[0]->getCount(),
  162. (int)bestAttack.from,
  163. (int)bestAttack.attack.attacker->getPosition().hex,
  164. bestAttack.attack.chargeDistance,
  165. bestAttack.attack.attacker->speed(0, true),
  166. bestAttack.defenderDamageReduce,
  167. bestAttack.attackerDamageReduce, bestAttack.attackValue()
  168. );
  169. if (moveTarget.score <= score)
  170. {
  171. if(evaluationResult.wait)
  172. {
  173. return BattleAction::makeWait(stack);
  174. }
  175. else if(bestAttack.attack.shooting)
  176. {
  177. movesSkippedByDefense = 0;
  178. return BattleAction::makeShotAttack(stack, bestAttack.attack.defender);
  179. }
  180. else
  181. {
  182. movesSkippedByDefense = 0;
  183. return BattleAction::makeMeleeAttack(stack, bestAttack.attack.defender->getPosition(), bestAttack.from);
  184. }
  185. }
  186. }
  187. }
  188. //ThreatMap threatsToUs(stack); // These lines may be usefull but they are't used in the code.
  189. if(moveTarget.score > score)
  190. {
  191. score = moveTarget.score;
  192. if(stack->waited())
  193. {
  194. return goTowardsNearest(stack, moveTarget.positions);
  195. }
  196. else
  197. {
  198. return BattleAction::makeWait(stack);
  199. }
  200. }
  201. if(score <= EvaluationResult::INEFFECTIVE_SCORE
  202. && !stack->hasBonusOfType(BonusType::FLYING)
  203. && stack->unitSide() == BattleSide::ATTACKER
  204. && cb->battleGetSiegeLevel() >= CGTownInstance::CITADEL)
  205. {
  206. auto brokenWallMoat = getBrokenWallMoatHexes();
  207. if(brokenWallMoat.size())
  208. {
  209. movesSkippedByDefense = 0;
  210. if(stack->doubleWide() && vstd::contains(brokenWallMoat, stack->getPosition()))
  211. return BattleAction::makeMove(stack, stack->getPosition().cloneInDirection(BattleHex::RIGHT));
  212. else
  213. return goTowardsNearest(stack, brokenWallMoat);
  214. }
  215. }
  216. return BattleAction::makeDefend(stack);
  217. }
  218. void CBattleAI::yourTacticPhase(int distance)
  219. {
  220. cb->battleMakeTacticAction(BattleAction::makeEndOFTacticPhase(cb->battleGetTacticsSide()));
  221. }
  222. uint64_t timeElapsed(std::chrono::time_point<std::chrono::high_resolution_clock> start)
  223. {
  224. auto end = std::chrono::high_resolution_clock::now();
  225. return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
  226. }
  227. void CBattleAI::activeStack( const CStack * stack )
  228. {
  229. LOG_TRACE_PARAMS(logAi, "stack: %s", stack->nodeName());
  230. BattleAction result = BattleAction::makeDefend(stack);
  231. setCbc(cb); //TODO: make solid sure that AIs always use their callbacks (need to take care of event handlers too)
  232. auto start = std::chrono::high_resolution_clock::now();
  233. try
  234. {
  235. if(stack->creatureId() == CreatureID::CATAPULT)
  236. {
  237. cb->battleMakeUnitAction(useCatapult(stack));
  238. return;
  239. }
  240. if(stack->hasBonusOfType(BonusType::SIEGE_WEAPON) && stack->hasBonusOfType(BonusType::HEALER))
  241. {
  242. cb->battleMakeUnitAction(useHealingTent(stack));
  243. return;
  244. }
  245. if(autobattlePreferences.enableSpellsUsage)
  246. attemptCastingSpell();
  247. logAi->trace("Spellcast attempt completed in %lld", timeElapsed(start));
  248. if(cb->battleIsFinished() || !stack->alive())
  249. {
  250. //spellcast may finish battle or kill active stack
  251. //send special preudo-action
  252. BattleAction cancel;
  253. cancel.actionType = EActionType::CANCEL;
  254. cb->battleMakeUnitAction(cancel);
  255. return;
  256. }
  257. if(auto action = considerFleeingOrSurrendering())
  258. {
  259. cb->battleMakeUnitAction(*action);
  260. return;
  261. }
  262. result = selectStackAction(stack);
  263. }
  264. catch(boost::thread_interrupted &)
  265. {
  266. throw;
  267. }
  268. catch(std::exception &e)
  269. {
  270. logAi->error("Exception occurred in %s %s",__FUNCTION__, e.what());
  271. }
  272. if(result.actionType == EActionType::DEFEND)
  273. {
  274. movesSkippedByDefense++;
  275. }
  276. else if(result.actionType != EActionType::WAIT)
  277. {
  278. movesSkippedByDefense = 0;
  279. }
  280. logAi->trace("BattleAI decission made in %lld", timeElapsed(start));
  281. cb->battleMakeUnitAction(result);
  282. }
  283. BattleAction CBattleAI::goTowardsNearest(const CStack * stack, std::vector<BattleHex> hexes) const
  284. {
  285. auto reachability = cb->getReachability(stack);
  286. auto avHexes = cb->battleGetAvailableHexes(reachability, stack, false);
  287. if(!avHexes.size() || !hexes.size()) //we are blocked or dest is blocked
  288. {
  289. return BattleAction::makeDefend(stack);
  290. }
  291. std::sort(hexes.begin(), hexes.end(), [&](BattleHex h1, BattleHex h2) -> bool
  292. {
  293. return reachability.distances[h1] < reachability.distances[h2];
  294. });
  295. for(auto hex : hexes)
  296. {
  297. if(vstd::contains(avHexes, hex))
  298. {
  299. return BattleAction::makeMove(stack, hex);
  300. }
  301. if(stack->coversPos(hex))
  302. {
  303. logAi->warn("Warning: already standing on neighbouring tile!");
  304. //We shouldn't even be here...
  305. return BattleAction::makeDefend(stack);
  306. }
  307. }
  308. BattleHex bestNeighbor = hexes.front();
  309. if(reachability.distances[bestNeighbor] > GameConstants::BFIELD_SIZE)
  310. {
  311. return BattleAction::makeDefend(stack);
  312. }
  313. BattleExchangeEvaluator scoreEvaluator(cb, env);
  314. HypotheticBattle hb(env.get(), cb);
  315. scoreEvaluator.updateReachabilityMap(hb);
  316. if(stack->hasBonusOfType(BonusType::FLYING))
  317. {
  318. std::set<BattleHex> obstacleHexes;
  319. auto insertAffected = [](const CObstacleInstance & spellObst, std::set<BattleHex> obstacleHexes) {
  320. auto affectedHexes = spellObst.getAffectedTiles();
  321. obstacleHexes.insert(affectedHexes.cbegin(), affectedHexes.cend());
  322. };
  323. const auto & obstacles = hb.battleGetAllObstacles();
  324. for (const auto & obst: obstacles) {
  325. if(obst->triggersEffects())
  326. {
  327. auto triggerAbility = VLC->spells()->getById(obst->getTrigger());
  328. auto triggerIsNegative = triggerAbility->isNegative() || triggerAbility->isDamage();
  329. if(triggerIsNegative)
  330. insertAffected(*obst, obstacleHexes);
  331. }
  332. }
  333. // Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
  334. // We just check all available hexes and pick the one closest to the target.
  335. auto nearestAvailableHex = vstd::minElementByFun(avHexes, [&](BattleHex hex) -> int
  336. {
  337. const int NEGATIVE_OBSTACLE_PENALTY = 100; // avoid landing on negative obstacle (moat, fire wall, etc)
  338. const int BLOCKED_STACK_PENALTY = 100; // avoid landing on moat
  339. auto distance = BattleHex::getDistance(bestNeighbor, hex);
  340. if(vstd::contains(obstacleHexes, hex))
  341. distance += NEGATIVE_OBSTACLE_PENALTY;
  342. return scoreEvaluator.checkPositionBlocksOurStacks(hb, stack, hex) ? BLOCKED_STACK_PENALTY + distance : distance;
  343. });
  344. return BattleAction::makeMove(stack, *nearestAvailableHex);
  345. }
  346. else
  347. {
  348. BattleHex currentDest = bestNeighbor;
  349. while(1)
  350. {
  351. if(!currentDest.isValid())
  352. {
  353. return BattleAction::makeDefend(stack);
  354. }
  355. if(vstd::contains(avHexes, currentDest)
  356. && !scoreEvaluator.checkPositionBlocksOurStacks(hb, stack, currentDest))
  357. return BattleAction::makeMove(stack, currentDest);
  358. currentDest = reachability.predecessors[currentDest];
  359. }
  360. }
  361. }
  362. BattleAction CBattleAI::useCatapult(const CStack * stack)
  363. {
  364. BattleAction attack;
  365. BattleHex targetHex = BattleHex::INVALID;
  366. if(cb->battleGetGateState() == EGateState::CLOSED)
  367. {
  368. targetHex = cb->wallPartToBattleHex(EWallPart::GATE);
  369. }
  370. else
  371. {
  372. EWallPart wallParts[] = {
  373. EWallPart::KEEP,
  374. EWallPart::BOTTOM_TOWER,
  375. EWallPart::UPPER_TOWER,
  376. EWallPart::BELOW_GATE,
  377. EWallPart::OVER_GATE,
  378. EWallPart::BOTTOM_WALL,
  379. EWallPart::UPPER_WALL
  380. };
  381. for(auto wallPart : wallParts)
  382. {
  383. auto wallState = cb->battleGetWallState(wallPart);
  384. if(wallState == EWallState::REINFORCED || wallState == EWallState::INTACT || wallState == EWallState::DAMAGED)
  385. {
  386. targetHex = cb->wallPartToBattleHex(wallPart);
  387. break;
  388. }
  389. }
  390. }
  391. if(!targetHex.isValid())
  392. {
  393. return BattleAction::makeDefend(stack);
  394. }
  395. attack.aimToHex(targetHex);
  396. attack.actionType = EActionType::CATAPULT;
  397. attack.side = side;
  398. attack.stackNumber = stack->unitId();
  399. movesSkippedByDefense = 0;
  400. return attack;
  401. }
  402. void CBattleAI::attemptCastingSpell()
  403. {
  404. auto hero = cb->battleGetMyHero();
  405. if(!hero)
  406. return;
  407. if(cb->battleCanCastSpell(hero, spells::Mode::HERO) != ESpellCastProblem::OK)
  408. return;
  409. LOGL("Casting spells sounds like fun. Let's see...");
  410. //Get all spells we can cast
  411. std::vector<const CSpell*> possibleSpells;
  412. vstd::copy_if(VLC->spellh->objects, std::back_inserter(possibleSpells), [hero, this](const CSpell *s) -> bool
  413. {
  414. return s->canBeCast(cb.get(), spells::Mode::HERO, hero);
  415. });
  416. LOGFL("I can cast %d spells.", possibleSpells.size());
  417. vstd::erase_if(possibleSpells, [](const CSpell *s)
  418. {
  419. return spellType(s) != SpellTypes::BATTLE;
  420. });
  421. LOGFL("I know how %d of them works.", possibleSpells.size());
  422. //Get possible spell-target pairs
  423. std::vector<PossibleSpellcast> possibleCasts;
  424. for(auto spell : possibleSpells)
  425. {
  426. spells::BattleCast temp(cb.get(), hero, spells::Mode::HERO, spell);
  427. if(!spell->isDamage() && spell->getTargetType() == spells::AimType::LOCATION)
  428. continue;
  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;
  441. using ValueMap = PossibleSpellcast::ValueMap;
  442. auto evaluateQueue = [&](ValueMap & values, const std::vector<battle::Units> & queue, 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(0);//todo: set actual value?
  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 pt(unit, state);
  476. if(!pt.possibleAttacks.empty())
  477. {
  478. AttackPossibility ap = pt.bestAction();
  479. auto swb = state.getForUpdate(unit->unitId());
  480. *swb = *ap.attackerState;
  481. if(ap.defenderDamageReduce > 0)
  482. swb->removeUnitBonus(Bonus::UntilAttack);
  483. if(ap.attackerDamageReduce > 0)
  484. swb->removeUnitBonus(Bonus::UntilBeingAttacked);
  485. for(auto affected : ap.affectedUnits)
  486. {
  487. swb = state.getForUpdate(affected->unitId());
  488. *swb = *affected;
  489. if(ap.defenderDamageReduce > 0)
  490. swb->removeUnitBonus(Bonus::UntilBeingAttacked);
  491. if(ap.attackerDamageReduce > 0 && ap.attack.defender->unitId() == affected->unitId())
  492. swb->removeUnitBonus(Bonus::UntilAttack);
  493. }
  494. }
  495. auto bav = pt.bestActionValue();
  496. //best action is from effective owner`s point if view, we need to convert to our point if view
  497. if(state.battleGetOwner(unit) != playerID)
  498. bav = -bav;
  499. values[unit->unitId()] += bav;
  500. }
  501. firstRound = false;
  502. if(stop)
  503. break;
  504. }
  505. if(enemyHadTurnOut)
  506. *enemyHadTurnOut = enemyHadTurn;
  507. return ourTurnSpan >= minTurnSpan;
  508. };
  509. ValueMap valueOfStack;
  510. ValueMap healthOfStack;
  511. TStacks all = cb->battleGetAllStacks(false);
  512. size_t ourRemainingTurns = 0;
  513. for(auto unit : all)
  514. {
  515. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  516. valueOfStack[unit->unitId()] = 0;
  517. if(cb->battleGetOwner(unit) == playerID && unit->canMove() && !unit->moved())
  518. ourRemainingTurns++;
  519. }
  520. LOGFL("I have %d turns left in this round", ourRemainingTurns);
  521. const bool castNow = ourRemainingTurns <= 1;
  522. if(castNow)
  523. print("I should try to cast a spell now");
  524. else
  525. print("I could wait better moment to cast a spell");
  526. auto amount = all.size();
  527. std::vector<battle::Units> turnOrder;
  528. cb->battleGetTurnOrder(turnOrder, amount, 2); //no more than 1 turn after current, each unit at least once
  529. {
  530. bool enemyHadTurn = false;
  531. HypotheticBattle state(env.get(), cb);
  532. evaluateQueue(valueOfStack, turnOrder, state, 0, &enemyHadTurn);
  533. if(!enemyHadTurn)
  534. {
  535. auto battleIsFinishedOpt = state.battleIsFinished();
  536. if(battleIsFinishedOpt)
  537. {
  538. print("No need to cast a spell. Battle will finish soon.");
  539. return;
  540. }
  541. }
  542. }
  543. struct ScriptsCache
  544. {
  545. //todo: re-implement scripts context cache
  546. };
  547. auto evaluateSpellcast = [&] (PossibleSpellcast * ps, std::shared_ptr<ScriptsCache>)
  548. {
  549. HypotheticBattle state(env.get(), cb);
  550. spells::BattleCast cast(&state, hero, spells::Mode::HERO, ps->spell);
  551. cast.castEval(state.getServerCallback(), ps->dest);
  552. ValueMap newHealthOfStack;
  553. ValueMap newValueOfStack;
  554. size_t ourUnits = 0;
  555. std::set<uint32_t> unitIds;
  556. state.battleGetUnitsIf([&](const battle::Unit * u)->bool
  557. {
  558. if(!u->isGhost() && !u->isTurret())
  559. unitIds.insert(u->unitId());
  560. return false;
  561. });
  562. for(auto unitId : unitIds)
  563. {
  564. auto localUnit = state.battleGetUnitByID(unitId);
  565. newHealthOfStack[unitId] = localUnit->getAvailableHealth();
  566. newValueOfStack[unitId] = 0;
  567. if(state.battleGetOwner(localUnit) == playerID && localUnit->alive() && localUnit->willMove())
  568. ourUnits++;
  569. }
  570. size_t minTurnSpan = ourUnits/3; //todo: tweak this
  571. std::vector<battle::Units> newTurnOrder;
  572. state.battleGetTurnOrder(newTurnOrder, amount, 2);
  573. const bool turnSpanOK = evaluateQueue(newValueOfStack, newTurnOrder, state, minTurnSpan, nullptr);
  574. if(turnSpanOK || castNow)
  575. {
  576. int64_t totalGain = 0;
  577. for(auto unitId : unitIds)
  578. {
  579. auto localUnit = state.battleGetUnitByID(unitId);
  580. auto newValue = getValOr(newValueOfStack, unitId, 0);
  581. auto oldValue = getValOr(valueOfStack, unitId, 0);
  582. auto healthDiff = newHealthOfStack[unitId] - healthOfStack[unitId];
  583. if(localUnit->unitOwner() != playerID)
  584. healthDiff = -healthDiff;
  585. if(healthDiff < 0)
  586. {
  587. ps->value = -1;
  588. return; //do not damage own units at all
  589. }
  590. totalGain += (newValue - oldValue + healthDiff);
  591. }
  592. ps->value = totalGain;
  593. }
  594. else
  595. {
  596. ps->value = -1;
  597. }
  598. };
  599. using EvalRunner = ThreadPool<ScriptsCache>;
  600. EvalRunner::Tasks tasks;
  601. for(PossibleSpellcast & psc : possibleCasts)
  602. tasks.push_back(std::bind(evaluateSpellcast, &psc, _1));
  603. uint32_t threadCount = boost::thread::hardware_concurrency();
  604. if(threadCount == 0)
  605. {
  606. logGlobal->warn("No information of CPU cores available");
  607. threadCount = 1;
  608. }
  609. CStopWatch timer;
  610. std::vector<std::shared_ptr<ScriptsCache>> scriptsPool;
  611. for(uint32_t idx = 0; idx < threadCount; idx++)
  612. {
  613. scriptsPool.emplace_back();
  614. }
  615. EvalRunner runner(&tasks, scriptsPool);
  616. runner.run();
  617. LOGFL("Evaluation took %d ms", timer.getDiff());
  618. auto pscValue = [](const PossibleSpellcast &ps) -> int64_t
  619. {
  620. return ps.value;
  621. };
  622. auto castToPerform = *vstd::maxElementByFun(possibleCasts, pscValue);
  623. if(castToPerform.value > 0)
  624. {
  625. LOGFL("Best spell is %s (value %d). Will cast.", castToPerform.spell->getNameTranslated() % castToPerform.value);
  626. BattleAction spellcast;
  627. spellcast.actionType = EActionType::HERO_SPELL;
  628. spellcast.actionSubtype = castToPerform.spell->id;
  629. spellcast.setTarget(castToPerform.dest);
  630. spellcast.side = side;
  631. spellcast.stackNumber = (!side) ? -1 : -2;
  632. cb->battleMakeSpellAction(spellcast);
  633. movesSkippedByDefense = 0;
  634. }
  635. else
  636. {
  637. LOGFL("Best spell is %s. But it is actually useless (value %d).", castToPerform.spell->getNameTranslated() % castToPerform.value);
  638. }
  639. }
  640. //Below method works only for offensive spells
  641. void CBattleAI::evaluateCreatureSpellcast(const CStack * stack, PossibleSpellcast & ps)
  642. {
  643. using ValueMap = PossibleSpellcast::ValueMap;
  644. RNGStub rngStub;
  645. HypotheticBattle state(env.get(), cb);
  646. TStacks all = cb->battleGetAllStacks(false);
  647. ValueMap healthOfStack;
  648. ValueMap newHealthOfStack;
  649. for(auto unit : all)
  650. {
  651. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  652. }
  653. spells::BattleCast cast(&state, stack, spells::Mode::CREATURE_ACTIVE, ps.spell);
  654. cast.castEval(state.getServerCallback(), ps.dest);
  655. for(auto unit : all)
  656. {
  657. auto unitId = unit->unitId();
  658. auto localUnit = state.battleGetUnitByID(unitId);
  659. newHealthOfStack[unitId] = localUnit->getAvailableHealth();
  660. }
  661. int64_t totalGain = 0;
  662. for(auto unit : all)
  663. {
  664. auto unitId = unit->unitId();
  665. auto localUnit = state.battleGetUnitByID(unitId);
  666. auto healthDiff = newHealthOfStack[unitId] - healthOfStack[unitId];
  667. if(localUnit->unitOwner() != getCbc()->getPlayerID())
  668. healthDiff = -healthDiff;
  669. if(healthDiff < 0)
  670. {
  671. ps.value = -1;
  672. return; //do not damage own units at all
  673. }
  674. totalGain += healthDiff;
  675. }
  676. ps.value = totalGain;
  677. }
  678. void CBattleAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool Side, bool replayAllowed)
  679. {
  680. LOG_TRACE(logAi);
  681. side = Side;
  682. }
  683. void CBattleAI::print(const std::string &text) const
  684. {
  685. logAi->trace("%s Battle AI[%p]: %s", playerID.getStr(), this, text);
  686. }
  687. std::optional<BattleAction> CBattleAI::considerFleeingOrSurrendering()
  688. {
  689. BattleStateInfoForRetreat bs;
  690. bs.canFlee = cb->battleCanFlee();
  691. bs.canSurrender = cb->battleCanSurrender(playerID);
  692. bs.ourSide = cb->battleGetMySide();
  693. bs.ourHero = cb->battleGetMyHero();
  694. bs.enemyHero = nullptr;
  695. for(auto stack : cb->battleGetAllStacks(false))
  696. {
  697. if(stack->alive())
  698. {
  699. if(stack->unitSide() == bs.ourSide)
  700. bs.ourStacks.push_back(stack);
  701. else
  702. {
  703. bs.enemyStacks.push_back(stack);
  704. bs.enemyHero = cb->battleGetOwnerHero(stack);
  705. }
  706. }
  707. }
  708. bs.turnsSkippedByDefense = movesSkippedByDefense / bs.ourStacks.size();
  709. if(!bs.canFlee && !bs.canSurrender)
  710. {
  711. return std::nullopt;
  712. }
  713. auto result = cb->makeSurrenderRetreatDecision(bs);
  714. if(!result && bs.canFlee && bs.turnsSkippedByDefense > 30)
  715. {
  716. return BattleAction::makeRetreat(bs.ourSide);
  717. }
  718. return result;
  719. }