2
0

AINodeStorage.cpp 42 KB

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