BattleExchangeVariant.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  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 "BattleExchangeVariant.h"
  12. #include "../../lib/CStack.h"
  13. AttackerValue::AttackerValue()
  14. : value(0),
  15. isRetalitated(false)
  16. {
  17. }
  18. MoveTarget::MoveTarget()
  19. : positions(), cachedAttack(), score(EvaluationResult::INEFFECTIVE_SCORE), scorePerTurn(EvaluationResult::INEFFECTIVE_SCORE)
  20. {
  21. turnsToRich = 1;
  22. }
  23. float BattleExchangeVariant::trackAttack(
  24. const AttackPossibility & ap,
  25. std::shared_ptr<HypotheticBattle> hb,
  26. DamageCache & damageCache)
  27. {
  28. auto attacker = hb->getForUpdate(ap.attack.attacker->unitId());
  29. const std::string cachingStringBlocksRetaliation = "type_BLOCKS_RETALIATION";
  30. static const auto selectorBlocksRetaliation = Selector::type()(BonusType::BLOCKS_RETALIATION);
  31. const bool counterAttacksBlocked = attacker->hasBonus(selectorBlocksRetaliation, cachingStringBlocksRetaliation);
  32. float attackValue = 0;
  33. auto affectedUnits = ap.affectedUnits;
  34. affectedUnits.push_back(ap.attackerState);
  35. for(auto affectedUnit : affectedUnits)
  36. {
  37. auto unitToUpdate = hb->getForUpdate(affectedUnit->unitId());
  38. if(unitToUpdate->unitSide() == attacker->unitSide())
  39. {
  40. if(unitToUpdate->unitId() == attacker->unitId())
  41. {
  42. auto defender = hb->getForUpdate(ap.attack.defender->unitId());
  43. if(!defender->alive() || counterAttacksBlocked || ap.attack.shooting || !defender->ableToRetaliate())
  44. continue;
  45. auto retaliationDamage = damageCache.getDamage(defender.get(), unitToUpdate.get(), hb);
  46. auto attackerDamageReduce = AttackPossibility::calculateDamageReduce(defender.get(), unitToUpdate.get(), retaliationDamage, damageCache, hb);
  47. attackValue -= attackerDamageReduce;
  48. dpsScore.ourDamageReduce += attackerDamageReduce;
  49. attackerValue[unitToUpdate->unitId()].isRetalitated = true;
  50. unitToUpdate->damage(retaliationDamage);
  51. defender->afterAttack(false, true);
  52. #if BATTLE_TRACE_LEVEL>=1
  53. logAi->trace(
  54. "%s -> %s, ap retalitation, %s, dps: %2f, score: %2f",
  55. defender->getDescription(),
  56. unitToUpdate->getDescription(),
  57. ap.attack.shooting ? "shot" : "mellee",
  58. retaliationDamage,
  59. attackerDamageReduce);
  60. #endif
  61. }
  62. else
  63. {
  64. auto collateralDamage = damageCache.getDamage(attacker.get(), unitToUpdate.get(), hb);
  65. auto collateralDamageReduce = AttackPossibility::calculateDamageReduce(attacker.get(), unitToUpdate.get(), collateralDamage, damageCache, hb);
  66. attackValue -= collateralDamageReduce;
  67. dpsScore.ourDamageReduce += collateralDamageReduce;
  68. unitToUpdate->damage(collateralDamage);
  69. #if BATTLE_TRACE_LEVEL>=1
  70. logAi->trace(
  71. "%s -> %s, ap collateral, %s, dps: %2f, score: %2f",
  72. attacker->getDescription(),
  73. unitToUpdate->getDescription(),
  74. ap.attack.shooting ? "shot" : "mellee",
  75. collateralDamage,
  76. collateralDamageReduce);
  77. #endif
  78. }
  79. }
  80. else
  81. {
  82. int64_t attackDamage = damageCache.getDamage(attacker.get(), unitToUpdate.get(), hb);
  83. float defenderDamageReduce = AttackPossibility::calculateDamageReduce(attacker.get(), unitToUpdate.get(), attackDamage, damageCache, hb);
  84. attackValue += defenderDamageReduce;
  85. dpsScore.enemyDamageReduce += defenderDamageReduce;
  86. attackerValue[attacker->unitId()].value += defenderDamageReduce;
  87. unitToUpdate->damage(attackDamage);
  88. #if BATTLE_TRACE_LEVEL>=1
  89. logAi->trace(
  90. "%s -> %s, ap attack, %s, dps: %2f, score: %2f",
  91. attacker->getDescription(),
  92. unitToUpdate->getDescription(),
  93. ap.attack.shooting ? "shot" : "mellee",
  94. attackDamage,
  95. defenderDamageReduce);
  96. #endif
  97. }
  98. }
  99. #if BATTLE_TRACE_LEVEL >= 1
  100. logAi->trace("ap shooters blocking: %lld", ap.shootersBlockedDmg);
  101. #endif
  102. attackValue += ap.shootersBlockedDmg;
  103. dpsScore.enemyDamageReduce += ap.shootersBlockedDmg;
  104. attacker->afterAttack(ap.attack.shooting, false);
  105. return attackValue;
  106. }
  107. float BattleExchangeVariant::trackAttack(
  108. std::shared_ptr<StackWithBonuses> attacker,
  109. std::shared_ptr<StackWithBonuses> defender,
  110. bool shooting,
  111. bool isOurAttack,
  112. DamageCache & damageCache,
  113. std::shared_ptr<HypotheticBattle> hb,
  114. bool evaluateOnly)
  115. {
  116. const std::string cachingStringBlocksRetaliation = "type_BLOCKS_RETALIATION";
  117. static const auto selectorBlocksRetaliation = Selector::type()(BonusType::BLOCKS_RETALIATION);
  118. const bool counterAttacksBlocked = attacker->hasBonus(selectorBlocksRetaliation, cachingStringBlocksRetaliation);
  119. int64_t attackDamage = damageCache.getDamage(attacker.get(), defender.get(), hb);
  120. float defenderDamageReduce = AttackPossibility::calculateDamageReduce(attacker.get(), defender.get(), attackDamage, damageCache, hb);
  121. float attackerDamageReduce = 0;
  122. if(!evaluateOnly)
  123. {
  124. #if BATTLE_TRACE_LEVEL>=1
  125. logAi->trace(
  126. "%s -> %s, normal attack, %s, dps: %lld, %2f",
  127. attacker->getDescription(),
  128. defender->getDescription(),
  129. shooting ? "shot" : "mellee",
  130. attackDamage,
  131. defenderDamageReduce);
  132. #endif
  133. if(isOurAttack)
  134. {
  135. dpsScore.enemyDamageReduce += defenderDamageReduce;
  136. attackerValue[attacker->unitId()].value += defenderDamageReduce;
  137. }
  138. else
  139. dpsScore.ourDamageReduce += defenderDamageReduce;
  140. defender->damage(attackDamage);
  141. attacker->afterAttack(shooting, false);
  142. }
  143. if(!evaluateOnly && defender->alive() && defender->ableToRetaliate() && !counterAttacksBlocked && !shooting)
  144. {
  145. auto retaliationDamage = damageCache.getDamage(defender.get(), attacker.get(), hb);
  146. attackerDamageReduce = AttackPossibility::calculateDamageReduce(defender.get(), attacker.get(), retaliationDamage, damageCache, hb);
  147. #if BATTLE_TRACE_LEVEL>=1
  148. logAi->trace(
  149. "%s -> %s, retaliation, dps: %lld, %2f",
  150. defender->getDescription(),
  151. attacker->getDescription(),
  152. retaliationDamage,
  153. attackerDamageReduce);
  154. #endif
  155. if(isOurAttack)
  156. {
  157. dpsScore.ourDamageReduce += attackerDamageReduce;
  158. attackerValue[attacker->unitId()].isRetalitated = true;
  159. }
  160. else
  161. {
  162. dpsScore.enemyDamageReduce += attackerDamageReduce;
  163. attackerValue[defender->unitId()].value += attackerDamageReduce;
  164. }
  165. attacker->damage(retaliationDamage);
  166. defender->afterAttack(false, true);
  167. }
  168. auto score = defenderDamageReduce - attackerDamageReduce;
  169. #if BATTLE_TRACE_LEVEL>=1
  170. if(!score)
  171. {
  172. logAi->trace("Attack has zero score def:%2f att:%2f", defenderDamageReduce, attackerDamageReduce);
  173. }
  174. #endif
  175. return score;
  176. }
  177. float BattleExchangeEvaluator::scoreValue(const BattleScore & score) const
  178. {
  179. return score.enemyDamageReduce * getPositiveEffectMultiplier() - score.ourDamageReduce * getNegativeEffectMultiplier();
  180. }
  181. EvaluationResult BattleExchangeEvaluator::findBestTarget(
  182. const battle::Unit * activeStack,
  183. PotentialTargets & targets,
  184. DamageCache & damageCache,
  185. std::shared_ptr<HypotheticBattle> hb)
  186. {
  187. EvaluationResult result(targets.bestAction());
  188. if(!activeStack->waited() && !activeStack->acquireState()->hadMorale)
  189. {
  190. #if BATTLE_TRACE_LEVEL>=1
  191. logAi->trace("Evaluating waited attack for %s", activeStack->getDescription());
  192. #endif
  193. auto hbWaited = std::make_shared<HypotheticBattle>(env.get(), hb);
  194. hbWaited->getForUpdate(activeStack->unitId())->waiting = true;
  195. hbWaited->getForUpdate(activeStack->unitId())->waitedThisTurn = true;
  196. updateReachabilityMap(hbWaited);
  197. for(auto & ap : targets.possibleAttacks)
  198. {
  199. float score = evaluateExchange(ap, 0, targets, damageCache, hbWaited);
  200. if(score > result.score)
  201. {
  202. result.score = score;
  203. result.bestAttack = ap;
  204. result.wait = true;
  205. #if BATTLE_TRACE_LEVEL >= 1
  206. logAi->trace("New high score %2f", result.score);
  207. #endif
  208. }
  209. }
  210. }
  211. #if BATTLE_TRACE_LEVEL>=1
  212. logAi->trace("Evaluating normal attack for %s", activeStack->getDescription());
  213. #endif
  214. updateReachabilityMap(hb);
  215. if(result.bestAttack.attack.shooting
  216. && !activeStack->waited()
  217. && hb->battleHasShootingPenalty(activeStack, result.bestAttack.dest))
  218. {
  219. if(!canBeHitThisTurn(result.bestAttack))
  220. return result; // lets wait
  221. }
  222. for(auto & ap : targets.possibleAttacks)
  223. {
  224. float score = evaluateExchange(ap, 0, targets, damageCache, hb);
  225. if(score > result.score || (vstd::isAlmostEqual(score, result.score) && result.wait))
  226. {
  227. result.score = score;
  228. result.bestAttack = ap;
  229. result.wait = false;
  230. #if BATTLE_TRACE_LEVEL >= 1
  231. logAi->trace("New high score %2f", result.score);
  232. #endif
  233. }
  234. }
  235. return result;
  236. }
  237. MoveTarget BattleExchangeEvaluator::findMoveTowardsUnreachable(
  238. const battle::Unit * activeStack,
  239. PotentialTargets & targets,
  240. DamageCache & damageCache,
  241. std::shared_ptr<HypotheticBattle> hb)
  242. {
  243. MoveTarget result;
  244. BattleExchangeVariant ev;
  245. if(targets.unreachableEnemies.empty())
  246. return result;
  247. auto speed = activeStack->getMovementRange();
  248. if(speed == 0)
  249. return result;
  250. updateReachabilityMap(hb);
  251. auto dists = cb->getReachability(activeStack);
  252. for(const battle::Unit * enemy : targets.unreachableEnemies)
  253. {
  254. std::vector<const battle::Unit *> adjacentStacks = getAdjacentUnits(enemy);
  255. auto closestStack = *vstd::minElementByFun(adjacentStacks, [&](const battle::Unit * u) -> int64_t
  256. {
  257. return dists.distToNearestNeighbour(activeStack, u) * 100000 - activeStack->getTotalHealth();
  258. });
  259. auto distance = dists.distToNearestNeighbour(activeStack, closestStack);
  260. if(distance >= GameConstants::BFIELD_SIZE)
  261. continue;
  262. if(distance <= speed)
  263. continue;
  264. auto turnsToRich = (distance - 1) / speed + 1;
  265. auto hexes = closestStack->getSurroundingHexes();
  266. auto enemySpeed = closestStack->getMovementRange();
  267. auto speedRatio = speed / static_cast<float>(enemySpeed);
  268. auto multiplier = speedRatio > 1 ? 1 : speedRatio;
  269. if(enemy->canShoot())
  270. multiplier *= 1.5f;
  271. for(auto hex : hexes)
  272. {
  273. // FIXME: provide distance info for Jousting bonus
  274. auto bai = BattleAttackInfo(activeStack, closestStack, 0, cb->battleCanShoot(activeStack));
  275. auto attack = AttackPossibility::evaluate(bai, hex, damageCache, hb);
  276. attack.shootersBlockedDmg = 0; // we do not want to count on it, it is not for sure
  277. auto score = calculateExchange(attack, turnsToRich, targets, damageCache, hb);
  278. auto scorePerTurn = BattleScore(score.enemyDamageReduce * std::sqrt(multiplier / turnsToRich), score.ourDamageReduce);
  279. if(result.scorePerTurn < scoreValue(scorePerTurn))
  280. {
  281. result.scorePerTurn = scoreValue(scorePerTurn);
  282. result.score = scoreValue(score);
  283. result.positions = closestStack->getAttackableHexes(activeStack);
  284. result.cachedAttack = attack;
  285. result.turnsToRich = turnsToRich;
  286. }
  287. }
  288. }
  289. return result;
  290. }
  291. std::vector<const battle::Unit *> BattleExchangeEvaluator::getAdjacentUnits(const battle::Unit * blockerUnit) const
  292. {
  293. std::queue<const battle::Unit *> queue;
  294. std::vector<const battle::Unit *> checkedStacks;
  295. queue.push(blockerUnit);
  296. while(!queue.empty())
  297. {
  298. auto stack = queue.front();
  299. queue.pop();
  300. checkedStacks.push_back(stack);
  301. auto hexes = stack->getSurroundingHexes();
  302. for(auto hex : hexes)
  303. {
  304. auto neighbor = cb->battleGetUnitByPos(hex);
  305. if(neighbor && neighbor->unitSide() == stack->unitSide() && !vstd::contains(checkedStacks, neighbor))
  306. {
  307. queue.push(neighbor);
  308. checkedStacks.push_back(neighbor);
  309. }
  310. }
  311. }
  312. return checkedStacks;
  313. }
  314. ReachabilityData BattleExchangeEvaluator::getExchangeUnits(
  315. const AttackPossibility & ap,
  316. uint8_t turn,
  317. PotentialTargets & targets,
  318. std::shared_ptr<HypotheticBattle> hb) const
  319. {
  320. ReachabilityData result;
  321. auto hexes = ap.attack.defender->getSurroundingHexes();
  322. if(!ap.attack.shooting) hexes.push_back(ap.from);
  323. std::vector<const battle::Unit *> allReachableUnits;
  324. for(auto hex : hexes)
  325. {
  326. vstd::concatenate(allReachableUnits, turn == 0 ? reachabilityMap.at(hex) : getOneTurnReachableUnits(turn, hex));
  327. }
  328. vstd::removeDuplicates(allReachableUnits);
  329. auto copy = allReachableUnits;
  330. for(auto unit : copy)
  331. {
  332. for(auto adjacentUnit : getAdjacentUnits(unit))
  333. {
  334. auto unitWithBonuses = hb->battleGetUnitByID(adjacentUnit->unitId());
  335. if(vstd::contains(targets.unreachableEnemies, adjacentUnit)
  336. && !vstd::contains(allReachableUnits, unitWithBonuses))
  337. {
  338. allReachableUnits.push_back(unitWithBonuses);
  339. }
  340. }
  341. }
  342. vstd::removeDuplicates(allReachableUnits);
  343. if(!vstd::contains(allReachableUnits, ap.attack.attacker))
  344. {
  345. allReachableUnits.push_back(ap.attack.attacker);
  346. }
  347. if(allReachableUnits.size() < 2)
  348. {
  349. #if BATTLE_TRACE_LEVEL>=1
  350. logAi->trace("Reachability map contains only %d stacks", allReachableUnits.size());
  351. #endif
  352. return result;
  353. }
  354. for(auto unit : allReachableUnits)
  355. {
  356. auto accessible = !unit->canShoot();
  357. if(!accessible)
  358. {
  359. for(auto hex : unit->getSurroundingHexes())
  360. {
  361. if(ap.attack.defender->coversPos(hex))
  362. {
  363. accessible = true;
  364. }
  365. }
  366. }
  367. if(accessible)
  368. result.melleeAccessible.push_back(unit);
  369. else
  370. result.shooters.push_back(unit);
  371. }
  372. for(int turn = 0; turn < turnOrder.size(); turn++)
  373. {
  374. for(auto unit : turnOrder[turn])
  375. {
  376. if(vstd::contains(allReachableUnits, unit))
  377. result.units.push_back(unit);
  378. }
  379. }
  380. vstd::erase_if(result.units, [&](const battle::Unit * u) -> bool
  381. {
  382. return !hb->battleGetUnitByID(u->unitId())->alive();
  383. });
  384. return result;
  385. }
  386. float BattleExchangeEvaluator::evaluateExchange(
  387. const AttackPossibility & ap,
  388. uint8_t turn,
  389. PotentialTargets & targets,
  390. DamageCache & damageCache,
  391. std::shared_ptr<HypotheticBattle> hb) const
  392. {
  393. BattleScore score = calculateExchange(ap, turn, targets, damageCache, hb);
  394. #if BATTLE_TRACE_LEVEL >= 1
  395. logAi->trace(
  396. "calculateExchange score +%2f -%2fx%2f = %2f",
  397. score.enemyDamageReduce,
  398. score.ourDamageReduce,
  399. getNegativeEffectMultiplier(),
  400. scoreValue(score));
  401. #endif
  402. return scoreValue(score);
  403. }
  404. BattleScore BattleExchangeEvaluator::calculateExchange(
  405. const AttackPossibility & ap,
  406. uint8_t turn,
  407. PotentialTargets & targets,
  408. DamageCache & damageCache,
  409. std::shared_ptr<HypotheticBattle> hb) const
  410. {
  411. #if BATTLE_TRACE_LEVEL>=1
  412. logAi->trace("Battle exchange at %d", ap.attack.shooting ? ap.dest.hex : ap.from.hex);
  413. #endif
  414. if(cb->battleGetMySide() == BattlePerspective::LEFT_SIDE
  415. && cb->battleGetGateState() == EGateState::BLOCKED
  416. && ap.attack.defender->coversPos(BattleHex::GATE_BRIDGE))
  417. {
  418. return BattleScore(EvaluationResult::INEFFECTIVE_SCORE, 0);
  419. }
  420. std::vector<const battle::Unit *> ourStacks;
  421. std::vector<const battle::Unit *> enemyStacks;
  422. if(hb->battleGetUnitByID(ap.attack.defender->unitId())->alive())
  423. enemyStacks.push_back(ap.attack.defender);
  424. ReachabilityData exchangeUnits = getExchangeUnits(ap, turn, targets, hb);
  425. if(exchangeUnits.units.empty())
  426. {
  427. return BattleScore();
  428. }
  429. auto exchangeBattle = std::make_shared<HypotheticBattle>(env.get(), hb);
  430. BattleExchangeVariant v;
  431. for(auto unit : exchangeUnits.units)
  432. {
  433. if(unit->isTurret())
  434. continue;
  435. bool isOur = exchangeBattle->battleMatchOwner(ap.attack.attacker, unit, true);
  436. auto & attackerQueue = isOur ? ourStacks : enemyStacks;
  437. auto u = exchangeBattle->getForUpdate(unit->unitId());
  438. if(u->alive() && !vstd::contains(attackerQueue, unit))
  439. {
  440. attackerQueue.push_back(unit);
  441. #if BATTLE_TRACE_LEVEL
  442. logAi->trace("Exchanging: %s", u->getDescription());
  443. #endif
  444. }
  445. }
  446. auto melleeAttackers = ourStacks;
  447. vstd::removeDuplicates(melleeAttackers);
  448. vstd::erase_if(melleeAttackers, [&](const battle::Unit * u) -> bool
  449. {
  450. return cb->battleCanShoot(u);
  451. });
  452. bool canUseAp = true;
  453. for(auto activeUnit : exchangeUnits.units)
  454. {
  455. bool isOur = exchangeBattle->battleMatchOwner(ap.attack.attacker, activeUnit, true);
  456. battle::Units & attackerQueue = isOur ? ourStacks : enemyStacks;
  457. battle::Units & oppositeQueue = isOur ? enemyStacks : ourStacks;
  458. auto attacker = exchangeBattle->getForUpdate(activeUnit->unitId());
  459. if(!attacker->alive())
  460. {
  461. #if BATTLE_TRACE_LEVEL>=1
  462. logAi->trace( "Attacker is dead");
  463. #endif
  464. continue;
  465. }
  466. auto targetUnit = ap.attack.defender;
  467. if(!isOur || !exchangeBattle->battleGetUnitByID(targetUnit->unitId())->alive())
  468. {
  469. auto estimateAttack = [&](const battle::Unit * u) -> float
  470. {
  471. auto stackWithBonuses = exchangeBattle->getForUpdate(u->unitId());
  472. auto score = v.trackAttack(
  473. attacker,
  474. stackWithBonuses,
  475. exchangeBattle->battleCanShoot(stackWithBonuses.get()),
  476. isOur,
  477. damageCache,
  478. hb,
  479. true);
  480. #if BATTLE_TRACE_LEVEL>=1
  481. logAi->trace("Best target selector %s->%s score = %2f", attacker->getDescription(), stackWithBonuses->getDescription(), score);
  482. #endif
  483. return score;
  484. };
  485. auto unitsInOppositeQueueExceptInaccessible = oppositeQueue;
  486. vstd::erase_if(unitsInOppositeQueueExceptInaccessible, [&](const battle::Unit * u)->bool
  487. {
  488. return vstd::contains(exchangeUnits.shooters, u);
  489. });
  490. if(!unitsInOppositeQueueExceptInaccessible.empty())
  491. {
  492. targetUnit = *vstd::maxElementByFun(unitsInOppositeQueueExceptInaccessible, estimateAttack);
  493. }
  494. else
  495. {
  496. auto reachable = exchangeBattle->battleGetUnitsIf([this, &exchangeBattle, &attacker](const battle::Unit * u) -> bool
  497. {
  498. if(u->unitSide() == attacker->unitSide())
  499. return false;
  500. if(!exchangeBattle->getForUpdate(u->unitId())->alive())
  501. return false;
  502. return vstd::contains_if(reachabilityMap.at(u->getPosition()), [&attacker](const battle::Unit * other) -> bool
  503. {
  504. return attacker->unitId() == other->unitId();
  505. });
  506. });
  507. if(!reachable.empty())
  508. {
  509. targetUnit = *vstd::maxElementByFun(reachable, estimateAttack);
  510. }
  511. else
  512. {
  513. #if BATTLE_TRACE_LEVEL>=1
  514. logAi->trace("Battle queue is empty and no reachable enemy.");
  515. #endif
  516. continue;
  517. }
  518. }
  519. }
  520. auto defender = exchangeBattle->getForUpdate(targetUnit->unitId());
  521. auto shooting = exchangeBattle->battleCanShoot(attacker.get());
  522. const int totalAttacks = attacker->getTotalAttacks(shooting);
  523. if(canUseAp && activeUnit->unitId() == ap.attack.attacker->unitId()
  524. && targetUnit->unitId() == ap.attack.defender->unitId())
  525. {
  526. v.trackAttack(ap, exchangeBattle, damageCache);
  527. }
  528. else
  529. {
  530. for(int i = 0; i < totalAttacks; i++)
  531. {
  532. v.trackAttack(attacker, defender, shooting, isOur, damageCache, exchangeBattle);
  533. if(!attacker->alive() || !defender->alive())
  534. break;
  535. }
  536. }
  537. canUseAp = false;
  538. vstd::erase_if(attackerQueue, [&](const battle::Unit * u) -> bool
  539. {
  540. return !exchangeBattle->battleGetUnitByID(u->unitId())->alive();
  541. });
  542. vstd::erase_if(oppositeQueue, [&](const battle::Unit * u) -> bool
  543. {
  544. return !exchangeBattle->battleGetUnitByID(u->unitId())->alive();
  545. });
  546. }
  547. // avoid blocking path for stronger stack by weaker stack
  548. // the method checks if all stacks can be placed around enemy
  549. std::map<BattleHex, battle::Units> reachabilityMap;
  550. auto hexes = ap.attack.defender->getSurroundingHexes();
  551. for(auto hex : hexes)
  552. reachabilityMap[hex] = getOneTurnReachableUnits(turn, hex);
  553. #if BATTLE_TRACE_LEVEL>=1
  554. logAi->trace("Exchange score: enemy: %2f, our -%2f", v.getScore().enemyDamageReduce, v.getScore().ourDamageReduce);
  555. #endif
  556. return v.getScore();
  557. }
  558. bool BattleExchangeEvaluator::canBeHitThisTurn(const AttackPossibility & ap)
  559. {
  560. for(auto pos : ap.attack.attacker->getSurroundingHexes())
  561. {
  562. for(auto u : reachabilityMap[pos])
  563. {
  564. if(u->unitSide() != ap.attack.attacker->unitSide())
  565. {
  566. return true;
  567. }
  568. }
  569. }
  570. return false;
  571. }
  572. void BattleExchangeEvaluator::updateReachabilityMap(std::shared_ptr<HypotheticBattle> hb)
  573. {
  574. const int TURN_DEPTH = 2;
  575. turnOrder.clear();
  576. hb->battleGetTurnOrder(turnOrder, std::numeric_limits<int>::max(), TURN_DEPTH);
  577. for(auto turn : turnOrder)
  578. {
  579. for(auto u : turn)
  580. {
  581. if(!vstd::contains(reachabilityCache, u->unitId()))
  582. {
  583. reachabilityCache[u->unitId()] = hb->getReachability(u);
  584. }
  585. }
  586. }
  587. for(BattleHex hex = BattleHex::TOP_LEFT; hex.isValid(); hex = hex + 1)
  588. {
  589. reachabilityMap[hex] = getOneTurnReachableUnits(0, hex);
  590. }
  591. }
  592. std::vector<const battle::Unit *> BattleExchangeEvaluator::getOneTurnReachableUnits(uint8_t turn, BattleHex hex) const
  593. {
  594. std::vector<const battle::Unit *> result;
  595. for(int i = 0; i < turnOrder.size(); i++, turn++)
  596. {
  597. auto & turnQueue = turnOrder[i];
  598. HypotheticBattle turnBattle(env.get(), cb);
  599. for(const battle::Unit * unit : turnQueue)
  600. {
  601. if(unit->isTurret())
  602. continue;
  603. if(turnBattle.battleCanShoot(unit))
  604. {
  605. result.push_back(unit);
  606. continue;
  607. }
  608. auto unitSpeed = unit->getMovementRange(turn);
  609. auto radius = unitSpeed * (turn + 1);
  610. auto reachabilityIter = reachabilityCache.find(unit->unitId());
  611. assert(reachabilityIter != reachabilityCache.end()); // missing updateReachabilityMap call?
  612. ReachabilityInfo unitReachability = reachabilityIter != reachabilityCache.end() ? reachabilityIter->second : turnBattle.getReachability(unit);
  613. bool reachable = unitReachability.distances[hex] <= radius;
  614. if(!reachable && unitReachability.accessibility[hex] == EAccessibility::ALIVE_STACK)
  615. {
  616. const battle::Unit * hexStack = cb->battleGetUnitByPos(hex);
  617. if(hexStack && cb->battleMatchOwner(unit, hexStack, false))
  618. {
  619. for(BattleHex neighbor : hex.neighbouringTiles())
  620. {
  621. reachable = unitReachability.distances[neighbor] <= radius;
  622. if(reachable) break;
  623. }
  624. }
  625. }
  626. if(reachable)
  627. {
  628. result.push_back(unit);
  629. }
  630. }
  631. }
  632. return result;
  633. }
  634. // avoid blocking path for stronger stack by weaker stack
  635. bool BattleExchangeEvaluator::checkPositionBlocksOurStacks(HypotheticBattle & hb, const battle::Unit * activeUnit, BattleHex position)
  636. {
  637. const int BLOCKING_THRESHOLD = 70;
  638. const int BLOCKING_OWN_ATTACK_PENALTY = 100;
  639. const int BLOCKING_OWN_MOVE_PENALTY = 1;
  640. float blockingScore = 0;
  641. auto activeUnitDamage = activeUnit->getMinDamage(hb.battleCanShoot(activeUnit)) * activeUnit->getCount();
  642. for(int turn = 0; turn < turnOrder.size(); turn++)
  643. {
  644. auto & turnQueue = turnOrder[turn];
  645. HypotheticBattle turnBattle(env.get(), cb);
  646. auto unitToUpdate = turnBattle.getForUpdate(activeUnit->unitId());
  647. unitToUpdate->setPosition(position);
  648. for(const battle::Unit * unit : turnQueue)
  649. {
  650. if(unit->unitId() == unitToUpdate->unitId() || cb->battleMatchOwner(unit, activeUnit, false))
  651. continue;
  652. auto blockedUnitDamage = unit->getMinDamage(hb.battleCanShoot(unit)) * unit->getCount();
  653. float ratio = blockedUnitDamage / (float)(blockedUnitDamage + activeUnitDamage + 0.01);
  654. auto unitReachability = turnBattle.getReachability(unit);
  655. auto unitSpeed = unit->getMovementRange(turn); // Cached value, to avoid performance hit
  656. for(BattleHex hex = BattleHex::TOP_LEFT; hex.isValid(); hex = hex + 1)
  657. {
  658. bool enemyUnit = false;
  659. bool reachable = unitReachability.distances[hex] <= unitSpeed;
  660. if(!reachable && unitReachability.accessibility[hex] == EAccessibility::ALIVE_STACK)
  661. {
  662. const battle::Unit * hexStack = turnBattle.battleGetUnitByPos(hex);
  663. if(hexStack && cb->battleMatchOwner(unit, hexStack, false))
  664. {
  665. enemyUnit = true;
  666. for(BattleHex neighbor : hex.neighbouringTiles())
  667. {
  668. reachable = unitReachability.distances[neighbor] <= unitSpeed;
  669. if(reachable) break;
  670. }
  671. }
  672. }
  673. if(!reachable && std::count(reachabilityMap[hex].begin(), reachabilityMap[hex].end(), unit) > 1)
  674. {
  675. blockingScore += ratio * (enemyUnit ? BLOCKING_OWN_ATTACK_PENALTY : BLOCKING_OWN_MOVE_PENALTY);
  676. }
  677. }
  678. }
  679. }
  680. #if BATTLE_TRACE_LEVEL>=1
  681. logAi->trace("Position %d, blocking score %f", position.hex, blockingScore);
  682. #endif
  683. return blockingScore > BLOCKING_THRESHOLD;
  684. }