AINodeStorage.cpp 41 KB

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