AINodeStorage.cpp 37 KB

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