AINodeStorage.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  1. /*
  2. * AINodeStorage.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 "AINodeStorage.h"
  12. #include "Actions/TownPortalAction.h"
  13. #include "../Goals/Goals.h"
  14. #include "../VCAI.h"
  15. #include "../Engine/Nullkiller.h"
  16. #include "../../../CCallback.h"
  17. #include "../../../lib/mapping/CMap.h"
  18. #include "../../../lib/mapObjects/MapObjects.h"
  19. #include "../../../lib/PathfinderUtil.h"
  20. #include "../../../lib/CPlayerState.h"
  21. std::shared_ptr<boost::multi_array<AIPathNode, 5>> AISharedStorage::shared;
  22. std::set<int3> commitedTiles;
  23. std::set<int3> commitedTilesInitial;
  24. const uint64_t FirstActorMask = 1;
  25. const int BUCKET_COUNT = 11;
  26. const int BUCKET_SIZE = GameConstants::MAX_HEROES_PER_PLAYER;
  27. const int NUM_CHAINS = BUCKET_COUNT * BUCKET_SIZE;
  28. AISharedStorage::AISharedStorage(int3 sizes)
  29. {
  30. if(!shared){
  31. shared.reset(new boost::multi_array<AIPathNode, 5>(
  32. boost::extents[sizes.x][sizes.y][sizes.z][EPathfindingLayer::NUM_LAYERS][NUM_CHAINS]));
  33. }
  34. nodes = shared;
  35. }
  36. AISharedStorage::~AISharedStorage()
  37. {
  38. nodes.reset();
  39. if(shared && shared.use_count() == 1)
  40. {
  41. shared.reset();
  42. }
  43. }
  44. AINodeStorage::AINodeStorage(const Nullkiller * ai, const int3 & Sizes)
  45. : sizes(Sizes), ai(ai), cb(ai->cb.get()), nodes(Sizes)
  46. {
  47. dangerEvaluator.reset(new FuzzyHelper(ai));
  48. }
  49. AINodeStorage::~AINodeStorage() = default;
  50. void AINodeStorage::initialize(const PathfinderOptions & options, const CGameState * gs)
  51. {
  52. if(heroChainPass)
  53. return;
  54. //TODO: fix this code duplication with NodeStorage::initialize, problem is to keep `resetTile` inline
  55. int3 pos;
  56. const PlayerColor player = playerID;
  57. const PlayerColor fowPlayer = ai->playerID;
  58. const int3 sizes = gs->getMapSize();
  59. const auto & fow = static_cast<const CGameInfoCallback *>(gs)->getPlayerTeam(fowPlayer)->fogOfWarMap;
  60. //make 200% sure that these are loop invariants (also a bit shorter code), let compiler do the rest(loop unswitching)
  61. const bool useFlying = options.useFlying;
  62. const bool useWaterWalking = options.useWaterWalking;
  63. for(pos.x=0; pos.x < sizes.x; ++pos.x)
  64. {
  65. for(pos.y=0; pos.y < sizes.y; ++pos.y)
  66. {
  67. for(pos.z=0; pos.z < sizes.z; ++pos.z)
  68. {
  69. const TerrainTile * tile = &gs->map->getTile(pos);
  70. switch(tile->terType)
  71. {
  72. case ETerrainType::ROCK:
  73. break;
  74. case ETerrainType::WATER:
  75. resetTile(pos, ELayer::SAIL, PathfinderUtil::evaluateAccessibility<ELayer::SAIL>(pos, tile, fow, player, gs));
  76. if(useFlying)
  77. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  78. if(useWaterWalking)
  79. resetTile(pos, ELayer::WATER, PathfinderUtil::evaluateAccessibility<ELayer::WATER>(pos, tile, fow, player, gs));
  80. break;
  81. default:
  82. resetTile(pos, ELayer::LAND, PathfinderUtil::evaluateAccessibility<ELayer::LAND>(pos, tile, fow, player, gs));
  83. if(useFlying)
  84. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  85. break;
  86. }
  87. }
  88. }
  89. }
  90. }
  91. void AINodeStorage::clear()
  92. {
  93. actors.clear();
  94. heroChainPass = EHeroChainPass::INITIAL;
  95. heroChainTurn = 0;
  96. heroChainMaxTurns = 1;
  97. scoutTurnDistanceLimit = 255;
  98. }
  99. const AIPathNode * AINodeStorage::getAINode(const CGPathNode * node) const
  100. {
  101. return static_cast<const AIPathNode *>(node);
  102. }
  103. void AINodeStorage::updateAINode(CGPathNode * node, std::function<void(AIPathNode *)> updater)
  104. {
  105. auto aiNode = static_cast<AIPathNode *>(node);
  106. updater(aiNode);
  107. }
  108. boost::optional<AIPathNode *> AINodeStorage::getOrCreateNode(
  109. const int3 & pos,
  110. const EPathfindingLayer layer,
  111. const ChainActor * actor)
  112. {
  113. int bucketIndex = ((uintptr_t)actor) % BUCKET_COUNT;
  114. int bucketOffset = bucketIndex * BUCKET_SIZE;
  115. auto chains = nodes.get(pos, layer);
  116. if(chains[0].blocked())
  117. {
  118. return boost::none;
  119. }
  120. for(auto i = BUCKET_SIZE - 1; i >= 0; i--)
  121. {
  122. AIPathNode & node = chains[i + bucketOffset];
  123. if(node.actor == actor)
  124. {
  125. return &node;
  126. }
  127. if(!node.actor)
  128. {
  129. node.actor = actor;
  130. return &node;
  131. }
  132. }
  133. return boost::none;
  134. }
  135. std::vector<CGPathNode *> AINodeStorage::getInitialNodes()
  136. {
  137. if(heroChainPass)
  138. {
  139. calculateTownPortalTeleportations(heroChain);
  140. return heroChain;
  141. }
  142. std::vector<CGPathNode *> initialNodes;
  143. for(auto actorPtr : actors)
  144. {
  145. ChainActor * actor = actorPtr.get();
  146. AIPathNode * initialNode =
  147. getOrCreateNode(actor->initialPosition, actor->layer, actor)
  148. .get();
  149. if(!initialNode)
  150. continue;
  151. initialNode->inPQ = false;
  152. initialNode->pq = nullptr;
  153. initialNode->turns = actor->initialTurn;
  154. initialNode->moveRemains = actor->initialMovement;
  155. initialNode->danger = 0;
  156. initialNode->cost = actor->initialTurn;
  157. initialNode->action = CGPathNode::ENodeAction::NORMAL;
  158. if(actor->isMovable)
  159. {
  160. initialNodes.push_back(initialNode);
  161. }
  162. else
  163. {
  164. initialNode->locked = true;
  165. }
  166. }
  167. calculateTownPortalTeleportations(initialNodes);
  168. return initialNodes;
  169. }
  170. void AINodeStorage::resetTile(const int3 & coord, EPathfindingLayer layer, CGPathNode::EAccessibility accessibility)
  171. {
  172. for(AIPathNode & heroNode : nodes.get(coord, layer))
  173. {
  174. heroNode.actor = nullptr;
  175. heroNode.danger = 0;
  176. heroNode.manaCost = 0;
  177. heroNode.specialAction.reset();
  178. heroNode.armyLoss = 0;
  179. heroNode.chainOther = nullptr;
  180. heroNode.update(coord, layer, accessibility);
  181. }
  182. }
  183. void AINodeStorage::commit(CDestinationNodeInfo & destination, const PathNodeInfo & source)
  184. {
  185. const AIPathNode * srcNode = getAINode(source.node);
  186. updateAINode(destination.node, [&](AIPathNode * dstNode)
  187. {
  188. commit(dstNode, srcNode, destination.action, destination.turn, destination.movementLeft, destination.cost);
  189. if(srcNode->specialAction || srcNode->chainOther)
  190. {
  191. // there is some action on source tile which should be performed before we can bypass it
  192. destination.node->theNodeBefore = source.node;
  193. }
  194. if(dstNode->specialAction && dstNode->actor)
  195. {
  196. dstNode->specialAction->applyOnDestination(dstNode->actor->hero, destination, source, dstNode, srcNode);
  197. }
  198. });
  199. }
  200. void AINodeStorage::commit(
  201. AIPathNode * destination,
  202. const AIPathNode * source,
  203. CGPathNode::ENodeAction action,
  204. int turn,
  205. int movementLeft,
  206. float cost) const
  207. {
  208. destination->action = action;
  209. destination->cost = cost;
  210. destination->moveRemains = movementLeft;
  211. destination->turns = turn;
  212. destination->armyLoss = source->armyLoss;
  213. destination->manaCost = source->manaCost;
  214. destination->danger = source->danger;
  215. destination->theNodeBefore = source->theNodeBefore;
  216. destination->chainOther = nullptr;
  217. #if PATHFINDER_TRACE_LEVEL >= 2
  218. logAi->trace(
  219. "Commited %s -> %s, cost: %f, turn: %s, mp: %d, hero: %s, mask: %x, army: %lld",
  220. source->coord.toString(),
  221. destination->coord.toString(),
  222. destination->getCost(),
  223. std::to_string(destination->turns),
  224. destination->moveRemains,
  225. destination->actor->toString(),
  226. destination->actor->chainMask,
  227. destination->actor->armyValue);
  228. #endif
  229. if(destination->turns <= heroChainTurn)
  230. {
  231. commitedTiles.insert(destination->coord);
  232. }
  233. }
  234. std::vector<CGPathNode *> AINodeStorage::calculateNeighbours(
  235. const PathNodeInfo & source,
  236. const PathfinderConfig * pathfinderConfig,
  237. const CPathfinderHelper * pathfinderHelper)
  238. {
  239. std::vector<CGPathNode *> neighbours;
  240. neighbours.reserve(16);
  241. const AIPathNode * srcNode = getAINode(source.node);
  242. auto accessibleNeighbourTiles = pathfinderHelper->getNeighbourTiles(source);
  243. for(auto & neighbour : accessibleNeighbourTiles)
  244. {
  245. for(EPathfindingLayer i = EPathfindingLayer::LAND; i <= EPathfindingLayer::AIR; i.advance(1))
  246. {
  247. auto nextNode = getOrCreateNode(neighbour, i, srcNode->actor);
  248. if(!nextNode || nextNode.get()->accessible == CGPathNode::NOT_SET)
  249. continue;
  250. neighbours.push_back(nextNode.get());
  251. }
  252. }
  253. return neighbours;
  254. }
  255. EPathfindingLayer phisycalLayers[2] = {EPathfindingLayer::LAND, EPathfindingLayer::SAIL};
  256. bool AINodeStorage::increaseHeroChainTurnLimit()
  257. {
  258. if(heroChainTurn >= heroChainMaxTurns)
  259. return false;
  260. heroChainTurn++;
  261. commitedTiles.clear();
  262. for(auto layer : phisycalLayers)
  263. {
  264. foreach_tile_pos([&](const int3 & pos)
  265. {
  266. auto chains = nodes.get(pos, layer);
  267. if(!chains[0].blocked())
  268. {
  269. for(AIPathNode & node : chains)
  270. {
  271. if(node.turns <= heroChainTurn && node.action != CGPathNode::ENodeAction::UNKNOWN)
  272. {
  273. commitedTiles.insert(pos);
  274. break;
  275. }
  276. }
  277. }
  278. });
  279. }
  280. return true;
  281. }
  282. bool AINodeStorage::calculateHeroChainFinal()
  283. {
  284. heroChainPass = EHeroChainPass::FINAL;
  285. heroChain.resize(0);
  286. for(auto layer : phisycalLayers)
  287. {
  288. foreach_tile_pos([&](const int3 & pos)
  289. {
  290. auto chains = nodes.get(pos, layer);
  291. if(!chains[0].blocked())
  292. {
  293. for(AIPathNode & node : chains)
  294. {
  295. if(node.turns > heroChainTurn
  296. && !node.locked
  297. && node.action != CGPathNode::ENodeAction::UNKNOWN
  298. && node.actor->actorExchangeCount > 1
  299. && !hasBetterChain(&node, &node, chains))
  300. {
  301. heroChain.push_back(&node);
  302. }
  303. }
  304. }
  305. });
  306. }
  307. return heroChain.size();
  308. }
  309. bool AINodeStorage::calculateHeroChain()
  310. {
  311. heroChainPass = EHeroChainPass::CHAIN;
  312. heroChain.resize(0);
  313. std::vector<AIPathNode *> existingChains;
  314. std::vector<ExchangeCandidate> newChains;
  315. existingChains.reserve(NUM_CHAINS);
  316. newChains.reserve(NUM_CHAINS);
  317. for(auto & pos : commitedTiles)
  318. {
  319. for(auto layer : phisycalLayers)
  320. {
  321. auto chains = nodes.get(pos, layer);
  322. // fast cut inactive nodes
  323. if(chains[0].blocked())
  324. continue;
  325. existingChains.clear();
  326. newChains.clear();
  327. for(AIPathNode & node : chains)
  328. {
  329. if(node.turns <= heroChainTurn && node.action != CGPathNode::ENodeAction::UNKNOWN)
  330. existingChains.push_back(&node);
  331. }
  332. for(AIPathNode * node : existingChains)
  333. {
  334. if(node->actor->isMovable)
  335. {
  336. calculateHeroChain(node, existingChains, newChains);
  337. }
  338. }
  339. cleanupInefectiveChains(newChains);
  340. addHeroChain(newChains);
  341. }
  342. }
  343. commitedTiles.clear();
  344. return heroChain.size();
  345. }
  346. bool AINodeStorage::selectFirstActor()
  347. {
  348. if(!actors.size())
  349. return false;
  350. auto strongest = *vstd::maxElementByFun(actors, [](std::shared_ptr<ChainActor> actor) -> uint64_t
  351. {
  352. return actor->armyValue;
  353. });
  354. chainMask = strongest->chainMask;
  355. commitedTilesInitial = commitedTiles;
  356. return true;
  357. }
  358. bool AINodeStorage::selectNextActor()
  359. {
  360. auto currentActor = std::find_if(actors.begin(), actors.end(), [&](std::shared_ptr<ChainActor> actor)-> bool
  361. {
  362. return actor->chainMask == chainMask;
  363. });
  364. auto nextActor = actors.end();
  365. for(auto actor = actors.begin(); actor != actors.end(); actor++)
  366. {
  367. if(actor->get()->armyValue > currentActor->get()->armyValue
  368. || actor->get()->armyValue == currentActor->get()->armyValue && actor <= currentActor)
  369. {
  370. continue;
  371. }
  372. if(nextActor == actors.end()
  373. || actor->get()->armyValue > nextActor->get()->armyValue)
  374. {
  375. nextActor = actor;
  376. }
  377. }
  378. if(nextActor != actors.end())
  379. {
  380. chainMask = nextActor->get()->chainMask;
  381. commitedTiles = commitedTilesInitial;
  382. return true;
  383. }
  384. return false;
  385. }
  386. void AINodeStorage::cleanupInefectiveChains(std::vector<ExchangeCandidate> & result) const
  387. {
  388. vstd::erase_if(result, [&](const ExchangeCandidate & chainInfo) -> bool
  389. {
  390. auto pos = chainInfo.coord;
  391. auto chains = nodes.get(pos, EPathfindingLayer::LAND);
  392. return hasBetterChain(chainInfo.carrierParent, &chainInfo, chains)
  393. || hasBetterChain(chainInfo.carrierParent, &chainInfo, result);
  394. });
  395. }
  396. void AINodeStorage::calculateHeroChain(
  397. AIPathNode * srcNode,
  398. const std::vector<AIPathNode *> & variants,
  399. std::vector<ExchangeCandidate> & result) const
  400. {
  401. for(AIPathNode * node : variants)
  402. {
  403. if(node == srcNode || !node->actor)
  404. continue;
  405. if((node->actor->chainMask & chainMask) == 0 && (srcNode->actor->chainMask & chainMask) == 0)
  406. continue;
  407. if(node->action == CGPathNode::ENodeAction::BATTLE
  408. || node->action == CGPathNode::ENodeAction::TELEPORT_BATTLE
  409. || node->action == CGPathNode::ENodeAction::TELEPORT_NORMAL
  410. || node->action == CGPathNode::ENodeAction::TELEPORT_BLOCKING_VISIT)
  411. {
  412. continue;
  413. }
  414. if(node->turns > heroChainTurn
  415. || (node->action == CGPathNode::ENodeAction::UNKNOWN && node->actor->hero)
  416. || (node->actor->chainMask & srcNode->actor->chainMask) != 0)
  417. {
  418. #if PATHFINDER_TRACE_LEVEL >= 2
  419. logAi->trace(
  420. "Skip exchange %s[%x] -> %s[%x] at %s because of %s",
  421. node->actor->toString(),
  422. node->actor->chainMask,
  423. srcNode->actor->toString(),
  424. srcNode->actor->chainMask,
  425. srcNode->coord.toString(),
  426. (node->turns > heroChainTurn
  427. ? "turn limit"
  428. : (node->action == CGPathNode::ENodeAction::UNKNOWN && node->actor->hero)
  429. ? "action unknown"
  430. : "chain mask"));
  431. #endif
  432. continue;
  433. }
  434. #if PATHFINDER_TRACE_LEVEL >= 2
  435. logAi->trace(
  436. "Thy exchange %s[%x] -> %s[%x] at %s",
  437. node->actor->toString(),
  438. node->actor->chainMask,
  439. srcNode->actor->toString(),
  440. srcNode->actor->chainMask,
  441. srcNode->coord.toString());
  442. #endif
  443. calculateHeroChain(srcNode, node, result);
  444. }
  445. }
  446. void AINodeStorage::calculateHeroChain(
  447. AIPathNode * carrier,
  448. AIPathNode * other,
  449. std::vector<ExchangeCandidate> & result) const
  450. {
  451. if(carrier->armyLoss < carrier->actor->armyValue
  452. && (carrier->action != CGPathNode::BATTLE || (carrier->actor->allowBattle && carrier->specialAction))
  453. && carrier->action != CGPathNode::BLOCKING_VISIT
  454. && (other->armyLoss == 0 || other->armyLoss < other->actor->armyValue)
  455. && carrier->actor->canExchange(other->actor))
  456. {
  457. #if PATHFINDER_TRACE_LEVEL >= 2
  458. logAi->trace(
  459. "Exchange allowed %s[%x] -> %s[%x] at %s",
  460. other->actor->toString(),
  461. other->actor->chainMask,
  462. carrier->actor->toString(),
  463. carrier->actor->chainMask,
  464. carrier->coord.toString());
  465. #endif
  466. if(other->actor->isMovable)
  467. {
  468. bool hasLessMp = carrier->turns > other->turns || (carrier->turns == other->turns && carrier->moveRemains < other->moveRemains);
  469. bool hasLessExperience = carrier->actor->hero->exp < other->actor->hero->exp;
  470. if(hasLessMp && hasLessExperience)
  471. {
  472. #if PATHFINDER_TRACE_LEVEL >= 2
  473. logAi->trace("Exchange at %s is ineficient. Blocked.", carrier->coord.toString());
  474. #endif
  475. return;
  476. }
  477. }
  478. auto newActor = carrier->actor->exchange(other->actor);
  479. result.push_back(calculateExchange(newActor, carrier, other));
  480. }
  481. }
  482. void AINodeStorage::addHeroChain(const std::vector<ExchangeCandidate> & result)
  483. {
  484. for(const ExchangeCandidate & chainInfo : result)
  485. {
  486. auto carrier = chainInfo.carrierParent;
  487. auto newActor = chainInfo.actor;
  488. auto other = chainInfo.otherParent;
  489. auto chainNodeOptional = getOrCreateNode(carrier->coord, carrier->layer, newActor);
  490. if(!chainNodeOptional)
  491. {
  492. #if PATHFINDER_TRACE_LEVEL >= 2
  493. logAi->trace("Exchange at %s can not allocate node. Blocked.", carrier->coord.toString());
  494. #endif
  495. continue;
  496. }
  497. auto exchangeNode = chainNodeOptional.get();
  498. if(exchangeNode->action != CGPathNode::ENodeAction::UNKNOWN)
  499. {
  500. #if PATHFINDER_TRACE_LEVEL >= 2
  501. logAi->trace("Exchange at %s node is already in use. Blocked.", carrier->coord.toString());
  502. #endif
  503. continue;
  504. }
  505. if(exchangeNode->turns != 0xFF && exchangeNode->cost < chainInfo.cost)
  506. {
  507. #if PATHFINDER_TRACE_LEVEL >= 2
  508. logAi->trace(
  509. "Exchange at %s is is not effective enough. %f < %f",
  510. exchangeNode->coord.toString(),
  511. exchangeNode->getCost(),
  512. chainInfo.getCost());
  513. #endif
  514. continue;
  515. }
  516. commit(exchangeNode, carrier, carrier->action, chainInfo.turns, chainInfo.moveRemains, chainInfo.cost);
  517. if(carrier->specialAction || carrier->chainOther)
  518. {
  519. // there is some action on source tile which should be performed before we can bypass it
  520. exchangeNode->theNodeBefore = carrier;
  521. }
  522. if(exchangeNode->actor->actorAction)
  523. {
  524. exchangeNode->theNodeBefore = carrier;
  525. exchangeNode->specialAction = exchangeNode->actor->actorAction;
  526. }
  527. exchangeNode->chainOther = other;
  528. exchangeNode->armyLoss = chainInfo.armyLoss;
  529. #if PATHFINDER_TRACE_LEVEL >= 2
  530. logAi->trace(
  531. "Chain accepted at %s %s -> %s, mask %x, cost %f, turn: %s, mp: %d, army %i",
  532. exchangeNode->coord.toString(),
  533. other->actor->toString(),
  534. exchangeNode->actor->toString(),
  535. exchangeNode->actor->chainMask,
  536. exchangeNode->getCost(),
  537. std::to_string(exchangeNode->turns),
  538. exchangeNode->moveRemains,
  539. exchangeNode->actor->armyValue);
  540. #endif
  541. heroChain.push_back(exchangeNode);
  542. }
  543. }
  544. ExchangeCandidate AINodeStorage::calculateExchange(
  545. ChainActor * exchangeActor,
  546. AIPathNode * carrierParentNode,
  547. AIPathNode * otherParentNode) const
  548. {
  549. ExchangeCandidate candidate;
  550. candidate.layer = carrierParentNode->layer;
  551. candidate.coord = carrierParentNode->coord;
  552. candidate.carrierParent = carrierParentNode;
  553. candidate.otherParent = otherParentNode;
  554. candidate.actor = exchangeActor;
  555. candidate.armyLoss = carrierParentNode->armyLoss + otherParentNode->armyLoss;
  556. candidate.turns = carrierParentNode->turns;
  557. candidate.cost = carrierParentNode->cost + otherParentNode->cost / 1000.0;
  558. candidate.moveRemains = carrierParentNode->moveRemains;
  559. if(carrierParentNode->turns < otherParentNode->turns)
  560. {
  561. int moveRemains = exchangeActor->hero->maxMovePoints(carrierParentNode->layer);
  562. float waitingCost = otherParentNode->turns - carrierParentNode->turns - 1
  563. + carrierParentNode->moveRemains / (float)moveRemains;
  564. candidate.turns = otherParentNode->turns;
  565. candidate.cost += waitingCost;
  566. candidate.moveRemains = moveRemains;
  567. }
  568. return candidate;
  569. }
  570. const CGHeroInstance * AINodeStorage::getHero(const CGPathNode * node) const
  571. {
  572. auto aiNode = getAINode(node);
  573. return aiNode->actor->hero;
  574. }
  575. const std::set<const CGHeroInstance *> AINodeStorage::getAllHeroes() const
  576. {
  577. std::set<const CGHeroInstance *> heroes;
  578. for(auto actor : actors)
  579. {
  580. if(actor->hero)
  581. heroes.insert(actor->hero);
  582. }
  583. return heroes;
  584. }
  585. bool AINodeStorage::isDistanceLimitReached(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  586. {
  587. if(heroChainPass == EHeroChainPass::CHAIN && destination.node->turns > heroChainTurn)
  588. {
  589. return true;
  590. }
  591. auto aiNode = getAINode(destination.node);
  592. if(heroChainPass == EHeroChainPass::FINAL)
  593. {
  594. if(aiNode->actor->heroRole == HeroRole::SCOUT && destination.node->turns > scoutTurnDistanceLimit)
  595. return true;
  596. }
  597. else if(heroChainPass == EHeroChainPass::INITIAL)
  598. {
  599. if(aiNode->actor->heroRole == HeroRole::SCOUT && destination.node->turns > scoutTurnDistanceLimit)
  600. return true;
  601. }
  602. return false;
  603. }
  604. void AINodeStorage::setHeroes(std::map<const CGHeroInstance *, HeroRole> heroes)
  605. {
  606. playerID = ai->playerID;
  607. for(auto & hero : heroes)
  608. {
  609. uint64_t mask = FirstActorMask << actors.size();
  610. auto actor = std::make_shared<HeroActor>(hero.first, hero.second, mask, ai);
  611. if(actor->hero->tempOwner != ai->playerID)
  612. {
  613. bool onLand = !actor->hero->boat;
  614. actor->initialMovement = actor->hero->maxMovePoints(onLand);
  615. }
  616. playerID = actor->hero->tempOwner;
  617. actors.push_back(actor);
  618. }
  619. }
  620. void AINodeStorage::setTownsAndDwellings(
  621. const std::vector<const CGTownInstance *> & towns,
  622. const std::set<const CGObjectInstance *> & visitableObjs)
  623. {
  624. for(auto town : towns)
  625. {
  626. uint64_t mask = FirstActorMask << actors.size();
  627. // TODO: investigate logix of second condition || ai->nullkiller->getHeroLockedReason(town->garrisonHero) != HeroLockedReason::DEFENCE
  628. // check defence imrove
  629. if(!town->garrisonHero)
  630. {
  631. actors.push_back(std::make_shared<TownGarrisonActor>(town, mask));
  632. }
  633. }
  634. /*auto dayOfWeek = cb->getDate(Date::DAY_OF_WEEK);
  635. auto waitForGrowth = dayOfWeek > 4;*/
  636. for(auto obj: visitableObjs)
  637. {
  638. if(obj->ID == Obj::HILL_FORT)
  639. {
  640. uint64_t mask = FirstActorMask << actors.size();
  641. actors.push_back(std::make_shared<HillFortActor>(obj, mask));
  642. }
  643. /*const CGDwelling * dwelling = dynamic_cast<const CGDwelling *>(obj);
  644. if(dwelling)
  645. {
  646. uint64_t mask = 1 << actors.size();
  647. auto dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, false, dayOfWeek);
  648. if(dwellingActor->creatureSet->getArmyStrength())
  649. {
  650. actors.push_back(dwellingActor);
  651. }
  652. if(waitForGrowth)
  653. {
  654. mask = 1 << actors.size();
  655. dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, waitForGrowth, dayOfWeek);
  656. if(dwellingActor->creatureSet->getArmyStrength())
  657. {
  658. actors.push_back(dwellingActor);
  659. }
  660. }
  661. }*/
  662. }
  663. }
  664. std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
  665. const PathNodeInfo & source,
  666. const PathfinderConfig * pathfinderConfig,
  667. const CPathfinderHelper * pathfinderHelper)
  668. {
  669. std::vector<CGPathNode *> neighbours;
  670. if(source.isNodeObjectVisitable())
  671. {
  672. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  673. auto srcNode = getAINode(source.node);
  674. for(auto & neighbour : accessibleExits)
  675. {
  676. auto node = getOrCreateNode(neighbour, source.node->layer, srcNode->actor);
  677. if(!node)
  678. continue;
  679. neighbours.push_back(node.get());
  680. }
  681. }
  682. return neighbours;
  683. }
  684. struct TowmPortalFinder
  685. {
  686. const std::vector<CGPathNode *> & initialNodes;
  687. SecSkillLevel::SecSkillLevel townPortalSkillLevel;
  688. uint64_t movementNeeded;
  689. const ChainActor * actor;
  690. const CGHeroInstance * hero;
  691. std::vector<const CGTownInstance *> targetTowns;
  692. AINodeStorage * nodeStorage;
  693. SpellID spellID;
  694. const CSpell * townPortal;
  695. TowmPortalFinder(
  696. const ChainActor * actor,
  697. const std::vector<CGPathNode *> & initialNodes,
  698. std::vector<const CGTownInstance *> targetTowns,
  699. AINodeStorage * nodeStorage)
  700. :actor(actor), initialNodes(initialNodes), hero(actor->hero),
  701. targetTowns(targetTowns), nodeStorage(nodeStorage)
  702. {
  703. spellID = SpellID::TOWN_PORTAL;
  704. townPortal = spellID.toSpell();
  705. // TODO: Copy/Paste from TownPortalMechanics
  706. townPortalSkillLevel = SecSkillLevel::SecSkillLevel(hero->getSpellSchoolLevel(townPortal));
  707. movementNeeded = GameConstants::BASE_MOVEMENT_COST * (townPortalSkillLevel >= SecSkillLevel::EXPERT ? 2 : 3);
  708. }
  709. bool actorCanCastTownPortal()
  710. {
  711. return hero->canCastThisSpell(townPortal) && hero->mana >= hero->getSpellCost(townPortal);
  712. }
  713. CGPathNode * getBestInitialNodeForTownPortal(const CGTownInstance * targetTown)
  714. {
  715. CGPathNode * bestNode = nullptr;
  716. for(CGPathNode * node : initialNodes)
  717. {
  718. auto aiNode = nodeStorage->getAINode(node);
  719. if(aiNode->actor->baseActor != actor
  720. || node->layer != EPathfindingLayer::LAND
  721. || node->moveRemains < movementNeeded)
  722. {
  723. continue;
  724. }
  725. if(townPortalSkillLevel < SecSkillLevel::ADVANCED)
  726. {
  727. const CGTownInstance * nearestTown = *vstd::minElementByFun(targetTowns, [&](const CGTownInstance * t) -> int
  728. {
  729. return node->coord.dist2dSQ(t->visitablePos());
  730. });
  731. if(targetTown != nearestTown)
  732. continue;
  733. }
  734. if(!bestNode || bestNode->cost > node->cost)
  735. bestNode = node;
  736. }
  737. return bestNode;
  738. }
  739. boost::optional<AIPathNode *> createTownPortalNode(const CGTownInstance * targetTown)
  740. {
  741. auto bestNode = getBestInitialNodeForTownPortal(targetTown);
  742. if(!bestNode)
  743. return boost::none;
  744. auto nodeOptional = nodeStorage->getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, actor->castActor);
  745. if(!nodeOptional)
  746. return boost::none;
  747. AIPathNode * node = nodeOptional.get();
  748. float movementCost = (float)movementNeeded / (float)hero->maxMovePoints(EPathfindingLayer::LAND);
  749. movementCost += bestNode->cost;
  750. if(node->action == CGPathNode::UNKNOWN || node->cost > movementCost)
  751. {
  752. nodeStorage->commit(
  753. node,
  754. nodeStorage->getAINode(bestNode),
  755. CGPathNode::TELEPORT_NORMAL,
  756. bestNode->turns,
  757. bestNode->moveRemains - movementNeeded,
  758. movementCost);
  759. node->theNodeBefore = bestNode;
  760. node->specialAction.reset(new AIPathfinding::TownPortalAction(targetTown));
  761. }
  762. return nodeOptional;
  763. }
  764. };
  765. void AINodeStorage::calculateTownPortalTeleportations(std::vector<CGPathNode *> & initialNodes)
  766. {
  767. std::set<const ChainActor *> actorsOfInitial;
  768. for(const CGPathNode * node : initialNodes)
  769. {
  770. auto aiNode = getAINode(node);
  771. actorsOfInitial.insert(aiNode->actor->baseActor);
  772. }
  773. std::map<const CGHeroInstance *, int> maskMap;
  774. for(std::shared_ptr<ChainActor> basicActor : actors)
  775. {
  776. if(basicActor->hero)
  777. maskMap[basicActor->hero] = basicActor->chainMask;
  778. }
  779. for(const ChainActor * actor : actorsOfInitial)
  780. {
  781. if(!actor->hero)
  782. continue;
  783. auto towns = cb->getTownsInfo(false);
  784. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  785. {
  786. return cb->getPlayerRelations(actor->hero->tempOwner, t->tempOwner) == PlayerRelations::ENEMIES;
  787. });
  788. if(!towns.size())
  789. {
  790. return; // no towns no need to run loop further
  791. }
  792. TowmPortalFinder townPortalFinder(actor, initialNodes, towns, this);
  793. if(townPortalFinder.actorCanCastTownPortal())
  794. {
  795. for(const CGTownInstance * targetTown : towns)
  796. {
  797. // TODO: allow to hide visiting hero in garrison
  798. if(targetTown->visitingHero)
  799. {
  800. auto basicMask = maskMap[targetTown->visitingHero.get()];
  801. bool heroIsInChain = (actor->chainMask & basicMask) != 0;
  802. bool sameActorInTown = actor->chainMask == basicMask;
  803. if(sameActorInTown || !heroIsInChain)
  804. continue;
  805. }
  806. auto nodeOptional = townPortalFinder.createTownPortalNode(targetTown);
  807. if(nodeOptional)
  808. {
  809. #if PATHFINDER_TRACE_LEVEL >= 1
  810. logAi->trace("Adding town portal node at %s", targetTown->name);
  811. #endif
  812. initialNodes.push_back(nodeOptional.get());
  813. }
  814. }
  815. }
  816. }
  817. }
  818. bool AINodeStorage::hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  819. {
  820. auto pos = destination.coord;
  821. auto chains = nodes.get(pos, EPathfindingLayer::LAND);
  822. return hasBetterChain(source.node, getAINode(destination.node), chains);
  823. }
  824. template<class NodeRange>
  825. bool AINodeStorage::hasBetterChain(
  826. const CGPathNode * source,
  827. const AIPathNode * candidateNode,
  828. const NodeRange & chains) const
  829. {
  830. auto candidateActor = candidateNode->actor;
  831. for(const AIPathNode & node : chains)
  832. {
  833. auto sameNode = node.actor == candidateNode->actor;
  834. if(sameNode || node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor->hero)
  835. {
  836. continue;
  837. }
  838. if(node.danger <= candidateNode->danger && candidateNode->actor == node.actor->battleActor)
  839. {
  840. if(node.cost < candidateNode->cost)
  841. {
  842. #if PATHFINDER_TRACE_LEVEL >= 2
  843. logAi->trace(
  844. "Block ineficient battle move %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  845. source->coord.toString(),
  846. candidateNode->coord.toString(),
  847. candidateNode->actor->hero->name,
  848. candidateNode->actor->chainMask,
  849. candidateNode->actor->armyValue,
  850. node.moveRemains - candidateNode->moveRemains);
  851. #endif
  852. return true;
  853. }
  854. }
  855. if(candidateActor->chainMask != node.actor->chainMask && heroChainPass != EHeroChainPass::FINAL)
  856. continue;
  857. auto nodeActor = node.actor;
  858. auto nodeArmyValue = nodeActor->armyValue - node.armyLoss;
  859. auto candidateArmyValue = candidateActor->armyValue - candidateNode->armyLoss;
  860. if(nodeArmyValue > candidateArmyValue
  861. && node.cost <= candidateNode->cost)
  862. {
  863. #if PATHFINDER_TRACE_LEVEL >= 2
  864. logAi->trace(
  865. "Block ineficient move because of stronger army %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  866. source->coord.toString(),
  867. candidateNode->coord.toString(),
  868. candidateNode->actor->hero->name,
  869. candidateNode->actor->chainMask,
  870. candidateNode->actor->armyValue,
  871. node.moveRemains - candidateNode->moveRemains);
  872. #endif
  873. return true;
  874. }
  875. if(heroChainPass == EHeroChainPass::FINAL)
  876. {
  877. if(nodeArmyValue == candidateArmyValue
  878. && nodeActor->heroFightingStrength >= candidateActor->heroFightingStrength
  879. && node.cost <= candidateNode->cost)
  880. {
  881. if(nodeActor->heroFightingStrength == candidateActor->heroFightingStrength
  882. && node.cost == candidateNode->cost
  883. && &node < candidateNode)
  884. {
  885. continue;
  886. }
  887. #if AI_TRACE_LEVEL >= 2
  888. logAi->trace(
  889. "Block ineficient move because of stronger hero %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  890. source->coord.toString(),
  891. candidateNode->coord.toString(),
  892. candidateNode->actor->hero->name,
  893. candidateNode->actor->chainMask,
  894. candidateNode->actor->armyValue,
  895. node.moveRemains - candidateNode->moveRemains);
  896. #endif
  897. return true;
  898. }
  899. }
  900. }
  901. return false;
  902. }
  903. bool AINodeStorage::isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const
  904. {
  905. auto chains = nodes.get(pos, layer);
  906. for(const AIPathNode & node : chains)
  907. {
  908. if(node.action != CGPathNode::ENodeAction::UNKNOWN
  909. && node.actor && node.actor->hero == hero.h)
  910. {
  911. return true;
  912. }
  913. }
  914. return false;
  915. }
  916. std::vector<AIPath> AINodeStorage::getChainInfo(const int3 & pos, bool isOnLand) const
  917. {
  918. std::vector<AIPath> paths;
  919. paths.reserve(NUM_CHAINS / 4);
  920. auto chains = nodes.get(pos, isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL);
  921. for(const AIPathNode & node : chains)
  922. {
  923. if(node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor || !node.actor->hero)
  924. {
  925. continue;
  926. }
  927. AIPath path;
  928. path.targetHero = node.actor->hero;
  929. path.heroArmy = node.actor->creatureSet;
  930. path.armyLoss = node.armyLoss;
  931. path.targetObjectDanger = evaluateDanger(pos, path.targetHero, false);
  932. path.targetObjectArmyLoss = evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), path.targetObjectDanger);
  933. path.chainMask = node.actor->chainMask;
  934. path.exchangeCount = node.actor->actorExchangeCount;
  935. fillChainInfo(&node, path, -1);
  936. paths.push_back(path);
  937. }
  938. return paths;
  939. }
  940. void AINodeStorage::fillChainInfo(const AIPathNode * node, AIPath & path, int parentIndex) const
  941. {
  942. while(node != nullptr)
  943. {
  944. if(!node->actor->hero)
  945. return;
  946. if(node->chainOther)
  947. fillChainInfo(node->chainOther, path, parentIndex);
  948. //if(node->actor->hero->visitablePos() != node->coord)
  949. {
  950. AIPathNodeInfo pathNode;
  951. pathNode.cost = node->cost;
  952. pathNode.targetHero = node->actor->hero;
  953. pathNode.chainMask = node->actor->chainMask;
  954. pathNode.specialAction = node->specialAction;
  955. pathNode.turns = node->turns;
  956. pathNode.danger = node->danger;
  957. pathNode.coord = node->coord;
  958. pathNode.parentIndex = parentIndex;
  959. pathNode.actionIsBlocked = false;
  960. if(pathNode.specialAction)
  961. {
  962. auto targetNode =node->theNodeBefore ? getAINode(node->theNodeBefore) : node;
  963. pathNode.actionIsBlocked = !pathNode.specialAction->canAct(targetNode);
  964. }
  965. parentIndex = path.nodes.size();
  966. path.nodes.push_back(pathNode);
  967. }
  968. node = getAINode(node->theNodeBefore);
  969. }
  970. }
  971. AIPath::AIPath()
  972. : nodes({})
  973. {
  974. }
  975. std::shared_ptr<const SpecialAction> AIPath::getFirstBlockedAction() const
  976. {
  977. for(auto node = nodes.rbegin(); node != nodes.rend(); node++)
  978. {
  979. if(node->specialAction && node->actionIsBlocked)
  980. return node->specialAction;
  981. }
  982. return std::shared_ptr<const SpecialAction>();
  983. }
  984. int3 AIPath::firstTileToGet() const
  985. {
  986. if(nodes.size())
  987. {
  988. return nodes.back().coord;
  989. }
  990. return int3(-1, -1, -1);
  991. }
  992. int3 AIPath::targetTile() const
  993. {
  994. if(nodes.size())
  995. {
  996. return targetNode().coord;
  997. }
  998. return int3(-1, -1, -1);
  999. }
  1000. const AIPathNodeInfo & AIPath::firstNode() const
  1001. {
  1002. return nodes.back();
  1003. }
  1004. const AIPathNodeInfo & AIPath::targetNode() const
  1005. {
  1006. auto & node = nodes.front();
  1007. return targetHero == node.targetHero ? node : nodes.at(1);
  1008. }
  1009. uint64_t AIPath::getPathDanger() const
  1010. {
  1011. if(nodes.empty())
  1012. return 0;
  1013. return targetNode().danger;
  1014. }
  1015. float AIPath::movementCost() const
  1016. {
  1017. if(nodes.empty())
  1018. return 0.0f;
  1019. return targetNode().cost;
  1020. }
  1021. uint8_t AIPath::turn() const
  1022. {
  1023. if(nodes.empty())
  1024. return 0;
  1025. return targetNode().turns;
  1026. }
  1027. uint64_t AIPath::getHeroStrength() const
  1028. {
  1029. return targetHero->getFightingStrength() * heroArmy->getArmyStrength();
  1030. }
  1031. uint64_t AIPath::getTotalDanger() const
  1032. {
  1033. uint64_t pathDanger = getPathDanger();
  1034. uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger;
  1035. return danger;
  1036. }
  1037. bool AIPath::containsHero(const CGHeroInstance * hero) const
  1038. {
  1039. if(targetHero == hero)
  1040. return true;
  1041. for(auto node : nodes)
  1042. {
  1043. if(node.targetHero == hero)
  1044. return true;
  1045. }
  1046. return false;
  1047. }
  1048. uint64_t AIPath::getTotalArmyLoss() const
  1049. {
  1050. return armyLoss + targetObjectArmyLoss;
  1051. }
  1052. std::string AIPath::toString() const
  1053. {
  1054. std::stringstream str;
  1055. str << targetHero->name << "[" << std::hex << chainMask << std::dec << "]" << ", turn " << (int)(turn()) << ": ";
  1056. for(auto node : nodes)
  1057. str << node.targetHero->name << "[" << std::hex << node.chainMask << std::dec << "]" << "->" << node.coord.toString() << "; ";
  1058. return str.str();
  1059. }