AINodeStorage.cpp 43 KB

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