BattleExchangeVariant.cpp 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  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. turnsToReach = 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. if(!activeStack->waited() && !activeStack->acquireState()->hadMorale)
  194. {
  195. #if BATTLE_TRACE_LEVEL>=1
  196. logAi->trace("Evaluating waited attack for %s", activeStack->getDescription());
  197. #endif
  198. auto hbWaited = std::make_shared<HypotheticBattle>(env.get(), hb);
  199. hbWaited->makeWait(activeStack);
  200. updateReachabilityMap(hbWaited);
  201. for(auto & ap : targets.possibleAttacks)
  202. {
  203. if (siegeDefense && !hb->battleIsInsideWalls(ap.from))
  204. continue;
  205. float score = evaluateExchange(ap, 0, targets, damageCache, hbWaited);
  206. if(score > result.score)
  207. {
  208. result.score = score;
  209. result.bestAttack = ap;
  210. result.wait = true;
  211. #if BATTLE_TRACE_LEVEL >= 1
  212. logAi->trace("New high score %2f", result.score);
  213. #endif
  214. }
  215. }
  216. }
  217. #if BATTLE_TRACE_LEVEL>=1
  218. logAi->trace("Evaluating normal attack for %s", activeStack->getDescription());
  219. #endif
  220. updateReachabilityMap(hb);
  221. if(result.bestAttack.attack.shooting
  222. && !result.bestAttack.defenderDead
  223. && !activeStack->waited()
  224. && hb->battleHasShootingPenalty(activeStack, result.bestAttack.dest))
  225. {
  226. if(!canBeHitThisTurn(result.bestAttack))
  227. return result; // lets wait
  228. }
  229. for(auto & ap : targets.possibleAttacks)
  230. {
  231. if (siegeDefense && !hb->battleIsInsideWalls(ap.from))
  232. continue;
  233. float score = evaluateExchange(ap, 0, targets, damageCache, hb);
  234. bool sameScoreButWaited = vstd::isAlmostEqual(score, result.score) && result.wait;
  235. if(score > result.score || sameScoreButWaited)
  236. {
  237. result.score = score;
  238. result.bestAttack = ap;
  239. result.wait = false;
  240. #if BATTLE_TRACE_LEVEL >= 1
  241. logAi->trace("New high score %2f", result.score);
  242. #endif
  243. }
  244. }
  245. return result;
  246. }
  247. ReachabilityInfo getReachabilityWithEnemyBypass(
  248. const battle::Unit * activeStack,
  249. DamageCache & damageCache,
  250. std::shared_ptr<HypotheticBattle> state)
  251. {
  252. ReachabilityInfo::Parameters params(activeStack, activeStack->getPosition());
  253. if(!params.flying)
  254. {
  255. for(const auto * unit : state->battleAliveUnits())
  256. {
  257. if(unit->unitSide() == activeStack->unitSide())
  258. continue;
  259. auto dmg = damageCache.getOriginalDamage(activeStack, unit, state);
  260. auto turnsToKill = unit->getAvailableHealth() / std::max(dmg, (int64_t)1);
  261. vstd::amin(turnsToKill, 100);
  262. for(auto & hex : unit->getHexes())
  263. if(hex.isAvailable()) //towers can have <0 pos; we don't also want to overwrite side columns
  264. params.destructibleEnemyTurns[hex.toInt()] = turnsToKill * unit->getMovementRange();
  265. }
  266. params.bypassEnemyStacks = true;
  267. }
  268. return state->getReachability(params);
  269. }
  270. MoveTarget BattleExchangeEvaluator::findMoveTowardsUnreachable(
  271. const battle::Unit * activeStack,
  272. PotentialTargets & targets,
  273. DamageCache & damageCache,
  274. std::shared_ptr<HypotheticBattle> hb)
  275. {
  276. MoveTarget result;
  277. BattleExchangeVariant ev;
  278. logAi->trace("Find move towards unreachable. Enemies count %d", targets.unreachableEnemies.size());
  279. if(targets.unreachableEnemies.empty())
  280. return result;
  281. auto speed = activeStack->getMovementRange();
  282. if(speed == 0)
  283. return result;
  284. updateReachabilityMap(hb);
  285. auto dists = getReachabilityWithEnemyBypass(activeStack, damageCache, hb);
  286. auto flying = activeStack->hasBonusOfType(BonusType::FLYING);
  287. for(const battle::Unit * enemy : targets.unreachableEnemies)
  288. {
  289. logAi->trace(
  290. "Checking movement towards %d of %s",
  291. enemy->getCount(),
  292. enemy->creatureId().toCreature()->getNameSingularTranslated());
  293. auto distance = dists.distToNearestNeighbour(activeStack, enemy);
  294. if(distance >= GameConstants::BFIELD_SIZE)
  295. continue;
  296. if(distance <= speed)
  297. continue;
  298. float penaltyMultiplier = 1.0f; // Default multiplier, no penalty
  299. float closestAllyDistance = std::numeric_limits<float>::max();
  300. for (const battle::Unit* ally : hb->battleAliveUnits())
  301. {
  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. {
  315. penaltyMultiplier = closestAllyDistance / distance; // Ratio of distances
  316. }
  317. auto turnsToReach = (distance - 1) / speed + 1;
  318. const BattleHexArray & hexes = enemy->getSurroundingHexes();
  319. auto enemySpeed = enemy->getMovementRange();
  320. auto speedRatio = speed / static_cast<float>(enemySpeed);
  321. auto multiplier = (speedRatio > 1 ? 1 : speedRatio) * penaltyMultiplier;
  322. for(auto & hex : hexes)
  323. {
  324. // FIXME: provide distance info for Jousting bonus
  325. auto bai = BattleAttackInfo(activeStack, enemy, 0, cb->battleCanShoot(activeStack));
  326. auto attack = AttackPossibility::evaluate(bai, hex, damageCache, hb);
  327. attack.shootersBlockedDmg = 0; // we do not want to count on it, it is not for sure
  328. auto score = calculateExchange(attack, turnsToReach, targets, damageCache, hb);
  329. score.enemyDamageReduce *= multiplier;
  330. #if BATTLE_TRACE_LEVEL >= 1
  331. logAi->trace("Multiplier: %f, turns: %d, current score %f, new score %f", multiplier, turnsToReach, result.score, scoreValue(score));
  332. #endif
  333. if(result.score < scoreValue(score)
  334. || (result.turnsToReach > turnsToReach && vstd::isAlmostEqual(result.score, scoreValue(score))))
  335. {
  336. result.score = scoreValue(score);
  337. result.positions.clear();
  338. #if BATTLE_TRACE_LEVEL >= 1
  339. logAi->trace("New high score");
  340. #endif
  341. for(BattleHex enemyHex : enemy->getAttackableHexes(activeStack))
  342. {
  343. while(!flying && dists.distances[enemyHex.toInt()] > speed && dists.predecessors.at(enemyHex.toInt()).isValid())
  344. {
  345. enemyHex = dists.predecessors.at(enemyHex.toInt());
  346. if(dists.accessibility[enemyHex.toInt()] == 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.toInt()];
  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.toInt()],
  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.insert(enemyHex);
  378. }
  379. result.cachedAttack = attack;
  380. result.turnsToReach = turnsToReach;
  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 const & hexes = stack->getSurroundingHexes();
  397. for(auto hex : hexes)
  398. {
  399. auto neighbour = cb->battleGetUnitByPos(hex);
  400. if(neighbour && neighbour->unitSide() == stack->unitSide() && !vstd::contains(checkedStacks, neighbour))
  401. {
  402. queue.push(neighbour);
  403. checkedStacks.push_back(neighbour);
  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)
  419. hexes.insert(ap.from);
  420. std::vector<const battle::Unit *> allReachableUnits = additionalUnits;
  421. for(auto hex : hexes)
  422. {
  423. vstd::concatenate(allReachableUnits, turn == 0 ? reachabilityMap.at(hex) : getOneTurnReachableUnits(turn, hex));
  424. }
  425. if(!ap.attack.attacker->isTurret())
  426. {
  427. for(auto hex : ap.attack.attacker->getHexes())
  428. {
  429. auto unitsReachingAttacker = turn == 0 ? reachabilityMap.at(hex) : getOneTurnReachableUnits(turn, hex);
  430. for(auto unit : unitsReachingAttacker)
  431. {
  432. if(unit->unitSide() != ap.attack.attacker->unitSide())
  433. {
  434. allReachableUnits.push_back(unit);
  435. result.enemyUnitsReachingAttacker.insert(unit->unitId());
  436. }
  437. }
  438. }
  439. }
  440. vstd::removeDuplicates(allReachableUnits);
  441. auto copy = allReachableUnits;
  442. for(auto unit : copy)
  443. {
  444. for(auto adjacentUnit : getAdjacentUnits(unit))
  445. {
  446. auto unitWithBonuses = hb->battleGetUnitByID(adjacentUnit->unitId());
  447. if(vstd::contains(targets.unreachableEnemies, adjacentUnit)
  448. && !vstd::contains(allReachableUnits, unitWithBonuses))
  449. {
  450. allReachableUnits.push_back(unitWithBonuses);
  451. }
  452. }
  453. }
  454. vstd::removeDuplicates(allReachableUnits);
  455. if(!vstd::contains(allReachableUnits, ap.attack.attacker))
  456. {
  457. allReachableUnits.push_back(ap.attack.attacker);
  458. }
  459. if(allReachableUnits.size() < 2)
  460. {
  461. #if BATTLE_TRACE_LEVEL>=1
  462. logAi->trace("Reachability map contains only %d stacks", allReachableUnits.size());
  463. #endif
  464. return result;
  465. }
  466. for(auto unit : allReachableUnits)
  467. {
  468. auto accessible = !unit->canShoot() || vstd::contains(additionalUnits, unit);
  469. if(!accessible)
  470. {
  471. for(auto hex : unit->getSurroundingHexes())
  472. {
  473. if(ap.attack.defender->coversPos(hex))
  474. {
  475. accessible = true;
  476. }
  477. }
  478. }
  479. if(accessible)
  480. result.melleeAccessible.push_back(unit);
  481. else
  482. result.shooters.push_back(unit);
  483. }
  484. for(int turn = 0; turn < turnOrder.size(); turn++)
  485. {
  486. for(auto unit : turnOrder[turn])
  487. {
  488. if(vstd::contains(allReachableUnits, unit))
  489. result.units[turn].push_back(unit);
  490. }
  491. vstd::erase_if(result.units[turn], [&](const battle::Unit * u) -> bool
  492. {
  493. return !hb->battleGetUnitByID(u->unitId())->alive();
  494. });
  495. }
  496. return result;
  497. }
  498. float BattleExchangeEvaluator::evaluateExchange(
  499. const AttackPossibility & ap,
  500. uint8_t turn,
  501. PotentialTargets & targets,
  502. DamageCache & damageCache,
  503. std::shared_ptr<HypotheticBattle> hb) const
  504. {
  505. BattleScore score = calculateExchange(ap, turn, targets, damageCache, hb);
  506. #if BATTLE_TRACE_LEVEL >= 1
  507. logAi->trace(
  508. "calculateExchange score +%2f -%2fx%2f = %2f",
  509. score.enemyDamageReduce,
  510. score.ourDamageReduce,
  511. getNegativeEffectMultiplier(),
  512. scoreValue(score));
  513. #endif
  514. return scoreValue(score);
  515. }
  516. BattleScore BattleExchangeEvaluator::calculateExchange(
  517. const AttackPossibility & ap,
  518. uint8_t turn,
  519. PotentialTargets & targets,
  520. DamageCache & damageCache,
  521. std::shared_ptr<HypotheticBattle> hb,
  522. std::vector<const battle::Unit *> additionalUnits) const
  523. {
  524. #if BATTLE_TRACE_LEVEL>=1
  525. logAi->trace("Battle exchange at %d", ap.attack.shooting ? ap.dest.hex : ap.from.hex);
  526. #endif
  527. if(cb->battleGetMySide() == BattleSide::LEFT_SIDE
  528. && cb->battleGetGateState() == EGateState::BLOCKED
  529. && ap.attack.defender->coversPos(BattleHex::GATE_BRIDGE))
  530. {
  531. return BattleScore(EvaluationResult::INEFFECTIVE_SCORE, 0);
  532. }
  533. std::vector<const battle::Unit *> ourStacks;
  534. std::vector<const battle::Unit *> enemyStacks;
  535. if(hb->battleGetUnitByID(ap.attack.defender->unitId())->alive())
  536. enemyStacks.push_back(ap.attack.defender);
  537. ReachabilityData exchangeUnits = getExchangeUnits(ap, turn, targets, hb, additionalUnits);
  538. if(exchangeUnits.units.empty())
  539. {
  540. return BattleScore();
  541. }
  542. auto exchangeBattle = std::make_shared<HypotheticBattle>(env.get(), hb);
  543. BattleExchangeVariant v;
  544. for(int exchangeTurn = 0; exchangeTurn < exchangeUnits.units.size(); exchangeTurn++)
  545. {
  546. for(auto unit : exchangeUnits.units.at(exchangeTurn))
  547. {
  548. if(unit->isTurret())
  549. continue;
  550. bool isOur = exchangeBattle->battleMatchOwner(ap.attack.attacker, unit, true);
  551. auto & attackerQueue = isOur ? ourStacks : enemyStacks;
  552. auto u = exchangeBattle->getForUpdate(unit->unitId());
  553. if(u->alive() && !vstd::contains(attackerQueue, unit))
  554. {
  555. attackerQueue.push_back(unit);
  556. #if BATTLE_TRACE_LEVEL
  557. logAi->trace("Exchanging: %s", u->getDescription());
  558. #endif
  559. }
  560. }
  561. }
  562. auto melleeAttackers = ourStacks;
  563. vstd::removeDuplicates(melleeAttackers);
  564. vstd::erase_if(melleeAttackers, [&](const battle::Unit * u) -> bool
  565. {
  566. return cb->battleCanShoot(u);
  567. });
  568. bool canUseAp = true;
  569. std::set<uint32_t> blockedShooters;
  570. int totalTurnsCount = simulationTurnsCount >= turn + turnOrder.size()
  571. ? simulationTurnsCount
  572. : turn + turnOrder.size();
  573. for(int exchangeTurn = 0; exchangeTurn < simulationTurnsCount; exchangeTurn++)
  574. {
  575. bool isMovingTurm = exchangeTurn < turn;
  576. int queueTurn = exchangeTurn >= exchangeUnits.units.size()
  577. ? exchangeUnits.units.size() - 1
  578. : exchangeTurn;
  579. for(auto activeUnit : exchangeUnits.units.at(queueTurn))
  580. {
  581. bool isOur = exchangeBattle->battleMatchOwner(ap.attack.attacker, activeUnit, true);
  582. battle::Units & attackerQueue = isOur ? ourStacks : enemyStacks;
  583. battle::Units & oppositeQueue = isOur ? enemyStacks : ourStacks;
  584. auto attacker = exchangeBattle->getForUpdate(activeUnit->unitId());
  585. auto shooting = exchangeBattle->battleCanShoot(attacker.get())
  586. && !vstd::contains(blockedShooters, attacker->unitId());
  587. if(!attacker->alive())
  588. {
  589. #if BATTLE_TRACE_LEVEL>=1
  590. logAi->trace("Attacker is dead");
  591. #endif
  592. continue;
  593. }
  594. if(isMovingTurm && !shooting
  595. && !vstd::contains(exchangeUnits.enemyUnitsReachingAttacker, attacker->unitId()))
  596. {
  597. #if BATTLE_TRACE_LEVEL>=1
  598. logAi->trace("Attacker is moving");
  599. #endif
  600. continue;
  601. }
  602. auto targetUnit = ap.attack.defender;
  603. if(!isOur || !exchangeBattle->battleGetUnitByID(targetUnit->unitId())->alive())
  604. {
  605. #if BATTLE_TRACE_LEVEL>=2
  606. logAi->trace("Best target selector for %s", attacker->getDescription());
  607. #endif
  608. auto estimateAttack = [&](const battle::Unit * u) -> float
  609. {
  610. auto stackWithBonuses = exchangeBattle->getForUpdate(u->unitId());
  611. auto score = v.trackAttack(
  612. attacker,
  613. stackWithBonuses,
  614. exchangeBattle->battleCanShoot(stackWithBonuses.get()),
  615. isOur,
  616. damageCache,
  617. hb,
  618. true);
  619. #if BATTLE_TRACE_LEVEL>=2
  620. logAi->trace("Best target selector %s->%s score = %2f", attacker->getDescription(), stackWithBonuses->getDescription(), score);
  621. #endif
  622. return score;
  623. };
  624. auto unitsInOppositeQueueExceptInaccessible = oppositeQueue;
  625. vstd::erase_if(unitsInOppositeQueueExceptInaccessible, [&](const battle::Unit * u)->bool
  626. {
  627. return vstd::contains(exchangeUnits.shooters, u);
  628. });
  629. if(!isOur
  630. && exchangeTurn == 0
  631. && exchangeUnits.units.at(exchangeTurn).at(0)->unitId() != ap.attack.attacker->unitId()
  632. && !vstd::contains(exchangeUnits.enemyUnitsReachingAttacker, attacker->unitId()))
  633. {
  634. vstd::erase_if(unitsInOppositeQueueExceptInaccessible, [&](const battle::Unit * u) -> bool
  635. {
  636. return u->unitId() == ap.attack.attacker->unitId();
  637. });
  638. }
  639. if(!unitsInOppositeQueueExceptInaccessible.empty())
  640. {
  641. targetUnit = *vstd::maxElementByFun(unitsInOppositeQueueExceptInaccessible, estimateAttack);
  642. }
  643. else
  644. {
  645. auto reachable = exchangeBattle->battleGetUnitsIf([this, &exchangeBattle, &attacker](const battle::Unit * u) -> bool
  646. {
  647. if(u->unitSide() == attacker->unitSide())
  648. return false;
  649. if(!exchangeBattle->getForUpdate(u->unitId())->alive())
  650. return false;
  651. if(!u->getPosition().isValid())
  652. return false; // e.g. tower shooters
  653. return vstd::contains_if(reachabilityMap.at(u->getPosition()), [&attacker](const battle::Unit * other) -> bool
  654. {
  655. return attacker->unitId() == other->unitId();
  656. });
  657. });
  658. if(!reachable.empty())
  659. {
  660. targetUnit = *vstd::maxElementByFun(reachable, estimateAttack);
  661. }
  662. else
  663. {
  664. #if BATTLE_TRACE_LEVEL>=1
  665. logAi->trace("Battle queue is empty and no reachable enemy.");
  666. #endif
  667. continue;
  668. }
  669. }
  670. }
  671. auto defender = exchangeBattle->getForUpdate(targetUnit->unitId());
  672. const int totalAttacks = attacker->getTotalAttacks(shooting);
  673. if(canUseAp && activeUnit->unitId() == ap.attack.attacker->unitId()
  674. && targetUnit->unitId() == ap.attack.defender->unitId())
  675. {
  676. v.trackAttack(ap, exchangeBattle, damageCache);
  677. }
  678. else
  679. {
  680. for(int i = 0; i < totalAttacks; i++)
  681. {
  682. v.trackAttack(attacker, defender, shooting, isOur, damageCache, exchangeBattle);
  683. if(!attacker->alive() || !defender->alive())
  684. break;
  685. }
  686. }
  687. if(!shooting)
  688. blockedShooters.insert(defender->unitId());
  689. canUseAp = false;
  690. vstd::erase_if(attackerQueue, [&](const battle::Unit * u) -> bool
  691. {
  692. return !exchangeBattle->battleGetUnitByID(u->unitId())->alive();
  693. });
  694. vstd::erase_if(oppositeQueue, [&](const battle::Unit * u) -> bool
  695. {
  696. return !exchangeBattle->battleGetUnitByID(u->unitId())->alive();
  697. });
  698. }
  699. exchangeBattle->nextRound();
  700. }
  701. auto score = v.getScore();
  702. if(simulationTurnsCount < totalTurnsCount)
  703. {
  704. float scalingRatio = simulationTurnsCount / static_cast<float>(totalTurnsCount);
  705. score.enemyDamageReduce *= scalingRatio;
  706. score.ourDamageReduce *= scalingRatio;
  707. }
  708. if(turn > 0)
  709. {
  710. auto turnMultiplier = 1 - std::min(0.2, 0.05 * turn);
  711. score.enemyDamageReduce *= turnMultiplier;
  712. }
  713. #if BATTLE_TRACE_LEVEL>=1
  714. logAi->trace("Exchange score: enemy: %2f, our -%2f", score.enemyDamageReduce, score.ourDamageReduce);
  715. #endif
  716. return score;
  717. }
  718. bool BattleExchangeEvaluator::canBeHitThisTurn(const AttackPossibility & ap)
  719. {
  720. for(auto pos : ap.attack.attacker->getSurroundingHexes())
  721. {
  722. for(auto u : reachabilityMap[pos])
  723. {
  724. if(u->unitSide() != ap.attack.attacker->unitSide())
  725. {
  726. return true;
  727. }
  728. }
  729. }
  730. return false;
  731. }
  732. void BattleExchangeEvaluator::updateReachabilityMap(std::shared_ptr<HypotheticBattle> hb)
  733. {
  734. const int TURN_DEPTH = 2;
  735. turnOrder.clear();
  736. hb->battleGetTurnOrder(turnOrder, std::numeric_limits<int>::max(), TURN_DEPTH);
  737. for(auto turn : turnOrder)
  738. {
  739. for(auto u : turn)
  740. {
  741. if(!vstd::contains(reachabilityCache, u->unitId()))
  742. {
  743. reachabilityCache[u->unitId()] = hb->getReachability(u);
  744. }
  745. }
  746. }
  747. for(BattleHex hex = BattleHex::TOP_LEFT; hex.isValid(); ++hex)
  748. {
  749. reachabilityMap[hex] = getOneTurnReachableUnits(0, hex);
  750. }
  751. }
  752. std::vector<const battle::Unit *> BattleExchangeEvaluator::getOneTurnReachableUnits(uint8_t turn, BattleHex hex) const
  753. {
  754. std::vector<const battle::Unit *> result;
  755. for(int i = 0; i < turnOrder.size(); i++, turn++)
  756. {
  757. auto & turnQueue = turnOrder[i];
  758. HypotheticBattle turnBattle(env.get(), cb);
  759. for(const battle::Unit * unit : turnQueue)
  760. {
  761. if(unit->isTurret())
  762. continue;
  763. if(turnBattle.battleCanShoot(unit))
  764. {
  765. result.push_back(unit);
  766. continue;
  767. }
  768. auto unitSpeed = unit->getMovementRange(turn);
  769. auto radius = unitSpeed * (turn + 1);
  770. auto reachabilityIter = reachabilityCache.find(unit->unitId());
  771. assert(reachabilityIter != reachabilityCache.end()); // missing updateReachabilityMap call?
  772. ReachabilityInfo unitReachability = reachabilityIter != reachabilityCache.end() ? reachabilityIter->second : turnBattle.getReachability(unit);
  773. bool reachable = unitReachability.distances.at(hex.toInt()) <= radius;
  774. if(!reachable && unitReachability.accessibility[hex.toInt()] == EAccessibility::ALIVE_STACK)
  775. {
  776. const battle::Unit * hexStack = cb->battleGetUnitByPos(hex);
  777. if(hexStack && cb->battleMatchOwner(unit, hexStack, false))
  778. {
  779. for(BattleHex neighbour : hex.getNeighbouringTiles())
  780. {
  781. reachable = unitReachability.distances.at(neighbour.toInt()) <= radius;
  782. if(reachable) break;
  783. }
  784. }
  785. }
  786. if(reachable)
  787. {
  788. result.push_back(unit);
  789. }
  790. }
  791. }
  792. return result;
  793. }
  794. // avoid blocking path for stronger stack by weaker stack
  795. bool BattleExchangeEvaluator::checkPositionBlocksOurStacks(HypotheticBattle & hb, const battle::Unit * activeUnit, BattleHex position)
  796. {
  797. const int BLOCKING_THRESHOLD = 70;
  798. const int BLOCKING_OWN_ATTACK_PENALTY = 100;
  799. const int BLOCKING_OWN_MOVE_PENALTY = 1;
  800. float blockingScore = 0;
  801. auto activeUnitDamage = activeUnit->getMinDamage(hb.battleCanShoot(activeUnit)) * activeUnit->getCount();
  802. for(int turn = 0; turn < turnOrder.size(); turn++)
  803. {
  804. auto & turnQueue = turnOrder[turn];
  805. HypotheticBattle turnBattle(env.get(), cb);
  806. auto unitToUpdate = turnBattle.getForUpdate(activeUnit->unitId());
  807. unitToUpdate->setPosition(position);
  808. for(const battle::Unit * unit : turnQueue)
  809. {
  810. if(unit->unitId() == unitToUpdate->unitId() || cb->battleMatchOwner(unit, activeUnit, false))
  811. continue;
  812. auto blockedUnitDamage = unit->getMinDamage(hb.battleCanShoot(unit)) * unit->getCount();
  813. float ratio = blockedUnitDamage / (float)(blockedUnitDamage + activeUnitDamage + 0.01);
  814. auto unitReachability = turnBattle.getReachability(unit);
  815. auto unitSpeed = unit->getMovementRange(turn); // Cached value, to avoid performance hit
  816. for(BattleHex hex = BattleHex::TOP_LEFT; hex.isValid(); hex++)
  817. {
  818. bool enemyUnit = false;
  819. bool reachable = unitReachability.distances.at(hex.toInt()) <= unitSpeed;
  820. if(!reachable && unitReachability.accessibility[hex.toInt()] == EAccessibility::ALIVE_STACK)
  821. {
  822. const battle::Unit * hexStack = turnBattle.battleGetUnitByPos(hex);
  823. if(hexStack && cb->battleMatchOwner(unit, hexStack, false))
  824. {
  825. enemyUnit = true;
  826. for(BattleHex neighbour : hex.getNeighbouringTiles())
  827. {
  828. reachable = unitReachability.distances.at(neighbour.toInt()) <= unitSpeed;
  829. if(reachable) break;
  830. }
  831. }
  832. }
  833. if(!reachable && std::count(reachabilityMap[hex].begin(), reachabilityMap[hex].end(), unit) > 1)
  834. {
  835. blockingScore += ratio * (enemyUnit ? BLOCKING_OWN_ATTACK_PENALTY : BLOCKING_OWN_MOVE_PENALTY);
  836. }
  837. }
  838. }
  839. }
  840. #if BATTLE_TRACE_LEVEL>=1
  841. logAi->trace("Position %d, blocking score %f", position.hex, blockingScore);
  842. #endif
  843. return blockingScore > BLOCKING_THRESHOLD;
  844. }