AINodeStorage.cpp 37 KB

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