AINodeStorage.cpp 39 KB

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