AINodeStorage.cpp 36 KB

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