BattleExchangeVariant.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  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 "BattleEvaluator.h"
  13. #include "../../lib/CStack.h"
  14. AttackerValue::AttackerValue()
  15. : value(0),
  16. isRetaliated(false)
  17. {
  18. }
  19. MoveTarget::MoveTarget()
  20. : positions(), cachedAttack(), score(EvaluationResult::INEFFECTIVE_SCORE)
  21. {
  22. turnsToRich = 1;
  23. }
  24. float BattleExchangeVariant::trackAttack(
  25. const AttackPossibility & ap,
  26. std::shared_ptr<HypotheticBattle> hb,
  27. DamageCache & damageCache)
  28. {
  29. if(!ap.attackerState)
  30. {
  31. logAi->trace("Skipping fake ap attack");
  32. return 0;
  33. }
  34. auto attacker = hb->getForUpdate(ap.attack.attacker->unitId());
  35. float attackValue = ap.attackValue();
  36. auto affectedUnits = ap.affectedUnits;
  37. dpsScore.ourDamageReduce += ap.attackerDamageReduce + ap.collateralDamageReduce;
  38. dpsScore.enemyDamageReduce += ap.defenderDamageReduce + ap.shootersBlockedDmg;
  39. attackerValue[attacker->unitId()].value = attackValue;
  40. affectedUnits.push_back(ap.attackerState);
  41. for(auto affectedUnit : affectedUnits)
  42. {
  43. auto unitToUpdate = hb->getForUpdate(affectedUnit->unitId());
  44. auto damageDealt = unitToUpdate->getAvailableHealth() - affectedUnit->getAvailableHealth();
  45. if(damageDealt > 0)
  46. {
  47. unitToUpdate->damage(damageDealt);
  48. }
  49. if(unitToUpdate->unitSide() == attacker->unitSide())
  50. {
  51. if(unitToUpdate->unitId() == attacker->unitId())
  52. {
  53. unitToUpdate->afterAttack(ap.attack.shooting, false);
  54. #if BATTLE_TRACE_LEVEL>=1
  55. logAi->trace(
  56. "%s -> %s, ap retaliation, %s, dps: %lld",
  57. hb->getForUpdate(ap.attack.defender->unitId())->getDescription(),
  58. ap.attack.attacker->getDescription(),
  59. ap.attack.shooting ? "shot" : "mellee",
  60. damageDealt);
  61. #endif
  62. }
  63. else
  64. {
  65. #if BATTLE_TRACE_LEVEL>=1
  66. logAi->trace(
  67. "%s, ap collateral, dps: %lld",
  68. unitToUpdate->getDescription(),
  69. damageDealt);
  70. #endif
  71. }
  72. }
  73. else
  74. {
  75. if(unitToUpdate->unitId() == ap.attack.defender->unitId())
  76. {
  77. if(unitToUpdate->ableToRetaliate() && !affectedUnit->ableToRetaliate())
  78. {
  79. unitToUpdate->afterAttack(ap.attack.shooting, true);
  80. }
  81. #if BATTLE_TRACE_LEVEL>=1
  82. logAi->trace(
  83. "%s -> %s, ap attack, %s, dps: %lld",
  84. attacker->getDescription(),
  85. ap.attack.defender->getDescription(),
  86. ap.attack.shooting ? "shot" : "mellee",
  87. damageDealt);
  88. #endif
  89. }
  90. else
  91. {
  92. #if BATTLE_TRACE_LEVEL>=1
  93. logAi->trace(
  94. "%s, ap enemy collateral, dps: %lld",
  95. unitToUpdate->getDescription(),
  96. damageDealt);
  97. #endif
  98. }
  99. }
  100. }
  101. #if BATTLE_TRACE_LEVEL >= 1
  102. logAi->trace(
  103. "ap score: our: %2f, enemy: %2f, collateral: %2f, blocked: %2f",
  104. ap.attackerDamageReduce,
  105. ap.defenderDamageReduce,
  106. ap.collateralDamageReduce,
  107. ap.shootersBlockedDmg);
  108. #endif
  109. return attackValue;
  110. }
  111. float BattleExchangeVariant::trackAttack(
  112. std::shared_ptr<StackWithBonuses> attacker,
  113. std::shared_ptr<StackWithBonuses> defender,
  114. bool shooting,
  115. bool isOurAttack,
  116. DamageCache & damageCache,
  117. std::shared_ptr<HypotheticBattle> hb,
  118. bool evaluateOnly)
  119. {
  120. const std::string cachingStringBlocksRetaliation = "type_BLOCKS_RETALIATION";
  121. static const auto selectorBlocksRetaliation = Selector::type()(BonusType::BLOCKS_RETALIATION);
  122. const bool counterAttacksBlocked = attacker->hasBonus(selectorBlocksRetaliation, cachingStringBlocksRetaliation);
  123. int64_t attackDamage = damageCache.getDamage(attacker.get(), defender.get(), hb);
  124. float defenderDamageReduce = AttackPossibility::calculateDamageReduce(attacker.get(), defender.get(), attackDamage, damageCache, hb);
  125. float attackerDamageReduce = 0;
  126. if(!evaluateOnly)
  127. {
  128. #if BATTLE_TRACE_LEVEL>=1
  129. logAi->trace(
  130. "%s -> %s, normal attack, %s, dps: %lld, %2f",
  131. attacker->getDescription(),
  132. defender->getDescription(),
  133. shooting ? "shot" : "mellee",
  134. attackDamage,
  135. defenderDamageReduce);
  136. #endif
  137. if(isOurAttack)
  138. {
  139. dpsScore.enemyDamageReduce += defenderDamageReduce;
  140. attackerValue[attacker->unitId()].value += defenderDamageReduce;
  141. }
  142. else
  143. dpsScore.ourDamageReduce += defenderDamageReduce;
  144. defender->damage(attackDamage);
  145. attacker->afterAttack(shooting, false);
  146. }
  147. if(!evaluateOnly && defender->alive() && defender->ableToRetaliate() && !counterAttacksBlocked && !shooting)
  148. {
  149. auto retaliationDamage = damageCache.getDamage(defender.get(), attacker.get(), hb);
  150. attackerDamageReduce = AttackPossibility::calculateDamageReduce(defender.get(), attacker.get(), retaliationDamage, damageCache, hb);
  151. #if BATTLE_TRACE_LEVEL>=1
  152. logAi->trace(
  153. "%s -> %s, retaliation, dps: %lld, %2f",
  154. defender->getDescription(),
  155. attacker->getDescription(),
  156. retaliationDamage,
  157. attackerDamageReduce);
  158. #endif
  159. if(isOurAttack)
  160. {
  161. dpsScore.ourDamageReduce += attackerDamageReduce;
  162. attackerValue[attacker->unitId()].isRetaliated = true;
  163. }
  164. else
  165. {
  166. dpsScore.enemyDamageReduce += attackerDamageReduce;
  167. attackerValue[defender->unitId()].value += attackerDamageReduce;
  168. }
  169. attacker->damage(retaliationDamage);
  170. defender->afterAttack(false, true);
  171. }
  172. auto score = defenderDamageReduce - attackerDamageReduce;
  173. #if BATTLE_TRACE_LEVEL>=1
  174. if(!score)
  175. {
  176. logAi->trace("Attack has zero score def:%2f att:%2f", defenderDamageReduce, attackerDamageReduce);
  177. }
  178. #endif
  179. return score;
  180. }
  181. float BattleExchangeEvaluator::scoreValue(const BattleScore & score) const
  182. {
  183. return score.enemyDamageReduce * getPositiveEffectMultiplier() - score.ourDamageReduce * getNegativeEffectMultiplier();
  184. }
  185. EvaluationResult BattleExchangeEvaluator::findBestTarget(
  186. const battle::Unit * activeStack,
  187. PotentialTargets & targets,
  188. DamageCache & damageCache,
  189. std::shared_ptr<HypotheticBattle> hb,
  190. bool siegeDefense)
  191. {
  192. EvaluationResult result(targets.bestAction());
  193. std::vector<BattleHex> castleHexes = BattleEvaluator::getCastleHexes();
  194. if(!activeStack->waited() && !activeStack->acquireState()->hadMorale)
  195. {
  196. #if BATTLE_TRACE_LEVEL>=1
  197. logAi->trace("Evaluating waited attack for %s", activeStack->getDescription());
  198. #endif
  199. auto hbWaited = std::make_shared<HypotheticBattle>(env.get(), hb);
  200. hbWaited->makeWait(activeStack);
  201. updateReachabilityMap(hbWaited);
  202. for(auto & ap : targets.possibleAttacks)
  203. {
  204. if (siegeDefense && std::find(castleHexes.begin(), castleHexes.end(), ap.from) == castleHexes.end())
  205. continue;
  206. float score = evaluateExchange(ap, 0, targets, damageCache, hbWaited);
  207. if(score > result.score)
  208. {
  209. result.score = score;
  210. result.bestAttack = ap;
  211. result.wait = true;
  212. #if BATTLE_TRACE_LEVEL >= 1
  213. logAi->trace("New high score %2f", result.score);
  214. #endif
  215. }
  216. }
  217. }
  218. #if BATTLE_TRACE_LEVEL>=1
  219. logAi->trace("Evaluating normal attack for %s", activeStack->getDescription());
  220. #endif
  221. updateReachabilityMap(hb);
  222. if(result.bestAttack.attack.shooting
  223. && !result.bestAttack.defenderDead
  224. && !activeStack->waited()
  225. && hb->battleHasShootingPenalty(activeStack, result.bestAttack.dest))
  226. {
  227. if(!canBeHitThisTurn(result.bestAttack))
  228. return result; // lets wait
  229. }
  230. for(auto & ap : targets.possibleAttacks)
  231. {
  232. if (siegeDefense && std::find(castleHexes.begin(), castleHexes.end(), ap.from) == castleHexes.end())
  233. continue;
  234. float score = evaluateExchange(ap, 0, targets, damageCache, hb);
  235. bool sameScoreButWaited = vstd::isAlmostEqual(score, result.score) && result.wait;
  236. if(score > result.score || sameScoreButWaited)
  237. {
  238. result.score = score;
  239. result.bestAttack = ap;
  240. result.wait = false;
  241. #if BATTLE_TRACE_LEVEL >= 1
  242. logAi->trace("New high score %2f", result.score);
  243. #endif
  244. }
  245. }
  246. return result;
  247. }
  248. ReachabilityInfo getReachabilityWithEnemyBypass(
  249. const battle::Unit * activeStack,
  250. DamageCache & damageCache,
  251. std::shared_ptr<HypotheticBattle> state)
  252. {
  253. ReachabilityInfo::Parameters params(activeStack, activeStack->getPosition());
  254. if(!params.flying)
  255. {
  256. for(const auto * unit : state->battleAliveUnits())
  257. {
  258. if(unit->unitSide() == activeStack->unitSide())
  259. continue;
  260. auto dmg = damageCache.getOriginalDamage(activeStack, unit, state);
  261. auto turnsToKill = unit->getAvailableHealth() / std::max(dmg, (int64_t)1);
  262. vstd::amin(turnsToKill, 100);
  263. for(auto & hex : unit->getHexes())
  264. if(hex.isAvailable()) //towers can have <0 pos; we don't also want to overwrite side columns
  265. params.destructibleEnemyTurns[hex] = turnsToKill * unit->getMovementRange();
  266. }
  267. params.bypassEnemyStacks = true;
  268. }
  269. return state->getReachability(params);
  270. }
  271. MoveTarget BattleExchangeEvaluator::findMoveTowardsUnreachable(
  272. const battle::Unit * activeStack,
  273. PotentialTargets & targets,
  274. DamageCache & damageCache,
  275. std::shared_ptr<HypotheticBattle> hb)
  276. {
  277. MoveTarget result;
  278. BattleExchangeVariant ev;
  279. logAi->trace("Find move towards unreachable. Enemies count %d", targets.unreachableEnemies.size());
  280. if(targets.unreachableEnemies.empty())
  281. return result;
  282. auto speed = activeStack->getMovementRange();
  283. if(speed == 0)
  284. return result;
  285. updateReachabilityMap(hb);
  286. auto dists = getReachabilityWithEnemyBypass(activeStack, damageCache, hb);
  287. auto flying = activeStack->hasBonusOfType(BonusType::FLYING);
  288. for(const battle::Unit * enemy : targets.unreachableEnemies)
  289. {
  290. logAi->trace(
  291. "Checking movement towards %d of %s",
  292. enemy->getCount(),
  293. enemy->creatureId().toCreature()->getNameSingularTranslated());
  294. auto distance = dists.distToNearestNeighbour(activeStack, enemy);
  295. if(distance >= GameConstants::BFIELD_SIZE)
  296. continue;
  297. if(distance <= speed)
  298. continue;
  299. float penaltyMultiplier = 1.0f; // Default multiplier, no penalty
  300. float closestAllyDistance = std::numeric_limits<float>::max();
  301. for (const battle::Unit* ally : hb->battleAliveUnits()) {
  302. if (ally == activeStack)
  303. continue;
  304. if (ally->unitSide() != activeStack->unitSide())
  305. continue;
  306. float allyDistance = dists.distToNearestNeighbour(ally, enemy);
  307. if (allyDistance < closestAllyDistance)
  308. {
  309. closestAllyDistance = allyDistance;
  310. }
  311. }
  312. // If an ally is closer to the enemy, compute the penaltyMultiplier
  313. if (closestAllyDistance < distance) {
  314. penaltyMultiplier = closestAllyDistance / distance; // Ratio of distances
  315. }
  316. auto turnsToRich = (distance - 1) / speed + 1;
  317. auto hexes = enemy->getSurroundingHexes();
  318. auto enemySpeed = enemy->getMovementRange();
  319. auto speedRatio = speed / static_cast<float>(enemySpeed);
  320. auto multiplier = (speedRatio > 1 ? 1 : speedRatio) * penaltyMultiplier;
  321. for(auto & hex : hexes)
  322. {
  323. // FIXME: provide distance info for Jousting bonus
  324. auto bai = BattleAttackInfo(activeStack, enemy, 0, cb->battleCanShoot(activeStack));
  325. auto attack = AttackPossibility::evaluate(bai, hex, damageCache, hb);
  326. attack.shootersBlockedDmg = 0; // we do not want to count on it, it is not for sure
  327. auto score = calculateExchange(attack, turnsToRich, targets, damageCache, hb);
  328. score.enemyDamageReduce *= multiplier;
  329. #if BATTLE_TRACE_LEVEL >= 1
  330. logAi->trace("Multiplier: %f, turns: %d, current score %f, new score %f", multiplier, turnsToRich, result.score, scoreValue(score));
  331. #endif
  332. if(result.score < scoreValue(score)
  333. || (result.turnsToRich > turnsToRich && vstd::isAlmostEqual(result.score, scoreValue(score))))
  334. {
  335. result.score = scoreValue(score);
  336. result.positions.clear();
  337. #if BATTLE_TRACE_LEVEL >= 1
  338. logAi->trace("New high score");
  339. #endif
  340. for(const BattleHex & initialEnemyHex : enemy->getAttackableHexes(activeStack))
  341. {
  342. BattleHex enemyHex = initialEnemyHex;
  343. while(!flying && dists.distances[enemyHex] > speed && dists.predecessors.at(enemyHex).isValid())
  344. {
  345. enemyHex = dists.predecessors.at(enemyHex);
  346. if(dists.accessibility[enemyHex] == EAccessibility::ALIVE_STACK)
  347. {
  348. auto defenderToBypass = hb->battleGetUnitByPos(enemyHex);
  349. if(defenderToBypass)
  350. {
  351. #if BATTLE_TRACE_LEVEL >= 1
  352. logAi->trace("Found target to bypass at %d", enemyHex.hex);
  353. #endif
  354. auto attackHex = dists.predecessors[enemyHex];
  355. auto baiBypass = BattleAttackInfo(activeStack, defenderToBypass, 0, cb->battleCanShoot(activeStack));
  356. auto attackBypass = AttackPossibility::evaluate(baiBypass, attackHex, damageCache, hb);
  357. auto adjacentStacks = getAdjacentUnits(enemy);
  358. adjacentStacks.push_back(defenderToBypass);
  359. vstd::removeDuplicates(adjacentStacks);
  360. auto bypassScore = calculateExchange(
  361. attackBypass,
  362. dists.distances[attackHex],
  363. targets,
  364. damageCache,
  365. hb,
  366. adjacentStacks);
  367. if(scoreValue(bypassScore) > result.score)
  368. {
  369. result.score = scoreValue(bypassScore);
  370. #if BATTLE_TRACE_LEVEL >= 1
  371. logAi->trace("New high score after bypass %f", scoreValue(bypassScore));
  372. #endif
  373. }
  374. }
  375. }
  376. }
  377. result.positions.push_back(enemyHex);
  378. }
  379. result.cachedAttack = attack;
  380. result.turnsToRich = turnsToRich;
  381. }
  382. }
  383. }
  384. return result;
  385. }
  386. std::vector<const battle::Unit *> BattleExchangeEvaluator::getAdjacentUnits(const battle::Unit * blockerUnit) const
  387. {
  388. std::queue<const battle::Unit *> queue;
  389. std::vector<const battle::Unit *> checkedStacks;
  390. queue.push(blockerUnit);
  391. while(!queue.empty())
  392. {
  393. auto stack = queue.front();
  394. queue.pop();
  395. checkedStacks.push_back(stack);
  396. auto hexes = stack->getSurroundingHexes();
  397. for(auto hex : hexes)
  398. {
  399. auto neighbor = cb->battleGetUnitByPos(hex);
  400. if(neighbor && neighbor->unitSide() == stack->unitSide() && !vstd::contains(checkedStacks, neighbor))
  401. {
  402. queue.push(neighbor);
  403. checkedStacks.push_back(neighbor);
  404. }
  405. }
  406. }
  407. return checkedStacks;
  408. }
  409. ReachabilityData BattleExchangeEvaluator::getExchangeUnits(
  410. const AttackPossibility & ap,
  411. uint8_t turn,
  412. PotentialTargets & targets,
  413. std::shared_ptr<HypotheticBattle> hb,
  414. std::vector<const battle::Unit *> additionalUnits) const
  415. {
  416. ReachabilityData result;
  417. auto hexes = ap.attack.defender->getSurroundingHexes();
  418. if(!ap.attack.shooting) hexes.push_back(ap.from);
  419. std::vector<const battle::Unit *> allReachableUnits = additionalUnits;
  420. for(auto hex : hexes)
  421. {
  422. vstd::concatenate(allReachableUnits, turn == 0 ? reachabilityMap.at(hex) : getOneTurnReachableUnits(turn, hex));
  423. }
  424. if(!ap.attack.attacker->isTurret())
  425. {
  426. for(auto hex : ap.attack.attacker->getHexes())
  427. {
  428. auto unitsReachingAttacker = turn == 0 ? reachabilityMap.at(hex) : getOneTurnReachableUnits(turn, hex);
  429. for(auto unit : unitsReachingAttacker)
  430. {
  431. if(unit->unitSide() != ap.attack.attacker->unitSide())
  432. {
  433. allReachableUnits.push_back(unit);
  434. result.enemyUnitsReachingAttacker.insert(unit->unitId());
  435. }
  436. }
  437. }
  438. }
  439. vstd::removeDuplicates(allReachableUnits);
  440. auto copy = allReachableUnits;
  441. for(auto unit : copy)
  442. {
  443. for(auto adjacentUnit : getAdjacentUnits(unit))
  444. {
  445. auto unitWithBonuses = hb->battleGetUnitByID(adjacentUnit->unitId());
  446. if(vstd::contains(targets.unreachableEnemies, adjacentUnit)
  447. && !vstd::contains(allReachableUnits, unitWithBonuses))
  448. {
  449. allReachableUnits.push_back(unitWithBonuses);
  450. }
  451. }
  452. }
  453. vstd::removeDuplicates(allReachableUnits);
  454. if(!vstd::contains(allReachableUnits, ap.attack.attacker))
  455. {
  456. allReachableUnits.push_back(ap.attack.attacker);
  457. }
  458. if(allReachableUnits.size() < 2)
  459. {
  460. #if BATTLE_TRACE_LEVEL>=1
  461. logAi->trace("Reachability map contains only %d stacks", allReachableUnits.size());
  462. #endif
  463. return result;
  464. }
  465. for(auto unit : allReachableUnits)
  466. {
  467. auto accessible = !unit->canShoot() || vstd::contains(additionalUnits, unit);
  468. if(!accessible)
  469. {
  470. for(auto hex : unit->getSurroundingHexes())
  471. {
  472. if(ap.attack.defender->coversPos(hex))
  473. {
  474. accessible = true;
  475. }
  476. }
  477. }
  478. if(accessible)
  479. result.melleeAccessible.push_back(unit);
  480. else
  481. result.shooters.push_back(unit);
  482. }
  483. for(int turn = 0; turn < turnOrder.size(); turn++)
  484. {
  485. for(auto unit : turnOrder[turn])
  486. {
  487. if(vstd::contains(allReachableUnits, unit))
  488. result.units[turn].push_back(unit);
  489. }
  490. vstd::erase_if(result.units[turn], [&](const battle::Unit * u) -> bool
  491. {
  492. return !hb->battleGetUnitByID(u->unitId())->alive();
  493. });
  494. }
  495. return result;
  496. }
  497. float BattleExchangeEvaluator::evaluateExchange(
  498. const AttackPossibility & ap,
  499. uint8_t turn,
  500. PotentialTargets & targets,
  501. DamageCache & damageCache,
  502. std::shared_ptr<HypotheticBattle> hb) const
  503. {
  504. BattleScore score = calculateExchange(ap, turn, targets, damageCache, hb);
  505. #if BATTLE_TRACE_LEVEL >= 1
  506. logAi->trace(
  507. "calculateExchange score +%2f -%2fx%2f = %2f",
  508. score.enemyDamageReduce,
  509. score.ourDamageReduce,
  510. getNegativeEffectMultiplier(),
  511. scoreValue(score));
  512. #endif
  513. return scoreValue(score);
  514. }
  515. BattleScore BattleExchangeEvaluator::calculateExchange(
  516. const AttackPossibility & ap,
  517. uint8_t turn,
  518. PotentialTargets & targets,
  519. DamageCache & damageCache,
  520. std::shared_ptr<HypotheticBattle> hb,
  521. std::vector<const battle::Unit *> additionalUnits) const
  522. {
  523. #if BATTLE_TRACE_LEVEL>=1
  524. logAi->trace("Battle exchange at %d", ap.attack.shooting ? ap.dest.hex : ap.from.hex);
  525. #endif
  526. if(cb->battleGetMySide() == BattleSide::LEFT_SIDE
  527. && cb->battleGetGateState() == EGateState::BLOCKED
  528. && ap.attack.defender->coversPos(BattleHex::GATE_BRIDGE))
  529. {
  530. return BattleScore(EvaluationResult::INEFFECTIVE_SCORE, 0);
  531. }
  532. std::vector<const battle::Unit *> ourStacks;
  533. std::vector<const battle::Unit *> enemyStacks;
  534. if(hb->battleGetUnitByID(ap.attack.defender->unitId())->alive())
  535. enemyStacks.push_back(ap.attack.defender);
  536. ReachabilityData exchangeUnits = getExchangeUnits(ap, turn, targets, hb, additionalUnits);
  537. if(exchangeUnits.units.empty())
  538. {
  539. return BattleScore();
  540. }
  541. auto exchangeBattle = std::make_shared<HypotheticBattle>(env.get(), hb);
  542. BattleExchangeVariant v;
  543. for(int exchangeTurn = 0; exchangeTurn < exchangeUnits.units.size(); exchangeTurn++)
  544. {
  545. for(auto unit : exchangeUnits.units.at(exchangeTurn))
  546. {
  547. if(unit->isTurret())
  548. continue;
  549. bool isOur = exchangeBattle->battleMatchOwner(ap.attack.attacker, unit, true);
  550. auto & attackerQueue = isOur ? ourStacks : enemyStacks;
  551. auto u = exchangeBattle->getForUpdate(unit->unitId());
  552. if(u->alive() && !vstd::contains(attackerQueue, unit))
  553. {
  554. attackerQueue.push_back(unit);
  555. #if BATTLE_TRACE_LEVEL
  556. logAi->trace("Exchanging: %s", u->getDescription());
  557. #endif
  558. }
  559. }
  560. }
  561. auto melleeAttackers = ourStacks;
  562. vstd::removeDuplicates(melleeAttackers);
  563. vstd::erase_if(melleeAttackers, [&](const battle::Unit * u) -> bool
  564. {
  565. return cb->battleCanShoot(u);
  566. });
  567. bool canUseAp = true;
  568. std::set<uint32_t> blockedShooters;
  569. int totalTurnsCount = simulationTurnsCount >= turn + turnOrder.size()
  570. ? simulationTurnsCount
  571. : turn + turnOrder.size();
  572. for(int exchangeTurn = 0; exchangeTurn < simulationTurnsCount; exchangeTurn++)
  573. {
  574. bool isMovingTurm = exchangeTurn < turn;
  575. int queueTurn = exchangeTurn >= exchangeUnits.units.size()
  576. ? exchangeUnits.units.size() - 1
  577. : exchangeTurn;
  578. for(auto activeUnit : exchangeUnits.units.at(queueTurn))
  579. {
  580. bool isOur = exchangeBattle->battleMatchOwner(ap.attack.attacker, activeUnit, true);
  581. battle::Units & attackerQueue = isOur ? ourStacks : enemyStacks;
  582. battle::Units & oppositeQueue = isOur ? enemyStacks : ourStacks;
  583. auto attacker = exchangeBattle->getForUpdate(activeUnit->unitId());
  584. auto shooting = exchangeBattle->battleCanShoot(attacker.get())
  585. && !vstd::contains(blockedShooters, attacker->unitId());
  586. if(!attacker->alive())
  587. {
  588. #if BATTLE_TRACE_LEVEL>=1
  589. logAi->trace("Attacker is dead");
  590. #endif
  591. continue;
  592. }
  593. if(isMovingTurm && !shooting
  594. && !vstd::contains(exchangeUnits.enemyUnitsReachingAttacker, attacker->unitId()))
  595. {
  596. #if BATTLE_TRACE_LEVEL>=1
  597. logAi->trace("Attacker is moving");
  598. #endif
  599. continue;
  600. }
  601. auto targetUnit = ap.attack.defender;
  602. if(!isOur || !exchangeBattle->battleGetUnitByID(targetUnit->unitId())->alive())
  603. {
  604. #if BATTLE_TRACE_LEVEL>=2
  605. logAi->trace("Best target selector for %s", attacker->getDescription());
  606. #endif
  607. auto estimateAttack = [&](const battle::Unit * u) -> float
  608. {
  609. auto stackWithBonuses = exchangeBattle->getForUpdate(u->unitId());
  610. auto score = v.trackAttack(
  611. attacker,
  612. stackWithBonuses,
  613. exchangeBattle->battleCanShoot(stackWithBonuses.get()),
  614. isOur,
  615. damageCache,
  616. hb,
  617. true);
  618. #if BATTLE_TRACE_LEVEL>=2
  619. logAi->trace("Best target selector %s->%s score = %2f", attacker->getDescription(), stackWithBonuses->getDescription(), score);
  620. #endif
  621. return score;
  622. };
  623. auto unitsInOppositeQueueExceptInaccessible = oppositeQueue;
  624. vstd::erase_if(unitsInOppositeQueueExceptInaccessible, [&](const battle::Unit * u)->bool
  625. {
  626. return vstd::contains(exchangeUnits.shooters, u);
  627. });
  628. if(!isOur
  629. && exchangeTurn == 0
  630. && exchangeUnits.units.at(exchangeTurn).at(0)->unitId() != ap.attack.attacker->unitId()
  631. && !vstd::contains(exchangeUnits.enemyUnitsReachingAttacker, attacker->unitId()))
  632. {
  633. vstd::erase_if(unitsInOppositeQueueExceptInaccessible, [&](const battle::Unit * u) -> bool
  634. {
  635. return u->unitId() == ap.attack.attacker->unitId();
  636. });
  637. }
  638. if(!unitsInOppositeQueueExceptInaccessible.empty())
  639. {
  640. targetUnit = *vstd::maxElementByFun(unitsInOppositeQueueExceptInaccessible, estimateAttack);
  641. }
  642. else
  643. {
  644. auto reachable = exchangeBattle->battleGetUnitsIf([this, &exchangeBattle, &attacker](const battle::Unit * u) -> bool
  645. {
  646. if(u->unitSide() == attacker->unitSide())
  647. return false;
  648. if(!exchangeBattle->getForUpdate(u->unitId())->alive())
  649. return false;
  650. if(!u->getPosition().isValid())
  651. return false; // e.g. tower shooters
  652. return vstd::contains_if(reachabilityMap.at(u->getPosition()), [&attacker](const battle::Unit * other) -> bool
  653. {
  654. return attacker->unitId() == other->unitId();
  655. });
  656. });
  657. if(!reachable.empty())
  658. {
  659. targetUnit = *vstd::maxElementByFun(reachable, estimateAttack);
  660. }
  661. else
  662. {
  663. #if BATTLE_TRACE_LEVEL>=1
  664. logAi->trace("Battle queue is empty and no reachable enemy.");
  665. #endif
  666. continue;
  667. }
  668. }
  669. }
  670. auto defender = exchangeBattle->getForUpdate(targetUnit->unitId());
  671. const int totalAttacks = attacker->getTotalAttacks(shooting);
  672. if(canUseAp && activeUnit->unitId() == ap.attack.attacker->unitId()
  673. && targetUnit->unitId() == ap.attack.defender->unitId())
  674. {
  675. v.trackAttack(ap, exchangeBattle, damageCache);
  676. }
  677. else
  678. {
  679. for(int i = 0; i < totalAttacks; i++)
  680. {
  681. v.trackAttack(attacker, defender, shooting, isOur, damageCache, exchangeBattle);
  682. if(!attacker->alive() || !defender->alive())
  683. break;
  684. }
  685. }
  686. if(!shooting)
  687. blockedShooters.insert(defender->unitId());
  688. canUseAp = false;
  689. vstd::erase_if(attackerQueue, [&](const battle::Unit * u) -> bool
  690. {
  691. return !exchangeBattle->battleGetUnitByID(u->unitId())->alive();
  692. });
  693. vstd::erase_if(oppositeQueue, [&](const battle::Unit * u) -> bool
  694. {
  695. return !exchangeBattle->battleGetUnitByID(u->unitId())->alive();
  696. });
  697. }
  698. exchangeBattle->nextRound();
  699. }
  700. // avoid blocking path for stronger stack by weaker stack
  701. // the method checks if all stacks can be placed around enemy
  702. std::map<BattleHex, battle::Units> reachabilityMap;
  703. auto hexes = ap.attack.defender->getSurroundingHexes();
  704. for(auto hex : hexes)
  705. reachabilityMap[hex] = getOneTurnReachableUnits(turn, hex);
  706. auto score = v.getScore();
  707. if(simulationTurnsCount < totalTurnsCount)
  708. {
  709. float scalingRatio = simulationTurnsCount / static_cast<float>(totalTurnsCount);
  710. score.enemyDamageReduce *= scalingRatio;
  711. score.ourDamageReduce *= scalingRatio;
  712. }
  713. if(turn > 0)
  714. {
  715. auto turnMultiplier = 1 - std::min(0.2, 0.05 * turn);
  716. score.enemyDamageReduce *= turnMultiplier;
  717. }
  718. #if BATTLE_TRACE_LEVEL>=1
  719. logAi->trace("Exchange score: enemy: %2f, our -%2f", score.enemyDamageReduce, score.ourDamageReduce);
  720. #endif
  721. return score;
  722. }
  723. bool BattleExchangeEvaluator::canBeHitThisTurn(const AttackPossibility & ap)
  724. {
  725. for(auto pos : ap.attack.attacker->getSurroundingHexes())
  726. {
  727. for(auto u : reachabilityMap[pos])
  728. {
  729. if(u->unitSide() != ap.attack.attacker->unitSide())
  730. {
  731. return true;
  732. }
  733. }
  734. }
  735. return false;
  736. }
  737. void BattleExchangeEvaluator::updateReachabilityMap(std::shared_ptr<HypotheticBattle> hb)
  738. {
  739. const int TURN_DEPTH = 2;
  740. turnOrder.clear();
  741. hb->battleGetTurnOrder(turnOrder, std::numeric_limits<int>::max(), TURN_DEPTH);
  742. for(auto turn : turnOrder)
  743. {
  744. for(auto u : turn)
  745. {
  746. if(!vstd::contains(reachabilityCache, u->unitId()))
  747. {
  748. reachabilityCache[u->unitId()] = hb->getReachability(u);
  749. }
  750. }
  751. }
  752. for(BattleHex hex = BattleHex::TOP_LEFT; hex.isValid(); hex = hex + 1)
  753. {
  754. reachabilityMap[hex] = getOneTurnReachableUnits(0, hex);
  755. }
  756. }
  757. std::vector<const battle::Unit *> BattleExchangeEvaluator::getOneTurnReachableUnits(uint8_t turn, BattleHex hex) const
  758. {
  759. std::vector<const battle::Unit *> result;
  760. for(int i = 0; i < turnOrder.size(); i++, turn++)
  761. {
  762. auto & turnQueue = turnOrder[i];
  763. HypotheticBattle turnBattle(env.get(), cb);
  764. for(const battle::Unit * unit : turnQueue)
  765. {
  766. if(unit->isTurret())
  767. continue;
  768. if(turnBattle.battleCanShoot(unit))
  769. {
  770. result.push_back(unit);
  771. continue;
  772. }
  773. auto unitSpeed = unit->getMovementRange(turn);
  774. auto radius = unitSpeed * (turn + 1);
  775. auto reachabilityIter = reachabilityCache.find(unit->unitId());
  776. assert(reachabilityIter != reachabilityCache.end()); // missing updateReachabilityMap call?
  777. ReachabilityInfo unitReachability = reachabilityIter != reachabilityCache.end() ? reachabilityIter->second : turnBattle.getReachability(unit);
  778. bool reachable = unitReachability.distances.at(hex) <= radius;
  779. if(!reachable && unitReachability.accessibility[hex] == EAccessibility::ALIVE_STACK)
  780. {
  781. const battle::Unit * hexStack = cb->battleGetUnitByPos(hex);
  782. if(hexStack && cb->battleMatchOwner(unit, hexStack, false))
  783. {
  784. for(BattleHex neighbor : hex.neighbouringTiles())
  785. {
  786. reachable = unitReachability.distances.at(neighbor) <= radius;
  787. if(reachable) break;
  788. }
  789. }
  790. }
  791. if(reachable)
  792. {
  793. result.push_back(unit);
  794. }
  795. }
  796. }
  797. return result;
  798. }
  799. // avoid blocking path for stronger stack by weaker stack
  800. bool BattleExchangeEvaluator::checkPositionBlocksOurStacks(HypotheticBattle & hb, const battle::Unit * activeUnit, BattleHex position)
  801. {
  802. const int BLOCKING_THRESHOLD = 70;
  803. const int BLOCKING_OWN_ATTACK_PENALTY = 100;
  804. const int BLOCKING_OWN_MOVE_PENALTY = 1;
  805. float blockingScore = 0;
  806. auto activeUnitDamage = activeUnit->getMinDamage(hb.battleCanShoot(activeUnit)) * activeUnit->getCount();
  807. for(int turn = 0; turn < turnOrder.size(); turn++)
  808. {
  809. auto & turnQueue = turnOrder[turn];
  810. HypotheticBattle turnBattle(env.get(), cb);
  811. auto unitToUpdate = turnBattle.getForUpdate(activeUnit->unitId());
  812. unitToUpdate->setPosition(position);
  813. for(const battle::Unit * unit : turnQueue)
  814. {
  815. if(unit->unitId() == unitToUpdate->unitId() || cb->battleMatchOwner(unit, activeUnit, false))
  816. continue;
  817. auto blockedUnitDamage = unit->getMinDamage(hb.battleCanShoot(unit)) * unit->getCount();
  818. float ratio = blockedUnitDamage / (float)(blockedUnitDamage + activeUnitDamage + 0.01);
  819. auto unitReachability = turnBattle.getReachability(unit);
  820. auto unitSpeed = unit->getMovementRange(turn); // Cached value, to avoid performance hit
  821. for(BattleHex hex = BattleHex::TOP_LEFT; hex.isValid(); hex = hex + 1)
  822. {
  823. bool enemyUnit = false;
  824. bool reachable = unitReachability.distances.at(hex) <= unitSpeed;
  825. if(!reachable && unitReachability.accessibility[hex] == EAccessibility::ALIVE_STACK)
  826. {
  827. const battle::Unit * hexStack = turnBattle.battleGetUnitByPos(hex);
  828. if(hexStack && cb->battleMatchOwner(unit, hexStack, false))
  829. {
  830. enemyUnit = true;
  831. for(BattleHex neighbor : hex.neighbouringTiles())
  832. {
  833. reachable = unitReachability.distances.at(neighbor) <= unitSpeed;
  834. if(reachable) break;
  835. }
  836. }
  837. }
  838. if(!reachable && std::count(reachabilityMap[hex].begin(), reachabilityMap[hex].end(), unit) > 1)
  839. {
  840. blockingScore += ratio * (enemyUnit ? BLOCKING_OWN_ATTACK_PENALTY : BLOCKING_OWN_MOVE_PENALTY);
  841. }
  842. }
  843. }
  844. }
  845. #if BATTLE_TRACE_LEVEL>=1
  846. logAi->trace("Position %d, blocking score %f", position.hex, blockingScore);
  847. #endif
  848. return blockingScore > BLOCKING_THRESHOLD;
  849. }