AINodeStorage.cpp 41 KB

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