2
0

AINodeStorage.cpp 39 KB

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