AINodeStorage.cpp 42 KB

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