BattleAI.cpp 24 KB

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