AINodeStorage.cpp 44 KB

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