AINodeStorage.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666
  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(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. // 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([&](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([&](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::random_device randomDevice;
  437. std::mt19937 randomEngine(randomDevice());
  438. for(int i = r.begin(); i != r.end(); i++)
  439. {
  440. auto & pos = tiles[i];
  441. for(auto layer : phisycalLayers)
  442. {
  443. existingChains.clear();
  444. storage.iterateValidNodes(pos, layer, [this](AIPathNode & node)
  445. {
  446. if(node.turns <= heroChainTurn && node.action != EPathNodeAction::UNKNOWN)
  447. existingChains.push_back(&node);
  448. });
  449. if(existingChains.empty())
  450. continue;
  451. newChains.clear();
  452. std::shuffle(existingChains.begin(), existingChains.end(), randomEngine);
  453. for(AIPathNode * node : existingChains)
  454. {
  455. if(node->actor->isMovable)
  456. {
  457. calculateHeroChain(node, existingChains, newChains);
  458. }
  459. }
  460. for(auto delayed = delayedWork.begin(); delayed != delayedWork.end();)
  461. {
  462. auto newActor = delayed->carrier->actor->tryExchangeNoLock(delayed->other->actor);
  463. if(!newActor.lockAcquired) continue;
  464. if(newActor.actor)
  465. {
  466. newChains.push_back(calculateExchange(newActor.actor, delayed->carrier, delayed->other));
  467. }
  468. delayed++;
  469. }
  470. delayedWork.clear();
  471. cleanupInefectiveChains(newChains);
  472. addHeroChain(newChains);
  473. }
  474. }
  475. }
  476. void calculateHeroChain(
  477. AIPathNode * srcNode,
  478. const std::vector<AIPathNode *> & variants,
  479. std::vector<ExchangeCandidate> & result);
  480. void calculateHeroChain(
  481. AIPathNode * carrier,
  482. AIPathNode * other,
  483. std::vector<ExchangeCandidate> & result);
  484. void cleanupInefectiveChains(std::vector<ExchangeCandidate> & result) const;
  485. void addHeroChain(const std::vector<ExchangeCandidate> & result);
  486. ExchangeCandidate calculateExchange(
  487. ChainActor * exchangeActor,
  488. AIPathNode * carrierParentNode,
  489. AIPathNode * otherParentNode) const;
  490. void flushResult(std::vector<CGPathNode *> & result)
  491. {
  492. vstd::concatenate(result, heroChain);
  493. }
  494. };
  495. bool AINodeStorage::calculateHeroChain()
  496. {
  497. heroChainPass = EHeroChainPass::CHAIN;
  498. heroChain.clear();
  499. std::vector<int3> data(committedTiles.begin(), committedTiles.end());
  500. int maxConcurrency = tbb::this_task_arena::max_concurrency();
  501. std::vector<std::vector<CGPathNode *>> results(maxConcurrency);
  502. logAi->trace("Caculating hero chain for %d items", data.size());
  503. tbb::parallel_for(tbb::blocked_range<size_t>(0, data.size()), [&](const tbb::blocked_range<size_t>& r)
  504. {
  505. SET_GLOBAL_STATE_TBB(aiNk->aiGw);
  506. HeroChainCalculationTask task(*this, data, chainMask, heroChainTurn);
  507. int ourThread = tbb::this_task_arena::current_thread_index();
  508. task.execute(r);
  509. task.flushResult(results.at(ourThread));
  510. });
  511. // FIXME: potentially non-deterministic behavior due to parallel_for
  512. for (const auto & result : results)
  513. vstd::concatenate(heroChain, result);
  514. committedTiles.clear();
  515. return !heroChain.empty();
  516. }
  517. bool AINodeStorage::selectFirstActor()
  518. {
  519. if(actors.empty())
  520. return false;
  521. auto strongest = *vstd::maxElementByFun(actors, [](std::shared_ptr<ChainActor> actor) -> uint64_t
  522. {
  523. return actor->armyValue;
  524. });
  525. chainMask = strongest->chainMask;
  526. committedTilesInitial = committedTiles;
  527. return true;
  528. }
  529. bool AINodeStorage::selectNextActor()
  530. {
  531. auto currentActor = std::find_if(actors.begin(), actors.end(), [&](std::shared_ptr<ChainActor> actor)-> bool
  532. {
  533. return actor->chainMask == chainMask;
  534. });
  535. auto nextActor = actors.end();
  536. for(auto actor = actors.begin(); actor != actors.end(); actor++)
  537. {
  538. if(actor->get()->armyValue > currentActor->get()->armyValue
  539. || (actor->get()->armyValue == currentActor->get()->armyValue && actor <= currentActor))
  540. {
  541. continue;
  542. }
  543. if(nextActor == actors.end()
  544. || actor->get()->armyValue > nextActor->get()->armyValue)
  545. {
  546. nextActor = actor;
  547. }
  548. }
  549. if(nextActor != actors.end())
  550. {
  551. if(nextActor->get()->armyValue < MIN_ARMY_STRENGTH_FOR_NEXT_ACTOR)
  552. return false;
  553. chainMask = nextActor->get()->chainMask;
  554. committedTiles = committedTilesInitial;
  555. return true;
  556. }
  557. return false;
  558. }
  559. uint64_t AINodeStorage::evaluateArmyLoss(const CGHeroInstance * hero, uint64_t armyValue, uint64_t danger) const
  560. {
  561. float fightingStrength = aiNk->heroManager->getFightingStrengthCached(hero);
  562. double ratio = (double)danger / (armyValue * fightingStrength);
  563. return (uint64_t)(armyValue * ratio * ratio);
  564. }
  565. void HeroChainCalculationTask::cleanupInefectiveChains(std::vector<ExchangeCandidate> & result) const
  566. {
  567. vstd::erase_if(result, [&](const ExchangeCandidate & chainInfo) -> bool
  568. {
  569. auto isNotEffective = storage.hasBetterChain(chainInfo.carrierParent, chainInfo)
  570. || storage.hasBetterChain(chainInfo.carrierParent, chainInfo, result);
  571. #if NK2AI_PATHFINDER_TRACE_LEVEL >= 2
  572. if(isNotEffective)
  573. {
  574. logAi->trace(
  575. "Skip exchange %s[%x] -> %s[%x] at %s is inefficient",
  576. chainInfo.otherParent->actor->toString(),
  577. chainInfo.otherParent->actor->chainMask,
  578. chainInfo.carrierParent->actor->toString(),
  579. chainInfo.carrierParent->actor->chainMask,
  580. chainInfo.carrierParent->coord.toString());
  581. }
  582. #endif
  583. return isNotEffective;
  584. });
  585. }
  586. void HeroChainCalculationTask::calculateHeroChain(
  587. AIPathNode * srcNode,
  588. const std::vector<AIPathNode *> & variants,
  589. std::vector<ExchangeCandidate> & result)
  590. {
  591. for(AIPathNode * node : variants)
  592. {
  593. if(node == srcNode || !node->actor || node->version != AISharedStorage::version)
  594. continue;
  595. if((node->actor->chainMask & chainMask) == 0 && (srcNode->actor->chainMask & chainMask) == 0)
  596. continue;
  597. if(node->actor->actorExchangeCount + srcNode->actor->actorExchangeCount > CHAIN_MAX_DEPTH)
  598. continue;
  599. if(node->action == EPathNodeAction::BATTLE
  600. || node->action == EPathNodeAction::TELEPORT_BATTLE
  601. || node->action == EPathNodeAction::TELEPORT_NORMAL
  602. || node->action == EPathNodeAction::DISEMBARK
  603. || node->action == EPathNodeAction::TELEPORT_BLOCKING_VISIT)
  604. {
  605. continue;
  606. }
  607. if(node->turns > heroChainTurn
  608. || (node->action == EPathNodeAction::UNKNOWN && node->actor->hero)
  609. || (node->actor->chainMask & srcNode->actor->chainMask) != 0)
  610. {
  611. #if NK2AI_PATHFINDER_TRACE_LEVEL >= 2
  612. logAi->trace(
  613. "Skip exchange %s[%x] -> %s[%x] at %s because of %s",
  614. node->actor->toString(),
  615. node->actor->chainMask,
  616. srcNode->actor->toString(),
  617. srcNode->actor->chainMask,
  618. srcNode->coord.toString(),
  619. (node->turns > heroChainTurn
  620. ? "turn limit"
  621. : (node->action == EPathNodeAction::UNKNOWN && node->actor->hero)
  622. ? "action unknown"
  623. : "chain mask"));
  624. #endif
  625. continue;
  626. }
  627. #if NK2AI_PATHFINDER_TRACE_LEVEL >= 2
  628. logAi->trace(
  629. "Thy exchange %s[%x] -> %s[%x] at %s",
  630. node->actor->toString(),
  631. node->actor->chainMask,
  632. srcNode->actor->toString(),
  633. srcNode->actor->chainMask,
  634. srcNode->coord.toString());
  635. #endif
  636. calculateHeroChain(srcNode, node, result);
  637. }
  638. }
  639. void HeroChainCalculationTask::calculateHeroChain(
  640. AIPathNode * carrier,
  641. AIPathNode * other,
  642. std::vector<ExchangeCandidate> & result)
  643. {
  644. if(carrier->armyLoss < carrier->actor->armyValue
  645. && (carrier->action != EPathNodeAction::BATTLE || (carrier->actor->allowBattle && carrier->specialAction))
  646. && carrier->action != EPathNodeAction::BLOCKING_VISIT
  647. && (other->armyLoss == 0 || other->armyLoss < other->actor->armyValue))
  648. {
  649. #if NK2AI_PATHFINDER_TRACE_LEVEL >= 2
  650. logAi->trace(
  651. "Exchange allowed %s[%x] -> %s[%x] at %s",
  652. other->actor->toString(),
  653. other->actor->chainMask,
  654. carrier->actor->toString(),
  655. carrier->actor->chainMask,
  656. carrier->coord.toString());
  657. #endif
  658. if(other->actor->isMovable)
  659. {
  660. bool hasLessMp = carrier->turns > other->turns || (carrier->turns == other->turns && carrier->moveRemains < other->moveRemains);
  661. bool hasLessExperience = carrier->actor->hero->exp < other->actor->hero->exp;
  662. if(hasLessMp && hasLessExperience)
  663. {
  664. #if NK2AI_PATHFINDER_TRACE_LEVEL >= 2
  665. logAi->trace("Exchange at %s is inefficient. Blocked.", carrier->coord.toString());
  666. #endif
  667. return;
  668. }
  669. }
  670. auto newActor = carrier->actor->tryExchangeNoLock(other->actor);
  671. if(!newActor.lockAcquired) delayedWork.push_back(DelayedWork(carrier, other));
  672. if(newActor.actor) result.push_back(calculateExchange(newActor.actor, carrier, other));
  673. }
  674. }
  675. void HeroChainCalculationTask::addHeroChain(const std::vector<ExchangeCandidate> & result)
  676. {
  677. for(const ExchangeCandidate & chainInfo : result)
  678. {
  679. auto carrier = chainInfo.carrierParent;
  680. auto newActor = chainInfo.actor;
  681. auto other = chainInfo.otherParent;
  682. auto chainNodeOptional = storage.getOrCreateNode(carrier->coord, carrier->layer, newActor);
  683. if(!chainNodeOptional)
  684. {
  685. #if NK2AI_PATHFINDER_TRACE_LEVEL >= 2
  686. logAi->trace(
  687. "HeroChainCalculationTask::addHeroChain Failed to allocate node at %s[%d]",
  688. carrier->coord.toString(),
  689. static_cast<int32_t>(carrier->layer));
  690. #endif
  691. continue;
  692. }
  693. auto * const exchangeNode = chainNodeOptional.value();
  694. if(exchangeNode->action != EPathNodeAction::UNKNOWN)
  695. {
  696. #if NK2AI_PATHFINDER_TRACE_LEVEL >= 2
  697. logAi->trace(
  698. "HeroChainCalculationTask::addHeroChain Skip exchange %s[%x] -> %s[%x] at %s because node is in use",
  699. other->actor->toString(),
  700. other->actor->chainMask,
  701. carrier->actor->toString(),
  702. carrier->actor->chainMask,
  703. carrier->coord.toString());
  704. #endif
  705. continue;
  706. }
  707. if(exchangeNode->turns != 0xFF && exchangeNode->getCost() < chainInfo.getCost())
  708. {
  709. #if NK2AI_PATHFINDER_TRACE_LEVEL >= 2
  710. logAi->trace(
  711. "HeroChainCalculationTask::addHeroChain Skip exchange %s[%x] -> %s[%x] at %s because not effective enough. %f < %f",
  712. other->actor->toString(),
  713. other->actor->chainMask,
  714. carrier->actor->toString(),
  715. carrier->actor->chainMask,
  716. carrier->coord.toString(),
  717. exchangeNode->getCost(),
  718. chainInfo.getCost());
  719. #endif
  720. continue;
  721. }
  722. storage.commit(
  723. exchangeNode,
  724. carrier,
  725. carrier->action,
  726. chainInfo.turns,
  727. chainInfo.moveRemains,
  728. chainInfo.getCost(),
  729. DO_NOT_SAVE_TO_COMMITTED_TILES);
  730. if(carrier->specialAction || carrier->chainOther)
  731. {
  732. // there is some action on source tile which should be performed before we can bypass it
  733. exchangeNode->theNodeBefore = carrier;
  734. }
  735. if(exchangeNode->actor->actorAction)
  736. {
  737. exchangeNode->theNodeBefore = carrier;
  738. exchangeNode->addSpecialAction(exchangeNode->actor->actorAction);
  739. }
  740. exchangeNode->chainOther = other;
  741. exchangeNode->armyLoss = chainInfo.armyLoss;
  742. #if NK2AI_PATHFINDER_TRACE_LEVEL >= 2
  743. logAi->trace(
  744. "HeroChainCalculationTask::addHeroChain Chain accepted at %s %s -> %s, mask %x, cost %f, turn: %s, mp: %d, army %i",
  745. exchangeNode->coord.toString(),
  746. other->actor->toString(),
  747. exchangeNode->actor->toString(),
  748. exchangeNode->actor->chainMask,
  749. exchangeNode->getCost(),
  750. std::to_string(exchangeNode->turns),
  751. exchangeNode->moveRemains,
  752. exchangeNode->actor->armyValue);
  753. #endif
  754. heroChain.push_back(exchangeNode);
  755. }
  756. }
  757. ExchangeCandidate HeroChainCalculationTask::calculateExchange(
  758. ChainActor * exchangeActor,
  759. AIPathNode * carrierParentNode,
  760. AIPathNode * otherParentNode) const
  761. {
  762. ExchangeCandidate candidate;
  763. candidate.layer = carrierParentNode->layer;
  764. candidate.coord = carrierParentNode->coord;
  765. candidate.carrierParent = carrierParentNode;
  766. candidate.otherParent = otherParentNode;
  767. candidate.actor = exchangeActor;
  768. candidate.armyLoss = carrierParentNode->armyLoss + otherParentNode->armyLoss;
  769. candidate.turns = carrierParentNode->turns;
  770. candidate.setCost(carrierParentNode->getCost() + otherParentNode->getCost() / 1000.0);
  771. candidate.moveRemains = carrierParentNode->moveRemains;
  772. candidate.danger = carrierParentNode->danger;
  773. candidate.version = carrierParentNode->version;
  774. if(carrierParentNode->turns < otherParentNode->turns)
  775. {
  776. int moveRemains = exchangeActor->maxMovePoints(carrierParentNode->layer);
  777. float waitingCost = otherParentNode->turns - carrierParentNode->turns - 1
  778. + carrierParentNode->moveRemains / (float)moveRemains;
  779. candidate.turns = otherParentNode->turns;
  780. candidate.setCost(candidate.getCost() + waitingCost);
  781. candidate.moveRemains = moveRemains;
  782. }
  783. return candidate;
  784. }
  785. const std::set<const CGHeroInstance *> AINodeStorage::getAllHeroes() const
  786. {
  787. std::set<const CGHeroInstance *> heroes;
  788. for(auto actor : actors)
  789. {
  790. if(actor->hero)
  791. heroes.insert(actor->hero);
  792. }
  793. return heroes;
  794. }
  795. bool AINodeStorage::isDistanceLimitReached(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  796. {
  797. if(heroChainPass == EHeroChainPass::CHAIN && destination.node->turns > heroChainTurn)
  798. {
  799. return true;
  800. }
  801. auto aiNode = getAINode(destination.node);
  802. if(heroChainPass != EHeroChainPass::CHAIN
  803. && destination.node->turns > turnDistanceLimit[aiNode->actor->heroRole])
  804. {
  805. return true;
  806. }
  807. return false;
  808. }
  809. void AINodeStorage::setHeroes(std::map<const CGHeroInstance *, HeroRole> heroes)
  810. {
  811. playerID = aiNk->playerID;
  812. for(auto & hero : heroes)
  813. {
  814. // do not allow our own heroes in garrison to act on map
  815. if(hero.first->getOwner() == aiNk->playerID
  816. && hero.first->isGarrisoned()
  817. && (aiNk->isHeroLocked(hero.first) || aiNk->heroManager->heroCapReached(false)))
  818. {
  819. continue;
  820. }
  821. uint64_t mask = FirstActorMask << actors.size();
  822. auto actor = std::make_shared<HeroActor>(hero.first, hero.second, mask, aiNk);
  823. if(actor->hero->tempOwner != aiNk->playerID)
  824. {
  825. bool onLand = !actor->hero->inBoat() || actor->hero->getBoat()->layer != EPathfindingLayer::SAIL;
  826. actor->initialMovement = actor->hero->movementPointsLimit(onLand);
  827. }
  828. playerID = actor->hero->tempOwner;
  829. actors.push_back(actor);
  830. }
  831. }
  832. void AINodeStorage::setTownsAndDwellings(
  833. const std::vector<const CGTownInstance *> & towns,
  834. const std::set<const CGObjectInstance *> & visitableObjs)
  835. {
  836. for(auto town : towns)
  837. {
  838. uint64_t mask = FirstActorMask << actors.size();
  839. // TODO: investigate logix of second condition || ai->nullkiller->getHeroLockedReason(town->getGarrisonHero()) != HeroLockedReason::DEFENCE
  840. // check defence imrove
  841. if(!town->getGarrisonHero())
  842. {
  843. actors.push_back(std::make_shared<TownGarrisonActor>(town, mask));
  844. }
  845. }
  846. /*auto dayOfWeek = cb->getDate(Date::DAY_OF_WEEK);
  847. auto waitForGrowth = dayOfWeek > 4;*/
  848. for(auto obj: visitableObjs)
  849. {
  850. if(obj->ID == Obj::HILL_FORT)
  851. {
  852. uint64_t mask = FirstActorMask << actors.size();
  853. actors.push_back(std::make_shared<HillFortActor>(obj, mask));
  854. }
  855. /*const CGDwelling * dwelling = dynamic_cast<const CGDwelling *>(obj);
  856. if(dwelling)
  857. {
  858. uint64_t mask = 1 << actors.size();
  859. auto dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, false, dayOfWeek);
  860. if(dwellingActor->creatureSet->getArmyStrength())
  861. {
  862. actors.push_back(dwellingActor);
  863. }
  864. if(waitForGrowth)
  865. {
  866. mask = 1 << actors.size();
  867. dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, waitForGrowth, dayOfWeek);
  868. if(dwellingActor->creatureSet->getArmyStrength())
  869. {
  870. actors.push_back(dwellingActor);
  871. }
  872. }
  873. }*/
  874. }
  875. }
  876. std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
  877. const PathNodeInfo & source,
  878. const PathfinderConfig * pathfinderConfig,
  879. const CPathfinderHelper * pathfinderHelper)
  880. {
  881. std::vector<CGPathNode *> neighbours;
  882. if(source.isNodeObjectVisitable())
  883. {
  884. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  885. auto srcNode = getAINode(source.node);
  886. for(auto & neighbour : accessibleExits)
  887. {
  888. std::optional<AIPathNode *> node = getOrCreateNode(neighbour, source.node->layer, srcNode->actor);
  889. if(!node)
  890. {
  891. #if NK2AI_PATHFINDER_TRACE_LEVEL >= 2
  892. logAi->trace(
  893. "AINodeStorage::calculateTeleportations Failed to allocate node at %s[%d]",
  894. neighbour.toString(),
  895. static_cast<int32_t>(source.node->layer));
  896. #endif
  897. continue;
  898. }
  899. neighbours.push_back(node.value());
  900. }
  901. }
  902. return neighbours;
  903. }
  904. struct TownPortalFinder
  905. {
  906. const std::vector<CGPathNode *> & initialNodes;
  907. const ChainActor * actor;
  908. const CGHeroInstance * hero;
  909. std::vector<const CGTownInstance *> targetTowns;
  910. AINodeStorage * nodeStorage;
  911. const CSpell * townPortal;
  912. uint64_t movementNeeded;
  913. SpellID spellID;
  914. bool townSelectionAllowed;
  915. TownPortalFinder(const ChainActor * actor, const std::vector<CGPathNode *> & initialNodes, const std::vector<const CGTownInstance *> & targetTowns, AINodeStorage * nodeStorage, SpellID spellID)
  916. : initialNodes(initialNodes)
  917. , actor(actor)
  918. , hero(actor->hero)
  919. , targetTowns(targetTowns)
  920. , nodeStorage(nodeStorage)
  921. , townPortal(spellID.toSpell())
  922. , spellID(spellID)
  923. {
  924. auto townPortalEffect = townPortal->getAdventureMechanics().getEffectAs<TownPortalEffect>(hero);
  925. movementNeeded = townPortalEffect->getMovementPointsRequired();
  926. townSelectionAllowed = townPortalEffect->townSelectionAllowed();
  927. }
  928. bool actorCanCastTownPortal()
  929. {
  930. return hero->canCastThisSpell(townPortal) && hero->mana >= hero->getSpellCost(townPortal);
  931. }
  932. CGPathNode * getBestInitialNodeForTownPortal(const CGTownInstance * targetTown)
  933. {
  934. for(CGPathNode * node : initialNodes)
  935. {
  936. auto aiNode = nodeStorage->getAINode(node);
  937. if(aiNode->actor->baseActor != actor
  938. || node->layer != EPathfindingLayer::LAND
  939. || node->moveRemains < movementNeeded)
  940. {
  941. continue;
  942. }
  943. if(!townSelectionAllowed)
  944. {
  945. const CGTownInstance * nearestTown = *vstd::minElementByFun(targetTowns, [&](const CGTownInstance * t) -> int
  946. {
  947. return node->coord.dist2dSQ(t->visitablePos());
  948. });
  949. if(targetTown != nearestTown)
  950. continue;
  951. }
  952. return node;
  953. }
  954. return nullptr;
  955. }
  956. std::optional<AIPathNode *> createTownPortalNode(const CGTownInstance * targetTown)
  957. {
  958. auto bestNode = getBestInitialNodeForTownPortal(targetTown);
  959. if(!bestNode)
  960. return std::nullopt;
  961. const auto nodeOptional = nodeStorage->getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, actor->castActor);
  962. if(!nodeOptional)
  963. {
  964. #if NK2AI_PATHFINDER_TRACE_LEVEL >= 2
  965. logAi->trace(
  966. "createTownPortalNode Failed to allocate node at %s[%d]",
  967. targetTown->visitablePos().toString(),
  968. static_cast<int32_t>(EPathfindingLayer::LAND));
  969. #endif
  970. return std::nullopt;
  971. }
  972. AIPathNode * node = nodeOptional.value();
  973. float movementCost = (float)movementNeeded / (float)hero->movementPointsLimit(EPathfindingLayer::LAND);
  974. movementCost += bestNode->getCost();
  975. if(node->action == EPathNodeAction::UNKNOWN || node->getCost() > movementCost)
  976. {
  977. nodeStorage->commit(
  978. node,
  979. nodeStorage->getAINode(bestNode),
  980. EPathNodeAction::TELEPORT_NORMAL,
  981. bestNode->turns,
  982. bestNode->moveRemains - movementNeeded,
  983. movementCost,
  984. DO_NOT_SAVE_TO_COMMITTED_TILES);
  985. node->theNodeBefore = bestNode;
  986. node->addSpecialAction(std::make_shared<AIPathfinding::TownPortalAction>(targetTown, spellID));
  987. }
  988. return nodeOptional;
  989. }
  990. };
  991. template<class TVector>
  992. void AINodeStorage::calculateTownPortal(
  993. const ChainActor * actor,
  994. const std::map<const CGHeroInstance *, int> & maskMap,
  995. const std::vector<CGPathNode *> & initialNodes,
  996. TVector & output)
  997. {
  998. auto towns = aiNk->cc->getTownsInfo(false);
  999. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  1000. {
  1001. return aiNk->cc->getPlayerRelations(actor->hero->tempOwner, t->tempOwner) == PlayerRelations::ENEMIES;
  1002. });
  1003. if(!towns.size())
  1004. {
  1005. return; // no towns no need to run loop further
  1006. }
  1007. for (const auto & spell : LIBRARY->spellh->objects)
  1008. {
  1009. if (!spell || !spell->isAdventure())
  1010. continue;
  1011. auto townPortalEffect = spell->getAdventureMechanics().getEffectAs<TownPortalEffect>(actor->hero);
  1012. if (!townPortalEffect)
  1013. continue;
  1014. TownPortalFinder townPortalFinder(actor, initialNodes, towns, this, spell->id);
  1015. if(!townPortalFinder.actorCanCastTownPortal())
  1016. continue;
  1017. for(const CGTownInstance * targetTown : towns)
  1018. {
  1019. if(targetTown->getVisitingHero()
  1020. && targetTown->getUpperArmy()->stacksCount()
  1021. && maskMap.find(targetTown->getVisitingHero()) != maskMap.end())
  1022. {
  1023. auto basicMask = maskMap.at(targetTown->getVisitingHero());
  1024. bool sameActorInTown = actor->chainMask == basicMask;
  1025. if(!sameActorInTown)
  1026. continue;
  1027. }
  1028. if (targetTown->getVisitingHero()
  1029. && (targetTown->getVisitingHero()->getFactionID() != actor->hero->getFactionID()
  1030. || targetTown->getUpperArmy()->stacksCount()))
  1031. continue;
  1032. auto nodeOptional = townPortalFinder.createTownPortalNode(targetTown);
  1033. if(nodeOptional.has_value())
  1034. {
  1035. #if NK2AI_PATHFINDER_TRACE_LEVEL >= 1
  1036. logAi->trace("Adding town portal node at %s", targetTown->getObjectName());
  1037. #endif
  1038. output.push_back(nodeOptional.value());
  1039. }
  1040. }
  1041. }
  1042. }
  1043. void AINodeStorage::calculateTownPortalTeleportations(std::vector<CGPathNode *> & initialNodes)
  1044. {
  1045. std::set<const ChainActor *> actorsOfInitial;
  1046. for(const CGPathNode * node : initialNodes)
  1047. {
  1048. auto aiNode = getAINode(node);
  1049. if(aiNode->actor->hero)
  1050. actorsOfInitial.insert(aiNode->actor->baseActor);
  1051. }
  1052. std::map<const CGHeroInstance *, int> maskMap;
  1053. for(std::shared_ptr<ChainActor> basicActor : actors)
  1054. {
  1055. if(basicActor->hero)
  1056. maskMap[basicActor->hero] = basicActor->chainMask;
  1057. }
  1058. boost::sort(initialNodes, NodeComparer<CGPathNode>());
  1059. std::vector<const ChainActor *> actorsVector(actorsOfInitial.begin(), actorsOfInitial.end());
  1060. tbb::concurrent_vector<CGPathNode *> output;
  1061. // TODO: re-enable after fixing thread races. See issue for details:
  1062. // https://github.com/vcmi/vcmi/pull/4130
  1063. #if 0
  1064. if (actorsVector.size() * initialNodes.size() > 1000)
  1065. {
  1066. tbb::parallel_for(tbb::blocked_range<size_t>(0, actorsVector.size()), [&](const tbb::blocked_range<size_t> & r)
  1067. {
  1068. SET_GLOBAL_STATE_TBB(aiNk->aiGw);
  1069. for(int i = r.begin(); i != r.end(); i++)
  1070. {
  1071. calculateTownPortal(actorsVector[i], maskMap, initialNodes, output);
  1072. }
  1073. });
  1074. std::copy(output.begin(), output.end(), std::back_inserter(initialNodes));
  1075. }
  1076. else
  1077. #endif
  1078. {
  1079. for(auto actor : actorsVector)
  1080. {
  1081. calculateTownPortal(actor, maskMap, initialNodes, initialNodes);
  1082. }
  1083. }
  1084. }
  1085. bool AINodeStorage::hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  1086. {
  1087. auto candidateNode = getAINode(destination.node);
  1088. return hasBetterChain(source.node, *candidateNode);
  1089. }
  1090. bool AINodeStorage::hasBetterChain(
  1091. const CGPathNode * source,
  1092. const AIPathNode & candidateNode) const
  1093. {
  1094. return iterateValidNodesUntil(
  1095. candidateNode.coord,
  1096. candidateNode.layer,
  1097. [this, &source, candidateNode](const AIPathNode & node) -> bool
  1098. {
  1099. return isOtherChainBetter(source, candidateNode, node);
  1100. });
  1101. }
  1102. template<class NodeRange>
  1103. bool AINodeStorage::hasBetterChain(
  1104. const CGPathNode * source,
  1105. const AIPathNode & candidateNode,
  1106. const NodeRange & nodes) const
  1107. {
  1108. for(const AIPathNode & node : nodes)
  1109. {
  1110. if(isOtherChainBetter(source, candidateNode, node))
  1111. return true;
  1112. }
  1113. return false;
  1114. }
  1115. bool AINodeStorage::isOtherChainBetter(
  1116. const CGPathNode * source,
  1117. const AIPathNode & candidateNode,
  1118. const AIPathNode & other) const
  1119. {
  1120. auto sameNode = other.actor == candidateNode.actor;
  1121. if(sameNode || other.action == EPathNodeAction::UNKNOWN || !other.actor || !other.actor->hero)
  1122. {
  1123. return false;
  1124. }
  1125. if(other.danger <= candidateNode.danger && candidateNode.actor == other.actor->battleActor)
  1126. {
  1127. if(other.getCost() < candidateNode.getCost())
  1128. {
  1129. #if NK2AI_PATHFINDER_TRACE_LEVEL >= 2
  1130. logAi->trace(
  1131. "Block inefficient battle move %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  1132. source->coord.toString(),
  1133. candidateNode.coord.toString(),
  1134. candidateNode.actor->hero->getNameTranslated(),
  1135. candidateNode.actor->chainMask,
  1136. candidateNode.actor->armyValue,
  1137. other.moveRemains - candidateNode.moveRemains);
  1138. #endif
  1139. return true;
  1140. }
  1141. }
  1142. if(candidateNode.actor->chainMask != other.actor->chainMask && heroChainPass != EHeroChainPass::FINAL)
  1143. return false;
  1144. auto nodeActor = other.actor;
  1145. auto nodeArmyValue = nodeActor->armyValue - other.armyLoss;
  1146. auto candidateArmyValue = candidateNode.actor->armyValue - candidateNode.armyLoss;
  1147. if(nodeArmyValue > candidateArmyValue
  1148. && other.getCost() <= candidateNode.getCost())
  1149. {
  1150. #if NK2AI_PATHFINDER_TRACE_LEVEL >= 2
  1151. logAi->trace(
  1152. "Block inefficient move because of stronger army %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  1153. source->coord.toString(),
  1154. candidateNode.coord.toString(),
  1155. candidateNode.actor->hero->getNameTranslated(),
  1156. candidateNode.actor->chainMask,
  1157. candidateNode.actor->armyValue,
  1158. other.moveRemains - candidateNode.moveRemains);
  1159. #endif
  1160. return true;
  1161. }
  1162. if(heroChainPass == EHeroChainPass::FINAL)
  1163. {
  1164. if(nodeArmyValue == candidateArmyValue
  1165. && nodeActor->heroFightingStrength >= candidateNode.actor->heroFightingStrength
  1166. && other.getCost() <= candidateNode.getCost())
  1167. {
  1168. if(vstd::isAlmostEqual(nodeActor->heroFightingStrength, candidateNode.actor->heroFightingStrength)
  1169. && vstd::isAlmostEqual(other.getCost(), candidateNode.getCost())
  1170. && &other < &candidateNode)
  1171. {
  1172. return false;
  1173. }
  1174. #if NK2AI_PATHFINDER_TRACE_LEVEL >= 2
  1175. logAi->trace(
  1176. "Block inefficient move because of stronger hero %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  1177. source->coord.toString(),
  1178. candidateNode.coord.toString(),
  1179. candidateNode.actor->hero->getNameTranslated(),
  1180. candidateNode.actor->chainMask,
  1181. candidateNode.actor->armyValue,
  1182. other.moveRemains - candidateNode.moveRemains);
  1183. #endif
  1184. return true;
  1185. }
  1186. }
  1187. return false;
  1188. }
  1189. bool AINodeStorage::isTileAccessible(const HeroPtr & heroPtr, const int3 & pos, const EPathfindingLayer layer) const
  1190. {
  1191. auto chains = nodes.get(pos);
  1192. for(const AIPathNode & node : chains)
  1193. {
  1194. if(node.version == AISharedStorage::version
  1195. && node.layer == layer
  1196. && node.action != EPathNodeAction::UNKNOWN
  1197. && node.actor
  1198. && node.actor->hero == heroPtr.get())
  1199. {
  1200. return true;
  1201. }
  1202. }
  1203. return false;
  1204. }
  1205. void AINodeStorage::calculateChainInfo(std::vector<AIPath> & paths, const int3 & pos, const bool isOnLand) const
  1206. {
  1207. auto layer = isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL;
  1208. auto chains = nodes.get(pos);
  1209. for(const AIPathNode & node : chains)
  1210. {
  1211. if(node.version != AISharedStorage::version
  1212. || node.layer != layer
  1213. || node.action == EPathNodeAction::UNKNOWN
  1214. || !node.actor
  1215. || !node.actor->hero)
  1216. {
  1217. continue;
  1218. }
  1219. if(HeroPtr heroPtr(node.actor->hero, aiNk->cc); !heroPtr.isVerified(false))
  1220. {
  1221. #if NK2AI_TRACE_LEVEL >= 1
  1222. logAi->warn("AINodeStorage::calculateChainInfo Skipping path due to unverified hero: %s", heroPtr.nameOrDefault());
  1223. #endif
  1224. continue;
  1225. }
  1226. AIPath & path = paths.emplace_back();
  1227. path.targetHero = node.actor->hero;
  1228. path.heroArmy = node.actor->creatureSet;
  1229. path.armyLoss = node.armyLoss;
  1230. path.targetObjectDanger = aiNk->dangerEvaluator->evaluateDanger(pos, path.targetHero, !node.actor->allowBattle);
  1231. for (auto pathNode : path.nodes)
  1232. {
  1233. path.targetObjectDanger = std::max(aiNk->dangerEvaluator->evaluateDanger(pathNode.coord, path.targetHero, !node.actor->allowBattle), path.targetObjectDanger);
  1234. }
  1235. if(path.targetObjectDanger > 0)
  1236. {
  1237. if(node.theNodeBefore)
  1238. {
  1239. auto prevNode = getAINode(node.theNodeBefore);
  1240. if(node.coord == prevNode->coord && node.actor->hero == prevNode->actor->hero)
  1241. {
  1242. paths.pop_back();
  1243. continue;
  1244. }
  1245. else
  1246. {
  1247. path.armyLoss = prevNode->armyLoss;
  1248. }
  1249. }
  1250. else
  1251. {
  1252. path.armyLoss = 0;
  1253. }
  1254. }
  1255. int fortLevel = 0;
  1256. auto visitableObjects = aiNk->cc->getVisitableObjs(pos);
  1257. for (auto obj : visitableObjects)
  1258. {
  1259. if (objWithID<Obj::TOWN>(obj))
  1260. {
  1261. auto town = dynamic_cast<const CGTownInstance*>(obj);
  1262. fortLevel = town->fortLevel();
  1263. }
  1264. }
  1265. path.targetObjectArmyLoss = evaluateArmyLoss(
  1266. path.targetHero,
  1267. getHeroArmyStrengthWithCommander(path.targetHero, path.heroArmy, fortLevel),
  1268. path.targetObjectDanger);
  1269. path.chainMask = node.actor->chainMask;
  1270. path.exchangeCount = node.actor->actorExchangeCount;
  1271. fillChainInfo(&node, path, -1);
  1272. }
  1273. }
  1274. void AINodeStorage::fillChainInfo(const AIPathNode * node, AIPath & path, int parentIndex) const
  1275. {
  1276. while(node != nullptr)
  1277. {
  1278. if(!node->actor->hero)
  1279. return;
  1280. if(node->chainOther)
  1281. fillChainInfo(node->chainOther, path, parentIndex);
  1282. AIPathNodeInfo pathNode;
  1283. pathNode.cost = node->getCost();
  1284. pathNode.targetHero = node->actor->hero;
  1285. pathNode.chainMask = node->actor->chainMask;
  1286. pathNode.specialAction = node->specialAction;
  1287. pathNode.turns = node->turns;
  1288. pathNode.danger = node->danger;
  1289. pathNode.coord = node->coord;
  1290. pathNode.parentIndex = parentIndex;
  1291. pathNode.actionIsBlocked = false;
  1292. pathNode.layer = node->layer;
  1293. if(pathNode.specialAction)
  1294. {
  1295. auto targetNode =node->theNodeBefore ? getAINode(node->theNodeBefore) : node;
  1296. pathNode.actionIsBlocked = !pathNode.specialAction->canAct(aiNk, targetNode);
  1297. }
  1298. parentIndex = path.nodes.size();
  1299. path.nodes.push_back(pathNode);
  1300. node = getAINode(node->theNodeBefore);
  1301. }
  1302. }
  1303. AIPath::AIPath()
  1304. : nodes({})
  1305. {
  1306. }
  1307. std::shared_ptr<const SpecialAction> AIPath::getFirstBlockedAction() const
  1308. {
  1309. for(auto node = nodes.rbegin(); node != nodes.rend(); node++)
  1310. {
  1311. if(node->specialAction && node->actionIsBlocked)
  1312. return node->specialAction;
  1313. }
  1314. return std::shared_ptr<const SpecialAction>();
  1315. }
  1316. int3 AIPath::firstTileToGet() const
  1317. {
  1318. if(nodes.size())
  1319. {
  1320. return nodes.back().coord;
  1321. }
  1322. return int3(-1, -1, -1);
  1323. }
  1324. int3 AIPath::targetTile() const
  1325. {
  1326. if(nodes.size())
  1327. {
  1328. return targetNode().coord;
  1329. }
  1330. return int3(-1, -1, -1);
  1331. }
  1332. const AIPathNodeInfo & AIPath::firstNode() const
  1333. {
  1334. return nodes.back();
  1335. }
  1336. const AIPathNodeInfo & AIPath::targetNode() const
  1337. {
  1338. auto & node = nodes.front();
  1339. return targetHero == node.targetHero ? node : nodes.at(1);
  1340. }
  1341. uint64_t AIPath::getPathDanger() const
  1342. {
  1343. if(nodes.empty())
  1344. return 0;
  1345. return targetNode().danger;
  1346. }
  1347. float AIPath::movementCost() const
  1348. {
  1349. if(nodes.empty())
  1350. return 0.0f;
  1351. return targetNode().cost;
  1352. }
  1353. uint8_t AIPath::turn() const
  1354. {
  1355. if(nodes.empty())
  1356. return 0;
  1357. return targetNode().turns;
  1358. }
  1359. uint64_t AIPath::getHeroStrength() const
  1360. {
  1361. return targetHero->getHeroStrength() * getHeroArmyStrengthWithCommander(targetHero, heroArmy);
  1362. }
  1363. uint64_t AIPath::getTotalDanger() const
  1364. {
  1365. uint64_t pathDanger = getPathDanger();
  1366. uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger;
  1367. return danger;
  1368. }
  1369. bool AIPath::containsHero(const CGHeroInstance * hero) const
  1370. {
  1371. if(targetHero == hero)
  1372. return true;
  1373. for(auto node : nodes)
  1374. {
  1375. if(node.targetHero == hero)
  1376. return true;
  1377. }
  1378. return false;
  1379. }
  1380. uint64_t AIPath::getTotalArmyLoss() const
  1381. {
  1382. return armyLoss + targetObjectArmyLoss;
  1383. }
  1384. std::string AIPath::toString() const
  1385. {
  1386. std::stringstream str;
  1387. str << targetHero->getNameTranslated() << "[" << std::hex << chainMask << std::dec << "]" << ", turn " << (int)(turn()) << ": ";
  1388. for(auto node : nodes)
  1389. str << node.targetHero->getNameTranslated() << "[" << std::hex << node.chainMask << std::dec << "]" << "->" << node.coord.toString() << "; ";
  1390. return str.str();
  1391. }
  1392. }